-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcap_ffmpeg_impl.cpp
3868 lines (3397 loc) · 114 KB
/
cap_ffmpeg_impl.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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "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 Intel Corporation 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.
//
//M*/
#include "cap_ffmpeg_api.hpp"
//#include "cap_ffmpeg_impl.hpp"
#if !(defined(_WIN32) || defined(WINCE))
# include <pthread.h>
#endif
#include <assert.h>
#include <algorithm>
#include <limits>
#include <sys/stat.h>
#ifdef _WIN32
#define stat64 _stat64
#define fseek64 _fseeki64
#else
#define stricmp strcasecmp
# ifdef __ANDROID__
#pragma message("__ANDROID__ defined")
#define fseek64 fseeko
# else
#define fseek64 fseeko64
# endif
#endif
#ifndef __OPENCV_BUILD
#define CV_FOURCC(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24))
#endif
#define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c )
#if defined _MSC_VER && _MSC_VER >= 1200
#pragma warning( disable: 4244 4510 4610 )
#endif
#ifdef __GNUC__
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#ifndef CV_UNUSED // Required for standalone compilation mode (OpenCV defines this in base.hpp)
#define CV_UNUSED(name) (void)name
#endif
#ifdef __cplusplus
extern "C" {
#endif
#include "ffmpeg_codecs.hpp"
#include "libavutil/mathematics.h"
#if LIBAVUTIL_BUILD > CALC_FFMPEG_VERSION(51,11,0)
#include "libavutil/opt.h"
#endif
#if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 ? CALC_FFMPEG_VERSION(51, 63, 100) : CALC_FFMPEG_VERSION(54, 6, 0))
#include "libavutil/imgutils.h"
#endif
#include "libavcodec/avcodec.h"
#include "libswscale/swscale.h"
#include "libavutil/motion_vector.h"
#include "libavformat/avformat.h"
#ifdef __cplusplus
}
#endif
#if defined _MSC_VER && _MSC_VER >= 1200
#pragma warning( default: 4244 4510 4610 )
#endif
#ifdef NDEBUG
#define CV_WARN(message)
#else
#define CV_WARN(message) fprintf(stderr, "warning: %s (%s:%d)\n", message, __FILE__, __LINE__)
#endif
#if defined _WIN32
#include <windows.h>
#if defined _MSC_VER && _MSC_VER < 1900
struct timespec
{
time_t tv_sec;
long tv_nsec;
};
#endif
#elif defined __linux__ || defined __APPLE__ || defined __HAIKU__
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>
#if defined __APPLE__
#include <sys/sysctl.h>
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#endif
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))
#if defined(__APPLE__)
#define AV_NOPTS_VALUE_ ((int64_t)0x8000000000000000LL)
#else
#define AV_NOPTS_VALUE_ ((int64_t)AV_NOPTS_VALUE)
#endif
#ifndef AVERROR_EOF
#define AVERROR_EOF (-MKTAG( 'E','O','F',' '))
#endif
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54,25,0)
# define CV_CODEC_ID AVCodecID
# define CV_CODEC(name) AV_##name
#else
# define CV_CODEC_ID CodecID
# define CV_CODEC(name) name
#endif
#if LIBAVUTIL_BUILD < (LIBAVUTIL_VERSION_MICRO >= 100 ? CALC_FFMPEG_VERSION(51, 74, 100) : CALC_FFMPEG_VERSION(51, 42, 0))
#define AVPixelFormat PixelFormat
#define AV_PIX_FMT_BGR24 PIX_FMT_BGR24
#define AV_PIX_FMT_RGB24 PIX_FMT_RGB24
#define AV_PIX_FMT_GRAY8 PIX_FMT_GRAY8
#define AV_PIX_FMT_YUV422P PIX_FMT_YUV422P
#define AV_PIX_FMT_YUV420P PIX_FMT_YUV420P
#define AV_PIX_FMT_YUV444P PIX_FMT_YUV444P
#define AV_PIX_FMT_YUVJ420P PIX_FMT_YUVJ420P
#define AV_PIX_FMT_GRAY16LE PIX_FMT_GRAY16LE
#define AV_PIX_FMT_GRAY16BE PIX_FMT_GRAY16BE
#endif
#ifndef PKT_FLAG_KEY
#define PKT_FLAG_KEY AV_PKT_FLAG_KEY
#endif
#if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 ? CALC_FFMPEG_VERSION(52, 38, 100) : CALC_FFMPEG_VERSION(52, 13, 0))
#define USE_AV_FRAME_GET_BUFFER 1
#else
#define USE_AV_FRAME_GET_BUFFER 0
#ifndef AV_NUM_DATA_POINTERS // required for 0.7.x/0.8.x ffmpeg releases
#define AV_NUM_DATA_POINTERS 4
#endif
#endif
#ifndef USE_AV_INTERRUPT_CALLBACK
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 21, 0)
#define USE_AV_INTERRUPT_CALLBACK 1
#else
#define USE_AV_INTERRUPT_CALLBACK 0
#endif
#endif
#if USE_AV_INTERRUPT_CALLBACK
#define LIBAVFORMAT_INTERRUPT_OPEN_TIMEOUT_MS 30000
#define LIBAVFORMAT_INTERRUPT_READ_TIMEOUT_MS 30000
#ifdef _WIN32
// http://stackoverflow.com/questions/5404277/porting-clock-gettime-to-windows
#pragma comment(lib, "libavcodec.a")
#pragma comment(lib, "libavutil.a")
#pragma comment(lib, "libavformat.a")
#pragma comment(lib, "libavdevice.a")
//#pragma comment(lib, "libavfilter.a")
#pragma comment(lib, "libpostproc.a")
#pragma comment(lib, "libswresample.a")
#pragma comment(lib, "libswscale.a")
#pragma comment(lib, "libx264.lib")
#pragma comment(lib, "aom.lib")
//#pragma comment(lib, "dav1d.lib")
//#pragma comment(lib, "ole32.lib")
//#pragma comment(lib, "user32.lib")
#pragma comment(lib, "bcrypt.lib")
static inline LARGE_INTEGER get_filetime_offset()
{
SYSTEMTIME s;
FILETIME f;
LARGE_INTEGER t;
s.wYear = 1970;
s.wMonth = 1;
s.wDay = 1;
s.wHour = 0;
s.wMinute = 0;
s.wSecond = 0;
s.wMilliseconds = 0;
SystemTimeToFileTime(&s, &f);
t.QuadPart = f.dwHighDateTime;
t.QuadPart <<= 32;
t.QuadPart |= f.dwLowDateTime;
return t;
}
static inline void get_monotonic_time(timespec *tv)
{
LARGE_INTEGER t;
FILETIME f;
double microseconds;
static LARGE_INTEGER offset;
static double frequencyToMicroseconds;
static int initialized = 0;
static BOOL usePerformanceCounter = 0;
if (!initialized)
{
LARGE_INTEGER performanceFrequency;
initialized = 1;
usePerformanceCounter = QueryPerformanceFrequency(&performanceFrequency);
if (usePerformanceCounter)
{
QueryPerformanceCounter(&offset);
frequencyToMicroseconds = (double)performanceFrequency.QuadPart / 1000000.;
}
else
{
offset = get_filetime_offset();
frequencyToMicroseconds = 10.;
}
}
if (usePerformanceCounter)
{
QueryPerformanceCounter(&t);
} else {
GetSystemTimeAsFileTime(&f);
t.QuadPart = f.dwHighDateTime;
t.QuadPart <<= 32;
t.QuadPart |= f.dwLowDateTime;
}
t.QuadPart -= offset.QuadPart;
microseconds = (double)t.QuadPart / frequencyToMicroseconds;
t.QuadPart = microseconds;
tv->tv_sec = t.QuadPart / 1000000;
tv->tv_nsec = (t.QuadPart % 1000000) * 1000;
}
#else
static
inline void get_monotonic_time(timespec *time)
{
#if defined(__APPLE__) && defined(__MACH__)
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
time->tv_sec = mts.tv_sec;
time->tv_nsec = mts.tv_nsec;
#else
clock_gettime(CLOCK_MONOTONIC, time);
#endif
}
#endif
static inline timespec get_monotonic_time_diff(timespec start, timespec end)
{
timespec temp;
if (end.tv_nsec - start.tv_nsec < 0)
{
temp.tv_sec = end.tv_sec - start.tv_sec - 1;
temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
}
else
{
temp.tv_sec = end.tv_sec - start.tv_sec;
temp.tv_nsec = end.tv_nsec - start.tv_nsec;
}
return temp;
}
static inline double get_monotonic_time_diff_ms(timespec time1, timespec time2)
{
timespec delta = get_monotonic_time_diff(time1, time2);
double milliseconds = delta.tv_sec * 1000 + (double)delta.tv_nsec / 1000000.0;
return milliseconds;
}
#endif // USE_AV_INTERRUPT_CALLBACK
static int get_number_of_cpus(void)
{
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(52, 111, 0)
return 1;
#elif defined _WIN32
SYSTEM_INFO sysinfo;
GetSystemInfo( &sysinfo );
return (int)sysinfo.dwNumberOfProcessors;
#elif defined __linux__ || defined __HAIKU__
return (int)sysconf( _SC_NPROCESSORS_ONLN );
#elif defined __APPLE__
int numCPU=0;
int mib[4];
size_t len = sizeof(numCPU);
// set the mib for hw.ncpu
mib[0] = CTL_HW;
mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU;
// get the number of CPUs from the system
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if( numCPU < 1 )
{
mib[1] = HW_NCPU;
sysctl( mib, 2, &numCPU, &len, NULL, 0 );
if( numCPU < 1 )
numCPU = 1;
}
return (int)numCPU;
#else
return 1;
#endif
}
struct Image_FFMPEG
{
unsigned char* data;
int step;
int width;
int height;
int cn;
};
#if USE_AV_INTERRUPT_CALLBACK
struct AVInterruptCallbackMetadata
{
timespec value;
unsigned int timeout_after_ms;
int timeout;
};
// https://github.com/opencv/opencv/pull/12693#issuecomment-426236731
static inline const char* _opencv_avcodec_get_name(AVCodecID id)
{
#if LIBAVCODEC_VERSION_MICRO >= 100 \
&& LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(53, 47, 100)
return avcodec_get_name(id);
#else
const AVCodecDescriptor *cd;
AVCodec *codec;
if (id == AV_CODEC_ID_NONE)
{
return "none";
}
cd = avcodec_descriptor_get(id);
if (cd)
{
return cd->name;
}
codec = avcodec_find_decoder(id);
if (codec)
{
return codec->name;
}
codec = avcodec_find_encoder(id);
if (codec)
{
return codec->name;
}
return "unknown_codec";
#endif
}
static inline void _opencv_ffmpeg_free(void** ptr)
{
if(*ptr) free(*ptr);
*ptr = 0;
}
static inline int _opencv_ffmpeg_interrupt_callback(void *ptr)
{
AVInterruptCallbackMetadata* metadata = (AVInterruptCallbackMetadata*)ptr;
assert(metadata);
if (metadata->timeout_after_ms == 0)
{
return 0; // timeout is disabled
}
timespec now;
get_monotonic_time(&now);
metadata->timeout = get_monotonic_time_diff_ms(metadata->value, now) > metadata->timeout_after_ms;
return metadata->timeout ? -1 : 0;
}
#endif
static inline void _opencv_ffmpeg_av_packet_unref(AVPacket *pkt)
{
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 ? CALC_FFMPEG_VERSION(55, 25, 100) : CALC_FFMPEG_VERSION(55, 16, 0))
av_packet_unref(pkt);
#else
av_free_packet(pkt);
#endif
};
static inline void _opencv_ffmpeg_av_image_fill_arrays(void *frame, uint8_t *ptr, enum AVPixelFormat pix_fmt, int width, int height)
{
#if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 ? CALC_FFMPEG_VERSION(51, 63, 100) : CALC_FFMPEG_VERSION(54, 6, 0))
av_image_fill_arrays(((AVFrame*)frame)->data, ((AVFrame*)frame)->linesize, ptr, pix_fmt, width, height, 1);
#else
avpicture_fill((AVPicture*)frame, ptr, pix_fmt, width, height);
#endif
};
static inline int _opencv_ffmpeg_av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height)
{
#if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 ? CALC_FFMPEG_VERSION(51, 63, 100) : CALC_FFMPEG_VERSION(54, 6, 0))
return av_image_get_buffer_size(pix_fmt, width, height, 1);
#else
return avpicture_get_size(pix_fmt, width, height);
#endif
};
static AVRational _opencv_ffmpeg_get_sample_aspect_ratio(AVStream *stream)
{
#if LIBAVUTIL_VERSION_MICRO >= 100 && LIBAVUTIL_BUILD >= CALC_FFMPEG_VERSION(54, 5, 100)
return av_guess_sample_aspect_ratio(NULL, stream, NULL);
#else
AVRational undef = {0, 1};
// stream
AVRational ratio = stream ? stream->sample_aspect_ratio : undef;
av_reduce(&ratio.num, &ratio.den, ratio.num, ratio.den, INT_MAX);
if (ratio.num > 0 && ratio.den > 0)
return ratio;
// codec
ratio = stream && stream->codec ? stream->codec->sample_aspect_ratio : undef;
av_reduce(&ratio.num, &ratio.den, ratio.num, ratio.den, INT_MAX);
if (ratio.num > 0 && ratio.den > 0)
return ratio;
return undef;
#endif
}
// enum CvPixFormat
// {
// CV_PIX_FMT_I420, CV_PIX_FMT_I444, CV_PIX_FMT_NV12, CV_PIX_FMT_NV21, CV_PIX_FMT_I422H, CV_PIX_FMT_I422V, CV_PIX_FMT_YUYV, CV_PIX_FMT_UYVY, CV_PIX_FMT_GRAY,CV_PIX_FMT_I420P10LE, CV_PIX_FMT_I422H10LE, // pixel format for Video
// CV_PIX_FMT_J420, CV_PIX_FMT_J444, CV_PIX_FMT_J422H, CV_PIX_FMT_J422V, // pixel format for JPEG
// CV_PIX_FMT_RGB, CV_PIX_FMT_BGR
// };
static AVPixelFormat g_pPixFmt[]={ AV_PIX_FMT_NONE,
AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_NV12, AV_PIX_FMT_NV21, AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUYV422, AV_PIX_FMT_UYVY422, AV_PIX_FMT_GRAY8,AV_PIX_FMT_YUV420P10LE, AV_PIX_FMT_YUV422P10LE,
AV_PIX_FMT_YUVJ420P,AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24
};
#define ToAvPixFmt(pixfmt) g_pPixFmt[pixfmt]
static inline int IsHadPlane(CvPixFormat pixfmt, int idxPlane)
{
switch(pixfmt)
{
case CV_PIX_FMT_I420: return (idxPlane<=2);
case CV_PIX_FMT_I444: return (idxPlane<=2);
case CV_PIX_FMT_NV12: return (idxPlane<=1);
case CV_PIX_FMT_NV21: return (idxPlane<=1);
case CV_PIX_FMT_I422H: return (idxPlane<=2);
case CV_PIX_FMT_I422V: return (idxPlane<=2);
case CV_PIX_FMT_YUYV: return (idxPlane==0);
case CV_PIX_FMT_UYVY: return (idxPlane==0);
case CV_PIX_FMT_GRAY: return (idxPlane==0);
case CV_PIX_FMT_I420P10LE: return (idxPlane<=2);
case CV_PIX_FMT_I422H10LE: return (idxPlane<=2);
case CV_PIX_FMT_J420: return (idxPlane<=2);
case CV_PIX_FMT_J444: return (idxPlane<=2);
case CV_PIX_FMT_J422H: return (idxPlane<=2);
case CV_PIX_FMT_J422V: return (idxPlane<=2);
case CV_PIX_FMT_RGB: return (idxPlane==0);
case CV_PIX_FMT_BGR: return (idxPlane==0);
default: printf("IsHadPlane: format=%d not support\n", pixfmt); break;
}
return 0;
}
static inline int IsHalfHeight(CvPixFormat pixfmt, int idxPlane)
{
switch(pixfmt)
{
case CV_PIX_FMT_I420: return (idxPlane>=1);
case CV_PIX_FMT_I444: return 0;
case CV_PIX_FMT_NV12: return (idxPlane>=1);
case CV_PIX_FMT_NV21: return (idxPlane>=1);
case CV_PIX_FMT_I422H: return 0;
case CV_PIX_FMT_I422V: return (idxPlane>=1);
case CV_PIX_FMT_YUYV: return 0;
case CV_PIX_FMT_UYVY: return 0;
case CV_PIX_FMT_GRAY: return 0;
case CV_PIX_FMT_I420P10LE: return (idxPlane>=1);
case CV_PIX_FMT_I422H10LE: return 0;
case CV_PIX_FMT_J420: return (idxPlane>=1);
case CV_PIX_FMT_J444: return 0;
case CV_PIX_FMT_J422H: return 0;
case CV_PIX_FMT_J422V: return (idxPlane>=1);
case CV_PIX_FMT_RGB: return 0;
case CV_PIX_FMT_BGR: return 0;
default: printf("IsHalfPlane: format=%d not support\n", pixfmt); break;
}
return 0;
}
static inline CvPixFormat ToCvPixFmt(AVPixelFormat pixfmt)
{
switch(pixfmt)
{
case AV_PIX_FMT_YUV420P: return CV_PIX_FMT_I420;
case AV_PIX_FMT_YUYV422: return CV_PIX_FMT_YUYV;
case AV_PIX_FMT_RGB24: return CV_PIX_FMT_RGB;
case AV_PIX_FMT_BGR24: return CV_PIX_FMT_BGR;
case AV_PIX_FMT_YUV422P: return CV_PIX_FMT_I422H;
case AV_PIX_FMT_YUV444P: return CV_PIX_FMT_I444;
case AV_PIX_FMT_GRAY8: return CV_PIX_FMT_GRAY;
case AV_PIX_FMT_YUV420P10LE: return CV_PIX_FMT_I420P10LE;
case AV_PIX_FMT_YUV422P10LE: return CV_PIX_FMT_I422H10LE;
case AV_PIX_FMT_YUVJ420P: return CV_PIX_FMT_J420;
case AV_PIX_FMT_YUVJ422P: return CV_PIX_FMT_J422H;
case AV_PIX_FMT_YUVJ444P: return CV_PIX_FMT_J444;
case AV_PIX_FMT_UYVY422: return CV_PIX_FMT_UYVY;
case AV_PIX_FMT_NV12: return CV_PIX_FMT_NV12;
case AV_PIX_FMT_NV21: return CV_PIX_FMT_NV21;
case AV_PIX_FMT_YUV440P: return CV_PIX_FMT_I422V;
case AV_PIX_FMT_YUVJ440P: return CV_PIX_FMT_J422V;
}
return CV_PIX_FMT_NONE;
}
static size_t BKDRHash(const char* p)
{
size_t hash=0, ch=0;
while(ch=(size_t)(*p++))
hash=hash*131+ch;
return hash;
}
struct CvCapture_FFMPEG
{
bool open( const char* filename, int thread_num=0);
bool fastOpen(const char* filename);
int64_t fastTestTotalFrames();
void close();
int getFramesByGrab();
double getProperty(int) const;
bool setProperty(int, double);
bool grabFrame();
bool retrieveFrame(int, unsigned char** data, int* step, int* width, int* height, int* cn);
bool retrieveFrameYUV(unsigned char* ppData[4], int pStride[4], int width, int height, CvPixFormat pixfmt, CvScaleMethod method=CV_BICUBIC);
static bool resizeImage(unsigned char* ppSrcData[4], int pSrcStride[4], int srcW, int srcH, CvPixFormat srcFmt, unsigned char* ppDstData[4], int pDstStride[4], int dstW, int dstH, CvPixFormat dstFmt, CvScaleMethod method=CV_BICUBIC);
void init();
void seek(int64_t frame_number);
void seek(double sec);
bool slowSeek( int framenumber );
int64_t total_frames;
double duration;
//double fps;
int64_t total_size;
static size_t nameHash;
int64_t get_total_frames() const;
double get_duration_sec() const;
double get_fps() const;
int get_bitrate() const;
double r2d(AVRational r) const;
int64_t dts_to_frame_number(int64_t dts);
double dts_to_sec(int64_t dts) const;
AVFormatContext * ic;
AVCodec * avcodec;
int video_stream;
AVStream * video_st;
AVFrame * picture;
AVFrame rgb_picture;
int64_t picture_pts;
AVPacket packet;
Image_FFMPEG frame;
struct SwsContext *img_convert_ctx;
int64_t frame_number, first_frame_number;
double eps_zero;
int totalFrame;
//int frameType;
//int frameSize;
int width, height;
int export_mvs;
CvFrameInfo frameInfo;
CvFrameYUV frameYUV;
CvStreamInfo streamInfo;
CvCodecID codecID;
/*
'filename' contains the filename of the video source,
'filename==NULL' indicates that ffmpeg's seek support works
for the particular file.
'filename!=NULL' indicates that the slow fallback function is used for seeking,
and so the filename is needed to reopen the file on backward seeking.
*/
char * filename;
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
AVDictionary *dict;
#endif
#if USE_AV_INTERRUPT_CALLBACK
AVInterruptCallbackMetadata interrupt_metadata;
#endif
bool setRaw();
bool processRawPacket();
bool rawMode;
bool rawModeInitialized;
AVPacket packet_filtered;
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(58, 20, 100)
AVBSFContext* bsfc;
#else
AVBitStreamFilterContext* bsfc;
#endif
};
size_t CvCapture_FFMPEG::nameHash;
void CvCapture_FFMPEG::init()
{
ic = 0;
video_stream = -1;
video_st = 0;
picture = 0;
picture_pts = AV_NOPTS_VALUE_;
first_frame_number = -1;
memset( &rgb_picture, 0, sizeof(rgb_picture) );
memset( &frame, 0, sizeof(frame) );
filename = 0;
memset(&packet, 0, sizeof(packet));
av_init_packet(&packet);
img_convert_ctx = 0;
avcodec = 0;
frame_number = 0;
eps_zero = 0.000025;
export_mvs=1;
total_frames=0;
duration=0;
//fps=0;
totalFrame=0;
//frameSize=0;
//frameType=0;
width=height=0;
memset(&frameInfo, 0, sizeof(frameInfo));
memset(&frameYUV, 0, sizeof(frameYUV));
memset(&streamInfo, 0, sizeof(streamInfo));
codecID=CV_CODEC_UNKNOWN;
//nameHash=0;
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
dict = NULL;
#endif
rawMode = false;
rawModeInitialized = false;
memset(&packet_filtered, 0, sizeof(packet_filtered));
av_init_packet(&packet_filtered);
bsfc = NULL;
}
void CvCapture_FFMPEG::close()
{
if( img_convert_ctx )
{
sws_freeContext(img_convert_ctx);
img_convert_ctx = 0;
}
if( picture )
{
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
av_frame_free(&picture);
#elif LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 ? CALC_FFMPEG_VERSION(54, 59, 100) : CALC_FFMPEG_VERSION(54, 28, 0))
avcodec_free_frame(&picture);
#else
av_free(picture);
#endif
}
if( video_st )
{
#if LIBAVFORMAT_BUILD > 4628
avcodec_close( video_st->codec );
#else
avcodec_close( &(video_st->codec) );
#endif
video_st = NULL;
}
if( ic )
{
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 24, 2)
av_close_input_file(ic);
#else
avformat_close_input(&ic);
#endif
ic = NULL;
}
#if USE_AV_FRAME_GET_BUFFER
av_frame_unref(&rgb_picture);
#else
if( rgb_picture.data[0] )
{
free( rgb_picture.data[0] );
rgb_picture.data[0] = 0;
}
#endif
// free last packet if exist
if (packet.data)
{
_opencv_ffmpeg_av_packet_unref (&packet);
packet.data = NULL;
}
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
if (dict != NULL)
av_dict_free(&dict);
#endif
if (packet_filtered.data)
{
_opencv_ffmpeg_av_packet_unref(&packet_filtered);
packet_filtered.data = NULL;
}
if (bsfc)
{
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(58, 20, 100)
av_bsf_free(&bsfc);
#else
av_bitstream_filter_close(bsfc);
#endif
}
init();
}
#ifndef AVSEEK_FLAG_FRAME
#define AVSEEK_FLAG_FRAME 0
#endif
#ifndef AVSEEK_FLAG_ANY
#define AVSEEK_FLAG_ANY 1
#endif
#if defined(__OPENCV_BUILD) || defined(BUILD_PLUGIN)
typedef cv::Mutex ImplMutex;
#else
class ImplMutex
{
public:
ImplMutex() { init(); }
~ImplMutex() { destroy(); }
void init();
void destroy();
void lock();
bool trylock();
void unlock();
struct Impl;
protected:
Impl* impl;
private:
ImplMutex(const ImplMutex&);
ImplMutex& operator = (const ImplMutex& m);
};
#if defined _WIN32 || defined WINCE
struct ImplMutex::Impl
{
void init()
{
#if (_WIN32_WINNT >= 0x0600)
::InitializeCriticalSectionEx(&cs, 1000, 0);
#else
::InitializeCriticalSection(&cs);
#endif
refcount = 1;
}
void destroy() { DeleteCriticalSection(&cs); }
void lock() { EnterCriticalSection(&cs); }
bool trylock() { return TryEnterCriticalSection(&cs) != 0; }
void unlock() { LeaveCriticalSection(&cs); }
CRITICAL_SECTION cs;
int refcount;
};
#ifndef __GNUC__
static int _interlockedExchangeAdd(int* addr, int delta)
{
#if defined _MSC_VER && _MSC_VER >= 1500
return (int)_InterlockedExchangeAdd((long volatile*)addr, delta);
#else
return (int)InterlockedExchangeAdd((long volatile*)addr, delta);
#endif
}
#endif // __GNUC__
#elif defined __APPLE__
#include <libkern/OSAtomic.h>
struct ImplMutex::Impl
{
void init() { sl = OS_SPINLOCK_INIT; refcount = 1; }
void destroy() { }
void lock() { OSSpinLockLock(&sl); }
bool trylock() { return OSSpinLockTry(&sl); }
void unlock() { OSSpinLockUnlock(&sl); }
OSSpinLock sl;
int refcount;
};
#elif defined __linux__ && !defined __ANDROID__
struct ImplMutex::Impl
{
void init() { pthread_spin_init(&sl, 0); refcount = 1; }
void destroy() { pthread_spin_destroy(&sl); }
void lock() { pthread_spin_lock(&sl); }
bool trylock() { return pthread_spin_trylock(&sl) == 0; }
void unlock() { pthread_spin_unlock(&sl); }
pthread_spinlock_t sl;
int refcount;
};
#else
struct ImplMutex::Impl
{
void init() { pthread_mutex_init(&sl, 0); refcount = 1; }
void destroy() { pthread_mutex_destroy(&sl); }
void lock() { pthread_mutex_lock(&sl); }
bool trylock() { return pthread_mutex_trylock(&sl) == 0; }
void unlock() { pthread_mutex_unlock(&sl); }
pthread_mutex_t sl;
int refcount;
};
#endif
void ImplMutex::init()
{
impl = new Impl();
impl->init();
}
void ImplMutex::destroy()
{
impl->destroy();
delete(impl);
impl = NULL;
}
void ImplMutex::lock() { impl->lock(); }
void ImplMutex::unlock() { impl->unlock(); }
bool ImplMutex::trylock() { return impl->trylock(); }
class AutoLock
{
public:
AutoLock(ImplMutex& m) : mutex(&m) { mutex->lock(); }
~AutoLock() { mutex->unlock(); }
protected:
ImplMutex* mutex;
private:
AutoLock(const AutoLock&); // disabled
AutoLock& operator = (const AutoLock&); // disabled
};
#endif
static ImplMutex _mutex;
static int LockCallBack(void **mutex, AVLockOp op)
{
ImplMutex* localMutex = reinterpret_cast<ImplMutex*>(*mutex);
switch (op)
{
case AV_LOCK_CREATE:
localMutex = new ImplMutex();
if (!localMutex)
return 1;
*mutex = localMutex;
if (!*mutex)
return 1;
break;
case AV_LOCK_OBTAIN:
localMutex->lock();
break;
case AV_LOCK_RELEASE:
localMutex->unlock();
break;
case AV_LOCK_DESTROY:
delete localMutex;
localMutex = NULL;
*mutex = NULL;
break;
}
return 0;
}
static void ffmpeg_log_callback(void *ptr, int level, const char *fmt, va_list vargs)
{
static bool skip_header = false;
static int prev_level = -1;
CV_UNUSED(ptr);
if (!skip_header || level != prev_level) printf("[OPENCV:FFMPEG:%02d] ", level);
vprintf(fmt, vargs);
size_t fmt_len = strlen(fmt);
skip_header = fmt_len > 0 && fmt[fmt_len - 1] != '\n';
prev_level = level;
}
class InternalFFMpegRegister
{
public:
static void init()
{
AutoLock lock(_mutex);
static InternalFFMpegRegister instance;
}