Debian Codegraph @

cvd_src/videowriter.cc

raw symbols SCIP
1 #include "cvd/videowriter.h"
2 #include "cvd/videoscaler.h"
3
4 extern "C"
5 {
6 #include <libavcodec/avcodec.h>
7 #include <libavformat/avformat.h>
8 #include <libavutil/imgutils.h>
9 #include <libswscale/swscale.h>
10 }
11
12 namespace CVD
13 {
14 namespace
15 {
16 using std::uint8_t;
17
18 // Calculate the greatest common divisor of two values.
19 int gcd(int a, int b)
20 {
21 if(a < 0)
22 a = -a;
23 if(b < 0)
24 b = -b;
25 for(;;)
26 {
27 if(a == 0)
28 return b;
29 if(b == 0)
30 return a;
31 const int t = b;
32 b = a % b;
33 a = t;
34 }
35 }
36
37 // Multiply one rational number by another.
38 AVRational multiply_rational(const AVRational& left, const AVRational& right)
39 {
40 AVRational r { left.num * right.num, left.den * right.den };
41 if(r.num == 0)
42 {
43 r.den = 1;
44 }
45 else
46 {
47 int d = gcd(r.num, r.den);
48 if(d > 1)
49 {
50 r.num /= d;
51 r.den /= d;
52 }
53 }
54 return r;
55 }
56
57 // Divide one rational number by another.
58 AVRational divide_rational(const AVRational& left, const AVRational& right)
59 {
60 return multiply_rational(left, AVRational { right.den, right.num });
61 }
62
63 }
64
65 VideoWriter::VideoWriter(const std::string& filename,
66 const std::string& codec_name,
67 const std::string& pixel_format_name,
68 AVRational timebase,
69 AVRational frame_rate,
70 int rotation_degrees,
71 int threads,
72 int bitrate,
73 std::int64_t duration)
74 : m_filename(filename)
75 , m_timebase(timebase)
76 , m_threads(threads)
77 , m_bitrate(bitrate)
78 {
79 #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(58, 9, 100)
80 // see https://github.com/FFmpeg/FFmpeg/commit/0694d8702421e7aff1340038559c438b61bb30dd
81 av_register_all();
82 #endif
83 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 10, 100)
84 // see https://github.com/FFmpeg/FFmpeg/commit/3f0a41367eb9180ab6d22d43ad42b9bd85a26df0
85 avcodec_register_all();
86 #endif
87
88 m_codec = avcodec_find_encoder_by_name(codec_name.c_str());
89 if(!m_codec)
90 {
91 throw std::runtime_error("Unable to find codec");
92 }
93
94 AVFormatContext* format_ptr;
95 internal::CheckAVError(avformat_alloc_output_context2(&format_ptr, nullptr, nullptr, m_filename.c_str()));
96 m_format_context.reset(format_ptr);
97
98 auto stream = avformat_new_stream(m_format_context.get(), nullptr);
99 if(!stream)
100 {
101 throw std::runtime_error("avformat_new_stream");
102 }
103 stream->time_base = timebase;
104 if(codec_name == "mpeg4")
105 {
106 // MPEG-4 standard codec can only handle timebases with 16-bit numerator and denominator.
107 while(stream->time_base.den > 65535)
108 {
109 stream->time_base.den /= 2;
110 }
111 while(stream->time_base.num > 65535)
112 {
113 stream->time_base.num /= 2;
114 }
115 }
116
117 stream->avg_frame_rate = frame_rate;
118 stream->r_frame_rate = frame_rate;
119 if(duration >= 0)
120 {
121 stream->duration = duration;
122 }
123 internal::CheckAVError(av_dict_set(&stream->metadata, "rotate", std::to_string(rotation_degrees).c_str(), 0));
124
125 m_codec_context.reset(avcodec_alloc_context3(m_codec));
126 if(!m_codec_context)
127 {
128 throw std::runtime_error("avcodec_alloc_context3");
129 }
130 m_codec_context->thread_count = threads;
131 m_codec_context->codec_id = m_codec->id;
132 m_codec_context->time_base = stream->time_base;
133 m_codec_context->framerate = frame_rate;
134
135 AVPixelFormat pixel_format = av_get_pix_fmt(pixel_format_name.c_str());
136 if(pixel_format != AV_PIX_FMT_NONE)
137 {
138 m_codec_context->pix_fmt = pixel_format;
139 }
140 else
141 {
142 m_codec_context->pix_fmt = m_codec->pix_fmts ? m_codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
143 }
144 if(m_format_context->oformat->flags & AVFMT_GLOBALHEADER)
145 {
146 m_codec_context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
147 }
148 if(m_bitrate > 0)
149 {
150 m_codec_context->bit_rate = m_bitrate;
151 }
152 m_codec_context->colorspace = AVCOL_SPC_BT709;
153 m_codec_context->color_primaries = AVCOL_PRI_BT709;
154 m_codec_context->color_trc = AVCOL_TRC_BT709;
155 m_codec_context->sample_aspect_ratio = { 1, 1 };
156 }
157
158 void VideoWriter::put_frame(const BasicImage<Rgba<uint8_t>>& image, std::int64_t pts)
159 {
160 if(!m_scaler)
161 {
162 m_codec_context->width = image.size().x;
163 m_codec_context->height = image.size().y;
164
165 auto stream = m_format_context->streams[0];
166
167 AVDictionary* dict = nullptr;
168 internal::CheckAVError(avcodec_open2(m_codec_context.get(), m_codec, &dict));
169 internal::CheckAVError(avcodec_parameters_from_context(stream->codecpar, m_codec_context.get()));
170 internal::CheckAVError(avio_open2(&m_format_context->pb, m_filename.c_str(), AVIO_FLAG_WRITE, nullptr, &dict));
171 internal::CheckAVError(avformat_write_header(m_format_context.get(), &dict));
172 av_dict_free(&dict);
173
174 m_scaler = std::make_unique<internal::Scaler>(
175 m_codec_context->width,
176 m_codec_context->height,
177 AV_PIX_FMT_RGBA,
178 m_codec_context->pix_fmt,
179 SWS_CS_ITU709,
180 m_threads);
181 }
182
183 const uint8_t* data[4] = { reinterpret_cast<const uint8_t*>(image.data()), nullptr, nullptr, nullptr };
184 int stride[4] = { static_cast<int>(image.row_stride() * sizeof(Rgba<uint8_t>)), 0, 0, 0 };
185
186 std::unique_ptr<AVFrame, internal::AVFrameDeleter> output_frame(av_frame_alloc());
187 output_frame->width = m_codec_context->width;
188 output_frame->height = m_codec_context->height;
189 output_frame->format = m_codec_context->pix_fmt;
190 output_frame->colorspace = m_codec_context->colorspace;
191 output_frame->color_primaries = m_codec_context->color_primaries;
192 output_frame->color_trc = m_codec_context->color_trc;
193 output_frame->sample_aspect_ratio = m_codec_context->sample_aspect_ratio;
194 auto timebase_ratio = divide_rational(m_timebase, m_format_context->streams[0]->time_base);
195 output_frame->pts = (pts * timebase_ratio.num + timebase_ratio.den / 2) / timebase_ratio.den;
196 internal::CheckAVError(av_frame_get_buffer(output_frame.get(), 32));
197
198 m_scaler->scale(data, stride, 0, image.size().y, output_frame->data, output_frame->linesize);
199
200 internal::SendFrame(m_format_context.get(), m_codec_context.get(), output_frame.get());
201 }
202
203 VideoWriter::~VideoWriter()
204 {
205 if(m_scaler)
206 {
207 internal::SendFrame(m_format_context.get(), m_codec_context.get(), nullptr);
208 internal::CheckAVError(av_write_trailer(m_format_context.get()));
209 }
210 }
211
212 }