Debian Codegraph @

gui/qffmpeg/QVideoDecoder.cpp

raw symbols SCIP
1 /*
2 QTFFmpegWrapper - QT FFmpeg Wrapper Class
3 Copyright (C) 2009,2010:
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 "QVideoDecoder.h"
17 #include <limits.h>
18 #include <stdint.h>
19 #include "ffmpeg.h"
20
21
22 /******************************************************************************
23 *******************************************************************************
24 * QVideoDecoder QVideoDecoder QVideoDecoder QVideoDecoder QVideoDecoder
25 *******************************************************************************
26 ******************************************************************************/
27
28 /******************************************************************************
29 * PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC
30 ******************************************************************************/
31
32
33 /**
34 \brief Constructor - opens a video on later openFile call
35 **/
36 QVideoDecoder::QVideoDecoder()
37 {
38 InitVars();
39 initCodec();
40 }
41 /**
42 \brief Constructor - opens directly a video
43 **/
44 QVideoDecoder::QVideoDecoder(QString file)
45 {
46 InitVars();
47 initCodec();
48
49 ok = openFile(file.toStdString().c_str());
50 }
51
52 QVideoDecoder::~QVideoDecoder()
53 {
54 close();
55 }
56
57 void QVideoDecoder::InitVars()
58 {
59 ok=false;
60 pFormatCtx=0;
61 pCodecCtx=0;
62 pCodec=0;
63 pFrame=0;
64 pFrameRGB=0;
65 buffer=0;
66 img_convert_ctx=0;
67 }
68
69 void QVideoDecoder::close()
70 {
71 if(!ok)
72 return;
73
74 // Free the RGB image
75 if(buffer)
76 delete [] buffer;
77
78 // Free the YUV frame
79 if(pFrame)
80 av_free(pFrame);
81
82 // Free the RGB frame
83 if(pFrameRGB)
84 av_free(pFrameRGB);
85
86 // Close the codec
87 if(pCodecCtx)
88 avcodec_close(pCodecCtx);
89
90 // Close the video file
91 if(pFormatCtx)
92 av_close_input_file(pFormatCtx);
93
94 InitVars();
95 }
96
97
98 bool QVideoDecoder::initCodec()
99 {
100 ffmpeg::avcodec_init();
101 ffmpeg::avcodec_register_all();
102 ffmpeg::av_register_all();
103
104 qDebug("License: %s\n",ffmpeg::avformat_license());
105 qDebug("AVCodec version %d\n",ffmpeg::avformat_version());
106 qDebug("AVFormat configuration: %s\n",ffmpeg::avformat_configuration());
107
108 return true;
109 }
110
111 bool QVideoDecoder::openFile(QString filename)
112 {
113 // Close last video..
114 close();
115
116 LastLastFrameTime=INT_MIN; // Last last must be small to handle the seek well
117 LastFrameTime=0;
118 LastLastFrameNumber=INT_MIN;
119 LastFrameNumber=0;
120 DesiredFrameTime=DesiredFrameNumber=0;
121 LastFrameOk=false;
122
123
124 // Open video file
125 if(av_open_input_file(&pFormatCtx, filename.toStdString().c_str(), NULL, 0, NULL)!=0)
126 return false; // Couldn't open file
127
128 // Retrieve stream information
129 if(av_find_stream_info(pFormatCtx)<0)
130 return false; // Couldn't find stream information
131
132 // Dump information about file onto standard error
133 dump_format(pFormatCtx, 0, filename.toStdString().c_str(), false);
134
135 // Find the first video stream
136 videoStream=-1;
137 for(unsigned i=0; i<pFormatCtx->nb_streams; i++)
138 if(pFormatCtx->streams[i]->codec->codec_type==ffmpeg::AVMEDIA_TYPE_VIDEO)
139 {
140 videoStream=i;
141 break;
142 }
143 if(videoStream==-1)
144 return false; // Didn't find a video stream
145
146 // Get a pointer to the codec context for the video stream
147 pCodecCtx=pFormatCtx->streams[videoStream]->codec;
148
149 // Find the decoder for the video stream
150 pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
151 if(pCodec==NULL)
152 return false; // Codec not found
153
154 // Open codec
155 if(avcodec_open(pCodecCtx, pCodec)<0)
156 return false; // Could not open codec
157
158 // Hack to correct wrong frame rates that seem to be generated by some
159 // codecs
160 if(pCodecCtx->time_base.num>1000 && pCodecCtx->time_base.den==1)
161 pCodecCtx->time_base.den=1000;
162
163 // Allocate video frame
164 pFrame=ffmpeg::avcodec_alloc_frame();
165
166 // Allocate an AVFrame structure
167 pFrameRGB=ffmpeg::avcodec_alloc_frame();
168 if(pFrameRGB==NULL)
169 return false;
170
171 // Determine required buffer size and allocate buffer
172 numBytes=ffmpeg::avpicture_get_size(ffmpeg::PIX_FMT_RGB24, pCodecCtx->width,pCodecCtx->height);
173 buffer=new uint8_t[numBytes];
174
175 // Assign appropriate parts of buffer to image planes in pFrameRGB
176 avpicture_fill((ffmpeg::AVPicture *)pFrameRGB, buffer, ffmpeg::PIX_FMT_RGB24,
177 pCodecCtx->width, pCodecCtx->height);
178
179 ok=true;
180 return true;
181 }
182 bool QVideoDecoder::isOk()
183 {
184 return ok;
185 }
186
187 /**
188 Decodes the video stream until the first frame with number larger or equal than 'after' is found.
189
190 Returns:
191 - true if a frame is found, false otherwise.
192 - the image as a QImage if img is non-null
193 - time frame time, if frametime is non-null
194 - the frame number, if framenumber is non-null
195
196 All times are in milliseconds.
197 **/
198 bool QVideoDecoder::decodeSeekFrame(int after)
199 {
200 if(!ok)
201 return false;
202
203 //qDebug("decodeSeekFrame. after: %d. LLT: %d. LT: %d. LLF: %d. LF: %d. LastFrameOk: %d.\n",after,LastLastFrameTime,LastFrameTime,LastLastFrameNumber,LastFrameNumber,(int)LastFrameOk);
204
205
206
207 // If the last decoded frame satisfies the time condition we return it
208 //if( after!=-1 && ( LastDataInvalid==false && after>=LastLastFrameTime && after <= LastFrameTime))
209 if( after!=-1 && ( LastFrameOk==true && after>=LastLastFrameNumber && after <= LastFrameNumber))
210 {
211 // This is the frame we want to return
212
213 // Compute desired frame time
214 ffmpeg::AVRational millisecondbase = {1, 1000};
215 DesiredFrameTime = ffmpeg::av_rescale_q(after,pFormatCtx->streams[videoStream]->time_base,millisecondbase);
216
217 //qDebug("Returning already available frame %d @ %d. DesiredFrameTime: %d\n",LastFrameNumber,LastFrameTime,DesiredFrameTime);
218
219 return true;
220 }
221
222 // The last decoded frame wasn't ok; either we need any new frame (after=-1), or a specific new frame with time>after
223
224 bool done=false;
225 while(!done)
226 {
227 // Read a frame
228 if(av_read_frame(pFormatCtx, &packet)<0)
229 return false; // Frame read failed (e.g. end of stream)
230
231 //qDebug("Packet of stream %d, size %d\n",packet.stream_index,packet.size);
232
233 if(packet.stream_index==videoStream)
234 {
235 // Is this a packet from the video stream -> decode video frame
236
237 int frameFinished;
238 avcodec_decode_video2(pCodecCtx,pFrame,&frameFinished,&packet);
239
240 //qDebug("used %d out of %d bytes\n",len,packet.size);
241
242 //qDebug("Frame type: ");
243 //if(pFrame->pict_type == FF_B_TYPE)
244 // qDebug("B\n");
245 //else if (pFrame->pict_type == FF_I_TYPE)
246 // qDebug("I\n");
247 //else
248 // qDebug("P\n");
249
250
251 /*qDebug("codecctx time base: num: %d den: %d\n",pCodecCtx->time_base.num,pCodecCtx->time_base.den);
252 qDebug("formatctx time base: num: %d den: %d\n",pFormatCtx->streams[videoStream]->time_base.num,pFormatCtx->streams[videoStream]->time_base.den);
253 qDebug("pts: %ld\n",pts);
254 qDebug("dts: %ld\n",dts);*/
255
256
257
258
259 // Did we get a video frame?
260 if(frameFinished)
261 {
262 ffmpeg::AVRational millisecondbase = {1, 1000};
263 int f = packet.dts;
264 int t = ffmpeg::av_rescale_q(packet.dts,pFormatCtx->streams[videoStream]->time_base,millisecondbase);
265 if(LastFrameOk==false)
266 {
267 LastFrameOk=true;
268 LastLastFrameTime=LastFrameTime=t;
269 LastLastFrameNumber=LastFrameNumber=f;
270 }
271 else
272 {
273 // If we decoded 2 frames in a row, the last times are okay
274 LastLastFrameTime = LastFrameTime;
275 LastLastFrameNumber = LastFrameNumber;
276 LastFrameTime=t;
277 LastFrameNumber=f;
278 }
279 //qDebug("Frame %d @ %d. LastLastT: %d. LastLastF: %d. LastFrameOk: %d\n",LastFrameNumber,LastFrameTime,LastLastFrameTime,LastLastFrameNumber,(int)LastFrameOk);
280
281 // Is this frame the desired frame?
282 if(after==-1 || LastFrameNumber>=after)
283 {
284 // It's the desired frame
285
286 // Convert the image format (init the context the first time)
287 int w = pCodecCtx->width;
288 int h = pCodecCtx->height;
289 img_convert_ctx = ffmpeg::sws_getCachedContext(img_convert_ctx,w, h, pCodecCtx->pix_fmt, w, h, ffmpeg::PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);
290
291 if(img_convert_ctx == NULL)
292 {
293 qDebug("Cannot initialize the conversion context!\n");
294 return false;
295 }
296 ffmpeg::sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize);
297
298 // Convert the frame to QImage
299 LastFrame=QImage(w,h,QImage::Format_RGB888);
300
301 for(int y=0;y<h;y++)
302 memcpy(LastFrame.scanLine(y),pFrameRGB->data[0]+y*pFrameRGB->linesize[0],w*3);
303
304 // Set the time
305 DesiredFrameTime = ffmpeg::av_rescale_q(after,pFormatCtx->streams[videoStream]->time_base,millisecondbase);
306 LastFrameOk=true;
307
308
309 done = true;
310
311 } // frame of interest
312 } // frameFinished
313 } // stream_index==videoStream
314 av_free_packet(&packet); // Free the packet that was allocated by av_read_frame
315 }
316 //qDebug("Returning new frame %d @ %d. LastLastT: %d. LastLastF: %d. LastFrameOk: %d\n",LastFrameNumber,LastFrameTime,LastLastFrameTime,LastLastFrameNumber,(int)LastFrameOk);
317 //qDebug("\n");
318 return done; // done indicates whether or not we found a frame
319 }
320
321 /**
322 \brief Decodes the next frame in the video stream
323
324
325 **/
326 bool QVideoDecoder::seekNextFrame()
327 {
328 bool ret = decodeSeekFrame(DesiredFrameNumber+1);
329
330 if(ret)
331 DesiredFrameNumber++; // Only updates the DesiredFrameNumber if we were successful in getting that frame
332 else
333 LastFrameOk=false; // We didn't find the next frame (e.g. seek out of range) - mark we don't know where we are.
334 return ret;
335 }
336
337 /**
338 \brief Seek to millisecond
339 **/
340 bool QVideoDecoder::seekMs(int tsms)
341 {
342 if(!ok)
343 return false;
344
345
346 //qDebug("**** SEEK TO ms %d. LLT: %d. LT: %d. LLF: %d. LF: %d. LastFrameOk: %d\n",tsms,LastLastFrameTime,LastFrameTime,LastLastFrameNumber,LastFrameNumber,(int)LastFrameOk);
347
348 // Convert time into frame number
349 DesiredFrameNumber = ffmpeg::av_rescale(tsms,pFormatCtx->streams[videoStream]->time_base.den,pFormatCtx->streams[videoStream]->time_base.num);
350 DesiredFrameNumber/=1000;
351
352 return seekFrame(DesiredFrameNumber);
353 }
354 /**
355 \brief Seek to frame
356 **/
357 bool QVideoDecoder::seekFrame(int64_t frame)
358 {
359
360 if(!ok)
361 return false;
362
363 //qDebug("**** seekFrame to %d. LLT: %d. LT: %d. LLF: %d. LF: %d. LastFrameOk: %d\n",(int)frame,LastLastFrameTime,LastFrameTime,LastLastFrameNumber,LastFrameNumber,(int)LastFrameOk);
364
365 // Seek if:
366 // - we don't know where we are (Ok=false)
367 // - we know where we are but:
368 // - the desired frame is after the last decoded frame (this could be optimized: if the distance is small, calling decodeSeekFrame may be faster than seeking from the last key frame)
369 // - the desired frame is smaller or equal than the previous to the last decoded frame. Equal because if frame==LastLastFrameNumber we don't want the LastFrame, but the one before->we need to seek there
370 if( (LastFrameOk==false) || ((LastFrameOk==true) && (frame<=LastLastFrameNumber || frame>LastFrameNumber) ) )
371 {
372 //qDebug("\t avformat_seek_file\n");
373 if(ffmpeg::avformat_seek_file(pFormatCtx,videoStream,0,frame,frame,AVSEEK_FLAG_FRAME)<0)
374 return false;
375
376 avcodec_flush_buffers(pCodecCtx);
377
378 DesiredFrameNumber = frame;
379 LastFrameOk=false;
380 }
381 //qDebug("\t decodeSeekFrame\n");
382
383 return decodeSeekFrame(frame);
384
385 return true;
386 }
387
388
389
390 bool QVideoDecoder::getFrame(QImage&img,int *effectiveframenumber,int *effectiveframetime,int *desiredframenumber,int *desiredframetime)
391 {
392 img = LastFrame;
393
394 if(effectiveframenumber)
395 *effectiveframenumber = LastFrameNumber;
396 if(effectiveframetime)
397 *effectiveframetime = LastFrameTime;
398 if(desiredframenumber)
399 *desiredframenumber = DesiredFrameNumber;
400 if(desiredframetime)
401 *desiredframetime = DesiredFrameTime;
402
403 //qDebug("getFrame. Returning valid? %s. Desired %d @ %d. Effective %d @ %d\n",LastFrameOk?"yes":"no",DesiredFrameNumber,DesiredFrameTime,LastFrameNumber,LastFrameTime);
404
405 return LastFrameOk;
406 }
407
408
409 /**
410 \brief Debug function: saves a frame as PPM
411 **/
412 void QVideoDecoder::saveFramePPM(ffmpeg::AVFrame *pFrame, int width, int height, int iFrame)
413 {
414 FILE *pFile;
415 char szFilename[32];
416 int y;
417
418 // Open file
419 sprintf(szFilename, "frame%d.ppm", iFrame);
420 pFile=fopen(szFilename, "wb");
421 if(pFile==NULL)
422 return;
423
424 // Write header
425 fprintf(pFile, "P6\n%d %d\n255\n", width, height);
426
427 // Write pixel data
428 for(y=0; y<height; y++)
429 fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width*3, pFile);
430
431 // Close file
432 fclose(pFile);
433 }
434
435
436
437 void QVideoDecoder::dumpFormat(ffmpeg::AVFormatContext *ic,
438 int index,
439 const char *url,
440 int is_output)
441 {
442 //int i;
443 uint8_t *printed = (uint8_t*)ffmpeg::av_mallocz(ic->nb_streams);
444 if (ic->nb_streams && !printed)
445 return;
446
447 qDebug("AV_TIME_BASE: %d\n",AV_TIME_BASE);
448
449 qDebug("%s #%d, %s,\n %s '%s':\n",
450 is_output ? "Output" : "Input",
451 index,
452 is_output ? ic->oformat->name : ic->iformat->name,
453 is_output ? "to" : "from", url);
454 if (!is_output) {
455 qDebug(" Duration: ");
456 //if (ic->duration != AV_NOPTS_VALUE)
457 {
458 int hours, mins, secs, us;
459 secs = ic->duration / AV_TIME_BASE;
460 us = ic->duration % AV_TIME_BASE;
461 mins = secs / 60;
462 secs %= 60;
463 hours = mins / 60;
464 mins %= 60;
465 qDebug("%02d:%02d:%02d.%02d\n", hours, mins, secs,
466 (100 * us) / AV_TIME_BASE);
467 } //else {
468 //qDebug("N/A");
469 //}
470 //if (ic->start_time != AV_NOPTS_VALUE)
471 {
472 int secs, us;
473 qDebug(", start: ");
474 secs = ic->start_time / AV_TIME_BASE;
475 us = ic->start_time % AV_TIME_BASE;
476 qDebug("%d.%06d\n",
477 secs, (int)ffmpeg::av_rescale(us, 1000000, AV_TIME_BASE));
478 }
479 qDebug(", bitrate: ");
480 if (ic->bit_rate) {
481 qDebug("%d kb/s\n", ic->bit_rate / 1000);
482 } else {
483 qDebug("N/A\n");
484 }
485 qDebug("\n");
486 }
487 if(ic->nb_programs) {
488 unsigned int j, total=0;
489 for(j=0; j<ic->nb_programs; j++) {
490 ffmpeg::AVMetadataTag *name = av_metadata_get(ic->programs[j]->metadata,
491 "name", NULL, 0);
492 qDebug(" Program %d %s\n", ic->programs[j]->id,
493 name ? name->value : "");
494 /*for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
495 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
496 printed[ic->programs[j]->stream_index[k]] = 1;
497 }*/
498 total += ic->programs[j]->nb_stream_indexes;
499 }
500 if (total < ic->nb_streams)
501 qDebug( " No Program\n");
502 }
503 /*for(i=0;i<ic->nb_streams;i++)
504 if (!printed[i])
505 ffmpeg::dump_stream_format(ic, i, index, is_output);*/
506
507 if (ic->metadata) {
508 ffmpeg::AVMetadataTag *tag=NULL;
509 qDebug(" Metadata\n");
510 while((tag=av_metadata_get(ic->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
511 qDebug(" %-16s: %s\n", tag->key, tag->value);
512 }
513 }
514 ffmpeg::av_free(printed);
515 }
516
517 int QVideoDecoder::getVideoLengthMs()
518 {
519 if(!isOk())
520 return -1;
521
522
523 int secs = pFormatCtx->duration / AV_TIME_BASE;
524 int us = pFormatCtx->duration % AV_TIME_BASE;
525 int l = secs*1000 + us/1000;
526
527
528 dumpFormat(pFormatCtx,videoStream,"test video",0);
529
530 return l;
531 }