Debian Codegraph @

plugins/core/Standard/qAnimation/extern/QTFFmpegWrapper/QVideoEncoder.cpp

raw
1 #include "QVideoEncoder.h"
2
3 #ifdef _MSC_VER
4 #pragma warning(push)
5 #pragma warning(disable : 4996)
6 #endif
7
8 //FFmpeg
9 extern "C"
10 {
11 #include "libavcodec/avcodec.h"
12 #include "libavformat/avformat.h"
13 #include "libavformat/avio.h"
14
15 #include "libavutil/mathematics.h"
16 #include "libavutil/opt.h"
17 #include "libavutil/error.h"
18 #include "libavutil/rational.h"
19 #include "libavutil/frame.h"
20 #include "libavutil/avstring.h"
21 #include "libavutil/imgutils.h"
22
23 #include "libswscale/swscale.h"
24 }
25
26 //system
27 #include <assert.h>
28
29 struct FFmpegStuffEnc
30 {
31 AVFormatContext *formatContext;
32 AVCodecContext *codecContext;
33 AVStream *videoStream;
34 AVFrame *frame;
35 SwsContext *swsContext;
36
37 FFmpegStuffEnc()
38 : formatContext(0)
39 , codecContext(0)
40 , videoStream(0)
41 , frame(0)
42 , swsContext(0)
43 {}
44 };
45
46 QVideoEncoder::QVideoEncoder(QString filename, int width, int height, unsigned bitrate, int gop, int fps)
47 : m_filename(filename)
48 , m_width(width)
49 , m_height(height)
50 , m_bitrate(bitrate)
51 , m_gop(gop)
52 , m_fps(fps)
53 , m_isOpen(false)
54 , m_ff(new FFmpegStuffEnc)
55 {
56 }
57
58 QVideoEncoder::~QVideoEncoder()
59 {
60 close();
61
62 if (m_ff)
63 {
64 delete m_ff;
65 m_ff = 0;
66 }
67 }
68
69 bool QVideoEncoder::isSizeValid()
70 {
71 return (m_width % 8) == 0 && (m_height % 8) == 0;
72 }
73
74 bool QVideoEncoder::initFrame()
75 {
76 assert(!m_ff->frame);
77
78 m_ff->frame = av_frame_alloc();
79 if (!m_ff->frame)
80 {
81 return false;
82 }
83
84 m_ff->frame->format = m_ff->codecContext->pix_fmt;
85 m_ff->frame->width = m_ff->codecContext->width;
86 m_ff->frame->height = m_ff->codecContext->height;
87 m_ff->frame->pts = 0;
88
89 /* allocate the buffers for the frame data */
90 int ret = av_frame_get_buffer(m_ff->frame, 32);
91 if (ret < 0)
92 {
93 fprintf(stderr, "Could not allocate frame data.\n");
94 return false;
95 }
96
97 return true;
98 }
99
100 void QVideoEncoder::freeFrame()
101 {
102 if (m_ff->frame)
103 {
104 av_frame_free(&m_ff->frame);
105 m_ff->frame = 0;
106 }
107 }
108
109 bool QVideoEncoder::GetSupportedOutputFormats(std::vector<OutputFormat>& formats, bool ignoreIfNoFileExtension/*=true*/)
110 {
111 try
112 {
113 // list of all output formats
114 void *ofmt_opaque = nullptr;
115 while (true)
116 {
117 const AVOutputFormat *format = av_muxer_iterate(&ofmt_opaque);
118 if (format)
119 {
120 //potentially skip the output formats without any extension (= test formats mostly)
121 if ( format->video_codec != AV_CODEC_ID_NONE
122 && (!ignoreIfNoFileExtension || (format->extensions && format->extensions[0] != 0))
123 )
124 {
125 OutputFormat f;
126 {
127 f.shortName = format->name;
128 f.longName = format->long_name;
129 f.extensions = format->extensions;
130 }
131 formats.push_back(f);
132 }
133 }
134 else
135 {
136 break;
137 }
138 }
139 }
140 catch (const std::bad_alloc&)
141 {
142 //not enough memory
143 return false;
144 }
145
146 return true;
147 }
148
149 bool QVideoEncoder::open(QString formatShortName, QStringList& errors)
150 {
151 if (m_isOpen)
152 {
153 //the stream is already opened!
154 return false;
155 }
156
157 if (!isSizeValid())
158 {
159 errors << "Invalid video size";
160 return false;
161 }
162
163 const AVOutputFormat *outputFormat = nullptr;
164 if (!formatShortName.isEmpty())
165 {
166 outputFormat = av_guess_format(qPrintable(formatShortName), nullptr, nullptr);
167 if (!outputFormat)
168 {
169 errors << "Could not find output format from short name: " + formatShortName;
170 }
171 }
172
173 // find the output format
174 avformat_alloc_output_context2(&m_ff->formatContext, outputFormat, nullptr, outputFormat ? qPrintable(m_filename) : nullptr);
175 if (!m_ff->formatContext)
176 {
177 if (!outputFormat)
178 {
179 errors << "Could not deduce output format from file extension: using MPEG";
180
181 avformat_alloc_output_context2(&m_ff->formatContext, nullptr, "mpeg", qPrintable(m_filename));
182 if (!m_ff->formatContext)
183 {
184 errors << "Codec not found";
185 return false;
186 }
187 }
188 else
189 {
190 errors << "Failed to initialize the output context with the specified output format: " + formatShortName;
191 return false;
192 }
193 }
194
195 // get the codec
196 AVCodecID codec_id = m_ff->formatContext->oformat->video_codec;
197 //codec_id = AV_CODEC_ID_MPEG1VIDEO;
198 //codec_id = AV_CODEC_ID_H264;
199 const AVCodec *pCodec = avcodec_find_encoder(codec_id);
200 if (!pCodec)
201 {
202 errors << "Could not load the codec";
203 return false;
204 }
205 m_ff->codecContext = avcodec_alloc_context3(pCodec);
206
207 /* put sample parameters */
208 m_ff->codecContext->bit_rate = m_bitrate;
209 /* resolution must be a multiple of two */
210 m_ff->codecContext->width = m_width;
211 m_ff->codecContext->height = m_height;
212 /* frames per second */
213 m_ff->codecContext->time_base.num = 1;
214 m_ff->codecContext->time_base.den = m_fps;
215 m_ff->codecContext->gop_size = m_gop;
216 m_ff->codecContext->max_b_frames = 1;
217 m_ff->codecContext->pix_fmt = AV_PIX_FMT_YUV420P;
218
219 //DGM: doesn't really change anything. We only get different warnings if we enabled this :(
220 //m_ff->codecContext->rc_buffer_size = m_bitrate * 2;
221 //m_ff->codecContext->rc_max_rate = m_bitrate;
222
223 if (codec_id == AV_CODEC_ID_H264)
224 {
225 av_opt_set(m_ff->codecContext->priv_data, "preset", "slow", 0);
226 }
227 else if (codec_id == AV_CODEC_ID_MPEG1VIDEO)
228 {
229 /* Needed to avoid using macroblocks in which some coeffs overflow.
230 * This does not happen with normal video, it just happens here as
231 * the motion of the chroma plane does not match the luma plane. */
232 m_ff->codecContext->mb_decision = 2;
233 }
234
235 //some formats want stream headers to be separate
236 if (m_ff->formatContext->oformat->flags & AVFMT_GLOBALHEADER)
237 {
238 m_ff->codecContext->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
239 }
240
241 // Add the video stream
242 m_ff->videoStream = avformat_new_stream(m_ff->formatContext, pCodec);
243 if (!m_ff->videoStream )
244 {
245 errors << "Failed to allocate the output stream";
246 return false;
247 }
248 m_ff->videoStream->id = m_ff->formatContext->nb_streams-1;
249 avcodec_parameters_from_context(m_ff->videoStream->codecpar, m_ff->codecContext);
250 m_ff->videoStream->time_base.num = 1;
251 m_ff->videoStream->time_base.den = m_fps;
252
253 //av_dump_format(m_ff->formatContext, 0, fileName.toStdString().c_str(), 1);
254
255 // open the codec
256 if (avcodec_open2(m_ff->codecContext, pCodec, 0) < 0)
257 {
258 errors << "Could not open the codec";
259 return false;
260 }
261
262 // Allocate the YUV frame
263 if (!initFrame())
264 {
265 errors << "Could not init the internal frame";
266 return false;
267 }
268
269 if (avio_open(&m_ff->formatContext->pb, qPrintable(m_filename), AVIO_FLAG_WRITE) < 0)
270 {
271 errors << QString("Could not open '%1'").arg(m_filename);
272 return false;
273 }
274
275 int err = avformat_write_header(m_ff->formatContext, nullptr);
276
277 if ( err != 0 )
278 {
279 errors << QString("Could not write header for '%1'").arg(m_filename);
280 return false;
281 }
282
283 m_isOpen = true;
284
285 return true;
286 }
287
288 static int write_frame(FFmpegStuffEnc* ff, AVPacket *pkt)
289 {
290 if (!ff)
291 {
292 assert(ff);
293 return 0;
294 }
295
296 //if (ff->codecContext->coded_frame->key_frame)
297 //{
298 // pkt->flags |= AV_PKT_FLAG_KEY;
299 //}
300
301 // rescale output packet timestamp values from codec to stream timebase
302 av_packet_rescale_ts(pkt, ff->codecContext->time_base, ff->videoStream->time_base);
303 pkt->stream_index = ff->videoStream->index;
304
305 // write the compressed frame to the media file
306 return av_interleaved_write_frame(ff->formatContext, pkt);
307 }
308
309 bool QVideoEncoder::close()
310 {
311 if (!m_isOpen)
312 {
313 return false;
314 }
315
316 int ret = avcodec_send_frame(m_ff->codecContext, 0);
317
318 // delayed frames?
319 while (ret >= 0)
320 {
321 AVPacket pkt;
322 memset(&pkt, 0, sizeof(AVPacket));
323 av_init_packet(&pkt);
324
325 ret = avcodec_receive_packet(m_ff->codecContext, &pkt);
326 if (ret < 0)
327 {
328 break;
329 }
330
331 write_frame(m_ff, &pkt);
332 }
333
334 av_write_trailer(m_ff->formatContext);
335
336 // close the codec
337 avcodec_close(m_ff->codecContext);
338
339 // free the streams and other data
340 freeFrame();
341 for(unsigned i = 0; i < m_ff->formatContext->nb_streams; i++)
342 {
343 av_freep(&m_ff->formatContext->streams[i]);
344 }
345
346 // close the file
347 avio_close(m_ff->formatContext->pb);
348
349 // free the stream
350 av_free(m_ff->formatContext);
351
352 m_isOpen = false;
353
354 return true;
355 }
356
357 bool QVideoEncoder::encodeImage(const QImage &image, int frameIndex, QString* errorString/*=nullptr*/)
358 {
359 if (!isOpen())
360 {
361 if (errorString)
362 *errorString = "Stream is not opened";
363 return false;
364 }
365
366 // SWS conversion
367 if (!convertImage_sws(image, errorString))
368 {
369 return false;
370 }
371
372 // encode the image
373 {
374 //compute correct timestamp based on the input frame index
375 //int timestamp = ((m_ff->codecContext->time_base.num * 90000) / m_ff->codecContext->time_base.den) * frameIndex;
376 m_ff->frame->pts = frameIndex/*timestamp*/;
377
378 int ret = avcodec_send_frame(m_ff->codecContext, m_ff->frame);
379 if (ret < 0)
380 {
381 char errorStr[AV_ERROR_MAX_STRING_SIZE] = {0};
382 av_make_error_string(errorStr, AV_ERROR_MAX_STRING_SIZE, ret);
383 if (errorString)
384 *errorString = QString("Error encoding video frame: %1").arg(errorStr);
385 return false;
386 }
387
388 while (ret >= 0)
389 {
390 AVPacket pkt;
391 memset(&pkt, 0, sizeof(AVPacket));
392 av_init_packet(&pkt);
393
394 ret = avcodec_receive_packet(m_ff->codecContext, &pkt);
395 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
396 break;
397 else if (ret < 0)
398 {
399 char errorStr[AV_ERROR_MAX_STRING_SIZE] = {0};
400 av_make_error_string(errorStr, AV_ERROR_MAX_STRING_SIZE, ret);
401 if (errorString)
402 *errorString = QString("Error receiving video frame: %1").arg(errorStr);
403 return false;
404 }
405
406 int wRet = write_frame(m_ff, &pkt);
407 if (wRet < 0)
408 {
409 char errorStr[AV_ERROR_MAX_STRING_SIZE] = {0};
410 av_make_error_string(errorStr, AV_ERROR_MAX_STRING_SIZE, wRet);
411 if (errorString)
412 *errorString = QString("Error while writing video frame: %1").arg(errorStr);
413 return false;
414 }
415 }
416 }
417
418 return true;
419 }
420
421 bool QVideoEncoder::convertImage_sws(const QImage &image, QString* errorString/*=nullptr*/)
422 {
423 // Check if the image matches the size
424 if (image.width() != m_width || image.height() != m_height)
425 {
426 if (errorString)
427 *errorString = "Wrong image size";
428 return false;
429 }
430
431 QImage::Format format = image.format();
432 if ( format != QImage::Format_RGB32
433 && format != QImage::Format_ARGB32
434 && format != QImage::Format_ARGB32_Premultiplied )
435 {
436 if (errorString)
437 *errorString = "Wrong image format";
438 return false;
439 }
440
441 //Check if context can be reused, otherwise reallocate a new one
442 m_ff->swsContext = sws_getCachedContext(m_ff->swsContext,
443 m_width,
444 m_height,
445 AV_PIX_FMT_BGRA,
446 m_width,
447 m_height,
448 AV_PIX_FMT_YUV420P,
449 SWS_BICUBIC,
450 nullptr,
451 nullptr,
452 nullptr);
453
454 if (m_ff->swsContext == nullptr)
455 {
456 if (errorString)
457 *errorString = "[SWS] Cannot initialize the conversion context";
458 return false;
459 }
460
461 int num_bytes = av_image_get_buffer_size(AV_PIX_FMT_BGRA, m_width, m_height, 1);
462 if (num_bytes != image.byteCount())
463 {
464 if (errorString)
465 *errorString = "[SWS] Number of bytes mismatch";
466 return false;
467 }
468
469 const uint8_t *srcSlice[3] = { static_cast<const uint8_t*>(image.constBits()), 0, 0 };
470 int srcStride[3] = { image.bytesPerLine(), 0, 0 };
471
472 sws_scale( m_ff->swsContext,
473 srcSlice,
474 srcStride,
475 0,
476 m_height,
477 m_ff->frame->data,
478 m_ff->frame->linesize );
479
480 return true;
481 }
482
483 #ifdef _MSC_VER
484 #pragma warning(pop)
485 #endif
486