Merge pull request #15102 from dgel:force_input_format_ffmpeg
[platform/upstream/opencv.git] / modules / videoio / src / cap_ffmpeg_impl.hpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                          License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Third party copyrights are property of their respective owners.
16 //
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
19 //
20 //   * Redistribution's of source code must retain the above copyright notice,
21 //     this list of conditions and the following disclaimer.
22 //
23 //   * Redistribution's in binary form must reproduce the above copyright notice,
24 //     this list of conditions and the following disclaimer in the documentation
25 //     and/or other materials provided with the distribution.
26 //
27 //   * The name of the copyright holders may not be used to endorse or promote products
28 //     derived from this software without specific prior written permission.
29 //
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
40 //
41 //M*/
42
43 #include "cap_ffmpeg_api.hpp"
44 #if !(defined(_WIN32) || defined(WINCE))
45 # include <pthread.h>
46 #endif
47 #include <assert.h>
48 #include <algorithm>
49 #include <limits>
50
51 #ifndef __OPENCV_BUILD
52 #define CV_FOURCC(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24))
53 #endif
54
55 #define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c )
56
57 #if defined _MSC_VER && _MSC_VER >= 1200
58 #pragma warning( disable: 4244 4510 4610 )
59 #endif
60
61 #ifdef __GNUC__
62 #  pragma GCC diagnostic ignored "-Wdeprecated-declarations"
63 #endif
64
65 #ifndef CV_UNUSED  // Required for standalone compilation mode (OpenCV defines this in base.hpp)
66 #define CV_UNUSED(name) (void)name
67 #endif
68
69 #ifdef __cplusplus
70 extern "C" {
71 #endif
72
73 #include "ffmpeg_codecs.hpp"
74
75 #include <libavutil/mathematics.h>
76
77 #if LIBAVUTIL_BUILD > CALC_FFMPEG_VERSION(51,11,0)
78   #include <libavutil/opt.h>
79 #endif
80
81 #if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 \
82     ? CALC_FFMPEG_VERSION(51, 63, 100) : CALC_FFMPEG_VERSION(54, 6, 0))
83 #include <libavutil/imgutils.h>
84 #endif
85
86 #include <libavcodec/avcodec.h>
87 #include <libswscale/swscale.h>
88
89 #ifdef __cplusplus
90 }
91 #endif
92
93 #if defined _MSC_VER && _MSC_VER >= 1200
94 #pragma warning( default: 4244 4510 4610 )
95 #endif
96
97 #ifdef NDEBUG
98 #define CV_WARN(message)
99 #else
100 #define CV_WARN(message) fprintf(stderr, "warning: %s (%s:%d)\n", message, __FILE__, __LINE__)
101 #endif
102
103 #if defined _WIN32
104     #include <windows.h>
105     #if defined _MSC_VER && _MSC_VER < 1900
106     struct timespec
107     {
108         time_t tv_sec;
109         long   tv_nsec;
110     };
111   #endif
112 #elif defined __linux__ || defined __APPLE__ || defined __HAIKU__
113     #include <unistd.h>
114     #include <stdio.h>
115     #include <sys/types.h>
116     #include <sys/time.h>
117 #if defined __APPLE__
118     #include <sys/sysctl.h>
119     #include <mach/clock.h>
120     #include <mach/mach.h>
121 #endif
122 #endif
123
124 #ifndef MIN
125 #define MIN(a, b) ((a) < (b) ? (a) : (b))
126 #endif
127
128 #if defined(__APPLE__)
129 #define AV_NOPTS_VALUE_ ((int64_t)0x8000000000000000LL)
130 #else
131 #define AV_NOPTS_VALUE_ ((int64_t)AV_NOPTS_VALUE)
132 #endif
133
134 #ifndef AVERROR_EOF
135 #define AVERROR_EOF (-MKTAG( 'E','O','F',' '))
136 #endif
137
138 #if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54,25,0)
139 #  define CV_CODEC_ID AVCodecID
140 #  define CV_CODEC(name) AV_##name
141 #else
142 #  define CV_CODEC_ID CodecID
143 #  define CV_CODEC(name) name
144 #endif
145
146 #if LIBAVUTIL_BUILD < (LIBAVUTIL_VERSION_MICRO >= 100 \
147     ? CALC_FFMPEG_VERSION(51, 74, 100) : CALC_FFMPEG_VERSION(51, 42, 0))
148 #define AVPixelFormat PixelFormat
149 #define AV_PIX_FMT_BGR24 PIX_FMT_BGR24
150 #define AV_PIX_FMT_RGB24 PIX_FMT_RGB24
151 #define AV_PIX_FMT_GRAY8 PIX_FMT_GRAY8
152 #define AV_PIX_FMT_YUV422P PIX_FMT_YUV422P
153 #define AV_PIX_FMT_YUV420P PIX_FMT_YUV420P
154 #define AV_PIX_FMT_YUV444P PIX_FMT_YUV444P
155 #define AV_PIX_FMT_YUVJ420P PIX_FMT_YUVJ420P
156 #define AV_PIX_FMT_GRAY16LE PIX_FMT_GRAY16LE
157 #define AV_PIX_FMT_GRAY16BE PIX_FMT_GRAY16BE
158 #endif
159
160 #ifndef PKT_FLAG_KEY
161 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
162 #endif
163
164 #if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 \
165     ? CALC_FFMPEG_VERSION(52, 38, 100) : CALC_FFMPEG_VERSION(52, 13, 0))
166 #define USE_AV_FRAME_GET_BUFFER 1
167 #else
168 #define USE_AV_FRAME_GET_BUFFER 0
169 #ifndef AV_NUM_DATA_POINTERS // required for 0.7.x/0.8.x ffmpeg releases
170 #define AV_NUM_DATA_POINTERS 4
171 #endif
172 #endif
173
174
175 #ifndef USE_AV_INTERRUPT_CALLBACK
176 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 21, 0)
177 #define USE_AV_INTERRUPT_CALLBACK 1
178 #else
179 #define USE_AV_INTERRUPT_CALLBACK 0
180 #endif
181 #endif
182
183 #if USE_AV_INTERRUPT_CALLBACK
184 #define LIBAVFORMAT_INTERRUPT_OPEN_TIMEOUT_MS 30000
185 #define LIBAVFORMAT_INTERRUPT_READ_TIMEOUT_MS 30000
186
187 #ifdef _WIN32
188 // http://stackoverflow.com/questions/5404277/porting-clock-gettime-to-windows
189
190 static
191 inline LARGE_INTEGER get_filetime_offset()
192 {
193     SYSTEMTIME s;
194     FILETIME f;
195     LARGE_INTEGER t;
196
197     s.wYear = 1970;
198     s.wMonth = 1;
199     s.wDay = 1;
200     s.wHour = 0;
201     s.wMinute = 0;
202     s.wSecond = 0;
203     s.wMilliseconds = 0;
204     SystemTimeToFileTime(&s, &f);
205     t.QuadPart = f.dwHighDateTime;
206     t.QuadPart <<= 32;
207     t.QuadPart |= f.dwLowDateTime;
208     return t;
209 }
210
211 static
212 inline void get_monotonic_time(timespec *tv)
213 {
214     LARGE_INTEGER           t;
215     FILETIME                            f;
216     double                  microseconds;
217     static LARGE_INTEGER    offset;
218     static double           frequencyToMicroseconds;
219     static int              initialized = 0;
220     static BOOL             usePerformanceCounter = 0;
221
222     if (!initialized)
223     {
224         LARGE_INTEGER performanceFrequency;
225         initialized = 1;
226         usePerformanceCounter = QueryPerformanceFrequency(&performanceFrequency);
227         if (usePerformanceCounter)
228         {
229             QueryPerformanceCounter(&offset);
230             frequencyToMicroseconds = (double)performanceFrequency.QuadPart / 1000000.;
231         }
232         else
233         {
234             offset = get_filetime_offset();
235             frequencyToMicroseconds = 10.;
236         }
237     }
238
239     if (usePerformanceCounter)
240     {
241         QueryPerformanceCounter(&t);
242     } else {
243         GetSystemTimeAsFileTime(&f);
244         t.QuadPart = f.dwHighDateTime;
245         t.QuadPart <<= 32;
246         t.QuadPart |= f.dwLowDateTime;
247     }
248
249     t.QuadPart -= offset.QuadPart;
250     microseconds = (double)t.QuadPart / frequencyToMicroseconds;
251     t.QuadPart = microseconds;
252     tv->tv_sec = t.QuadPart / 1000000;
253     tv->tv_nsec = (t.QuadPart % 1000000) * 1000;
254 }
255 #else
256 static
257 inline void get_monotonic_time(timespec *time)
258 {
259 #if defined(__APPLE__) && defined(__MACH__)
260     clock_serv_t cclock;
261     mach_timespec_t mts;
262     host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
263     clock_get_time(cclock, &mts);
264     mach_port_deallocate(mach_task_self(), cclock);
265     time->tv_sec = mts.tv_sec;
266     time->tv_nsec = mts.tv_nsec;
267 #else
268     clock_gettime(CLOCK_MONOTONIC, time);
269 #endif
270 }
271 #endif
272
273 static
274 inline timespec get_monotonic_time_diff(timespec start, timespec end)
275 {
276     timespec temp;
277     if (end.tv_nsec - start.tv_nsec < 0)
278     {
279         temp.tv_sec = end.tv_sec - start.tv_sec - 1;
280         temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
281     }
282     else
283     {
284         temp.tv_sec = end.tv_sec - start.tv_sec;
285         temp.tv_nsec = end.tv_nsec - start.tv_nsec;
286     }
287     return temp;
288 }
289
290 static
291 inline double get_monotonic_time_diff_ms(timespec time1, timespec time2)
292 {
293     timespec delta = get_monotonic_time_diff(time1, time2);
294     double milliseconds = delta.tv_sec * 1000 + (double)delta.tv_nsec / 1000000.0;
295
296     return milliseconds;
297 }
298 #endif // USE_AV_INTERRUPT_CALLBACK
299
300 static int get_number_of_cpus(void)
301 {
302 #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(52, 111, 0)
303     return 1;
304 #elif defined _WIN32
305     SYSTEM_INFO sysinfo;
306     GetSystemInfo( &sysinfo );
307
308     return (int)sysinfo.dwNumberOfProcessors;
309 #elif defined __linux__ || defined __HAIKU__
310     return (int)sysconf( _SC_NPROCESSORS_ONLN );
311 #elif defined __APPLE__
312     int numCPU=0;
313     int mib[4];
314     size_t len = sizeof(numCPU);
315
316     // set the mib for hw.ncpu
317     mib[0] = CTL_HW;
318     mib[1] = HW_AVAILCPU;  // alternatively, try HW_NCPU;
319
320     // get the number of CPUs from the system
321     sysctl(mib, 2, &numCPU, &len, NULL, 0);
322
323     if( numCPU < 1 )
324     {
325         mib[1] = HW_NCPU;
326         sysctl( mib, 2, &numCPU, &len, NULL, 0 );
327
328         if( numCPU < 1 )
329             numCPU = 1;
330     }
331
332     return (int)numCPU;
333 #else
334     return 1;
335 #endif
336 }
337
338
339 struct Image_FFMPEG
340 {
341     unsigned char* data;
342     int step;
343     int width;
344     int height;
345     int cn;
346 };
347
348
349 #if USE_AV_INTERRUPT_CALLBACK
350 struct AVInterruptCallbackMetadata
351 {
352     timespec value;
353     unsigned int timeout_after_ms;
354     int timeout;
355 };
356
357 // https://github.com/opencv/opencv/pull/12693#issuecomment-426236731
358 static
359 inline const char* _opencv_avcodec_get_name(AVCodecID id)
360 {
361 #if LIBAVCODEC_VERSION_MICRO >= 100 \
362     && LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(53, 47, 100)
363     return avcodec_get_name(id);
364 #else
365     const AVCodecDescriptor *cd;
366     AVCodec *codec;
367
368     if (id == AV_CODEC_ID_NONE)
369     {
370         return "none";
371     }
372     cd = avcodec_descriptor_get(id);
373     if (cd)
374     {
375         return cd->name;
376     }
377     codec = avcodec_find_decoder(id);
378     if (codec)
379     {
380         return codec->name;
381     }
382     codec = avcodec_find_encoder(id);
383     if (codec)
384     {
385         return codec->name;
386     }
387
388     return "unknown_codec";
389 #endif
390 }
391
392 static
393 inline void _opencv_ffmpeg_free(void** ptr)
394 {
395     if(*ptr) free(*ptr);
396     *ptr = 0;
397 }
398
399 static
400 inline int _opencv_ffmpeg_interrupt_callback(void *ptr)
401 {
402     AVInterruptCallbackMetadata* metadata = (AVInterruptCallbackMetadata*)ptr;
403     assert(metadata);
404
405     if (metadata->timeout_after_ms == 0)
406     {
407         return 0; // timeout is disabled
408     }
409
410     timespec now;
411     get_monotonic_time(&now);
412
413     metadata->timeout = get_monotonic_time_diff_ms(metadata->value, now) > metadata->timeout_after_ms;
414
415     return metadata->timeout ? -1 : 0;
416 }
417 #endif
418
419 static
420 inline void _opencv_ffmpeg_av_packet_unref(AVPacket *pkt)
421 {
422 #if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
423     ? CALC_FFMPEG_VERSION(55, 25, 100) : CALC_FFMPEG_VERSION(55, 16, 0))
424     av_packet_unref(pkt);
425 #else
426     av_free_packet(pkt);
427 #endif
428 };
429
430 static
431 inline void _opencv_ffmpeg_av_image_fill_arrays(void *frame, uint8_t *ptr, enum AVPixelFormat pix_fmt, int width, int height)
432 {
433 #if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 \
434     ? CALC_FFMPEG_VERSION(51, 63, 100) : CALC_FFMPEG_VERSION(54, 6, 0))
435     av_image_fill_arrays(((AVFrame*)frame)->data, ((AVFrame*)frame)->linesize, ptr, pix_fmt, width, height, 1);
436 #else
437     avpicture_fill((AVPicture*)frame, ptr, pix_fmt, width, height);
438 #endif
439 };
440
441 static
442 inline int _opencv_ffmpeg_av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height)
443 {
444 #if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 \
445     ? CALC_FFMPEG_VERSION(51, 63, 100) : CALC_FFMPEG_VERSION(54, 6, 0))
446     return av_image_get_buffer_size(pix_fmt, width, height, 1);
447 #else
448     return avpicture_get_size(pix_fmt, width, height);
449 #endif
450 };
451
452 static AVRational _opencv_ffmpeg_get_sample_aspect_ratio(AVStream *stream)
453 {
454 #if LIBAVUTIL_VERSION_MICRO >= 100 && LIBAVUTIL_BUILD >= CALC_FFMPEG_VERSION(54, 5, 100)
455     return av_guess_sample_aspect_ratio(NULL, stream, NULL);
456 #else
457     AVRational undef = {0, 1};
458
459     // stream
460     AVRational ratio = stream ? stream->sample_aspect_ratio : undef;
461     av_reduce(&ratio.num, &ratio.den, ratio.num, ratio.den, INT_MAX);
462     if (ratio.num > 0 && ratio.den > 0)
463         return ratio;
464
465     // codec
466     ratio  = stream && stream->codec ? stream->codec->sample_aspect_ratio : undef;
467     av_reduce(&ratio.num, &ratio.den, ratio.num, ratio.den, INT_MAX);
468     if (ratio.num > 0 && ratio.den > 0)
469         return ratio;
470
471     return undef;
472 #endif
473 }
474
475
476 struct CvCapture_FFMPEG
477 {
478     bool open( const char* filename );
479     void close();
480
481     double getProperty(int) const;
482     bool setProperty(int, double);
483     bool grabFrame();
484     bool retrieveFrame(int, unsigned char** data, int* step, int* width, int* height, int* cn);
485
486     void init();
487
488     void    seek(int64_t frame_number);
489     void    seek(double sec);
490     bool    slowSeek( int framenumber );
491
492     int64_t get_total_frames() const;
493     double  get_duration_sec() const;
494     double  get_fps() const;
495     int     get_bitrate() const;
496
497     double  r2d(AVRational r) const;
498     int64_t dts_to_frame_number(int64_t dts);
499     double  dts_to_sec(int64_t dts) const;
500
501     AVFormatContext * ic;
502     AVCodec         * avcodec;
503     int               video_stream;
504     AVStream        * video_st;
505     AVFrame         * picture;
506     AVFrame           rgb_picture;
507     int64_t           picture_pts;
508
509     AVPacket          packet;
510     Image_FFMPEG      frame;
511     struct SwsContext *img_convert_ctx;
512
513     int64_t frame_number, first_frame_number;
514
515     double eps_zero;
516 /*
517    'filename' contains the filename of the videosource,
518    'filename==NULL' indicates that ffmpeg's seek support works
519    for the particular file.
520    'filename!=NULL' indicates that the slow fallback function is used for seeking,
521    and so the filename is needed to reopen the file on backward seeking.
522 */
523     char              * filename;
524
525 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
526     AVDictionary *dict;
527 #endif
528 #if USE_AV_INTERRUPT_CALLBACK
529     AVInterruptCallbackMetadata interrupt_metadata;
530 #endif
531 };
532
533 void CvCapture_FFMPEG::init()
534 {
535     ic = 0;
536     video_stream = -1;
537     video_st = 0;
538     picture = 0;
539     picture_pts = AV_NOPTS_VALUE_;
540     first_frame_number = -1;
541     memset( &rgb_picture, 0, sizeof(rgb_picture) );
542     memset( &frame, 0, sizeof(frame) );
543     filename = 0;
544     memset(&packet, 0, sizeof(packet));
545     av_init_packet(&packet);
546     img_convert_ctx = 0;
547
548     avcodec = 0;
549     frame_number = 0;
550     eps_zero = 0.000025;
551
552 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
553     dict = NULL;
554 #endif
555 }
556
557
558 void CvCapture_FFMPEG::close()
559 {
560     if( img_convert_ctx )
561     {
562         sws_freeContext(img_convert_ctx);
563         img_convert_ctx = 0;
564     }
565
566     if( picture )
567     {
568 #if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
569     ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
570         av_frame_free(&picture);
571 #elif LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
572     ? CALC_FFMPEG_VERSION(54, 59, 100) : CALC_FFMPEG_VERSION(54, 28, 0))
573         avcodec_free_frame(&picture);
574 #else
575         av_free(picture);
576 #endif
577     }
578
579     if( video_st )
580     {
581 #if LIBAVFORMAT_BUILD > 4628
582         avcodec_close( video_st->codec );
583
584 #else
585         avcodec_close( &(video_st->codec) );
586
587 #endif
588         video_st = NULL;
589     }
590
591     if( ic )
592     {
593 #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 24, 2)
594         av_close_input_file(ic);
595 #else
596         avformat_close_input(&ic);
597 #endif
598
599         ic = NULL;
600     }
601
602 #if USE_AV_FRAME_GET_BUFFER
603     av_frame_unref(&rgb_picture);
604 #else
605     if( rgb_picture.data[0] )
606     {
607         free( rgb_picture.data[0] );
608         rgb_picture.data[0] = 0;
609     }
610 #endif
611
612     // free last packet if exist
613     if (packet.data) {
614         _opencv_ffmpeg_av_packet_unref (&packet);
615         packet.data = NULL;
616     }
617
618 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
619     if (dict != NULL)
620        av_dict_free(&dict);
621 #endif
622
623     init();
624 }
625
626
627 #ifndef AVSEEK_FLAG_FRAME
628 #define AVSEEK_FLAG_FRAME 0
629 #endif
630 #ifndef AVSEEK_FLAG_ANY
631 #define AVSEEK_FLAG_ANY 1
632 #endif
633
634 class ImplMutex
635 {
636 public:
637     ImplMutex() { init(); }
638     ~ImplMutex() { destroy(); }
639
640     void init();
641     void destroy();
642
643     void lock();
644     bool trylock();
645     void unlock();
646
647     struct Impl;
648 protected:
649     Impl* impl;
650
651 private:
652     ImplMutex(const ImplMutex&);
653     ImplMutex& operator = (const ImplMutex& m);
654 };
655
656 #if defined _WIN32 || defined WINCE
657
658 struct ImplMutex::Impl
659 {
660     void init()
661     {
662 #if (_WIN32_WINNT >= 0x0600)
663         ::InitializeCriticalSectionEx(&cs, 1000, 0);
664 #else
665         ::InitializeCriticalSection(&cs);
666 #endif
667         refcount = 1;
668     }
669     void destroy() { DeleteCriticalSection(&cs); }
670
671     void lock() { EnterCriticalSection(&cs); }
672     bool trylock() { return TryEnterCriticalSection(&cs) != 0; }
673     void unlock() { LeaveCriticalSection(&cs); }
674
675     CRITICAL_SECTION cs;
676     int refcount;
677 };
678
679 #ifndef __GNUC__
680 static int _interlockedExchangeAdd(int* addr, int delta)
681 {
682 #if defined _MSC_VER && _MSC_VER >= 1500
683     return (int)_InterlockedExchangeAdd((long volatile*)addr, delta);
684 #else
685     return (int)InterlockedExchangeAdd((long volatile*)addr, delta);
686 #endif
687 }
688 #endif // __GNUC__
689
690 #elif defined __APPLE__
691
692 #include <libkern/OSAtomic.h>
693
694 struct ImplMutex::Impl
695 {
696     void init() { sl = OS_SPINLOCK_INIT; refcount = 1; }
697     void destroy() { }
698
699     void lock() { OSSpinLockLock(&sl); }
700     bool trylock() { return OSSpinLockTry(&sl); }
701     void unlock() { OSSpinLockUnlock(&sl); }
702
703     OSSpinLock sl;
704     int refcount;
705 };
706
707 #elif defined __linux__ && !defined __ANDROID__
708
709 struct ImplMutex::Impl
710 {
711     void init() { pthread_spin_init(&sl, 0); refcount = 1; }
712     void destroy() { pthread_spin_destroy(&sl); }
713
714     void lock() { pthread_spin_lock(&sl); }
715     bool trylock() { return pthread_spin_trylock(&sl) == 0; }
716     void unlock() { pthread_spin_unlock(&sl); }
717
718     pthread_spinlock_t sl;
719     int refcount;
720 };
721
722 #else
723
724 struct ImplMutex::Impl
725 {
726     void init() { pthread_mutex_init(&sl, 0); refcount = 1; }
727     void destroy() { pthread_mutex_destroy(&sl); }
728
729     void lock() { pthread_mutex_lock(&sl); }
730     bool trylock() { return pthread_mutex_trylock(&sl) == 0; }
731     void unlock() { pthread_mutex_unlock(&sl); }
732
733     pthread_mutex_t sl;
734     int refcount;
735 };
736
737 #endif
738
739 void ImplMutex::init()
740 {
741     impl = new Impl();
742     impl->init();
743 }
744 void ImplMutex::destroy()
745 {
746     impl->destroy();
747     delete(impl);
748     impl = NULL;
749 }
750 void ImplMutex::lock() { impl->lock(); }
751 void ImplMutex::unlock() { impl->unlock(); }
752 bool ImplMutex::trylock() { return impl->trylock(); }
753
754 static int LockCallBack(void **mutex, AVLockOp op)
755 {
756     ImplMutex* localMutex = reinterpret_cast<ImplMutex*>(*mutex);
757     switch (op)
758     {
759         case AV_LOCK_CREATE:
760             localMutex = reinterpret_cast<ImplMutex*>(malloc(sizeof(ImplMutex)));
761             if (!localMutex)
762                 return 1;
763             localMutex->init();
764             *mutex = localMutex;
765             if (!*mutex)
766                 return 1;
767         break;
768
769         case AV_LOCK_OBTAIN:
770             localMutex->lock();
771         break;
772
773         case AV_LOCK_RELEASE:
774             localMutex->unlock();
775         break;
776
777         case AV_LOCK_DESTROY:
778             localMutex->destroy();
779             free(localMutex);
780             localMutex = NULL;
781             *mutex = NULL;
782         break;
783     }
784     return 0;
785 }
786
787 static ImplMutex _mutex;
788 static bool _initialized = false;
789
790 class AutoLock
791 {
792 public:
793     AutoLock(ImplMutex& m) : mutex(&m) { mutex->lock(); }
794     ~AutoLock() { mutex->unlock(); }
795 protected:
796     ImplMutex* mutex;
797 private:
798     AutoLock(const AutoLock&); // disabled
799     AutoLock& operator = (const AutoLock&); // disabled
800 };
801
802 static void ffmpeg_log_callback(void *ptr, int level, const char *fmt, va_list vargs)
803 {
804     static bool skip_header = false;
805     static int prev_level = -1;
806     CV_UNUSED(ptr);
807     if (!skip_header || level != prev_level) printf("[OPENCV:FFMPEG:%02d] ", level);
808     vprintf(fmt, vargs);
809     size_t fmt_len = strlen(fmt);
810     skip_header = fmt_len > 0 && fmt[fmt_len - 1] != '\n';
811     prev_level = level;
812 }
813
814 class InternalFFMpegRegister
815 {
816 public:
817     InternalFFMpegRegister()
818     {
819         AutoLock lock(_mutex);
820         if (!_initialized)
821         {
822     #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 13, 0)
823             avformat_network_init();
824     #endif
825
826             /* register all codecs, demux and protocols */
827             av_register_all();
828
829             /* register a callback function for synchronization */
830             av_lockmgr_register(&LockCallBack);
831
832 #ifndef NO_GETENV
833             char* debug_option = getenv("OPENCV_FFMPEG_DEBUG");
834             if (debug_option != NULL)
835             {
836                 av_log_set_level(AV_LOG_VERBOSE);
837                 av_log_set_callback(ffmpeg_log_callback);
838             }
839             else
840 #endif
841             {
842                 av_log_set_level(AV_LOG_ERROR);
843             }
844
845             _initialized = true;
846         }
847     }
848
849     ~InternalFFMpegRegister()
850     {
851         _initialized = false;
852         av_lockmgr_register(NULL);
853     }
854 };
855
856 static InternalFFMpegRegister _init;
857
858 bool CvCapture_FFMPEG::open( const char* _filename )
859 {
860     AutoLock lock(_mutex);
861     unsigned i;
862     bool valid = false;
863
864     close();
865
866 #if USE_AV_INTERRUPT_CALLBACK
867     /* interrupt callback */
868     interrupt_metadata.timeout_after_ms = LIBAVFORMAT_INTERRUPT_OPEN_TIMEOUT_MS;
869     get_monotonic_time(&interrupt_metadata.value);
870
871     ic = avformat_alloc_context();
872     ic->interrupt_callback.callback = _opencv_ffmpeg_interrupt_callback;
873     ic->interrupt_callback.opaque = &interrupt_metadata;
874 #endif
875
876 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
877 #ifndef NO_GETENV
878     char* options = getenv("OPENCV_FFMPEG_CAPTURE_OPTIONS");
879     if(options == NULL)
880     {
881         av_dict_set(&dict, "rtsp_transport", "tcp", 0);
882     }
883     else
884     {
885 #if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 ? CALC_FFMPEG_VERSION(52, 17, 100) : CALC_FFMPEG_VERSION(52, 7, 0))
886         av_dict_parse_string(&dict, options, ";", "|", 0);
887 #else
888         av_dict_set(&dict, "rtsp_transport", "tcp", 0);
889 #endif
890     }
891 #else
892     av_dict_set(&dict, "rtsp_transport", "tcp", 0);
893 #endif
894     AVInputFormat* input_format = NULL;
895     AVDictionaryEntry* entry = av_dict_get(dict, "input_format", NULL, 0);
896     if (entry != 0)
897     {
898       input_format = av_find_input_format(entry->value);
899     }
900
901     int err = avformat_open_input(&ic, _filename, input_format, &dict);
902 #else
903     int err = av_open_input_file(&ic, _filename, NULL, 0, NULL);
904 #endif
905
906     if (err < 0)
907     {
908         CV_WARN("Error opening file");
909         CV_WARN(_filename);
910         goto exit_func;
911     }
912     err =
913 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
914     avformat_find_stream_info(ic, NULL);
915 #else
916     av_find_stream_info(ic);
917 #endif
918     if (err < 0)
919     {
920         CV_WARN("Could not find codec parameters");
921         goto exit_func;
922     }
923     for(i = 0; i < ic->nb_streams; i++)
924     {
925 #if LIBAVFORMAT_BUILD > 4628
926         AVCodecContext *enc = ic->streams[i]->codec;
927 #else
928         AVCodecContext *enc = &ic->streams[i]->codec;
929 #endif
930
931 //#ifdef FF_API_THREAD_INIT
932 //        avcodec_thread_init(enc, get_number_of_cpus());
933 //#else
934         enc->thread_count = get_number_of_cpus();
935 //#endif
936
937 #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
938 #define AVMEDIA_TYPE_VIDEO CODEC_TYPE_VIDEO
939 #endif
940
941         if( AVMEDIA_TYPE_VIDEO == enc->codec_type && video_stream < 0)
942         {
943             // backup encoder' width/height
944             int enc_width = enc->width;
945             int enc_height = enc->height;
946
947             AVCodec *codec;
948             if(av_dict_get(dict, "video_codec", NULL, 0) == NULL) {
949                 codec = avcodec_find_decoder(enc->codec_id);
950             } else {
951                 codec = avcodec_find_decoder_by_name(av_dict_get(dict, "video_codec", NULL, 0)->value);
952             }
953             if (!codec ||
954 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
955                 avcodec_open2(enc, codec, NULL)
956 #else
957                 avcodec_open(enc, codec)
958 #endif
959                 < 0)
960                 goto exit_func;
961
962             // checking width/height (since decoder can sometimes alter it, eg. vp6f)
963             if (enc_width && (enc->width != enc_width)) { enc->width = enc_width; }
964             if (enc_height && (enc->height != enc_height)) { enc->height = enc_height; }
965
966             video_stream = i;
967             video_st = ic->streams[i];
968 #if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
969     ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
970             picture = av_frame_alloc();
971 #else
972             picture = avcodec_alloc_frame();
973 #endif
974
975             frame.width = enc->width;
976             frame.height = enc->height;
977             frame.cn = 3;
978             frame.step = 0;
979             frame.data = NULL;
980             break;
981         }
982     }
983
984     if(video_stream >= 0) valid = true;
985
986 exit_func:
987
988 #if USE_AV_INTERRUPT_CALLBACK
989     // deactivate interrupt callback
990     interrupt_metadata.timeout_after_ms = 0;
991 #endif
992
993     if( !valid )
994         close();
995
996     return valid;
997 }
998
999
1000 bool CvCapture_FFMPEG::grabFrame()
1001 {
1002     bool valid = false;
1003     int got_picture;
1004
1005     int count_errs = 0;
1006     const int max_number_of_attempts = 1 << 9;
1007
1008     if( !ic || !video_st )  return false;
1009
1010     if( ic->streams[video_stream]->nb_frames > 0 &&
1011         frame_number > ic->streams[video_stream]->nb_frames )
1012         return false;
1013
1014     picture_pts = AV_NOPTS_VALUE_;
1015
1016 #if USE_AV_INTERRUPT_CALLBACK
1017     // activate interrupt callback
1018     get_monotonic_time(&interrupt_metadata.value);
1019     interrupt_metadata.timeout_after_ms = LIBAVFORMAT_INTERRUPT_READ_TIMEOUT_MS;
1020 #endif
1021
1022     // get the next frame
1023     while (!valid)
1024     {
1025
1026         _opencv_ffmpeg_av_packet_unref (&packet);
1027
1028 #if USE_AV_INTERRUPT_CALLBACK
1029         if (interrupt_metadata.timeout)
1030         {
1031             valid = false;
1032             break;
1033         }
1034 #endif
1035
1036         int ret = av_read_frame(ic, &packet);
1037         if (ret == AVERROR(EAGAIN)) continue;
1038
1039         /* else if (ret < 0) break; */
1040
1041         if( packet.stream_index != video_stream )
1042         {
1043             _opencv_ffmpeg_av_packet_unref (&packet);
1044             count_errs++;
1045             if (count_errs > max_number_of_attempts)
1046                 break;
1047             continue;
1048         }
1049
1050         // Decode video frame
1051         #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
1052             avcodec_decode_video2(video_st->codec, picture, &got_picture, &packet);
1053         #elif LIBAVFORMAT_BUILD > 4628
1054                 avcodec_decode_video(video_st->codec,
1055                                      picture, &got_picture,
1056                                      packet.data, packet.size);
1057         #else
1058                 avcodec_decode_video(&video_st->codec,
1059                                      picture, &got_picture,
1060                                      packet.data, packet.size);
1061         #endif
1062
1063         // Did we get a video frame?
1064         if(got_picture)
1065         {
1066             //picture_pts = picture->best_effort_timestamp;
1067             if( picture_pts == AV_NOPTS_VALUE_ )
1068                 picture_pts = picture->pkt_pts != AV_NOPTS_VALUE_ && picture->pkt_pts != 0 ? picture->pkt_pts : picture->pkt_dts;
1069
1070             frame_number++;
1071             valid = true;
1072         }
1073         else
1074         {
1075             count_errs++;
1076             if (count_errs > max_number_of_attempts)
1077                 break;
1078         }
1079     }
1080
1081     if( valid && first_frame_number < 0 )
1082         first_frame_number = dts_to_frame_number(picture_pts);
1083
1084 #if USE_AV_INTERRUPT_CALLBACK
1085     // deactivate interrupt callback
1086     interrupt_metadata.timeout_after_ms = 0;
1087 #endif
1088
1089     // return if we have a new picture or not
1090     return valid;
1091 }
1092
1093
1094 bool CvCapture_FFMPEG::retrieveFrame(int, unsigned char** data, int* step, int* width, int* height, int* cn)
1095 {
1096     if( !video_st || !picture->data[0] )
1097         return false;
1098
1099     if( img_convert_ctx == NULL ||
1100         frame.width != video_st->codec->width ||
1101         frame.height != video_st->codec->height ||
1102         frame.data == NULL )
1103     {
1104         // Some sws_scale optimizations have some assumptions about alignment of data/step/width/height
1105         // Also we use coded_width/height to workaround problem with legacy ffmpeg versions (like n0.8)
1106         int buffer_width = video_st->codec->coded_width, buffer_height = video_st->codec->coded_height;
1107
1108         img_convert_ctx = sws_getCachedContext(
1109                 img_convert_ctx,
1110                 buffer_width, buffer_height,
1111                 video_st->codec->pix_fmt,
1112                 buffer_width, buffer_height,
1113                 AV_PIX_FMT_BGR24,
1114                 SWS_BICUBIC,
1115                 NULL, NULL, NULL
1116                 );
1117
1118         if (img_convert_ctx == NULL)
1119             return false;//CV_Error(0, "Cannot initialize the conversion context!");
1120
1121 #if USE_AV_FRAME_GET_BUFFER
1122         av_frame_unref(&rgb_picture);
1123         rgb_picture.format = AV_PIX_FMT_BGR24;
1124         rgb_picture.width = buffer_width;
1125         rgb_picture.height = buffer_height;
1126         if (0 != av_frame_get_buffer(&rgb_picture, 32))
1127         {
1128             CV_WARN("OutOfMemory");
1129             return false;
1130         }
1131 #else
1132         int aligns[AV_NUM_DATA_POINTERS];
1133         avcodec_align_dimensions2(video_st->codec, &buffer_width, &buffer_height, aligns);
1134         rgb_picture.data[0] = (uint8_t*)realloc(rgb_picture.data[0],
1135                 _opencv_ffmpeg_av_image_get_buffer_size( AV_PIX_FMT_BGR24,
1136                                     buffer_width, buffer_height ));
1137         _opencv_ffmpeg_av_image_fill_arrays(&rgb_picture, rgb_picture.data[0],
1138                         AV_PIX_FMT_BGR24, buffer_width, buffer_height );
1139 #endif
1140         frame.width = video_st->codec->width;
1141         frame.height = video_st->codec->height;
1142         frame.cn = 3;
1143         frame.data = rgb_picture.data[0];
1144         frame.step = rgb_picture.linesize[0];
1145     }
1146
1147     sws_scale(
1148             img_convert_ctx,
1149             picture->data,
1150             picture->linesize,
1151             0, video_st->codec->coded_height,
1152             rgb_picture.data,
1153             rgb_picture.linesize
1154             );
1155
1156     *data = frame.data;
1157     *step = frame.step;
1158     *width = frame.width;
1159     *height = frame.height;
1160     *cn = frame.cn;
1161
1162     return true;
1163 }
1164
1165
1166 double CvCapture_FFMPEG::getProperty( int property_id ) const
1167 {
1168     if( !video_st ) return 0;
1169
1170     double codec_tag = 0;
1171     AVCodecID codec_id = AV_CODEC_ID_NONE;
1172     const char* codec_fourcc = NULL;
1173
1174     switch( property_id )
1175     {
1176     case CV_FFMPEG_CAP_PROP_POS_MSEC:
1177         if (picture_pts == AV_NOPTS_VALUE_)
1178         {
1179             return 0;
1180         }
1181         return (dts_to_sec(picture_pts) * 1000);
1182     case CV_FFMPEG_CAP_PROP_POS_FRAMES:
1183         return (double)frame_number;
1184     case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
1185         return r2d(ic->streams[video_stream]->time_base);
1186     case CV_FFMPEG_CAP_PROP_FRAME_COUNT:
1187         return (double)get_total_frames();
1188     case CV_FFMPEG_CAP_PROP_FRAME_WIDTH:
1189         return (double)frame.width;
1190     case CV_FFMPEG_CAP_PROP_FRAME_HEIGHT:
1191         return (double)frame.height;
1192     case CV_FFMPEG_CAP_PROP_FPS:
1193         return get_fps();
1194     case CV_FFMPEG_CAP_PROP_FOURCC:
1195 #if LIBAVFORMAT_BUILD > 4628
1196         codec_id = video_st->codec->codec_id;
1197         codec_tag = (double) video_st->codec->codec_tag;
1198 #else
1199         codec_id = video_st->codec.codec_id;
1200         codec_tag = (double)video_st->codec.codec_tag;
1201 #endif
1202
1203         if(codec_tag || codec_id == AV_CODEC_ID_NONE)
1204         {
1205             return codec_tag;
1206         }
1207
1208         codec_fourcc = _opencv_avcodec_get_name(codec_id);
1209         if(!codec_fourcc || strlen(codec_fourcc) < 4 || strcmp(codec_fourcc, "unknown_codec") == 0)
1210         {
1211             return codec_tag;
1212         }
1213
1214         return (double) CV_FOURCC(codec_fourcc[0], codec_fourcc[1], codec_fourcc[2], codec_fourcc[3]);
1215     case CV_FFMPEG_CAP_PROP_SAR_NUM:
1216         return _opencv_ffmpeg_get_sample_aspect_ratio(ic->streams[video_stream]).num;
1217     case CV_FFMPEG_CAP_PROP_SAR_DEN:
1218         return _opencv_ffmpeg_get_sample_aspect_ratio(ic->streams[video_stream]).den;
1219     default:
1220         break;
1221     }
1222
1223     return 0;
1224 }
1225
1226 double CvCapture_FFMPEG::r2d(AVRational r) const
1227 {
1228     return r.num == 0 || r.den == 0 ? 0. : (double)r.num / (double)r.den;
1229 }
1230
1231 double CvCapture_FFMPEG::get_duration_sec() const
1232 {
1233     double sec = (double)ic->duration / (double)AV_TIME_BASE;
1234
1235     if (sec < eps_zero)
1236     {
1237         sec = (double)ic->streams[video_stream]->duration * r2d(ic->streams[video_stream]->time_base);
1238     }
1239
1240     return sec;
1241 }
1242
1243 int CvCapture_FFMPEG::get_bitrate() const
1244 {
1245     return ic->bit_rate;
1246 }
1247
1248 double CvCapture_FFMPEG::get_fps() const
1249 {
1250 #if 0 && LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 1, 100) && LIBAVFORMAT_VERSION_MICRO >= 100
1251     double fps = r2d(av_guess_frame_rate(ic, ic->streams[video_stream], NULL));
1252 #else
1253 #if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54, 1, 0)
1254     double fps = r2d(ic->streams[video_stream]->avg_frame_rate);
1255 #else
1256     double fps = r2d(ic->streams[video_stream]->r_frame_rate);
1257 #endif
1258
1259 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
1260     if (fps < eps_zero)
1261     {
1262         fps = r2d(ic->streams[video_stream]->avg_frame_rate);
1263     }
1264 #endif
1265
1266     if (fps < eps_zero)
1267     {
1268         fps = 1.0 / r2d(ic->streams[video_stream]->codec->time_base);
1269     }
1270 #endif
1271     return fps;
1272 }
1273
1274 int64_t CvCapture_FFMPEG::get_total_frames() const
1275 {
1276     int64_t nbf = ic->streams[video_stream]->nb_frames;
1277
1278     if (nbf == 0)
1279     {
1280         nbf = (int64_t)floor(get_duration_sec() * get_fps() + 0.5);
1281     }
1282     return nbf;
1283 }
1284
1285 int64_t CvCapture_FFMPEG::dts_to_frame_number(int64_t dts)
1286 {
1287     double sec = dts_to_sec(dts);
1288     return (int64_t)(get_fps() * sec + 0.5);
1289 }
1290
1291 double CvCapture_FFMPEG::dts_to_sec(int64_t dts) const
1292 {
1293     return (double)(dts - ic->streams[video_stream]->start_time) *
1294         r2d(ic->streams[video_stream]->time_base);
1295 }
1296
1297 void CvCapture_FFMPEG::seek(int64_t _frame_number)
1298 {
1299     _frame_number = std::min(_frame_number, get_total_frames());
1300     int delta = 16;
1301
1302     // if we have not grabbed a single frame before first seek, let's read the first frame
1303     // and get some valuable information during the process
1304     if( first_frame_number < 0 && get_total_frames() > 1 )
1305         grabFrame();
1306
1307     for(;;)
1308     {
1309         int64_t _frame_number_temp = std::max(_frame_number-delta, (int64_t)0);
1310         double sec = (double)_frame_number_temp / get_fps();
1311         int64_t time_stamp = ic->streams[video_stream]->start_time;
1312         double  time_base  = r2d(ic->streams[video_stream]->time_base);
1313         time_stamp += (int64_t)(sec / time_base + 0.5);
1314         if (get_total_frames() > 1) av_seek_frame(ic, video_stream, time_stamp, AVSEEK_FLAG_BACKWARD);
1315         avcodec_flush_buffers(ic->streams[video_stream]->codec);
1316         if( _frame_number > 0 )
1317         {
1318             grabFrame();
1319
1320             if( _frame_number > 1 )
1321             {
1322                 frame_number = dts_to_frame_number(picture_pts) - first_frame_number;
1323                 //printf("_frame_number = %d, frame_number = %d, delta = %d\n",
1324                 //       (int)_frame_number, (int)frame_number, delta);
1325
1326                 if( frame_number < 0 || frame_number > _frame_number-1 )
1327                 {
1328                     if( _frame_number_temp == 0 || delta >= INT_MAX/4 )
1329                         break;
1330                     delta = delta < 16 ? delta*2 : delta*3/2;
1331                     continue;
1332                 }
1333                 while( frame_number < _frame_number-1 )
1334                 {
1335                     if(!grabFrame())
1336                         break;
1337                 }
1338                 frame_number++;
1339                 break;
1340             }
1341             else
1342             {
1343                 frame_number = 1;
1344                 break;
1345             }
1346         }
1347         else
1348         {
1349             frame_number = 0;
1350             break;
1351         }
1352     }
1353 }
1354
1355 void CvCapture_FFMPEG::seek(double sec)
1356 {
1357     seek((int64_t)(sec * get_fps() + 0.5));
1358 }
1359
1360 bool CvCapture_FFMPEG::setProperty( int property_id, double value )
1361 {
1362     if( !video_st ) return false;
1363
1364     switch( property_id )
1365     {
1366     case CV_FFMPEG_CAP_PROP_POS_MSEC:
1367     case CV_FFMPEG_CAP_PROP_POS_FRAMES:
1368     case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
1369         {
1370             switch( property_id )
1371             {
1372             case CV_FFMPEG_CAP_PROP_POS_FRAMES:
1373                 seek((int64_t)value);
1374                 break;
1375
1376             case CV_FFMPEG_CAP_PROP_POS_MSEC:
1377                 seek(value/1000.0);
1378                 break;
1379
1380             case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
1381                 seek((int64_t)(value*ic->duration));
1382                 break;
1383             }
1384
1385             picture_pts=(int64_t)value;
1386         }
1387         break;
1388     default:
1389         return false;
1390     }
1391
1392     return true;
1393 }
1394
1395
1396 ///////////////// FFMPEG CvVideoWriter implementation //////////////////////////
1397 struct CvVideoWriter_FFMPEG
1398 {
1399     bool open( const char* filename, int fourcc,
1400                double fps, int width, int height, bool isColor );
1401     void close();
1402     bool writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin );
1403
1404     void init();
1405
1406     AVOutputFormat  * fmt;
1407     AVFormatContext * oc;
1408     uint8_t         * outbuf;
1409     uint32_t          outbuf_size;
1410     FILE            * outfile;
1411     AVFrame         * picture;
1412     AVFrame         * input_picture;
1413     uint8_t         * picbuf;
1414     AVStream        * video_st;
1415     int               input_pix_fmt;
1416     unsigned char   * aligned_input;
1417     size_t            aligned_input_size;
1418     int               frame_width, frame_height;
1419     int               frame_idx;
1420     bool              ok;
1421     struct SwsContext *img_convert_ctx;
1422 };
1423
1424 static const char * icvFFMPEGErrStr(int err)
1425 {
1426 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
1427     switch(err) {
1428     case AVERROR_BSF_NOT_FOUND:
1429         return "Bitstream filter not found";
1430     case AVERROR_DECODER_NOT_FOUND:
1431         return "Decoder not found";
1432     case AVERROR_DEMUXER_NOT_FOUND:
1433         return "Demuxer not found";
1434     case AVERROR_ENCODER_NOT_FOUND:
1435         return "Encoder not found";
1436     case AVERROR_EOF:
1437         return "End of file";
1438     case AVERROR_EXIT:
1439         return "Immediate exit was requested; the called function should not be restarted";
1440     case AVERROR_FILTER_NOT_FOUND:
1441         return "Filter not found";
1442     case AVERROR_INVALIDDATA:
1443         return "Invalid data found when processing input";
1444     case AVERROR_MUXER_NOT_FOUND:
1445         return "Muxer not found";
1446     case AVERROR_OPTION_NOT_FOUND:
1447         return "Option not found";
1448     case AVERROR_PATCHWELCOME:
1449         return "Not yet implemented in FFmpeg, patches welcome";
1450     case AVERROR_PROTOCOL_NOT_FOUND:
1451         return "Protocol not found";
1452     case AVERROR_STREAM_NOT_FOUND:
1453         return "Stream not found";
1454     default:
1455         break;
1456     }
1457 #else
1458     switch(err) {
1459     case AVERROR_NUMEXPECTED:
1460         return "Incorrect filename syntax";
1461     case AVERROR_INVALIDDATA:
1462         return "Invalid data in header";
1463     case AVERROR_NOFMT:
1464         return "Unknown format";
1465     case AVERROR_IO:
1466         return "I/O error occurred";
1467     case AVERROR_NOMEM:
1468         return "Memory allocation error";
1469     default:
1470         break;
1471     }
1472 #endif
1473
1474     return "Unspecified error";
1475 }
1476
1477 /* function internal to FFMPEG (libavformat/riff.c) to lookup codec id by fourcc tag*/
1478 extern "C" {
1479     enum CV_CODEC_ID codec_get_bmp_id(unsigned int tag);
1480 }
1481
1482 void CvVideoWriter_FFMPEG::init()
1483 {
1484     fmt = 0;
1485     oc = 0;
1486     outbuf = 0;
1487     outbuf_size = 0;
1488     outfile = 0;
1489     picture = 0;
1490     input_picture = 0;
1491     picbuf = 0;
1492     video_st = 0;
1493     input_pix_fmt = 0;
1494     aligned_input = NULL;
1495     aligned_input_size = 0;
1496     img_convert_ctx = 0;
1497     frame_width = frame_height = 0;
1498     frame_idx = 0;
1499     ok = false;
1500 }
1501
1502 /**
1503  * the following function is a modified version of code
1504  * found in ffmpeg-0.4.9-pre1/output_example.c
1505  */
1506 static AVFrame * icv_alloc_picture_FFMPEG(int pix_fmt, int width, int height, bool alloc)
1507 {
1508     AVFrame * picture;
1509     uint8_t * picture_buf = 0;
1510     int size;
1511
1512 #if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
1513     ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
1514     picture = av_frame_alloc();
1515 #else
1516     picture = avcodec_alloc_frame();
1517 #endif
1518     if (!picture)
1519         return NULL;
1520
1521     picture->format = pix_fmt;
1522     picture->width = width;
1523     picture->height = height;
1524
1525     size = _opencv_ffmpeg_av_image_get_buffer_size( (AVPixelFormat) pix_fmt, width, height);
1526     if(alloc){
1527         picture_buf = (uint8_t *) malloc(size);
1528         if (!picture_buf)
1529         {
1530             av_free(picture);
1531             return NULL;
1532         }
1533         _opencv_ffmpeg_av_image_fill_arrays(picture, picture_buf,
1534                        (AVPixelFormat) pix_fmt, width, height);
1535     }
1536
1537     return picture;
1538 }
1539
1540 /* add a video output stream to the container */
1541 static AVStream *icv_add_video_stream_FFMPEG(AVFormatContext *oc,
1542                                              CV_CODEC_ID codec_id,
1543                                              int w, int h, int bitrate,
1544                                              double fps, int pixel_format)
1545 {
1546     AVCodecContext *c;
1547     AVStream *st;
1548     int frame_rate, frame_rate_base;
1549     AVCodec *codec;
1550
1551 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 10, 0)
1552     st = avformat_new_stream(oc, 0);
1553 #else
1554     st = av_new_stream(oc, 0);
1555 #endif
1556
1557     if (!st) {
1558         CV_WARN("Could not allocate stream");
1559         return NULL;
1560     }
1561
1562 #if LIBAVFORMAT_BUILD > 4628
1563     c = st->codec;
1564 #else
1565     c = &(st->codec);
1566 #endif
1567
1568 #if LIBAVFORMAT_BUILD > 4621
1569     c->codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
1570 #else
1571     c->codec_id = oc->oformat->video_codec;
1572 #endif
1573
1574     if(codec_id != CV_CODEC(CODEC_ID_NONE)){
1575         c->codec_id = codec_id;
1576     }
1577
1578     //if(codec_tag) c->codec_tag=codec_tag;
1579     codec = avcodec_find_encoder(c->codec_id);
1580
1581     c->codec_type = AVMEDIA_TYPE_VIDEO;
1582
1583 #if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54,25,0)
1584     // Set per-codec defaults
1585     AVCodecID c_id = c->codec_id;
1586     avcodec_get_context_defaults3(c, codec);
1587     // avcodec_get_context_defaults3 erases codec_id for some reason
1588     c->codec_id = c_id;
1589 #endif
1590
1591     /* put sample parameters */
1592     int64_t lbit_rate = (int64_t)bitrate;
1593     lbit_rate += (bitrate / 2);
1594     lbit_rate = std::min(lbit_rate, (int64_t)INT_MAX);
1595     c->bit_rate = lbit_rate;
1596
1597     // took advice from
1598     // http://ffmpeg-users.933282.n4.nabble.com/warning-clipping-1-dct-coefficients-to-127-127-td934297.html
1599     c->qmin = 3;
1600
1601     /* resolution must be a multiple of two */
1602     c->width = w;
1603     c->height = h;
1604
1605     /* time base: this is the fundamental unit of time (in seconds) in terms
1606        of which frame timestamps are represented. for fixed-fps content,
1607        timebase should be 1/framerate and timestamp increments should be
1608        identically 1. */
1609     frame_rate=(int)(fps+0.5);
1610     frame_rate_base=1;
1611     while (fabs(((double)frame_rate/frame_rate_base) - fps) > 0.001){
1612         frame_rate_base*=10;
1613         frame_rate=(int)(fps*frame_rate_base + 0.5);
1614     }
1615 #if LIBAVFORMAT_BUILD > 4752
1616     c->time_base.den = frame_rate;
1617     c->time_base.num = frame_rate_base;
1618     /* adjust time base for supported framerates */
1619     if(codec && codec->supported_framerates){
1620         const AVRational *p= codec->supported_framerates;
1621         AVRational req = {frame_rate, frame_rate_base};
1622         const AVRational *best=NULL;
1623         AVRational best_error= {INT_MAX, 1};
1624         for(; p->den!=0; p++){
1625             AVRational error= av_sub_q(req, *p);
1626             if(error.num <0) error.num *= -1;
1627             if(av_cmp_q(error, best_error) < 0){
1628                 best_error= error;
1629                 best= p;
1630             }
1631         }
1632         if (best == NULL)
1633             return NULL;
1634         c->time_base.den= best->num;
1635         c->time_base.num= best->den;
1636     }
1637 #else
1638     c->frame_rate = frame_rate;
1639     c->frame_rate_base = frame_rate_base;
1640 #endif
1641
1642     c->gop_size = 12; /* emit one intra frame every twelve frames at most */
1643     c->pix_fmt = (AVPixelFormat) pixel_format;
1644
1645     if (c->codec_id == CV_CODEC(CODEC_ID_MPEG2VIDEO)) {
1646         c->max_b_frames = 2;
1647     }
1648     if (c->codec_id == CV_CODEC(CODEC_ID_MPEG1VIDEO) || c->codec_id == CV_CODEC(CODEC_ID_MSMPEG4V3)){
1649         /* needed to avoid using macroblocks in which some coeffs overflow
1650            this doesn't happen with normal video, it just happens here as the
1651            motion of the chroma plane doesn't match the luma plane */
1652         /* avoid FFMPEG warning 'clipping 1 dct coefficients...' */
1653         c->mb_decision=2;
1654     }
1655
1656 #if LIBAVUTIL_BUILD > CALC_FFMPEG_VERSION(51,11,0)
1657     /* Some settings for libx264 encoding, restore dummy values for gop_size
1658      and qmin since they will be set to reasonable defaults by the libx264
1659      preset system. Also, use a crf encode with the default quality rating,
1660      this seems easier than finding an appropriate default bitrate. */
1661     if (c->codec_id == AV_CODEC_ID_H264) {
1662       c->gop_size = -1;
1663       c->qmin = -1;
1664       c->bit_rate = 0;
1665       if (c->priv_data)
1666           av_opt_set(c->priv_data,"crf","23", 0);
1667     }
1668 #endif
1669
1670 #if LIBAVCODEC_VERSION_INT>0x000409
1671     // some formats want stream headers to be separate
1672     if(oc->oformat->flags & AVFMT_GLOBALHEADER)
1673     {
1674 #if LIBAVCODEC_BUILD > CALC_FFMPEG_VERSION(56, 35, 0)
1675         c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
1676 #else
1677         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
1678 #endif
1679     }
1680 #endif
1681
1682 #if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(52, 42, 0)
1683 #if defined(_MSC_VER)
1684     AVRational avg_frame_rate = {frame_rate, frame_rate_base};
1685     st->avg_frame_rate = avg_frame_rate;
1686 #else
1687     st->avg_frame_rate = (AVRational){frame_rate, frame_rate_base};
1688 #endif
1689 #endif
1690 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 20, 0)
1691     st->time_base = c->time_base;
1692 #endif
1693
1694     return st;
1695 }
1696
1697 static const int OPENCV_NO_FRAMES_WRITTEN_CODE = 1000;
1698
1699 static int icv_av_write_frame_FFMPEG( AVFormatContext * oc, AVStream * video_st,
1700 #if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54, 1, 0)
1701                                       uint8_t *, uint32_t,
1702 #else
1703                                       uint8_t * outbuf, uint32_t outbuf_size,
1704 #endif
1705                                       AVFrame * picture )
1706 {
1707 #if LIBAVFORMAT_BUILD > 4628
1708     AVCodecContext * c = video_st->codec;
1709 #else
1710     AVCodecContext * c = &(video_st->codec);
1711 #endif
1712     int ret = OPENCV_NO_FRAMES_WRITTEN_CODE;
1713
1714 #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(57, 0, 0)
1715     if (oc->oformat->flags & AVFMT_RAWPICTURE)
1716     {
1717         /* raw video case. The API will change slightly in the near
1718            futur for that */
1719         AVPacket pkt;
1720         av_init_packet(&pkt);
1721
1722         pkt.flags |= PKT_FLAG_KEY;
1723         pkt.stream_index= video_st->index;
1724         pkt.data= (uint8_t *)picture;
1725         pkt.size= sizeof(AVPicture);
1726
1727         ret = av_write_frame(oc, &pkt);
1728     }
1729     else
1730 #endif
1731     {
1732         /* encode the image */
1733         AVPacket pkt;
1734         av_init_packet(&pkt);
1735 #if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54, 1, 0)
1736         int got_output = 0;
1737         pkt.data = NULL;
1738         pkt.size = 0;
1739         ret = avcodec_encode_video2(c, &pkt, picture, &got_output);
1740         if (ret < 0)
1741             ;
1742         else if (got_output) {
1743             if (pkt.pts != (int64_t)AV_NOPTS_VALUE)
1744                 pkt.pts = av_rescale_q(pkt.pts, c->time_base, video_st->time_base);
1745             if (pkt.dts != (int64_t)AV_NOPTS_VALUE)
1746                 pkt.dts = av_rescale_q(pkt.dts, c->time_base, video_st->time_base);
1747             if (pkt.duration)
1748                 pkt.duration = av_rescale_q(pkt.duration, c->time_base, video_st->time_base);
1749             pkt.stream_index= video_st->index;
1750             ret = av_write_frame(oc, &pkt);
1751             _opencv_ffmpeg_av_packet_unref(&pkt);
1752         }
1753         else
1754             ret = OPENCV_NO_FRAMES_WRITTEN_CODE;
1755 #else
1756         int out_size = avcodec_encode_video(c, outbuf, outbuf_size, picture);
1757         /* if zero size, it means the image was buffered */
1758         if (out_size > 0) {
1759 #if LIBAVFORMAT_BUILD > 4752
1760             if(c->coded_frame->pts != (int64_t)AV_NOPTS_VALUE)
1761                 pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st->time_base);
1762 #else
1763             pkt.pts = c->coded_frame->pts;
1764 #endif
1765             if(c->coded_frame->key_frame)
1766                 pkt.flags |= PKT_FLAG_KEY;
1767             pkt.stream_index= video_st->index;
1768             pkt.data= outbuf;
1769             pkt.size= out_size;
1770
1771             /* write the compressed frame in the media file */
1772             ret = av_write_frame(oc, &pkt);
1773         }
1774 #endif
1775     }
1776     return ret;
1777 }
1778
1779 /// write a frame with FFMPEG
1780 bool CvVideoWriter_FFMPEG::writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin )
1781 {
1782     // check parameters
1783     if (input_pix_fmt == AV_PIX_FMT_BGR24) {
1784         if (cn != 3) {
1785             return false;
1786         }
1787     }
1788     else if (input_pix_fmt == AV_PIX_FMT_GRAY8) {
1789         if (cn != 1) {
1790             return false;
1791         }
1792     }
1793     else {
1794         assert(false);
1795     }
1796
1797     if( (width & -2) != frame_width || (height & -2) != frame_height || !data )
1798         return false;
1799     width = frame_width;
1800     height = frame_height;
1801
1802     // typecast from opaque data type to implemented struct
1803 #if LIBAVFORMAT_BUILD > 4628
1804     AVCodecContext *c = video_st->codec;
1805 #else
1806     AVCodecContext *c = &(video_st->codec);
1807 #endif
1808
1809     // FFmpeg contains SIMD optimizations which can sometimes read data past
1810     // the supplied input buffer.
1811     // Related info: https://trac.ffmpeg.org/ticket/6763
1812     // 1. To ensure that doesn't happen, we pad the step to a multiple of 32
1813     // (that's the minimal alignment for which Valgrind doesn't raise any warnings).
1814     // 2. (dataend - SIMD_SIZE) and (dataend + SIMD_SIZE) is from the same 4k page
1815     const int CV_STEP_ALIGNMENT = 32;
1816     const size_t CV_SIMD_SIZE = 32;
1817     const size_t CV_PAGE_MASK = ~(4096 - 1);
1818     const unsigned char* dataend = data + ((size_t)height * step);
1819     if (step % CV_STEP_ALIGNMENT != 0 ||
1820         (((size_t)dataend - CV_SIMD_SIZE) & CV_PAGE_MASK) != (((size_t)dataend + CV_SIMD_SIZE) & CV_PAGE_MASK))
1821     {
1822         int aligned_step = (step + CV_STEP_ALIGNMENT - 1) & ~(CV_STEP_ALIGNMENT - 1);
1823
1824         size_t new_size = (aligned_step * height + CV_SIMD_SIZE);
1825
1826         if (!aligned_input || aligned_input_size < new_size)
1827         {
1828             if (aligned_input)
1829                 av_freep(&aligned_input);
1830             aligned_input_size = new_size;
1831             aligned_input = (unsigned char*)av_mallocz(aligned_input_size);
1832         }
1833
1834         if (origin == 1)
1835             for( int y = 0; y < height; y++ )
1836                 memcpy(aligned_input + y*aligned_step, data + (height-1-y)*step, step);
1837         else
1838             for( int y = 0; y < height; y++ )
1839                 memcpy(aligned_input + y*aligned_step, data + y*step, step);
1840
1841         data = aligned_input;
1842         step = aligned_step;
1843     }
1844
1845     if ( c->pix_fmt != input_pix_fmt ) {
1846         assert( input_picture );
1847         // let input_picture point to the raw data buffer of 'image'
1848         _opencv_ffmpeg_av_image_fill_arrays(input_picture, (uint8_t *) data,
1849                        (AVPixelFormat)input_pix_fmt, width, height);
1850         input_picture->linesize[0] = step;
1851
1852         if( !img_convert_ctx )
1853         {
1854             img_convert_ctx = sws_getContext(width,
1855                                              height,
1856                                              (AVPixelFormat)input_pix_fmt,
1857                                              c->width,
1858                                              c->height,
1859                                              c->pix_fmt,
1860                                              SWS_BICUBIC,
1861                                              NULL, NULL, NULL);
1862             if( !img_convert_ctx )
1863                 return false;
1864         }
1865
1866         if ( sws_scale(img_convert_ctx, input_picture->data,
1867                        input_picture->linesize, 0,
1868                        height,
1869                        picture->data, picture->linesize) < 0 )
1870             return false;
1871     }
1872     else{
1873         _opencv_ffmpeg_av_image_fill_arrays(picture, (uint8_t *) data,
1874                        (AVPixelFormat)input_pix_fmt, width, height);
1875         picture->linesize[0] = step;
1876     }
1877
1878     picture->pts = frame_idx;
1879     bool ret = icv_av_write_frame_FFMPEG( oc, video_st, outbuf, outbuf_size, picture) >= 0;
1880     frame_idx++;
1881
1882     return ret;
1883 }
1884
1885 /// close video output stream and free associated memory
1886 void CvVideoWriter_FFMPEG::close()
1887 {
1888     // nothing to do if already released
1889     if ( !picture )
1890         return;
1891
1892     /* no more frame to compress. The codec has a latency of a few
1893        frames if using B frames, so we get the last frames by
1894        passing the same picture again */
1895     // TODO -- do we need to account for latency here?
1896
1897     /* write the trailer, if any */
1898     if(ok && oc)
1899     {
1900 #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(57, 0, 0)
1901         if (!(oc->oformat->flags & AVFMT_RAWPICTURE))
1902 #endif
1903         {
1904             for(;;)
1905             {
1906                 int ret = icv_av_write_frame_FFMPEG( oc, video_st, outbuf, outbuf_size, NULL);
1907                 if( ret == OPENCV_NO_FRAMES_WRITTEN_CODE || ret < 0 )
1908                     break;
1909             }
1910         }
1911         av_write_trailer(oc);
1912     }
1913
1914     if( img_convert_ctx )
1915     {
1916         sws_freeContext(img_convert_ctx);
1917         img_convert_ctx = 0;
1918     }
1919
1920     // free pictures
1921 #if LIBAVFORMAT_BUILD > 4628
1922     if( video_st->codec->pix_fmt != input_pix_fmt)
1923 #else
1924     if( video_st->codec.pix_fmt != input_pix_fmt)
1925 #endif
1926     {
1927         if(picture->data[0])
1928             free(picture->data[0]);
1929         picture->data[0] = 0;
1930     }
1931     av_free(picture);
1932
1933     if (input_picture)
1934         av_free(input_picture);
1935
1936     /* close codec */
1937 #if LIBAVFORMAT_BUILD > 4628
1938     avcodec_close(video_st->codec);
1939 #else
1940     avcodec_close(&(video_st->codec));
1941 #endif
1942
1943     av_free(outbuf);
1944
1945     if (oc)
1946     {
1947         if (!(fmt->flags & AVFMT_NOFILE))
1948         {
1949             /* close the output file */
1950
1951 #if LIBAVCODEC_VERSION_INT < ((52<<16)+(123<<8)+0)
1952 #if LIBAVCODEC_VERSION_INT >= ((51<<16)+(49<<8)+0)
1953             url_fclose(oc->pb);
1954 #else
1955             url_fclose(&oc->pb);
1956 #endif
1957 #else
1958             avio_close(oc->pb);
1959 #endif
1960
1961         }
1962
1963         /* free the stream */
1964         avformat_free_context(oc);
1965     }
1966
1967     av_freep(&aligned_input);
1968
1969     init();
1970 }
1971
1972 #define CV_PRINTABLE_CHAR(ch) ((ch) < 32 ? '?' : (ch))
1973 #define CV_TAG_TO_PRINTABLE_CHAR4(tag) CV_PRINTABLE_CHAR((tag) & 255), CV_PRINTABLE_CHAR(((tag) >> 8) & 255), CV_PRINTABLE_CHAR(((tag) >> 16) & 255), CV_PRINTABLE_CHAR(((tag) >> 24) & 255)
1974
1975 static inline bool cv_ff_codec_tag_match(const AVCodecTag *tags, CV_CODEC_ID id, unsigned int tag)
1976 {
1977     while (tags->id != AV_CODEC_ID_NONE)
1978     {
1979         if (tags->id == id && tags->tag == tag)
1980             return true;
1981         tags++;
1982     }
1983     return false;
1984 }
1985
1986 static inline bool cv_ff_codec_tag_list_match(const AVCodecTag *const *tags, CV_CODEC_ID id, unsigned int tag)
1987 {
1988     int i;
1989     for (i = 0; tags && tags[i]; i++) {
1990         bool res = cv_ff_codec_tag_match(tags[i], id, tag);
1991         if (res)
1992             return res;
1993     }
1994     return false;
1995 }
1996
1997
1998 static inline void cv_ff_codec_tag_dump(const AVCodecTag *const *tags)
1999 {
2000     int i;
2001     for (i = 0; tags && tags[i]; i++) {
2002         const AVCodecTag * ptags = tags[i];
2003         while (ptags->id != AV_CODEC_ID_NONE)
2004         {
2005             unsigned int tag = ptags->tag;
2006             printf("fourcc tag 0x%08x/'%c%c%c%c' codec_id %04X\n", tag, CV_TAG_TO_PRINTABLE_CHAR4(tag), ptags->id);
2007             ptags++;
2008         }
2009     }
2010 }
2011
2012 /// Create a video writer object that uses FFMPEG
2013 bool CvVideoWriter_FFMPEG::open( const char * filename, int fourcc,
2014                                  double fps, int width, int height, bool is_color )
2015 {
2016     CV_CODEC_ID codec_id = CV_CODEC(CODEC_ID_NONE);
2017     int err, codec_pix_fmt;
2018     double bitrate_scale = 1;
2019
2020     close();
2021
2022     // check arguments
2023     if( !filename )
2024         return false;
2025     if(fps <= 0)
2026         return false;
2027
2028     // we allow frames of odd width or height, but in this case we truncate
2029     // the rightmost column/the bottom row. Probably, this should be handled more elegantly,
2030     // but some internal functions inside FFMPEG swscale require even width/height.
2031     width &= -2;
2032     height &= -2;
2033     if( width <= 0 || height <= 0 )
2034         return false;
2035
2036     /* auto detect the output format from the name and fourcc code. */
2037
2038 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
2039     fmt = av_guess_format(NULL, filename, NULL);
2040 #else
2041     fmt = guess_format(NULL, filename, NULL);
2042 #endif
2043
2044     if (!fmt)
2045         return false;
2046
2047     /* determine optimal pixel format */
2048     if (is_color) {
2049         input_pix_fmt = AV_PIX_FMT_BGR24;
2050     }
2051     else {
2052         input_pix_fmt = AV_PIX_FMT_GRAY8;
2053     }
2054
2055     if (fourcc == -1)
2056     {
2057         fprintf(stderr,"OpenCV: FFMPEG: format %s / %s\n", fmt->name, fmt->long_name);
2058         cv_ff_codec_tag_dump(fmt->codec_tag);
2059         return false;
2060     }
2061
2062     /* Lookup codec_id for given fourcc */
2063 #if LIBAVCODEC_VERSION_INT<((51<<16)+(49<<8)+0)
2064     if( (codec_id = codec_get_bmp_id( fourcc )) == CV_CODEC(CODEC_ID_NONE) )
2065         return false;
2066 #else
2067     if( (codec_id = av_codec_get_id(fmt->codec_tag, fourcc)) == CV_CODEC(CODEC_ID_NONE) )
2068     {
2069         const struct AVCodecTag * fallback_tags[] = {
2070 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(54, 1, 0)
2071 // APIchanges:
2072 // 2012-01-31 - dd6d3b0 - lavf 54.01.0
2073 //   Add avformat_get_riff_video_tags() and avformat_get_riff_audio_tags().
2074                 avformat_get_riff_video_tags(),
2075 #endif
2076 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 25, 100) && defined LIBAVFORMAT_VERSION_MICRO && LIBAVFORMAT_VERSION_MICRO >= 100
2077 // APIchanges: ffmpeg only
2078 // 2014-01-19 - 1a193c4 - lavf 55.25.100 - avformat.h
2079 //   Add avformat_get_mov_video_tags() and avformat_get_mov_audio_tags().
2080                 avformat_get_mov_video_tags(),
2081 #endif
2082                 codec_bmp_tags, // fallback for avformat < 54.1
2083                 NULL };
2084         if( (codec_id = av_codec_get_id(fallback_tags, fourcc)) == CV_CODEC(CODEC_ID_NONE) )
2085         {
2086             fflush(stdout);
2087             fprintf(stderr, "OpenCV: FFMPEG: tag 0x%08x/'%c%c%c%c' is not found (format '%s / %s')'\n",
2088                     fourcc, CV_TAG_TO_PRINTABLE_CHAR4(fourcc),
2089                     fmt->name, fmt->long_name);
2090             return false;
2091         }
2092     }
2093
2094
2095     // validate tag
2096     if (cv_ff_codec_tag_list_match(fmt->codec_tag, codec_id, fourcc) == false)
2097     {
2098         fflush(stdout);
2099         fprintf(stderr, "OpenCV: FFMPEG: tag 0x%08x/'%c%c%c%c' is not supported with codec id %d and format '%s / %s'\n",
2100                 fourcc, CV_TAG_TO_PRINTABLE_CHAR4(fourcc),
2101                 codec_id, fmt->name, fmt->long_name);
2102         int supported_tag;
2103         if( (supported_tag = av_codec_get_tag(fmt->codec_tag, codec_id)) != 0 )
2104         {
2105             fprintf(stderr, "OpenCV: FFMPEG: fallback to use tag 0x%08x/'%c%c%c%c'\n",
2106                     supported_tag, CV_TAG_TO_PRINTABLE_CHAR4(supported_tag));
2107             fourcc = supported_tag;
2108         }
2109     }
2110 #endif
2111
2112     // alloc memory for context
2113 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
2114     oc = avformat_alloc_context();
2115 #else
2116     oc = av_alloc_format_context();
2117 #endif
2118     assert (oc);
2119
2120     /* set file name */
2121     oc->oformat = fmt;
2122     snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
2123
2124     /* set some options */
2125     oc->max_delay = (int)(0.7*AV_TIME_BASE);  /* This reduces buffer underrun warnings with MPEG */
2126
2127     // set a few optimal pixel formats for lossless codecs of interest..
2128     switch (codec_id) {
2129 #if LIBAVCODEC_VERSION_INT>((50<<16)+(1<<8)+0)
2130     case CV_CODEC(CODEC_ID_JPEGLS):
2131         // BGR24 or GRAY8 depending on is_color...
2132         // supported: bgr24 rgb24 gray gray16le
2133         // as of version 3.4.1
2134         codec_pix_fmt = input_pix_fmt;
2135         break;
2136 #endif
2137     case CV_CODEC(CODEC_ID_HUFFYUV):
2138         // supported: yuv422p rgb24 bgra
2139         // as of version 3.4.1
2140         switch(input_pix_fmt)
2141         {
2142             case AV_PIX_FMT_RGB24:
2143             case AV_PIX_FMT_BGRA:
2144                 codec_pix_fmt = input_pix_fmt;
2145                 break;
2146             case AV_PIX_FMT_BGR24:
2147                 codec_pix_fmt = AV_PIX_FMT_RGB24;
2148                 break;
2149             default:
2150                 codec_pix_fmt = AV_PIX_FMT_YUV422P;
2151                 break;
2152         }
2153         break;
2154     case CV_CODEC(CODEC_ID_PNG):
2155         // supported: rgb24 rgba rgb48be rgba64be pal8 gray ya8 gray16be ya16be monob
2156         // as of version 3.4.1
2157         switch(input_pix_fmt)
2158         {
2159             case AV_PIX_FMT_GRAY8:
2160             case AV_PIX_FMT_GRAY16BE:
2161             case AV_PIX_FMT_RGB24:
2162             case AV_PIX_FMT_BGRA:
2163                 codec_pix_fmt = input_pix_fmt;
2164                 break;
2165             case AV_PIX_FMT_GRAY16LE:
2166                 codec_pix_fmt = AV_PIX_FMT_GRAY16BE;
2167                 break;
2168             case AV_PIX_FMT_BGR24:
2169                 codec_pix_fmt = AV_PIX_FMT_RGB24;
2170                 break;
2171             default:
2172                 codec_pix_fmt = AV_PIX_FMT_YUV422P;
2173                 break;
2174         }
2175         break;
2176     case CV_CODEC(CODEC_ID_FFV1):
2177         // supported: MANY
2178         // as of version 3.4.1
2179         switch(input_pix_fmt)
2180         {
2181             case AV_PIX_FMT_GRAY8:
2182             case AV_PIX_FMT_GRAY16LE:
2183 #ifdef AV_PIX_FMT_BGR0
2184             case AV_PIX_FMT_BGR0:
2185 #endif
2186             case AV_PIX_FMT_BGRA:
2187                 codec_pix_fmt = input_pix_fmt;
2188                 break;
2189             case AV_PIX_FMT_GRAY16BE:
2190                 codec_pix_fmt = AV_PIX_FMT_GRAY16LE;
2191                 break;
2192             case AV_PIX_FMT_BGR24:
2193             case AV_PIX_FMT_RGB24:
2194 #ifdef AV_PIX_FMT_BGR0
2195                 codec_pix_fmt = AV_PIX_FMT_BGR0;
2196 #else
2197                 codec_pix_fmt = AV_PIX_FMT_BGRA;
2198 #endif
2199                 break;
2200             default:
2201                 codec_pix_fmt = AV_PIX_FMT_YUV422P;
2202                 break;
2203         }
2204         break;
2205     case CV_CODEC(CODEC_ID_MJPEG):
2206     case CV_CODEC(CODEC_ID_LJPEG):
2207         codec_pix_fmt = AV_PIX_FMT_YUVJ420P;
2208         bitrate_scale = 3;
2209         break;
2210     case CV_CODEC(CODEC_ID_RAWVIDEO):
2211         // RGBA is the only RGB fourcc supported by AVI and MKV format
2212         if(fourcc == CV_FOURCC('R','G','B','A'))
2213         {
2214             codec_pix_fmt = AV_PIX_FMT_RGBA;
2215         }
2216         else
2217         {
2218             switch(input_pix_fmt)
2219             {
2220                 case AV_PIX_FMT_GRAY8:
2221                 case AV_PIX_FMT_GRAY16LE:
2222                 case AV_PIX_FMT_GRAY16BE:
2223                     codec_pix_fmt = input_pix_fmt;
2224                     break;
2225                 default:
2226                     codec_pix_fmt = AV_PIX_FMT_YUV420P;
2227                     break;
2228             }
2229         }
2230         break;
2231     default:
2232         // good for lossy formats, MPEG, etc.
2233         codec_pix_fmt = AV_PIX_FMT_YUV420P;
2234         break;
2235     }
2236
2237     double bitrate = MIN(bitrate_scale*fps*width*height, (double)INT_MAX/2);
2238
2239     // TODO -- safe to ignore output audio stream?
2240     video_st = icv_add_video_stream_FFMPEG(oc, codec_id,
2241                                            width, height, (int)(bitrate + 0.5),
2242                                            fps, codec_pix_fmt);
2243
2244     /* set the output parameters (must be done even if no
2245    parameters). */
2246 #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
2247     if (av_set_parameters(oc, NULL) < 0) {
2248         return false;
2249     }
2250 #endif
2251
2252 #if 0
2253 #if FF_API_DUMP_FORMAT
2254     dump_format(oc, 0, filename, 1);
2255 #else
2256     av_dump_format(oc, 0, filename, 1);
2257 #endif
2258 #endif
2259
2260     /* now that all the parameters are set, we can open the audio and
2261      video codecs and allocate the necessary encode buffers */
2262     if (!video_st){
2263         return false;
2264     }
2265
2266     AVCodec *codec;
2267     AVCodecContext *c;
2268
2269 #if LIBAVFORMAT_BUILD > 4628
2270     c = (video_st->codec);
2271 #else
2272     c = &(video_st->codec);
2273 #endif
2274
2275     c->codec_tag = fourcc;
2276     /* find the video encoder */
2277     codec = avcodec_find_encoder(c->codec_id);
2278     if (!codec) {
2279         fprintf(stderr, "Could not find encoder for codec id %d: %s\n", c->codec_id, icvFFMPEGErrStr(
2280         #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
2281                 AVERROR_ENCODER_NOT_FOUND
2282         #else
2283                 -1
2284         #endif
2285                 ));
2286         return false;
2287     }
2288
2289     int64_t lbit_rate = (int64_t)c->bit_rate;
2290     lbit_rate += (bitrate / 2);
2291     lbit_rate = std::min(lbit_rate, (int64_t)INT_MAX);
2292     c->bit_rate_tolerance = (int)lbit_rate;
2293     c->bit_rate = (int)lbit_rate;
2294
2295     /* open the codec */
2296     if ((err=
2297 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2298          avcodec_open2(c, codec, NULL)
2299 #else
2300          avcodec_open(c, codec)
2301 #endif
2302          ) < 0) {
2303         fprintf(stderr, "Could not open codec '%s': %s\n", codec->name, icvFFMPEGErrStr(err));
2304         return false;
2305     }
2306
2307     outbuf = NULL;
2308
2309
2310 #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(57, 0, 0)
2311     if (!(oc->oformat->flags & AVFMT_RAWPICTURE))
2312 #endif
2313     {
2314         /* allocate output buffer */
2315         /* assume we will never get codec output with more than 4 bytes per pixel... */
2316         outbuf_size = width*height*4;
2317         outbuf = (uint8_t *) av_malloc(outbuf_size);
2318     }
2319
2320     bool need_color_convert;
2321     need_color_convert = (c->pix_fmt != input_pix_fmt);
2322
2323     /* allocate the encoded raw picture */
2324     picture = icv_alloc_picture_FFMPEG(c->pix_fmt, c->width, c->height, need_color_convert);
2325     if (!picture) {
2326         return false;
2327     }
2328
2329     /* if the output format is not our input format, then a temporary
2330    picture of the input format is needed too. It is then converted
2331    to the required output format */
2332     input_picture = NULL;
2333     if ( need_color_convert ) {
2334         input_picture = icv_alloc_picture_FFMPEG(input_pix_fmt, c->width, c->height, false);
2335         if (!input_picture) {
2336             return false;
2337         }
2338     }
2339
2340     /* open the output file, if needed */
2341     if (!(fmt->flags & AVFMT_NOFILE)) {
2342 #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
2343         if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0)
2344 #else
2345             if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0)
2346 #endif
2347             {
2348             return false;
2349         }
2350     }
2351
2352 #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
2353     /* write the stream header, if any */
2354     err=avformat_write_header(oc, NULL);
2355 #else
2356     err=av_write_header( oc );
2357 #endif
2358
2359     if(err < 0)
2360     {
2361         close();
2362         remove(filename);
2363         return false;
2364     }
2365     frame_width = width;
2366     frame_height = height;
2367     frame_idx = 0;
2368     ok = true;
2369
2370     return true;
2371 }
2372
2373
2374
2375 CvCapture_FFMPEG* cvCreateFileCapture_FFMPEG( const char* filename )
2376 {
2377     CvCapture_FFMPEG* capture = (CvCapture_FFMPEG*)malloc(sizeof(*capture));
2378     if (!capture)
2379         return 0;
2380     capture->init();
2381     if( capture->open( filename ))
2382         return capture;
2383
2384     capture->close();
2385     free(capture);
2386     return 0;
2387 }
2388
2389
2390 void cvReleaseCapture_FFMPEG(CvCapture_FFMPEG** capture)
2391 {
2392     if( capture && *capture )
2393     {
2394         (*capture)->close();
2395         free(*capture);
2396         *capture = 0;
2397     }
2398 }
2399
2400 int cvSetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id, double value)
2401 {
2402     return capture->setProperty(prop_id, value);
2403 }
2404
2405 double cvGetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id)
2406 {
2407     return capture->getProperty(prop_id);
2408 }
2409
2410 int cvGrabFrame_FFMPEG(CvCapture_FFMPEG* capture)
2411 {
2412     return capture->grabFrame();
2413 }
2414
2415 int cvRetrieveFrame_FFMPEG(CvCapture_FFMPEG* capture, unsigned char** data, int* step, int* width, int* height, int* cn)
2416 {
2417     return capture->retrieveFrame(0, data, step, width, height, cn);
2418 }
2419
2420 CvVideoWriter_FFMPEG* cvCreateVideoWriter_FFMPEG( const char* filename, int fourcc, double fps,
2421                                                   int width, int height, int isColor )
2422 {
2423     CvVideoWriter_FFMPEG* writer = (CvVideoWriter_FFMPEG*)malloc(sizeof(*writer));
2424     if (!writer)
2425         return 0;
2426     writer->init();
2427     if( writer->open( filename, fourcc, fps, width, height, isColor != 0 ))
2428         return writer;
2429     writer->close();
2430     free(writer);
2431     return 0;
2432 }
2433
2434 void cvReleaseVideoWriter_FFMPEG( CvVideoWriter_FFMPEG** writer )
2435 {
2436     if( writer && *writer )
2437     {
2438         (*writer)->close();
2439         free(*writer);
2440         *writer = 0;
2441     }
2442 }
2443
2444
2445 int cvWriteFrame_FFMPEG( CvVideoWriter_FFMPEG* writer,
2446                          const unsigned char* data, int step,
2447                          int width, int height, int cn, int origin)
2448 {
2449     return writer->writeFrame(data, step, width, height, cn, origin);
2450 }
2451
2452
2453
2454 /*
2455  * For CUDA encoder
2456  */
2457
2458 struct OutputMediaStream_FFMPEG
2459 {
2460     bool open(const char* fileName, int width, int height, double fps);
2461     void close();
2462
2463     void write(unsigned char* data, int size, int keyFrame);
2464
2465     // add a video output stream to the container
2466     static AVStream* addVideoStream(AVFormatContext *oc, CV_CODEC_ID codec_id, int w, int h, int bitrate, double fps, AVPixelFormat pixel_format);
2467
2468     AVOutputFormat* fmt_;
2469     AVFormatContext* oc_;
2470     AVStream* video_st_;
2471 };
2472
2473 void OutputMediaStream_FFMPEG::close()
2474 {
2475     // no more frame to compress. The codec has a latency of a few
2476     // frames if using B frames, so we get the last frames by
2477     // passing the same picture again
2478
2479     // TODO -- do we need to account for latency here?
2480
2481     if (oc_)
2482     {
2483         // write the trailer, if any
2484         av_write_trailer(oc_);
2485
2486         // free the streams
2487         for (unsigned int i = 0; i < oc_->nb_streams; ++i)
2488         {
2489             av_freep(&oc_->streams[i]->codec);
2490             av_freep(&oc_->streams[i]);
2491         }
2492
2493         if (!(fmt_->flags & AVFMT_NOFILE) && oc_->pb)
2494         {
2495             // close the output file
2496
2497             #if LIBAVCODEC_VERSION_INT < ((52<<16)+(123<<8)+0)
2498                 #if LIBAVCODEC_VERSION_INT >= ((51<<16)+(49<<8)+0)
2499                     url_fclose(oc_->pb);
2500                 #else
2501                     url_fclose(&oc_->pb);
2502                 #endif
2503             #else
2504                 avio_close(oc_->pb);
2505             #endif
2506         }
2507
2508         // free the stream
2509         av_free(oc_);
2510     }
2511 }
2512
2513 AVStream* OutputMediaStream_FFMPEG::addVideoStream(AVFormatContext *oc, CV_CODEC_ID codec_id, int w, int h, int bitrate, double fps, AVPixelFormat pixel_format)
2514 {
2515     AVCodec* codec = avcodec_find_encoder(codec_id);
2516     if (!codec)
2517     {
2518         fprintf(stderr, "Could not find encoder for codec id %d\n", codec_id);
2519         return NULL;
2520     }
2521
2522     #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 10, 0)
2523         AVStream* st = avformat_new_stream(oc, 0);
2524     #else
2525         AVStream* st = av_new_stream(oc, 0);
2526     #endif
2527     if (!st)
2528         return 0;
2529
2530     #if LIBAVFORMAT_BUILD > 4628
2531         AVCodecContext* c = st->codec;
2532     #else
2533         AVCodecContext* c = &(st->codec);
2534     #endif
2535
2536     c->codec_id = codec_id;
2537     c->codec_type = AVMEDIA_TYPE_VIDEO;
2538
2539     // put sample parameters
2540     c->bit_rate = bitrate;
2541
2542     // took advice from
2543     // http://ffmpeg-users.933282.n4.nabble.com/warning-clipping-1-dct-coefficients-to-127-127-td934297.html
2544     c->qmin = 3;
2545
2546     // resolution must be a multiple of two
2547     c->width = w;
2548     c->height = h;
2549
2550     // time base: this is the fundamental unit of time (in seconds) in terms
2551     // of which frame timestamps are represented. for fixed-fps content,
2552     // timebase should be 1/framerate and timestamp increments should be
2553     // identically 1
2554
2555     int frame_rate = static_cast<int>(fps+0.5);
2556     int frame_rate_base = 1;
2557     while (fabs((static_cast<double>(frame_rate)/frame_rate_base) - fps) > 0.001)
2558     {
2559         frame_rate_base *= 10;
2560         frame_rate = static_cast<int>(fps*frame_rate_base + 0.5);
2561     }
2562     c->time_base.den = frame_rate;
2563     c->time_base.num = frame_rate_base;
2564
2565     #if LIBAVFORMAT_BUILD > 4752
2566         // adjust time base for supported framerates
2567         if (codec && codec->supported_framerates)
2568         {
2569             AVRational req = {frame_rate, frame_rate_base};
2570             const AVRational* best = NULL;
2571             AVRational best_error = {INT_MAX, 1};
2572
2573             for (const AVRational* p = codec->supported_framerates; p->den!=0; ++p)
2574             {
2575                 AVRational error = av_sub_q(req, *p);
2576
2577                 if (error.num < 0)
2578                     error.num *= -1;
2579
2580                 if (av_cmp_q(error, best_error) < 0)
2581                 {
2582                     best_error= error;
2583                     best= p;
2584                 }
2585             }
2586
2587             if (best == NULL)
2588                 return NULL;
2589             c->time_base.den= best->num;
2590             c->time_base.num= best->den;
2591         }
2592     #endif
2593
2594     c->gop_size = 12; // emit one intra frame every twelve frames at most
2595     c->pix_fmt = pixel_format;
2596
2597     if (c->codec_id == CV_CODEC(CODEC_ID_MPEG2VIDEO))
2598         c->max_b_frames = 2;
2599
2600     if (c->codec_id == CV_CODEC(CODEC_ID_MPEG1VIDEO) || c->codec_id == CV_CODEC(CODEC_ID_MSMPEG4V3))
2601     {
2602         // needed to avoid using macroblocks in which some coeffs overflow
2603         // this doesn't happen with normal video, it just happens here as the
2604         // motion of the chroma plane doesn't match the luma plane
2605
2606         // avoid FFMPEG warning 'clipping 1 dct coefficients...'
2607
2608         c->mb_decision = 2;
2609     }
2610
2611     #if LIBAVCODEC_VERSION_INT > 0x000409
2612         // some formats want stream headers to be separate
2613         if (oc->oformat->flags & AVFMT_GLOBALHEADER)
2614         {
2615             #if LIBAVCODEC_BUILD > CALC_FFMPEG_VERSION(56, 35, 0)
2616                 c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2617             #else
2618                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
2619             #endif
2620         }
2621     #endif
2622
2623     return st;
2624 }
2625
2626 bool OutputMediaStream_FFMPEG::open(const char* fileName, int width, int height, double fps)
2627 {
2628     fmt_ = 0;
2629     oc_ = 0;
2630     video_st_ = 0;
2631
2632     // auto detect the output format from the name and fourcc code
2633     #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
2634         fmt_ = av_guess_format(NULL, fileName, NULL);
2635     #else
2636         fmt_ = guess_format(NULL, fileName, NULL);
2637     #endif
2638     if (!fmt_)
2639         return false;
2640
2641     CV_CODEC_ID codec_id = CV_CODEC(CODEC_ID_H264);
2642
2643     // alloc memory for context
2644     #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
2645         oc_ = avformat_alloc_context();
2646     #else
2647         oc_ = av_alloc_format_context();
2648     #endif
2649     if (!oc_)
2650         return false;
2651
2652     // set some options
2653     oc_->oformat = fmt_;
2654     snprintf(oc_->filename, sizeof(oc_->filename), "%s", fileName);
2655
2656     oc_->max_delay = (int)(0.7 * AV_TIME_BASE); // This reduces buffer underrun warnings with MPEG
2657
2658     // set a few optimal pixel formats for lossless codecs of interest..
2659     AVPixelFormat codec_pix_fmt = AV_PIX_FMT_YUV420P;
2660     int bitrate_scale = 64;
2661
2662     // TODO -- safe to ignore output audio stream?
2663     video_st_ = addVideoStream(oc_, codec_id, width, height, width * height * bitrate_scale, fps, codec_pix_fmt);
2664     if (!video_st_)
2665         return false;
2666
2667     // set the output parameters (must be done even if no parameters)
2668     #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
2669         if (av_set_parameters(oc_, NULL) < 0)
2670             return false;
2671     #endif
2672
2673     // now that all the parameters are set, we can open the audio and
2674     // video codecs and allocate the necessary encode buffers
2675
2676     #if LIBAVFORMAT_BUILD > 4628
2677         AVCodecContext* c = (video_st_->codec);
2678     #else
2679         AVCodecContext* c = &(video_st_->codec);
2680     #endif
2681
2682     c->codec_tag = MKTAG('H', '2', '6', '4');
2683     c->bit_rate_tolerance = c->bit_rate;
2684
2685     // open the output file, if needed
2686     if (!(fmt_->flags & AVFMT_NOFILE))
2687     {
2688         #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
2689             int err = url_fopen(&oc_->pb, fileName, URL_WRONLY);
2690         #else
2691             int err = avio_open(&oc_->pb, fileName, AVIO_FLAG_WRITE);
2692         #endif
2693
2694         if (err != 0)
2695             return false;
2696     }
2697
2698     // write the stream header, if any
2699     int header_err =
2700     #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
2701         av_write_header(oc_);
2702     #else
2703         avformat_write_header(oc_, NULL);
2704     #endif
2705     if (header_err != 0)
2706         return false;
2707
2708     return true;
2709 }
2710
2711 void OutputMediaStream_FFMPEG::write(unsigned char* data, int size, int keyFrame)
2712 {
2713     // if zero size, it means the image was buffered
2714     if (size > 0)
2715     {
2716         AVPacket pkt;
2717         av_init_packet(&pkt);
2718
2719         if (keyFrame)
2720             pkt.flags |= PKT_FLAG_KEY;
2721
2722         pkt.stream_index = video_st_->index;
2723         pkt.data = data;
2724         pkt.size = size;
2725
2726         // write the compressed frame in the media file
2727         av_write_frame(oc_, &pkt);
2728     }
2729 }
2730
2731 struct OutputMediaStream_FFMPEG* create_OutputMediaStream_FFMPEG(const char* fileName, int width, int height, double fps)
2732 {
2733     OutputMediaStream_FFMPEG* stream = (OutputMediaStream_FFMPEG*) malloc(sizeof(OutputMediaStream_FFMPEG));
2734     if (!stream)
2735         return 0;
2736
2737     if (stream->open(fileName, width, height, fps))
2738         return stream;
2739
2740     stream->close();
2741     free(stream);
2742
2743     return 0;
2744 }
2745
2746 void release_OutputMediaStream_FFMPEG(struct OutputMediaStream_FFMPEG* stream)
2747 {
2748     stream->close();
2749     free(stream);
2750 }
2751
2752 void write_OutputMediaStream_FFMPEG(struct OutputMediaStream_FFMPEG* stream, unsigned char* data, int size, int keyFrame)
2753 {
2754     stream->write(data, size, keyFrame);
2755 }
2756
2757 /*
2758  * For CUDA decoder
2759  */
2760
2761 enum
2762 {
2763     VideoCodec_MPEG1 = 0,
2764     VideoCodec_MPEG2,
2765     VideoCodec_MPEG4,
2766     VideoCodec_VC1,
2767     VideoCodec_H264,
2768     VideoCodec_JPEG,
2769     VideoCodec_H264_SVC,
2770     VideoCodec_H264_MVC,
2771
2772     // Uncompressed YUV
2773     VideoCodec_YUV420 = (('I'<<24)|('Y'<<16)|('U'<<8)|('V')),   // Y,U,V (4:2:0)
2774     VideoCodec_YV12   = (('Y'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,V,U (4:2:0)
2775     VideoCodec_NV12   = (('N'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,UV  (4:2:0)
2776     VideoCodec_YUYV   = (('Y'<<24)|('U'<<16)|('Y'<<8)|('V')),   // YUYV/YUY2 (4:2:2)
2777     VideoCodec_UYVY   = (('U'<<24)|('Y'<<16)|('V'<<8)|('Y'))    // UYVY (4:2:2)
2778 };
2779
2780 enum
2781 {
2782     VideoChromaFormat_Monochrome = 0,
2783     VideoChromaFormat_YUV420,
2784     VideoChromaFormat_YUV422,
2785     VideoChromaFormat_YUV444
2786 };
2787
2788 struct InputMediaStream_FFMPEG
2789 {
2790 public:
2791     bool open(const char* fileName, int* codec, int* chroma_format, int* width, int* height);
2792     void close();
2793
2794     bool read(unsigned char** data, int* size, int* endOfFile);
2795
2796 private:
2797     InputMediaStream_FFMPEG(const InputMediaStream_FFMPEG&);
2798     InputMediaStream_FFMPEG& operator =(const InputMediaStream_FFMPEG&);
2799
2800     AVFormatContext* ctx_;
2801     int video_stream_id_;
2802     AVPacket pkt_;
2803
2804 #if USE_AV_INTERRUPT_CALLBACK
2805     AVInterruptCallbackMetadata interrupt_metadata;
2806 #endif
2807 };
2808
2809 bool InputMediaStream_FFMPEG::open(const char* fileName, int* codec, int* chroma_format, int* width, int* height)
2810 {
2811     int err;
2812
2813     ctx_ = 0;
2814     video_stream_id_ = -1;
2815     memset(&pkt_, 0, sizeof(AVPacket));
2816
2817 #if USE_AV_INTERRUPT_CALLBACK
2818     /* interrupt callback */
2819     interrupt_metadata.timeout_after_ms = LIBAVFORMAT_INTERRUPT_OPEN_TIMEOUT_MS;
2820     get_monotonic_time(&interrupt_metadata.value);
2821
2822     ctx_ = avformat_alloc_context();
2823     ctx_->interrupt_callback.callback = _opencv_ffmpeg_interrupt_callback;
2824     ctx_->interrupt_callback.opaque = &interrupt_metadata;
2825 #endif
2826
2827     #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 13, 0)
2828         avformat_network_init();
2829     #endif
2830
2831     #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
2832         err = avformat_open_input(&ctx_, fileName, 0, 0);
2833     #else
2834         err = av_open_input_file(&ctx_, fileName, 0, 0, 0);
2835     #endif
2836     if (err < 0)
2837         return false;
2838
2839     #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
2840         err = avformat_find_stream_info(ctx_, 0);
2841     #else
2842         err = av_find_stream_info(ctx_);
2843     #endif
2844     if (err < 0)
2845         return false;
2846
2847     for (unsigned int i = 0; i < ctx_->nb_streams; ++i)
2848     {
2849         #if LIBAVFORMAT_BUILD > 4628
2850             AVCodecContext *enc = ctx_->streams[i]->codec;
2851         #else
2852             AVCodecContext *enc = &ctx_->streams[i]->codec;
2853         #endif
2854
2855         if (enc->codec_type == AVMEDIA_TYPE_VIDEO)
2856         {
2857             video_stream_id_ = static_cast<int>(i);
2858
2859             switch (enc->codec_id)
2860             {
2861             case CV_CODEC(CODEC_ID_MPEG1VIDEO):
2862                 *codec = ::VideoCodec_MPEG1;
2863                 break;
2864
2865             case CV_CODEC(CODEC_ID_MPEG2VIDEO):
2866                 *codec = ::VideoCodec_MPEG2;
2867                 break;
2868
2869             case CV_CODEC(CODEC_ID_MPEG4):
2870                 *codec = ::VideoCodec_MPEG4;
2871                 break;
2872
2873             case CV_CODEC(CODEC_ID_VC1):
2874                 *codec = ::VideoCodec_VC1;
2875                 break;
2876
2877             case CV_CODEC(CODEC_ID_H264):
2878                 *codec = ::VideoCodec_H264;
2879                 break;
2880
2881             default:
2882                 return false;
2883             };
2884
2885             switch (enc->pix_fmt)
2886             {
2887             case AV_PIX_FMT_YUV420P:
2888                 *chroma_format = ::VideoChromaFormat_YUV420;
2889                 break;
2890
2891             case AV_PIX_FMT_YUV422P:
2892                 *chroma_format = ::VideoChromaFormat_YUV422;
2893                 break;
2894
2895             case AV_PIX_FMT_YUV444P:
2896                 *chroma_format = ::VideoChromaFormat_YUV444;
2897                 break;
2898
2899             default:
2900                 return false;
2901             }
2902
2903             *width = enc->coded_width;
2904             *height = enc->coded_height;
2905
2906             break;
2907         }
2908     }
2909
2910     if (video_stream_id_ < 0)
2911         return false;
2912
2913     av_init_packet(&pkt_);
2914
2915 #if USE_AV_INTERRUPT_CALLBACK
2916     // deactivate interrupt callback
2917     interrupt_metadata.timeout_after_ms = 0;
2918 #endif
2919
2920     return true;
2921 }
2922
2923 void InputMediaStream_FFMPEG::close()
2924 {
2925     if (ctx_)
2926     {
2927         #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 24, 2)
2928             avformat_close_input(&ctx_);
2929         #else
2930             av_close_input_file(ctx_);
2931         #endif
2932     }
2933
2934     // free last packet if exist
2935     if (pkt_.data)
2936         _opencv_ffmpeg_av_packet_unref(&pkt_);
2937 }
2938
2939 bool InputMediaStream_FFMPEG::read(unsigned char** data, int* size, int* endOfFile)
2940 {
2941     bool result = false;
2942
2943 #if USE_AV_INTERRUPT_CALLBACK
2944     // activate interrupt callback
2945     get_monotonic_time(&interrupt_metadata.value);
2946     interrupt_metadata.timeout_after_ms = LIBAVFORMAT_INTERRUPT_READ_TIMEOUT_MS;
2947 #endif
2948
2949     // free last packet if exist
2950     if (pkt_.data)
2951         _opencv_ffmpeg_av_packet_unref(&pkt_);
2952
2953     // get the next frame
2954     for (;;)
2955     {
2956 #if USE_AV_INTERRUPT_CALLBACK
2957         if(interrupt_metadata.timeout)
2958         {
2959             break;
2960         }
2961 #endif
2962
2963         int ret = av_read_frame(ctx_, &pkt_);
2964
2965         if (ret == AVERROR(EAGAIN))
2966             continue;
2967
2968         if (ret < 0)
2969         {
2970             if (ret == (int)AVERROR_EOF)
2971                 *endOfFile = true;
2972             break;
2973         }
2974
2975         if (pkt_.stream_index != video_stream_id_)
2976         {
2977             _opencv_ffmpeg_av_packet_unref(&pkt_);
2978             continue;
2979         }
2980
2981         result = true;
2982         break;
2983     }
2984
2985 #if USE_AV_INTERRUPT_CALLBACK
2986     // deactivate interrupt callback
2987     interrupt_metadata.timeout_after_ms = 0;
2988 #endif
2989
2990     if (result)
2991     {
2992         *data = pkt_.data;
2993         *size = pkt_.size;
2994         *endOfFile = false;
2995     }
2996
2997     return result;
2998 }
2999
3000 InputMediaStream_FFMPEG* create_InputMediaStream_FFMPEG(const char* fileName, int* codec, int* chroma_format, int* width, int* height)
3001 {
3002     InputMediaStream_FFMPEG* stream = (InputMediaStream_FFMPEG*) malloc(sizeof(InputMediaStream_FFMPEG));
3003     if (!stream)
3004         return 0;
3005
3006     if (stream && stream->open(fileName, codec, chroma_format, width, height))
3007         return stream;
3008
3009     stream->close();
3010     free(stream);
3011
3012     return 0;
3013 }
3014
3015 void release_InputMediaStream_FFMPEG(InputMediaStream_FFMPEG* stream)
3016 {
3017     stream->close();
3018     free(stream);
3019 }
3020
3021 int read_InputMediaStream_FFMPEG(InputMediaStream_FFMPEG* stream, unsigned char** data, int* size, int* endOfFile)
3022 {
3023     return stream->read(data, size, endOfFile);
3024 }