Debian Codegraph @

gui/qffmpeg/QVideoEncoder.cpp

raw symbols SCIP
1 /*
2 QTFFmpegWrapper - QT FFmpeg Wrapper Class
3 Copyright (C) 2009-2012:
4 Daniel Roggen, [email protected]
5
6 All rights reserved.
7
8 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
9
10 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
11 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
12
13 THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14 */
15
16 #include <QPainter>
17 #include "QVideoEncoder.h"
18 #include "ffmpeg.h"
19
20
21
22 /******************************************************************************
23 *******************************************************************************
24 * QVideoEncoder QVideoEncoder QVideoEncoder QVideoEncoder QVideoEncoder
25 *******************************************************************************
26 ******************************************************************************/
27
28
29 /******************************************************************************
30 * PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC
31 ******************************************************************************/
32
33 /**
34 gop: maximal interval in frames between keyframes
35 **/
36 QVideoEncoder::QVideoEncoder()
37 {
38 initVars();
39 initCodec();
40 }
41
42 QVideoEncoder::~QVideoEncoder()
43 {
44 close();
45 /*if(Initmodefile)
46 {
47 writeFooter();
48 Outdev->close();
49 delete Outdev;
50 Outdev=0;
51 }
52 else
53 {
54 // nothing to do
55 }*/
56 }
57
58 bool QVideoEncoder::createFile(QString fileName,unsigned width,unsigned height,unsigned bitrate,unsigned gop,unsigned fps)
59 {
60 // If we had an open video, close it.
61 close();
62
63 Width=width;
64 Height=height;
65 Gop=gop;
66 Bitrate=bitrate;
67
68 if(!isSizeValid())
69 {
70 qDebug("Invalid size\n");
71 return false;
72 }
73
74 pOutputFormat = ffmpeg::av_guess_format(NULL, fileName.toStdString().c_str(), NULL);
75 if (!pOutputFormat) {
76 qDebug("Could not deduce output format from file extension: using MPEG.\n");
77 pOutputFormat = ffmpeg::av_guess_format("mpeg", NULL, NULL);
78 }
79
80 pFormatCtx=ffmpeg::avformat_alloc_context();
81 if(!pFormatCtx)
82 {
83 qDebug("Error allocating format context\n");
84 return false;
85 }
86 pFormatCtx->oformat = pOutputFormat;
87 snprintf(pFormatCtx->filename, sizeof(pFormatCtx->filename), "%s", fileName.toStdString().c_str());
88
89
90 // Add the video stream
91
92 pVideoStream = av_new_stream(pFormatCtx,0);
93 if(!pVideoStream )
94 {
95 qDebug("Could not allocate stream\n");
96 return false;
97 }
98
99
100 pCodecCtx=pVideoStream->codec;
101 pCodecCtx->codec_id = pOutputFormat->video_codec;
102 pCodecCtx->codec_type = ffmpeg::AVMEDIA_TYPE_VIDEO;
103
104 pCodecCtx->bit_rate = Bitrate;
105 pCodecCtx->width = getWidth();
106 pCodecCtx->height = getHeight();
107 pCodecCtx->time_base.den = fps;
108 pCodecCtx->time_base.num = 1;
109 pCodecCtx->gop_size = Gop;
110 pCodecCtx->pix_fmt = ffmpeg::PIX_FMT_YUV420P;
111
112
113 avcodec_thread_init(pCodecCtx, 10);
114
115 //if (c->codec_id == CODEC_ID_MPEG2VIDEO)
116 //{
117 //c->max_b_frames = 2; // just for testing, we also add B frames
118 //}
119
120 // some formats want stream headers to be separate
121 if(pFormatCtx->oformat->flags & AVFMT_GLOBALHEADER)
122 pCodecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
123
124
125 if (av_set_parameters(pFormatCtx, NULL) < 0)
126 {
127 qDebug("Invalid output format parameters\n");
128 return false;
129 }
130
131 ffmpeg::dump_format(pFormatCtx, 0, fileName.toStdString().c_str(), 1);
132
133 // open_video
134 // find the video encoder
135 pCodec = avcodec_find_encoder(pCodecCtx->codec_id);
136 if (!pCodec)
137 {
138 qDebug("codec not found\n");
139 return false;
140 }
141 // open the codec
142 if (avcodec_open(pCodecCtx, pCodec) < 0)
143 {
144 qDebug("could not open codec\n");
145 return false;
146 }
147
148 // Allocate memory for output
149 if(!initOutputBuf())
150 {
151 qDebug("Can't allocate memory for output bitstream\n");
152 return false;
153 }
154
155 // Allocate the YUV frame
156 if(!initFrame())
157 {
158 qDebug("Can't init frame\n");
159 return false;
160 }
161
162 if (url_fopen(&pFormatCtx->pb, fileName.toStdString().c_str(), URL_WRONLY) < 0)
163 {
164 qDebug( "Could not open '%s'\n", fileName.toStdString().c_str());
165 return false;
166 }
167
168 av_write_header(pFormatCtx);
169
170
171
172 ok=true;
173
174 return true;
175 }
176
177 /**
178 \brief Completes writing the stream, closes it, release resources.
179 **/
180 bool QVideoEncoder::close()
181 {
182 if(!isOk())
183 return false;
184
185 av_write_trailer(pFormatCtx);
186
187 // close_video
188
189 avcodec_close(pVideoStream->codec);
190 freeFrame();
191 freeOutputBuf();
192
193
194 /* free the streams */
195
196 for(int i = 0; i < pFormatCtx->nb_streams; i++)
197 {
198 av_freep(&pFormatCtx->streams[i]->codec);
199 av_freep(&pFormatCtx->streams[i]);
200 }
201
202 // Close file
203 url_fclose(pFormatCtx->pb);
204
205 // Free the stream
206 av_free(pFormatCtx);
207
208 initVars();
209 return true;
210 }
211
212
213 /**
214 \brief Encode one frame
215
216 The frame must be of the same size as specified in the createFile call.
217
218 This is the standard method to encode videos with fixed frame rates.
219 Each call to encodeImage adds a frame, which will be played back at the frame rate
220 specified in the createFile call.
221 **/
222 int QVideoEncoder::encodeImage(const QImage &img)
223 {
224 return encodeImage_p(img);
225 }
226 /**
227 \brief Encode one frame
228
229 The frame must be of the same size as specified in the createFile call.
230
231 This mehtod allows to specify the presentation time stamp (pts) of the frame.
232 pts is specified in multiples of 1/framerate, where framerate was specified in the createFile call
233 E.g. to encode frames with a 1ms resolution: set the frame rate to 1000, and pts is the presentation
234 time in milliseconds.
235 pts must be monotonously increasing.
236 The first frame ought to have a pts of 0 to be immediately displayed.
237 **/
238 int QVideoEncoder::encodeImagePts(const QImage &img,unsigned pts)
239 {
240 return encodeImage_p(img,true,pts);
241 }
242
243
244 /******************************************************************************
245 * INTERNAL INTERNAL INTERNAL INTERNAL INTERNAL INTERNAL INTERNAL
246 ******************************************************************************/
247
248 void QVideoEncoder::initVars()
249 {
250 ok=false;
251 pFormatCtx=0;
252 pOutputFormat=0;
253 pCodecCtx=0;
254 pVideoStream=0;
255 pCodec=0;
256 ppicture=0;
257 outbuf=0;
258 picture_buf=0;
259 img_convert_ctx=0;
260 }
261
262
263 /**
264 \brief Register the codecs
265 **/
266 bool QVideoEncoder::initCodec()
267 {
268 ffmpeg::avcodec_init();
269 ffmpeg::av_register_all();
270
271 qDebug("License: %s\n",ffmpeg::avformat_license());
272 qDebug("AVCodec version %d\n",ffmpeg::avformat_version());
273 qDebug("AVFormat configuration: %s\n",ffmpeg::avformat_configuration());
274
275 return true;
276 }
277
278 /**
279 \brief Encode one frame - internal function
280 custompts: true if a custom presentation time stamp is used
281 pts: presentation time stamp in milliseconds
282 **/
283 int QVideoEncoder::encodeImage_p(const QImage &img,bool custompts, unsigned pts)
284 {
285 if(!isOk())
286 return -1;
287
288 //convertImage(img); // Custom conversion routine
289 convertImage_sws(img); // SWS conversion
290
291
292
293 if(custompts) // Handle custom pts
294 pCodecCtx->coded_frame->pts = pts; // Set the time stamp
295
296 int out_size = ffmpeg::avcodec_encode_video(pCodecCtx,outbuf,outbuf_size,ppicture);
297 //qDebug("Frame size: %d\n",out_size);
298
299
300 if(custompts) // Handle custom pts (must set it again for the rest of the processing)
301 pCodecCtx->coded_frame->pts = pts; // Set the time stamp
302
303 if (out_size > 0)
304 {
305
306 av_init_packet(&pkt);
307
308 //if (pCodecCtx->coded_frame->pts != AV_NOPTS_VALUE)
309 if (pCodecCtx->coded_frame->pts != (0x8000000000000000LL))
310 pkt.pts= av_rescale_q(pCodecCtx->coded_frame->pts, pCodecCtx->time_base, pVideoStream->time_base);
311 if(pCodecCtx->coded_frame->key_frame)
312 pkt.flags |= AV_PKT_FLAG_KEY;
313
314 //qDebug("c %d. pts %d. codedframepts: %ld pkt.pts: %ld\n",custompts,pts,pCodecCtx->coded_frame->pts,pkt.pts);
315
316 pkt.stream_index= pVideoStream->index;
317 pkt.data= outbuf;
318 pkt.size= out_size;
319 int ret = av_interleaved_write_frame(pFormatCtx, &pkt);
320 //qDebug("Wrote %d\n",ret);
321 if(ret<0)
322 return -1;
323 }
324 return out_size;
325 }
326
327
328
329 /**
330 Ensures sizes are some reasonable multiples
331 **/
332 bool QVideoEncoder::isSizeValid()
333 {
334 if(getWidth()%8)
335 return false;
336 if(getHeight()%8)
337 return false;
338 return true;
339 }
340
341 unsigned QVideoEncoder::getWidth()
342 {
343 return Width;
344 }
345 unsigned QVideoEncoder::getHeight()
346 {
347 return Height;
348 }
349 bool QVideoEncoder::isOk()
350 {
351 return ok;
352 }
353
354 /**
355 Allocate memory for the compressed bitstream
356 **/
357 bool QVideoEncoder::initOutputBuf()
358 {
359 outbuf_size = getWidth()*getHeight()*3; // Some extremely generous memory allocation for the encoded frame.
360 outbuf = new uint8_t[outbuf_size];
361 if(outbuf==0)
362 return false;
363 return true;
364 }
365 /**
366 Free memory for the compressed bitstream
367 **/
368 void QVideoEncoder::freeOutputBuf()
369 {
370 if(outbuf)
371 {
372 delete[] outbuf;
373 outbuf=0;
374 }
375 }
376
377 bool QVideoEncoder::initFrame()
378 {
379 ppicture = ffmpeg::avcodec_alloc_frame();
380 if(ppicture==0)
381 return false;
382
383 int size = avpicture_get_size(pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
384 picture_buf = new uint8_t[size];
385 if(picture_buf==0)
386 {
387 av_free(ppicture);
388 ppicture=0;
389 return false;
390 }
391
392 // Setup the planes
393 avpicture_fill((ffmpeg::AVPicture *)ppicture, picture_buf,pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
394
395 return true;
396 }
397 void QVideoEncoder::freeFrame()
398 {
399 if(picture_buf)
400 {
401 delete[] picture_buf;
402 picture_buf=0;
403 }
404 if(ppicture)
405 {
406 av_free(ppicture);
407 ppicture=0;
408 }
409 }
410
411 /**
412 \brief Convert the QImage to the internal YUV format
413
414 Custom conversion - not very optimized.
415
416 **/
417
418 bool QVideoEncoder::convertImage(const QImage &img)
419 {
420 // Check if the image matches the size
421 if(img.width()!=getWidth() || img.height()!=getHeight())
422 {
423 qDebug("Wrong image size!\n");
424 return false;
425 }
426 if(img.format()!=QImage::Format_RGB32 && img.format() != QImage::Format_ARGB32)
427 {
428 qDebug("Wrong image format\n");
429 return false;
430 }
431
432 // RGB32 to YUV420
433
434 int size = getWidth()*getHeight();
435 // Y
436 for(unsigned y=0;y<getHeight();y++)
437 {
438
439 unsigned char *s = (unsigned char*)img.scanLine(y);
440 unsigned char *d = (unsigned char*)&picture_buf[y*getWidth()];
441 //qDebug("Line %d. d: %p. picture_buf: %p\n",y,d,picture_buf);
442
443 for(unsigned x=0;x<getWidth();x++)
444 {
445 unsigned int r=s[2];
446 unsigned int g=s[1];
447 unsigned int b=s[0];
448
449 unsigned Y = (r*2104 + g*4130 + b*802 + 4096 + 131072) >> 13;
450 if(Y>235) Y=235;
451
452 *d = Y;
453
454 d+=1;
455 s+=4;
456 }
457 }
458
459 // U,V
460 for(unsigned y=0;y<getHeight();y+=2)
461 {
462 unsigned char *s = (unsigned char*)img.scanLine(y);
463 unsigned int ss = img.bytesPerLine();
464 unsigned char *d = (unsigned char*)&picture_buf[size+y/2*getWidth()/2];
465
466 //qDebug("Line %d. d: %p. picture_buf: %p\n",y,d,picture_buf);
467
468 for(unsigned x=0;x<getWidth();x+=2)
469 {
470 // Cr = 128 + 1/256 * ( 112.439 * R'd - 94.154 * G'd - 18.285 * B'd)
471 // Cb = 128 + 1/256 * (- 37.945 * R'd - 74.494 * G'd + 112.439 * B'd)
472
473 // Get the average RGB in a 2x2 block
474 int r=(s[2] + s[6] + s[ss+2] + s[ss+6] + 2) >> 2;
475 int g=(s[1] + s[5] + s[ss+1] + s[ss+5] + 2) >> 2;
476 int b=(s[0] + s[4] + s[ss+0] + s[ss+4] + 2) >> 2;
477
478 int Cb = (-1214*r - 2384*g + 3598*b + 4096 + 1048576)>>13;
479 if(Cb<16)
480 Cb=16;
481 if(Cb>240)
482 Cb=240;
483
484 int Cr = (3598*r - 3013*g - 585*b + 4096 + 1048576)>>13;
485 if(Cr<16)
486 Cr=16;
487 if(Cr>240)
488 Cr=240;
489
490 *d = Cb;
491 *(d+size/4) = Cr;
492
493 d+=1;
494 s+=8;
495 }
496 }
497 return true;
498 }
499
500 /**
501 \brief Convert the QImage to the internal YUV format
502
503 SWS conversion
504
505 Caution: the QImage is allocated by QT without guarantee about the alignment and bytes per lines.
506 It *should* be okay as we make sure the image is a multiple of many bytes (8 or 16)...
507 ... however it is not guaranteed that sws_scale won't at some point require more bytes per line.
508 We keep the custom conversion for that case.
509
510 **/
511
512 bool QVideoEncoder::convertImage_sws(const QImage &img)
513 {
514 // Check if the image matches the size
515 if(img.width()!=getWidth() || img.height()!=getHeight())
516 {
517 qDebug("Wrong image size!\n");
518 return false;
519 }
520 if(img.format()!=QImage::Format_RGB32 && img.format() != QImage::Format_ARGB32)
521 {
522 qDebug("Wrong image format\n");
523 return false;
524 }
525
526 img_convert_ctx = ffmpeg::sws_getCachedContext(img_convert_ctx,getWidth(),getHeight(),ffmpeg::PIX_FMT_BGRA,getWidth(),getHeight(),ffmpeg::PIX_FMT_YUV420P,SWS_BICUBIC, NULL, NULL, NULL);
527 //img_convert_ctx = ffmpeg::sws_getCachedContext(img_convert_ctx,getWidth(),getHeight(),ffmpeg::PIX_FMT_BGRA,getWidth(),getHeight(),ffmpeg::PIX_FMT_YUV420P,SWS_FAST_BILINEAR, NULL, NULL, NULL);
528 if (img_convert_ctx == NULL)
529 {
530 qDebug("Cannot initialize the conversion context\n");
531 return false;
532 }
533
534 uint8_t *srcplanes[3];
535 srcplanes[0]=(uint8_t*)img.bits();
536 srcplanes[1]=0;
537 srcplanes[2]=0;
538
539 int srcstride[3];
540 srcstride[0]=img.bytesPerLine();
541 srcstride[1]=0;
542 srcstride[2]=0;
543
544
545 ffmpeg::sws_scale(img_convert_ctx, srcplanes, srcstride,0, getHeight(), ppicture->data, ppicture->linesize);
546
547 return true;
548 }
549