-
Notifications
You must be signed in to change notification settings - Fork 0
/
QVideoDecoder.cpp
939 lines (813 loc) · 24.4 KB
/
QVideoDecoder.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
/*
ShotManager (2015 x64)
Luca Gallinari
Datio Stabili
Marco Ravazzini
IMPORTANT:
This wrapper is a porting of the QTFFmpegWrapper made by Daniel Roggen.
Changes:
FFmpeg git-a254452 2011-09-19 -> FFmpeg git-0671dc5 2015-07-22
32 bit FFmpeg libs -> 64 bit FFmpeg libs
Internal console for debugging -> qDebug() for debugging
We made a lot of changes and now it supports many formats and it works better.
--------------------------------------------------------------------------------
QTFFmpegWrapper
Copyright (C) 2009,2010:
Daniel Roggen, [email protected]
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
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.
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.
*/
#include "QVideoDecoder.h"
#include <stdint.h>
/*! \brief Constructor
*
* Constructor
*/
QVideoDecoder::QVideoDecoder()
{
InitVars();
initCodec();
}
/*! \brief Constructor
*
* Constructor
*/
QVideoDecoder::QVideoDecoder(const QString file)
{
InitVars();
initCodec();
ok = openFile(file.toStdString().c_str());
}
/*! \brief Destroyer
*
* Destroyer
*/
QVideoDecoder::~QVideoDecoder()
{
close();
InitVars();
}
/*! \brief Codec initialization
*
* Codec initialization
*/
void QVideoDecoder::initCodec()
{
ffmpeg::avcodec_register_all();
ffmpeg::av_register_all();
qDebug() << "License: " << ffmpeg::avformat_license();
qDebug() << "AVCodec version: " << ffmpeg::avformat_version();
qDebug() << "AVFormat configuration: " << ffmpeg::avformat_configuration();
}
/*! \brief Variables initialization
*
* Variables initialization
*/
void QVideoDecoder::InitVars()
{
ok=false;
pFormatCtx=0;
pCodecCtx=0;
pCodec=0;
pFrame=0;
pFrameRGB=0;
buffer=0;
img_convert_ctx=0;
millisecondbase = { 1, 1000 };
}
/*! \brief Close the file and reset all variables
*
* Close the file and reset all variables
*/
void QVideoDecoder::close()
{
/*if(!ok)
return;*/
// Free the RGB image
if(buffer)
delete [] buffer;
// Free the YUV frame
if(pFrame)
av_free(pFrame);
// Free the RGB frame
if(pFrameRGB)
av_free(pFrameRGB);
// Close the codec
if(pCodecCtx)
avcodec_close(pCodecCtx);
// Close the video file
if(pFormatCtx)
avformat_close_input(&pFormatCtx);
}
/*! \brief Open a file and setup all variables
*
* Open a file and setup all variables
* @param filename path of the file to open
* @return success or not
*/
bool QVideoDecoder::openFile(const QString filename)
{
// Close last video..
close();
LastLastFrameTime = INT_MIN; // Last last must be small to handle the seek well
LastFrameTime = 0;
LastLastFrameNumber = INT_MIN;
LastFrameNumber = 0;
LastIdealFrameNumber = 0;
LastFrameOk = false;
// Open video file
if(avformat_open_input(&pFormatCtx, filename.toStdString().c_str(), NULL, NULL)!=0)
return false; // Couldn't open file
// Retrieve stream information
if(avformat_find_stream_info(pFormatCtx, NULL)<0)
return false; // Couldn't find stream information
// Dump information about file onto standard error
av_dump_format(pFormatCtx, 0, filename.toStdString().c_str(), false);
// Find the first video stream
videoStream=-1;
for(unsigned i=0; i<pFormatCtx->nb_streams; i++)
if(pFormatCtx->streams[i]->codec->codec_type==ffmpeg::AVMEDIA_TYPE_VIDEO)
{
videoStream=i;
break;
}
if(videoStream==-1)
return false; // Didn't find a video stream
// Get a pointer to the codec context for the video stream
pCodecCtx=pFormatCtx->streams[videoStream]->codec;
// Find the decoder for the video stream
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL)
return false; // Codec not found
// Open codec
if(avcodec_open2(pCodecCtx, pCodec, NULL)<0)
return false; // Could not open codec
// Hack to correct wrong frame rates that seem to be generated by some
// codecs
if(pCodecCtx->time_base.num>1000 && pCodecCtx->time_base.den==1)
pCodecCtx->time_base.den=1000;
// Allocate video frame
pFrame=ffmpeg::avcodec_alloc_frame();
// Allocate an AVFrame structure
pFrameRGB=ffmpeg::avcodec_alloc_frame();
if(pFrameRGB==NULL)
return false;
// Determine required buffer size and allocate buffer
numBytes=ffmpeg::avpicture_get_size(ffmpeg::PIX_FMT_RGB24, pCodecCtx->width,pCodecCtx->height);
buffer=new uint8_t[numBytes];
// Assign appropriate parts of buffer to image planes in pFrameRGB
avpicture_fill((ffmpeg::AVPicture *)pFrameRGB, buffer, ffmpeg::PIX_FMT_RGB24,
pCodecCtx->width, pCodecCtx->height);
// Set variables
path = filename;
type = QString(pFormatCtx->iformat->name);
duration = pFormatCtx->duration;
baseFrameRate = av_q2d(pFormatCtx->streams[videoStream]->r_frame_rate);
frameMSec = 1000 / baseFrameRate;
if (type == "matroska,webm" || type.indexOf("mp4") != -1) {
frameMSecReal =
(double)(pFormatCtx->streams[videoStream]->time_base.den /
pFormatCtx->streams[videoStream]->time_base.num) /
(double)(pFormatCtx->streams[videoStream]->codec->time_base.den /
(double)pFormatCtx->streams[videoStream]->codec->time_base.num)*
pCodecCtx->ticks_per_frame;
if (!getFirstPacketInformation()) {
return false;
}
/* THIS IS BAD CODING but
* this is the only way that i found so far to retrieve the ms of a single frame
* in mkv video file. One of frameMsec and frameMsecReal is used as a single frame
* duration but i didn't find any solution, except this, to find which is correct.
* The problem is that some MKV files use frameMsec as base frame duration and
* some MKV use frameMsecReal as frame duration.
*/
if (frameDuration == floor(frameMSec)) {
chooseMSec = frameMSec;
}
else {
chooseMSec = frameMSecReal;
}
}
else {
frameMSecReal = frameMSec;
firstDts = pFormatCtx->streams[videoStream]->first_dts;
if (firstDts == AV_NOPTS_VALUE)
firstDts = 0;
startTs = pFormatCtx->streams[videoStream]->start_time;
if (startTs == AV_NOPTS_VALUE)
startTs = 0;
}
baseFRateReal = 1000 / (double) frameMSecReal;
timeBaseRat = pFormatCtx->streams[videoStream]->time_base;
timeBase = av_q2d(timeBaseRat);
w = pCodecCtx->width;
h = pCodecCtx->height;
ok = true;
dumpFormat(0);
return true;
}
/*! \brief Try to retrieve usefull inforamtion from the first packet
*
* This is the only way that i found so far to retrieve the ms of a single frame
* in mkv video file. One of frameMsec and frameMsecReal is used as a single frame
* duration but i could not find any solution, except this, to find which is correct.
* And
* @return true on success, false when the file is not supported
*/
bool QVideoDecoder::getFirstPacketInformation()
{
bool done = false;
while (!done) {
// Read a frame
if (av_read_frame(pFormatCtx, &packet)<0)
return false; // end of stream? impossible
// Packet of the video stream?
if (packet.stream_index == videoStream) {
int frameFinished;
avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
// Frame is completely decoded?
if (frameFinished) {
frameDuration = packet.duration;
firstDts = packet.dts;
startTs = packet.dts;
done = true;
if (pFormatCtx->streams[videoStream]->first_dts == AV_NOPTS_VALUE) {
/* TODO: I could not find any solution when the firstDts value is not valid.
* If you try to seek to 0 it will fail. Maybe in future ffmpeg version
* this will be resolved.
*/
return false;
}
} // frameFinished
} // stream_index==videoStream
av_free_packet(&packet);
}
if (av_seek_frame(pFormatCtx, videoStream, 0, AVSEEK_FLAG_BACKWARD) < 0) {
return false;
}
avcodec_flush_buffers(pCodecCtx);
return true;
}
/*! \brief Seek the given frame and decode it
*
* Decodes the video stream until the first frame with number larger or equal
* than 'idealFrameNumber' is found.
* TODO: if we already passed the wanted frame number?
* @param idealFrameNumber desired frame number
* @return success or not
*/
bool QVideoDecoder::decodeSeekFrame (const qint64 idealFrameNumber)
{
if (!ok)
return false;
qint64 f, t;
bool done = false;
// If the last decoded frame satisfies the time condition we return it
if (
idealFrameNumber != -1 &&
(LastFrameOk == true && idealFrameNumber >= LastLastFrameNumber && idealFrameNumber <= LastFrameNumber)
) {
return true;
}
while (!done) {
// Read a frame
if (av_read_frame(pFormatCtx, &packet)<0)
return false; // end of stream?
// Packet of the video stream?
if (packet.stream_index==videoStream) {
int frameFinished;
avcodec_decode_video2(pCodecCtx,pFrame,&frameFinished,&packet);
// Frame is completely decoded?
if (frameFinished) {
// Calculate real frame number and time based on the format
if (type == "mpeg" || type == "asf") {
f = (long)((packet.dts - startTs) * (baseFrameRate*timeBase) + 0.5);
t = ffmpeg::av_rescale_q(packet.dts - startTs, timeBaseRat, millisecondbase);
}
else if (type.indexOf("mp4") != -1) {
f = (long)((packet.dts + firstDts) * (baseFrameRate*timeBase) + 0.5);
t = ffmpeg::av_rescale_q(packet.dts + firstDts, timeBaseRat, millisecondbase);
}
else if (type == "matroska,webm") {
// t = av_frame_get_best_effort_timestamp(pFrame);
// f = round(t / frameMSec);
t = ffmpeg::av_rescale_q(packet.dts - firstDts, timeBaseRat, millisecondbase);
f = round(t / frameMSec);
}
else { // avi
f = packet.dts;
t = ffmpeg::av_rescale_q(packet.dts, timeBaseRat, millisecondbase);
}
qDebug() << "id:" << idealFrameNumber;
qDebug() << "f:" << f;
qDebug() << "t:" << t;
qDebug() << "dur:" << packet.duration;
qDebug() << "dts:" << packet.dts << endl;
if (LastFrameOk) {
// If we decoded 2 frames in a row, the last times are okay
LastLastFrameTime = LastFrameTime;
LastLastFrameNumber = LastFrameNumber;
LastFrameTime = t;
LastFrameNumber = f;
}
else {
LastFrameOk = true;
LastLastFrameTime = LastFrameTime = t;
LastLastFrameNumber = LastFrameNumber = f;
}
// this is the desired frame or at least one just after it
if (idealFrameNumber == -1 || LastFrameNumber >= idealFrameNumber)
{
// Convert and save the frame
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
);
if (img_convert_ctx == NULL) {
qDebug() << "Cannot initialize the conversion context!";
return false;
}
ffmpeg::sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize);
LastFrame = QImage(w, h, QImage::Format_RGB888);
for (int y=0; y < h; y++)
memcpy(LastFrame.scanLine(y), pFrameRGB->data[0] + y * pFrameRGB->linesize[0], w * 3);
LastFrameOk = true;
done = true;
} // frame of interes
} // frameFinished
} // stream_index==videoStream
av_free_packet(&packet);
}
return done;
}
/*! \brief Seek the next frame
*
* Seek the next frame.
* @return success or not
* @see seekFrame()
* @see seekPrevFrame()
*/
bool QVideoDecoder::seekNextFrame()
{
bool ret = decodeSeekFrame(LastIdealFrameNumber + 1);
if (ret)
++LastIdealFrameNumber;
else
LastFrameOk=false;
return ret;
}
/*! \brief Seek the previous frame
*
* Seek the previous frame.
* @return success or not
* @see seekFrame()
* @see seekNextFrame()
*/
bool QVideoDecoder::seekPrevFrame()
{
bool ret = seekFrame(LastIdealFrameNumber - 1);
if (!ret)
LastFrameOk = false;
return ret;
}
/*! \brief Seek the closest frame to the given time
*
* Seek the closest frame to the given time.
* @param tsms time in milliseconds
* @return success or not
* @see seekFrame()
*/
bool QVideoDecoder::seekMs(const qint64 tsms)
{
if(!ok)
return false;
return seekFrame((tsms <= 0 ? 0 : round(tsms / frameMSec)));
}
/*! \brief Seek the desired frame
*
TODO: case when idelFrameNumber less than 0
* Seek and retrieve desired frame by number.
* @param idealFrameNumber number of the desired frame
* @return success or not
* @see seekToAndGetFrame()
* @see seekMs()
*/
bool QVideoDecoder::seekFrame(const qint64 idealFrameNumber)
{
if (!ok)
return false;
// no seek needed, go to next frame
if (LastIdealFrameNumber + 1 == idealFrameNumber)
return seekNextFrame();
// have to seek?
if ((LastFrameOk == false) ||
((LastFrameOk == true) && (idealFrameNumber <= LastLastFrameNumber || idealFrameNumber > LastFrameNumber)))
{
if (!correctSeekToKeyFrame(idealFrameNumber))
return false;
avcodec_flush_buffers(pCodecCtx);
LastIdealFrameNumber = idealFrameNumber;
LastFrameOk = false;
}
// decode
return decodeSeekFrame(idealFrameNumber);
}
/*! \brief Corrects the seeking operation
*
* Corrects the seeking operation to a "key frame" because this varies from
* format and format. This is based on a prediction so we have to add a margin
* of error that can allow us to ..TODO
* @param idealFrameNumber number of the desired frame
* @return success or not
* @see seekFrame()
*/
bool QVideoDecoder::correctSeekToKeyFrame(const qint64 idealFrameNumber)
{
qint64 desiredDts;
qint64 startDts = INT64_MIN;
int flag;
//
if (type == "mpeg") { // .mpg
// ffmpeg bug?: with H.264 avformat_seek_file often seeks not in a keyframe,
// thus the following avcodec_decode_video2 iterations may go past desiredDts
desiredDts = (idealFrameNumber - 0.5 - baseFrameRate) / (baseFrameRate*timeBase) + firstDts;
if (desiredDts < firstDts) desiredDts = firstDts;
startDts = -0x7ffffffffffffff;
flag = AVSEEK_FLAG_BACKWARD;
}
else if (type.indexOf("mp4") != -1){ // .mp4
qint64 targetDts = idealFrameNumber * frameMSecReal;
// av_seek_frame(pFormatCtx, videoStream, targetDts, AVSEEK_FLAG_FRAME);
// flag = AVSEEK_FLAG_BACKWARD;
ffmpeg::avformat_seek_file(pFormatCtx, videoStream, startDts, targetDts, INT64_MAX, AVSEEK_FLAG_BACKWARD);
return true;
}
else if (type == "asf"){ // .asf (wmv)
desiredDts = idealFrameNumber * frameMSec;
flag = AVSEEK_FLAG_BACKWARD;
}
else if (type == "matroska,webm") { // .mkv
bool reset = false; // used to avoid deadlock situation into the "while"
// this prediction is not perfect but it gives a good start point close
// to the desired frame number
// while targetDts is based on the packets DTS, desiredDts is based on
// the wanted DTS
qint64 targetDts = idealFrameNumber * chooseMSec;
if (av_seek_frame(pFormatCtx, videoStream, targetDts, AVSEEK_FLAG_BACKWARD) < 0) {
return false;
}
avcodec_flush_buffers(pCodecCtx);
qint64 currDts = pFormatCtx->streams[videoStream]->cur_dts;
while (currDts > targetDts) {
// if i am after the desired frame, have to reseek
targetDts -= (60 * chooseMSec); // go back of 60frames. TODO: a better value?
qDebug() << "back";
if (targetDts < 0) {
if (reset) {//already resetted before this? Possible deadlock!
return true; // false?
}
targetDts = 0;
reset = true;
}
else {
reset = false;
}
if (av_seek_frame(pFormatCtx, videoStream, targetDts, AVSEEK_FLAG_BYTE) < 0) {
return false;
}
avcodec_flush_buffers(pCodecCtx);
currDts = pFormatCtx->streams[videoStream]->cur_dts;
}
return true;
}
else { // .avi, .wmv
desiredDts = idealFrameNumber;
flag = AVSEEK_FLAG_FRAME;
}
if (ffmpeg::avformat_seek_file(pFormatCtx, videoStream, startDts, desiredDts, INT64_MAX, flag) < 0) {
return false;
// qDebug() << "!!!SEEK ERROR!!!"
}
return true;
}
/*! \brief Seek and retrieve desired frame
*
* Seek and retrieve desired frame by number.
* @param idealFrameNumber number of the desired frame
* @param img where it stores the frame
* @param frameNum where it stores the frame number
* @param frameTime where it stores the frame time
* @return success or not
*/
bool QVideoDecoder::seekToAndGetFrame(const qint64 idealFrameNumber, QImage&img, qint64 *frameNum, qint64 *frameTime)
{
if (!seekFrame(idealFrameNumber))
return false;
return getFrame(img, frameNum, frameTime);
}
/***************************************
********* GETTERS *********
***************************************/
/*! \brief A file is loaded
*
* A file is loaded
* @return video loaded successfully
*/
bool QVideoDecoder::isOk()
{
return ok;
}
/*! \brief Get last loaded frame
*
* Get last loaded frame
* @param img where it stores the frame
* @param frameNum where it stores the frame number
* @param frameTime where it stores the frame time
* @return last frame was valid or not
*/
bool QVideoDecoder::getFrame(QImage &img, qint64 *frameNum, qint64 *frameTime)
{
img = LastFrame;
if (frameNum)
*frameNum = LastFrameNumber;
if (frameTime)
*frameTime = LastFrameTime;
return LastFrameOk;
}
/*! \brief Get last loaded frame "CODEC number"
*
* Get last loaded frame "CODEC number", "CODEC number" because codecs and
* formats use a different type of "number", some uses timestamps and some
* normal integers.
* @return last loaded frame number
*/
qint64 QVideoDecoder::getActualFrameNumber()
{
if (!isOk())
return -1;
return LastFrameNumber;
}
/*! \brief Get last loaded frame "IDEAL number"
*
* Get last loaded frame "IDEAL number", "IDEAL number" because codecs and
* formats use a different type of "number", some uses timestamps and some
* normal integers.
* @return last loaded frame number
*/
qint64 QVideoDecoder::getIdealFrameNumber()
{
if (!isOk())
return -1;
return LastIdealFrameNumber;
}
/*! \brief Get last loaded frame time milliseconds
*
* Get last loaded frame time milliseconds.
* @return last loaded frame time
*/
qint64 QVideoDecoder::getFrameTime()
{
if (!isOk())
return -1;
return LastFrameTime;
}
/*! \brief Get frame number by time
*
* Get the number of the closest frame to the given time
* @return frame number
*/
qint64 QVideoDecoder::getNumFrameByTime(const qint64 tsms)
{
if (!ok)
return false;
if (tsms <= 0)
return 0;
return round(tsms / frameMSec);
}
/*! \brief Get video duration in milliseconds
*
* Get video duration in milliseconds.
* @return video length in ms
*/
qint64 QVideoDecoder::getVideoLengthMs()
{
if (!isOk())
return -1;
qint64 secs = pFormatCtx->duration / AV_TIME_BASE;
qint64 us = pFormatCtx->duration % AV_TIME_BASE;
return secs * 1000 + us / 1000;
}
/*! \brief Get number of frames (Not accurate with some formats)
*
* Get number of frames based on video duration and frame rate. Some containers
* save a wrong value for duration and so the number of frames could be not so
* accurate.
* @return number of frams
*/
qint64 QVideoDecoder::getNumFrames()
{
return round(getVideoLengthMs() * (baseFrameRate / 1000.0));
}
/*! \brief Get video path
*
* Retrieve video path
*/
QString QVideoDecoder::getPath() {
return path;
}
/*! \brief Get video type
*
* Retrieve video type
*/
QString QVideoDecoder::getType() {
return type;
}
/*! \brief Get video time base as AVRational
*
* Get video time base, it's the base time that the container uses
* @return video time base
*/
ffmpeg::AVRational QVideoDecoder::getTimeBaseRat()
{
return timeBaseRat;
}
/*! \brief Get video time base as double
*
* Get video time base, it's the base time that the container uses
* @return video time base
*/
double QVideoDecoder::getTimeBase()
{
return timeBase;
}
/*! \brief Get video frame rate
*
* Retrieve video frame rate
*/
double QVideoDecoder::getFrameRate() {
return baseFrameRate;
}
/*! \brief Get video frame ms (theorycal)
*
* Retrieve video frame ms (theorycal)
*/
double QVideoDecoder::getFrameMsec() {
return frameMSec;
}
/*! \brief Get video frame ms (real)
*
* Retrieve video frame ms (real). Actually only "matroska" and "mp4" files
* have a different theorycal and real frame msec.
*/
double QVideoDecoder::getFrameMsecReal() {
return frameMSecReal;
}
/*! \brief Get frame width
*
* Get frame width
*/
int QVideoDecoder::getFrameWidth() {
return w;
}
/*! \brief Get frame height
*
* Get frame height
*/
int QVideoDecoder::getFrameHeight() {
return h;
}
/*! \brief Get video bitrate
*
* Get video bitrate
*/
QString QVideoDecoder::getBitrate() {
return (pFormatCtx->bit_rate ? QString::number((int)(pFormatCtx->bit_rate / 1000)).append(" kb/s") : "N / A");
}
/*! \brief Get string of programs used to make the video
*
* Get string of programs used to make the video
*/
QString QVideoDecoder::getProgramsString()
{
QString s;
// Programs
if (pFormatCtx->nb_programs) {
unsigned int j, total = 0;
for (j = 0; j<pFormatCtx->nb_programs; j++) {
ffmpeg::AVDictionaryEntry *name = av_dict_get(pFormatCtx->programs[j]->metadata, "name", NULL, 0);
s.push_back(QString("%1 %2 \n").arg(pFormatCtx->programs[j]->id).arg(" ").arg(name ? name->value : ""));
total += pFormatCtx->programs[j]->nb_stream_indexes;
}
if (total < pFormatCtx->nb_streams)
s.push_back("None");
}
else{
s.push_back("None");
}
return s;
}
/*! \brief Get string of metadatas presents in the video
*
* Get string of metadatas presents in the video
*/
QString QVideoDecoder::getMetadataString()
{
QString s;
// Programs
if (pFormatCtx->metadata) {
ffmpeg::AVDictionaryEntry *tag = NULL;
while ((tag = av_dict_get(pFormatCtx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
s.push_back(QString("%1: %2 \n").arg(tag->key).arg(tag->value));
}
}
else{
s.push_back("None");
}
return s;
}
/***************************************
********* HELPERS *********
***************************************/
/*! \brief Save a frame as PPM image
*
* Save a frame as PPM image. Usefull for debugging.
* @param pFrame the frame
* @param width frame width
* @param height frame height
* @param iFrame frame number
*/
void QVideoDecoder::saveFramePPM(const ffmpeg::AVFrame *pFrame, const int width, const int height, const int iFrame)
{
FILE *pFile;
char szFilename[32];
int y;
// Open file
sprintf(szFilename, "frame%d.ppm", iFrame);
pFile = fopen(szFilename, "wb");
if (pFile == NULL)
return;
// Write header
fprintf(pFile, "P6\n%d %d\n255\n", width, height);
// Write pixel data
for (y = 0; y<height; y++)
fwrite(pFrame->data[0] + y*pFrame->linesize[0], 1, width * 3, pFile);
// Close file
fclose(pFile);
}
/*! \brief Output video's informations
*
* Write video's information in the stdout. Usefull for debugging.
* @param path file path
* @param is_output writing or reading the file?
*/
void QVideoDecoder::dumpFormat(const int is_output)
{
qDebug() << (is_output ? "Output" : "Input");
qDebug() << "File: " << path;
qDebug() << "Stream: " << videoStream;
qDebug() << "Type: " << (is_output ? pFormatCtx->oformat->name : type);
qDebug() << "AV_TIME_BASE: " << AV_TIME_BASE;
// General infos
if (!is_output) {
qDebug() << "Time Base: " << timeBase;
qDebug() << "Start: " << startTs;
qDebug() << "First Dts: " << firstDts;
qDebug() << "FPS: " << baseFrameRate;
qDebug() << "Frame ms: " << frameMSec;
qDebug() << "Special ms: " << frameMSecReal;
qDebug() << "Frame duration ms: " << frameDuration;
qDebug() << "Frame w: " << w;
qDebug() << "Frame h: " << h;
qDebug() << "Number of frames: " << getNumFrames();
qDebug() << "Duration: " << duration << " us";
int hours, mins, secs, us;
secs = duration / AV_TIME_BASE;
us = duration % AV_TIME_BASE;
mins = secs / 60;
secs %= 60;
hours = mins / 60;
mins %= 60;
qDebug() << "\t" << hours << "h " << mins << "m " << secs << "s " << (100 * us) / AV_TIME_BASE;
qDebug() << "Bitrate: " << (pFormatCtx->bit_rate ? QString::number((int) (pFormatCtx->bit_rate / 1000)).append(" kb/s") : "N / A");
}
// Programs
qDebug() << "Program: \n" << getProgramsString();
// Metadata
qDebug() << "Metadata: \n" << getMetadataString();
}