~paparazzi-uav/paparazzi/v5.0-manual

« back to all changes in this revision

Viewing changes to sw/ext/opencv_bebop/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp

  • Committer: Paparazzi buildbot
  • Date: 2016-05-18 15:00:29 UTC
  • Revision ID: felix.ruess+docbot@gmail.com-20160518150029-e8lgzi5kvb4p7un9
Manual import commit 4b8bbb730080dac23cf816b98908dacfabe2a8ec from v5.0 branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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(_WIN32) || defined(WINCE))
 
45
# include <pthread.h>
 
46
#endif
 
47
#include <assert.h>
 
48
#include <algorithm>
 
49
#include <limits>
 
50
 
 
51
#define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c )
 
52
 
 
53
#if defined _MSC_VER && _MSC_VER >= 1200
 
54
#pragma warning( disable: 4244 4510 4512 4610 )
 
55
#endif
 
56
 
 
57
#ifdef __GNUC__
 
58
#  pragma GCC diagnostic ignored "-Wdeprecated-declarations"
 
59
#endif
 
60
 
 
61
#ifdef __cplusplus
 
62
extern "C" {
 
63
#endif
 
64
 
 
65
#include "ffmpeg_codecs.hpp"
 
66
 
 
67
#include <libavutil/mathematics.h>
 
68
 
 
69
#if LIBAVUTIL_BUILD > CALC_FFMPEG_VERSION(51,11,0)
 
70
  #include <libavutil/opt.h>
 
71
#endif
 
72
 
 
73
#ifdef WIN32
 
74
  #define HAVE_FFMPEG_SWSCALE 1
 
75
  #include <libavcodec/avcodec.h>
 
76
  #include <libswscale/swscale.h>
 
77
#else
 
78
 
 
79
#ifndef HAVE_FFMPEG_SWSCALE
 
80
    #error "libswscale is necessary to build the newer OpenCV ffmpeg wrapper"
 
81
#endif
 
82
 
 
83
// if the header path is not specified explicitly, let's deduce it
 
84
#if !defined HAVE_FFMPEG_AVCODEC_H && !defined HAVE_LIBAVCODEC_AVCODEC_H
 
85
 
 
86
#if defined(HAVE_GENTOO_FFMPEG)
 
87
  #define HAVE_LIBAVCODEC_AVCODEC_H 1
 
88
  #if defined(HAVE_FFMPEG_SWSCALE)
 
89
    #define HAVE_LIBSWSCALE_SWSCALE_H 1
 
90
  #endif
 
91
#elif defined HAVE_FFMPEG
 
92
  #define HAVE_FFMPEG_AVCODEC_H 1
 
93
  #if defined(HAVE_FFMPEG_SWSCALE)
 
94
    #define HAVE_FFMPEG_SWSCALE_H 1
 
95
  #endif
 
96
#endif
 
97
 
 
98
#endif
 
99
 
 
100
#if defined(HAVE_FFMPEG_AVCODEC_H)
 
101
  #include <ffmpeg/avcodec.h>
 
102
#endif
 
103
#if defined(HAVE_FFMPEG_SWSCALE_H)
 
104
  #include <ffmpeg/swscale.h>
 
105
#endif
 
106
 
 
107
#if defined(HAVE_LIBAVCODEC_AVCODEC_H)
 
108
  #include <libavcodec/avcodec.h>
 
109
#endif
 
110
#if defined(HAVE_LIBSWSCALE_SWSCALE_H)
 
111
  #include <libswscale/swscale.h>
 
112
#endif
 
113
 
 
114
#endif
 
115
 
 
116
#ifdef __cplusplus
 
117
}
 
118
#endif
 
119
 
 
120
#if defined _MSC_VER && _MSC_VER >= 1200
 
121
#pragma warning( default: 4244 4510 4512 4610 )
 
122
#endif
 
123
 
 
124
#ifdef NDEBUG
 
125
#define CV_WARN(message)
 
126
#else
 
127
#define CV_WARN(message) fprintf(stderr, "warning: %s (%s:%d)\n", message, __FILE__, __LINE__)
 
128
#endif
 
129
 
 
130
#if defined WIN32 || defined _WIN32
 
131
    #include <windows.h>
 
132
#elif defined __linux__ || defined __APPLE__
 
133
    #include <unistd.h>
 
134
    #include <stdio.h>
 
135
    #include <sys/types.h>
 
136
#if defined __APPLE__
 
137
    #include <sys/sysctl.h>
 
138
#endif
 
139
#endif
 
140
 
 
141
#ifndef MIN
 
142
#define MIN(a, b) ((a) < (b) ? (a) : (b))
 
143
#endif
 
144
 
 
145
#if defined(__APPLE__)
 
146
#define AV_NOPTS_VALUE_ ((int64_t)0x8000000000000000LL)
 
147
#else
 
148
#define AV_NOPTS_VALUE_ ((int64_t)AV_NOPTS_VALUE)
 
149
#endif
 
150
 
 
151
#ifndef AVERROR_EOF
 
152
#define AVERROR_EOF (-MKTAG( 'E','O','F',' '))
 
153
#endif
 
154
 
 
155
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54,25,0)
 
156
#  define CV_CODEC_ID AVCodecID
 
157
#  define CV_CODEC(name) AV_##name
 
158
#else
 
159
#  define CV_CODEC_ID CodecID
 
160
#  define CV_CODEC(name) name
 
161
#endif
 
162
 
 
163
#if LIBAVUTIL_BUILD < (LIBAVUTIL_VERSION_MICRO >= 100 \
 
164
    ? CALC_FFMPEG_VERSION(51, 74, 100) : CALC_FFMPEG_VERSION(51, 42, 0))
 
165
#define AVPixelFormat PixelFormat
 
166
#define AV_PIX_FMT_BGR24 PIX_FMT_BGR24
 
167
#define AV_PIX_FMT_RGB24 PIX_FMT_RGB24
 
168
#define AV_PIX_FMT_GRAY8 PIX_FMT_GRAY8
 
169
#define AV_PIX_FMT_YUV422P PIX_FMT_YUV422P
 
170
#define AV_PIX_FMT_YUV420P PIX_FMT_YUV420P
 
171
#define AV_PIX_FMT_YUV444P PIX_FMT_YUV444P
 
172
#define AV_PIX_FMT_YUVJ420P PIX_FMT_YUVJ420P
 
173
#define AV_PIX_FMT_GRAY16LE PIX_FMT_GRAY16LE
 
174
#define AV_PIX_FMT_GRAY16BE PIX_FMT_GRAY16BE
 
175
#endif
 
176
 
 
177
static int get_number_of_cpus(void)
 
178
{
 
179
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(52, 111, 0)
 
180
    return 1;
 
181
#elif defined WIN32 || defined _WIN32
 
182
    SYSTEM_INFO sysinfo;
 
183
    GetSystemInfo( &sysinfo );
 
184
 
 
185
    return (int)sysinfo.dwNumberOfProcessors;
 
186
#elif defined __linux__
 
187
    return (int)sysconf( _SC_NPROCESSORS_ONLN );
 
188
#elif defined __APPLE__
 
189
    int numCPU=0;
 
190
    int mib[4];
 
191
    size_t len = sizeof(numCPU);
 
192
 
 
193
    // set the mib for hw.ncpu
 
194
    mib[0] = CTL_HW;
 
195
    mib[1] = HW_AVAILCPU;  // alternatively, try HW_NCPU;
 
196
 
 
197
    // get the number of CPUs from the system
 
198
    sysctl(mib, 2, &numCPU, &len, NULL, 0);
 
199
 
 
200
    if( numCPU < 1 )
 
201
    {
 
202
        mib[1] = HW_NCPU;
 
203
        sysctl( mib, 2, &numCPU, &len, NULL, 0 );
 
204
 
 
205
        if( numCPU < 1 )
 
206
            numCPU = 1;
 
207
    }
 
208
 
 
209
    return (int)numCPU;
 
210
#else
 
211
    return 1;
 
212
#endif
 
213
}
 
214
 
 
215
 
 
216
struct Image_FFMPEG
 
217
{
 
218
    unsigned char* data;
 
219
    int step;
 
220
    int width;
 
221
    int height;
 
222
    int cn;
 
223
};
 
224
 
 
225
 
 
226
inline void _opencv_ffmpeg_free(void** ptr)
 
227
{
 
228
    if(*ptr) free(*ptr);
 
229
    *ptr = 0;
 
230
}
 
231
 
 
232
 
 
233
struct CvCapture_FFMPEG
 
234
{
 
235
    bool open( const char* filename );
 
236
    void close();
 
237
 
 
238
    double getProperty(int) const;
 
239
    bool setProperty(int, double);
 
240
    bool grabFrame();
 
241
    bool retrieveFrame(int, unsigned char** data, int* step, int* width, int* height, int* cn);
 
242
 
 
243
    void init();
 
244
 
 
245
    void    seek(int64_t frame_number);
 
246
    void    seek(double sec);
 
247
    bool    slowSeek( int framenumber );
 
248
 
 
249
    int64_t get_total_frames() const;
 
250
    double  get_duration_sec() const;
 
251
    double  get_fps() const;
 
252
    int     get_bitrate() const;
 
253
    AVRational get_sample_aspect_ratio(AVStream *stream) const;
 
254
 
 
255
    double  r2d(AVRational r) const;
 
256
    int64_t dts_to_frame_number(int64_t dts);
 
257
    double  dts_to_sec(int64_t dts);
 
258
 
 
259
    AVFormatContext * ic;
 
260
    AVCodec         * avcodec;
 
261
    int               video_stream;
 
262
    AVStream        * video_st;
 
263
    AVFrame         * picture;
 
264
    AVFrame           rgb_picture;
 
265
    int64_t           picture_pts;
 
266
 
 
267
    AVPacket          packet;
 
268
    Image_FFMPEG      frame;
 
269
    struct SwsContext *img_convert_ctx;
 
270
 
 
271
    int64_t frame_number, first_frame_number;
 
272
 
 
273
    double eps_zero;
 
274
/*
 
275
   'filename' contains the filename of the videosource,
 
276
   'filename==NULL' indicates that ffmpeg's seek support works
 
277
   for the particular file.
 
278
   'filename!=NULL' indicates that the slow fallback function is used for seeking,
 
279
   and so the filename is needed to reopen the file on backward seeking.
 
280
*/
 
281
    char              * filename;
 
282
 
 
283
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
 
284
    AVDictionary *dict;
 
285
#endif
 
286
};
 
287
 
 
288
void CvCapture_FFMPEG::init()
 
289
{
 
290
    ic = 0;
 
291
    video_stream = -1;
 
292
    video_st = 0;
 
293
    picture = 0;
 
294
    picture_pts = AV_NOPTS_VALUE_;
 
295
    first_frame_number = -1;
 
296
    memset( &rgb_picture, 0, sizeof(rgb_picture) );
 
297
    memset( &frame, 0, sizeof(frame) );
 
298
    filename = 0;
 
299
    memset(&packet, 0, sizeof(packet));
 
300
    av_init_packet(&packet);
 
301
    img_convert_ctx = 0;
 
302
 
 
303
    avcodec = 0;
 
304
    frame_number = 0;
 
305
    eps_zero = 0.000025;
 
306
 
 
307
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
 
308
    dict = NULL;
 
309
#endif
 
310
}
 
311
 
 
312
 
 
313
void CvCapture_FFMPEG::close()
 
314
{
 
315
    if( img_convert_ctx )
 
316
    {
 
317
        sws_freeContext(img_convert_ctx);
 
318
        img_convert_ctx = 0;
 
319
    }
 
320
 
 
321
    if( picture )
 
322
    {
 
323
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
 
324
    ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
 
325
        av_frame_free(&picture);
 
326
#elif LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
 
327
    ? CALC_FFMPEG_VERSION(54, 59, 100) : CALC_FFMPEG_VERSION(54, 28, 0))
 
328
        avcodec_free_frame(&picture);
 
329
#else
 
330
        av_free(picture);
 
331
#endif
 
332
    }
 
333
 
 
334
    if( video_st )
 
335
    {
 
336
#if LIBAVFORMAT_BUILD > 4628
 
337
        avcodec_close( video_st->codec );
 
338
 
 
339
#else
 
340
        avcodec_close( &(video_st->codec) );
 
341
 
 
342
#endif
 
343
        video_st = NULL;
 
344
    }
 
345
 
 
346
    if( ic )
 
347
    {
 
348
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 24, 2)
 
349
        av_close_input_file(ic);
 
350
#else
 
351
        avformat_close_input(&ic);
 
352
#endif
 
353
 
 
354
        ic = NULL;
 
355
    }
 
356
 
 
357
    if( rgb_picture.data[0] )
 
358
    {
 
359
        free( rgb_picture.data[0] );
 
360
        rgb_picture.data[0] = 0;
 
361
    }
 
362
 
 
363
    // free last packet if exist
 
364
    if (packet.data) {
 
365
        av_free_packet (&packet);
 
366
        packet.data = NULL;
 
367
    }
 
368
 
 
369
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
 
370
    if (dict != NULL)
 
371
       av_dict_free(&dict);
 
372
#endif
 
373
 
 
374
    init();
 
375
}
 
376
 
 
377
 
 
378
#ifndef AVSEEK_FLAG_FRAME
 
379
#define AVSEEK_FLAG_FRAME 0
 
380
#endif
 
381
#ifndef AVSEEK_FLAG_ANY
 
382
#define AVSEEK_FLAG_ANY 1
 
383
#endif
 
384
 
 
385
class ImplMutex
 
386
{
 
387
public:
 
388
    ImplMutex() { init(); }
 
389
    ~ImplMutex() { destroy(); }
 
390
 
 
391
    void init();
 
392
    void destroy();
 
393
 
 
394
    void lock();
 
395
    bool trylock();
 
396
    void unlock();
 
397
 
 
398
    struct Impl;
 
399
protected:
 
400
    Impl* impl;
 
401
 
 
402
private:
 
403
    ImplMutex(const ImplMutex&);
 
404
    ImplMutex& operator = (const ImplMutex& m);
 
405
};
 
406
 
 
407
#if defined WIN32 || defined _WIN32 || defined WINCE
 
408
 
 
409
struct ImplMutex::Impl
 
410
{
 
411
    void init()
 
412
    {
 
413
#if (_WIN32_WINNT >= 0x0600)
 
414
        ::InitializeCriticalSectionEx(&cs, 1000, 0);
 
415
#else
 
416
        ::InitializeCriticalSection(&cs);
 
417
#endif
 
418
        refcount = 1;
 
419
    }
 
420
    void destroy() { DeleteCriticalSection(&cs); }
 
421
 
 
422
    void lock() { EnterCriticalSection(&cs); }
 
423
    bool trylock() { return TryEnterCriticalSection(&cs) != 0; }
 
424
    void unlock() { LeaveCriticalSection(&cs); }
 
425
 
 
426
    CRITICAL_SECTION cs;
 
427
    int refcount;
 
428
};
 
429
 
 
430
#ifndef __GNUC__
 
431
static int _interlockedExchangeAdd(int* addr, int delta)
 
432
{
 
433
#if defined _MSC_VER && _MSC_VER >= 1500
 
434
    return (int)_InterlockedExchangeAdd((long volatile*)addr, delta);
 
435
#else
 
436
    return (int)InterlockedExchangeAdd((long volatile*)addr, delta);
 
437
#endif
 
438
}
 
439
#endif // __GNUC__
 
440
 
 
441
#elif defined __APPLE__
 
442
 
 
443
#include <libkern/OSAtomic.h>
 
444
 
 
445
struct ImplMutex::Impl
 
446
{
 
447
    void init() { sl = OS_SPINLOCK_INIT; refcount = 1; }
 
448
    void destroy() { }
 
449
 
 
450
    void lock() { OSSpinLockLock(&sl); }
 
451
    bool trylock() { return OSSpinLockTry(&sl); }
 
452
    void unlock() { OSSpinLockUnlock(&sl); }
 
453
 
 
454
    OSSpinLock sl;
 
455
    int refcount;
 
456
};
 
457
 
 
458
#elif defined __linux__ && !defined ANDROID
 
459
 
 
460
struct ImplMutex::Impl
 
461
{
 
462
    void init() { pthread_spin_init(&sl, 0); refcount = 1; }
 
463
    void destroy() { pthread_spin_destroy(&sl); }
 
464
 
 
465
    void lock() { pthread_spin_lock(&sl); }
 
466
    bool trylock() { return pthread_spin_trylock(&sl) == 0; }
 
467
    void unlock() { pthread_spin_unlock(&sl); }
 
468
 
 
469
    pthread_spinlock_t sl;
 
470
    int refcount;
 
471
};
 
472
 
 
473
#else
 
474
 
 
475
struct ImplMutex::Impl
 
476
{
 
477
    void init() { pthread_mutex_init(&sl, 0); refcount = 1; }
 
478
    void destroy() { pthread_mutex_destroy(&sl); }
 
479
 
 
480
    void lock() { pthread_mutex_lock(&sl); }
 
481
    bool trylock() { return pthread_mutex_trylock(&sl) == 0; }
 
482
    void unlock() { pthread_mutex_unlock(&sl); }
 
483
 
 
484
    pthread_mutex_t sl;
 
485
    int refcount;
 
486
};
 
487
 
 
488
#endif
 
489
 
 
490
void ImplMutex::init()
 
491
{
 
492
    impl = (Impl*)malloc(sizeof(Impl));
 
493
    impl->init();
 
494
}
 
495
void ImplMutex::destroy()
 
496
{
 
497
    impl->destroy();
 
498
    free(impl);
 
499
    impl = NULL;
 
500
}
 
501
void ImplMutex::lock() { impl->lock(); }
 
502
void ImplMutex::unlock() { impl->unlock(); }
 
503
bool ImplMutex::trylock() { return impl->trylock(); }
 
504
 
 
505
static int LockCallBack(void **mutex, AVLockOp op)
 
506
{
 
507
    ImplMutex* localMutex = reinterpret_cast<ImplMutex*>(*mutex);
 
508
    switch (op)
 
509
    {
 
510
        case AV_LOCK_CREATE:
 
511
            localMutex = reinterpret_cast<ImplMutex*>(malloc(sizeof(ImplMutex)));
 
512
            localMutex->init();
 
513
            *mutex = localMutex;
 
514
            if (!*mutex)
 
515
                return 1;
 
516
        break;
 
517
 
 
518
        case AV_LOCK_OBTAIN:
 
519
            localMutex->lock();
 
520
        break;
 
521
 
 
522
        case AV_LOCK_RELEASE:
 
523
            localMutex->unlock();
 
524
        break;
 
525
 
 
526
        case AV_LOCK_DESTROY:
 
527
            localMutex->destroy();
 
528
            free(localMutex);
 
529
            localMutex = NULL;
 
530
            *mutex = NULL;
 
531
        break;
 
532
    }
 
533
    return 0;
 
534
}
 
535
 
 
536
static ImplMutex _mutex;
 
537
static bool _initialized = false;
 
538
 
 
539
class InternalFFMpegRegister
 
540
{
 
541
public:
 
542
    InternalFFMpegRegister()
 
543
    {
 
544
        _mutex.lock();
 
545
        if (!_initialized)
 
546
        {
 
547
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 13, 0)
 
548
            avformat_network_init();
 
549
    #endif
 
550
 
 
551
            /* register all codecs, demux and protocols */
 
552
            av_register_all();
 
553
 
 
554
            /* register a callback function for synchronization */
 
555
            av_lockmgr_register(&LockCallBack);
 
556
 
 
557
            av_log_set_level(AV_LOG_ERROR);
 
558
 
 
559
            _initialized = true;
 
560
        }
 
561
        _mutex.unlock();
 
562
    }
 
563
 
 
564
    ~InternalFFMpegRegister()
 
565
    {
 
566
        _initialized = false;
 
567
        av_lockmgr_register(NULL);
 
568
    }
 
569
};
 
570
 
 
571
static InternalFFMpegRegister _init;
 
572
 
 
573
bool CvCapture_FFMPEG::open( const char* _filename )
 
574
{
 
575
    unsigned i;
 
576
    bool valid = false;
 
577
 
 
578
    close();
 
579
 
 
580
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
 
581
    av_dict_set(&dict, "rtsp_transport", "tcp", 0);
 
582
    int err = avformat_open_input(&ic, _filename, NULL, &dict);
 
583
#else
 
584
    int err = av_open_input_file(&ic, _filename, NULL, 0, NULL);
 
585
#endif
 
586
 
 
587
    if (err < 0)
 
588
    {
 
589
        CV_WARN("Error opening file");
 
590
        CV_WARN(_filename);
 
591
        goto exit_func;
 
592
    }
 
593
    err =
 
594
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
 
595
    avformat_find_stream_info(ic, NULL);
 
596
#else
 
597
    av_find_stream_info(ic);
 
598
#endif
 
599
    if (err < 0)
 
600
    {
 
601
        CV_WARN("Could not find codec parameters");
 
602
        goto exit_func;
 
603
    }
 
604
    for(i = 0; i < ic->nb_streams; i++)
 
605
    {
 
606
#if LIBAVFORMAT_BUILD > 4628
 
607
        AVCodecContext *enc = ic->streams[i]->codec;
 
608
#else
 
609
        AVCodecContext *enc = &ic->streams[i]->codec;
 
610
#endif
 
611
 
 
612
//#ifdef FF_API_THREAD_INIT
 
613
//        avcodec_thread_init(enc, get_number_of_cpus());
 
614
//#else
 
615
        enc->thread_count = get_number_of_cpus();
 
616
//#endif
 
617
 
 
618
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
 
619
#define AVMEDIA_TYPE_VIDEO CODEC_TYPE_VIDEO
 
620
#endif
 
621
 
 
622
        if( AVMEDIA_TYPE_VIDEO == enc->codec_type && video_stream < 0)
 
623
        {
 
624
            // backup encoder' width/height
 
625
            int enc_width = enc->width;
 
626
            int enc_height = enc->height;
 
627
 
 
628
            AVCodec *codec = avcodec_find_decoder(enc->codec_id);
 
629
            if (!codec ||
 
630
#if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
 
631
                avcodec_open2(enc, codec, NULL)
 
632
#else
 
633
                avcodec_open(enc, codec)
 
634
#endif
 
635
                < 0)
 
636
                goto exit_func;
 
637
 
 
638
            // checking width/height (since decoder can sometimes alter it, eg. vp6f)
 
639
            if (enc_width && (enc->width != enc_width)) { enc->width = enc_width; }
 
640
            if (enc_height && (enc->height != enc_height)) { enc->height = enc_height; }
 
641
 
 
642
            video_stream = i;
 
643
            video_st = ic->streams[i];
 
644
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
 
645
    ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
 
646
            picture = av_frame_alloc();
 
647
#else
 
648
            picture = avcodec_alloc_frame();
 
649
#endif
 
650
 
 
651
            rgb_picture.data[0] = (uint8_t*)malloc(
 
652
                    avpicture_get_size( AV_PIX_FMT_BGR24,
 
653
                                        enc->width, enc->height ));
 
654
            avpicture_fill( (AVPicture*)&rgb_picture, rgb_picture.data[0],
 
655
                            AV_PIX_FMT_BGR24, enc->width, enc->height );
 
656
 
 
657
            frame.width = enc->width;
 
658
            frame.height = enc->height;
 
659
            frame.cn = 3;
 
660
            frame.step = rgb_picture.linesize[0];
 
661
            frame.data = rgb_picture.data[0];
 
662
            break;
 
663
        }
 
664
    }
 
665
 
 
666
    if(video_stream >= 0) valid = true;
 
667
 
 
668
exit_func:
 
669
 
 
670
    if( !valid )
 
671
        close();
 
672
 
 
673
    return valid;
 
674
}
 
675
 
 
676
 
 
677
bool CvCapture_FFMPEG::grabFrame()
 
678
{
 
679
    bool valid = false;
 
680
    int got_picture;
 
681
 
 
682
    int count_errs = 0;
 
683
    const int max_number_of_attempts = 1 << 9;
 
684
 
 
685
    if( !ic || !video_st )  return false;
 
686
 
 
687
    if( ic->streams[video_stream]->nb_frames > 0 &&
 
688
        frame_number > ic->streams[video_stream]->nb_frames )
 
689
        return false;
 
690
 
 
691
    picture_pts = AV_NOPTS_VALUE_;
 
692
 
 
693
    // get the next frame
 
694
    while (!valid)
 
695
    {
 
696
 
 
697
        av_free_packet (&packet);
 
698
        int ret = av_read_frame(ic, &packet);
 
699
        if (ret == AVERROR(EAGAIN)) continue;
 
700
 
 
701
        /* else if (ret < 0) break; */
 
702
 
 
703
        if( packet.stream_index != video_stream )
 
704
        {
 
705
            av_free_packet (&packet);
 
706
            count_errs++;
 
707
            if (count_errs > max_number_of_attempts)
 
708
                break;
 
709
            continue;
 
710
        }
 
711
 
 
712
        // Decode video frame
 
713
        #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
 
714
            avcodec_decode_video2(video_st->codec, picture, &got_picture, &packet);
 
715
        #elif LIBAVFORMAT_BUILD > 4628
 
716
                avcodec_decode_video(video_st->codec,
 
717
                                     picture, &got_picture,
 
718
                                     packet.data, packet.size);
 
719
        #else
 
720
                avcodec_decode_video(&video_st->codec,
 
721
                                     picture, &got_picture,
 
722
                                     packet.data, packet.size);
 
723
        #endif
 
724
 
 
725
        // Did we get a video frame?
 
726
        if(got_picture)
 
727
        {
 
728
            //picture_pts = picture->best_effort_timestamp;
 
729
            if( picture_pts == AV_NOPTS_VALUE_ )
 
730
                picture_pts = packet.pts != AV_NOPTS_VALUE_ && packet.pts != 0 ? packet.pts : packet.dts;
 
731
            frame_number++;
 
732
            valid = true;
 
733
        }
 
734
        else
 
735
        {
 
736
            count_errs++;
 
737
            if (count_errs > max_number_of_attempts)
 
738
                break;
 
739
        }
 
740
    }
 
741
 
 
742
    if( valid && first_frame_number < 0 )
 
743
        first_frame_number = dts_to_frame_number(picture_pts);
 
744
 
 
745
    // return if we have a new picture or not
 
746
    return valid;
 
747
}
 
748
 
 
749
 
 
750
bool CvCapture_FFMPEG::retrieveFrame(int, unsigned char** data, int* step, int* width, int* height, int* cn)
 
751
{
 
752
    if( !video_st || !picture->data[0] )
 
753
        return false;
 
754
 
 
755
    if( img_convert_ctx == NULL ||
 
756
        frame.width != video_st->codec->width ||
 
757
        frame.height != video_st->codec->height )
 
758
    {
 
759
        if( img_convert_ctx )
 
760
            sws_freeContext(img_convert_ctx);
 
761
 
 
762
        frame.width = video_st->codec->width;
 
763
        frame.height = video_st->codec->height;
 
764
 
 
765
        img_convert_ctx = sws_getCachedContext(
 
766
                NULL,
 
767
                video_st->codec->width, video_st->codec->height,
 
768
                video_st->codec->pix_fmt,
 
769
                video_st->codec->width, video_st->codec->height,
 
770
                AV_PIX_FMT_BGR24,
 
771
                SWS_BICUBIC,
 
772
                NULL, NULL, NULL
 
773
                );
 
774
 
 
775
        if (img_convert_ctx == NULL)
 
776
            return false;//CV_Error(0, "Cannot initialize the conversion context!");
 
777
 
 
778
        rgb_picture.data[0] = (uint8_t*)realloc(rgb_picture.data[0],
 
779
                avpicture_get_size( AV_PIX_FMT_BGR24,
 
780
                                    video_st->codec->width, video_st->codec->height ));
 
781
        frame.data = rgb_picture.data[0];
 
782
    }
 
783
 
 
784
    avpicture_fill((AVPicture*)&rgb_picture, rgb_picture.data[0], AV_PIX_FMT_RGB24,
 
785
                   video_st->codec->width, video_st->codec->height);
 
786
    frame.step = rgb_picture.linesize[0];
 
787
 
 
788
    sws_scale(
 
789
            img_convert_ctx,
 
790
            picture->data,
 
791
            picture->linesize,
 
792
            0, video_st->codec->height,
 
793
            rgb_picture.data,
 
794
            rgb_picture.linesize
 
795
            );
 
796
 
 
797
    *data = frame.data;
 
798
    *step = frame.step;
 
799
    *width = frame.width;
 
800
    *height = frame.height;
 
801
    *cn = frame.cn;
 
802
 
 
803
    return true;
 
804
}
 
805
 
 
806
 
 
807
double CvCapture_FFMPEG::getProperty( int property_id ) const
 
808
{
 
809
    if( !video_st ) return 0;
 
810
 
 
811
    switch( property_id )
 
812
    {
 
813
    case CV_FFMPEG_CAP_PROP_POS_MSEC:
 
814
        return 1000.0*(double)frame_number/get_fps();
 
815
    case CV_FFMPEG_CAP_PROP_POS_FRAMES:
 
816
        return (double)frame_number;
 
817
    case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
 
818
        return r2d(ic->streams[video_stream]->time_base);
 
819
    case CV_FFMPEG_CAP_PROP_FRAME_COUNT:
 
820
        return (double)get_total_frames();
 
821
    case CV_FFMPEG_CAP_PROP_FRAME_WIDTH:
 
822
        return (double)frame.width;
 
823
    case CV_FFMPEG_CAP_PROP_FRAME_HEIGHT:
 
824
        return (double)frame.height;
 
825
    case CV_FFMPEG_CAP_PROP_FPS:
 
826
        return get_fps();
 
827
    case CV_FFMPEG_CAP_PROP_FOURCC:
 
828
#if LIBAVFORMAT_BUILD > 4628
 
829
        return (double)video_st->codec->codec_tag;
 
830
#else
 
831
        return (double)video_st->codec.codec_tag;
 
832
#endif
 
833
    case CV_FFMPEG_CAP_PROP_SAR_NUM:
 
834
        return get_sample_aspect_ratio(ic->streams[video_stream]).num;
 
835
    case CV_FFMPEG_CAP_PROP_SAR_DEN:
 
836
        return get_sample_aspect_ratio(ic->streams[video_stream]).den;
 
837
    default:
 
838
        break;
 
839
    }
 
840
 
 
841
    return 0;
 
842
}
 
843
 
 
844
double CvCapture_FFMPEG::r2d(AVRational r) const
 
845
{
 
846
    return r.num == 0 || r.den == 0 ? 0. : (double)r.num / (double)r.den;
 
847
}
 
848
 
 
849
double CvCapture_FFMPEG::get_duration_sec() const
 
850
{
 
851
    double sec = (double)ic->duration / (double)AV_TIME_BASE;
 
852
 
 
853
    if (sec < eps_zero)
 
854
    {
 
855
        sec = (double)ic->streams[video_stream]->duration * r2d(ic->streams[video_stream]->time_base);
 
856
    }
 
857
 
 
858
    if (sec < eps_zero)
 
859
    {
 
860
        sec = (double)ic->streams[video_stream]->duration * r2d(ic->streams[video_stream]->time_base);
 
861
    }
 
862
 
 
863
    return sec;
 
864
}
 
865
 
 
866
int CvCapture_FFMPEG::get_bitrate() const
 
867
{
 
868
    return ic->bit_rate;
 
869
}
 
870
 
 
871
double CvCapture_FFMPEG::get_fps() const
 
872
{
 
873
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54, 1, 0)
 
874
    double fps = r2d(ic->streams[video_stream]->avg_frame_rate);
 
875
#else
 
876
    double fps = r2d(ic->streams[video_stream]->r_frame_rate);
 
877
#endif
 
878
 
 
879
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
 
880
    if (fps < eps_zero)
 
881
    {
 
882
        fps = r2d(ic->streams[video_stream]->avg_frame_rate);
 
883
    }
 
884
#endif
 
885
 
 
886
    if (fps < eps_zero)
 
887
    {
 
888
        fps = 1.0 / r2d(ic->streams[video_stream]->codec->time_base);
 
889
    }
 
890
 
 
891
    return fps;
 
892
}
 
893
 
 
894
int64_t CvCapture_FFMPEG::get_total_frames() const
 
895
{
 
896
    int64_t nbf = ic->streams[video_stream]->nb_frames;
 
897
 
 
898
    if (nbf == 0)
 
899
    {
 
900
        nbf = (int64_t)floor(get_duration_sec() * get_fps() + 0.5);
 
901
    }
 
902
    return nbf;
 
903
}
 
904
 
 
905
int64_t CvCapture_FFMPEG::dts_to_frame_number(int64_t dts)
 
906
{
 
907
    double sec = dts_to_sec(dts);
 
908
    return (int64_t)(get_fps() * sec + 0.5);
 
909
}
 
910
 
 
911
AVRational CvCapture_FFMPEG::get_sample_aspect_ratio(AVStream *stream) const
 
912
{
 
913
    AVRational undef = {0, 1};
 
914
    AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
 
915
    AVRational frame_sample_aspect_ratio  = stream && stream->codec ? stream->codec->sample_aspect_ratio : undef;
 
916
 
 
917
    av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
 
918
        stream_sample_aspect_ratio.num,  stream_sample_aspect_ratio.den, INT_MAX);
 
919
    if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
 
920
        stream_sample_aspect_ratio = undef;
 
921
 
 
922
    av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
 
923
        frame_sample_aspect_ratio.num,  frame_sample_aspect_ratio.den, INT_MAX);
 
924
    if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
 
925
        frame_sample_aspect_ratio = undef;
 
926
 
 
927
    if (stream_sample_aspect_ratio.num)
 
928
        return stream_sample_aspect_ratio;
 
929
    else
 
930
        return frame_sample_aspect_ratio;
 
931
}
 
932
 
 
933
double CvCapture_FFMPEG::dts_to_sec(int64_t dts)
 
934
{
 
935
    return (double)(dts - ic->streams[video_stream]->start_time) *
 
936
        r2d(ic->streams[video_stream]->time_base);
 
937
}
 
938
 
 
939
void CvCapture_FFMPEG::seek(int64_t _frame_number)
 
940
{
 
941
    _frame_number = std::min(_frame_number, get_total_frames());
 
942
    int delta = 16;
 
943
 
 
944
    // if we have not grabbed a single frame before first seek, let's read the first frame
 
945
    // and get some valuable information during the process
 
946
    if( first_frame_number < 0 && get_total_frames() > 1 )
 
947
        grabFrame();
 
948
 
 
949
    for(;;)
 
950
    {
 
951
        int64_t _frame_number_temp = std::max(_frame_number-delta, (int64_t)0);
 
952
        double sec = (double)_frame_number_temp / get_fps();
 
953
        int64_t time_stamp = ic->streams[video_stream]->start_time;
 
954
        double  time_base  = r2d(ic->streams[video_stream]->time_base);
 
955
        time_stamp += (int64_t)(sec / time_base + 0.5);
 
956
        if (get_total_frames() > 1) av_seek_frame(ic, video_stream, time_stamp, AVSEEK_FLAG_BACKWARD);
 
957
        avcodec_flush_buffers(ic->streams[video_stream]->codec);
 
958
        if( _frame_number > 0 )
 
959
        {
 
960
            grabFrame();
 
961
 
 
962
            if( _frame_number > 1 )
 
963
            {
 
964
                frame_number = dts_to_frame_number(picture_pts) - first_frame_number;
 
965
                //printf("_frame_number = %d, frame_number = %d, delta = %d\n",
 
966
                //       (int)_frame_number, (int)frame_number, delta);
 
967
 
 
968
                if( frame_number < 0 || frame_number > _frame_number-1 )
 
969
                {
 
970
                    if( _frame_number_temp == 0 || delta >= INT_MAX/4 )
 
971
                        break;
 
972
                    delta = delta < 16 ? delta*2 : delta*3/2;
 
973
                    continue;
 
974
                }
 
975
                while( frame_number < _frame_number-1 )
 
976
                {
 
977
                    if(!grabFrame())
 
978
                        break;
 
979
                }
 
980
                frame_number++;
 
981
                break;
 
982
            }
 
983
            else
 
984
            {
 
985
                frame_number = 1;
 
986
                break;
 
987
            }
 
988
        }
 
989
        else
 
990
        {
 
991
            frame_number = 0;
 
992
            break;
 
993
        }
 
994
    }
 
995
}
 
996
 
 
997
void CvCapture_FFMPEG::seek(double sec)
 
998
{
 
999
    seek((int64_t)(sec * get_fps() + 0.5));
 
1000
}
 
1001
 
 
1002
bool CvCapture_FFMPEG::setProperty( int property_id, double value )
 
1003
{
 
1004
    if( !video_st ) return false;
 
1005
 
 
1006
    switch( property_id )
 
1007
    {
 
1008
    case CV_FFMPEG_CAP_PROP_POS_MSEC:
 
1009
    case CV_FFMPEG_CAP_PROP_POS_FRAMES:
 
1010
    case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
 
1011
        {
 
1012
            switch( property_id )
 
1013
            {
 
1014
            case CV_FFMPEG_CAP_PROP_POS_FRAMES:
 
1015
                seek((int64_t)value);
 
1016
                break;
 
1017
 
 
1018
            case CV_FFMPEG_CAP_PROP_POS_MSEC:
 
1019
                seek(value/1000.0);
 
1020
                break;
 
1021
 
 
1022
            case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
 
1023
                seek((int64_t)(value*ic->duration));
 
1024
                break;
 
1025
            }
 
1026
 
 
1027
            picture_pts=(int64_t)value;
 
1028
        }
 
1029
        break;
 
1030
    default:
 
1031
        return false;
 
1032
    }
 
1033
 
 
1034
    return true;
 
1035
}
 
1036
 
 
1037
 
 
1038
///////////////// FFMPEG CvVideoWriter implementation //////////////////////////
 
1039
struct CvVideoWriter_FFMPEG
 
1040
{
 
1041
    bool open( const char* filename, int fourcc,
 
1042
               double fps, int width, int height, bool isColor );
 
1043
    void close();
 
1044
    bool writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin );
 
1045
 
 
1046
    void init();
 
1047
 
 
1048
    AVOutputFormat  * fmt;
 
1049
    AVFormatContext * oc;
 
1050
    uint8_t         * outbuf;
 
1051
    uint32_t          outbuf_size;
 
1052
    FILE            * outfile;
 
1053
    AVFrame         * picture;
 
1054
    AVFrame         * input_picture;
 
1055
    uint8_t         * picbuf;
 
1056
    AVStream        * video_st;
 
1057
    int               input_pix_fmt;
 
1058
    Image_FFMPEG      temp_image;
 
1059
    int               frame_width, frame_height;
 
1060
    int               frame_idx;
 
1061
    bool              ok;
 
1062
    struct SwsContext *img_convert_ctx;
 
1063
};
 
1064
 
 
1065
static const char * icvFFMPEGErrStr(int err)
 
1066
{
 
1067
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
 
1068
    switch(err) {
 
1069
    case AVERROR_BSF_NOT_FOUND:
 
1070
        return "Bitstream filter not found";
 
1071
    case AVERROR_DECODER_NOT_FOUND:
 
1072
        return "Decoder not found";
 
1073
    case AVERROR_DEMUXER_NOT_FOUND:
 
1074
        return "Demuxer not found";
 
1075
    case AVERROR_ENCODER_NOT_FOUND:
 
1076
        return "Encoder not found";
 
1077
    case AVERROR_EOF:
 
1078
        return "End of file";
 
1079
    case AVERROR_EXIT:
 
1080
        return "Immediate exit was requested; the called function should not be restarted";
 
1081
    case AVERROR_FILTER_NOT_FOUND:
 
1082
        return "Filter not found";
 
1083
    case AVERROR_INVALIDDATA:
 
1084
        return "Invalid data found when processing input";
 
1085
    case AVERROR_MUXER_NOT_FOUND:
 
1086
        return "Muxer not found";
 
1087
    case AVERROR_OPTION_NOT_FOUND:
 
1088
        return "Option not found";
 
1089
    case AVERROR_PATCHWELCOME:
 
1090
        return "Not yet implemented in FFmpeg, patches welcome";
 
1091
    case AVERROR_PROTOCOL_NOT_FOUND:
 
1092
        return "Protocol not found";
 
1093
    case AVERROR_STREAM_NOT_FOUND:
 
1094
        return "Stream not found";
 
1095
    default:
 
1096
        break;
 
1097
    }
 
1098
#else
 
1099
    switch(err) {
 
1100
    case AVERROR_NUMEXPECTED:
 
1101
        return "Incorrect filename syntax";
 
1102
    case AVERROR_INVALIDDATA:
 
1103
        return "Invalid data in header";
 
1104
    case AVERROR_NOFMT:
 
1105
        return "Unknown format";
 
1106
    case AVERROR_IO:
 
1107
        return "I/O error occurred";
 
1108
    case AVERROR_NOMEM:
 
1109
        return "Memory allocation error";
 
1110
    default:
 
1111
        break;
 
1112
    }
 
1113
#endif
 
1114
 
 
1115
    return "Unspecified error";
 
1116
}
 
1117
 
 
1118
/* function internal to FFMPEG (libavformat/riff.c) to lookup codec id by fourcc tag*/
 
1119
extern "C" {
 
1120
    enum CV_CODEC_ID codec_get_bmp_id(unsigned int tag);
 
1121
}
 
1122
 
 
1123
void CvVideoWriter_FFMPEG::init()
 
1124
{
 
1125
    fmt = 0;
 
1126
    oc = 0;
 
1127
    outbuf = 0;
 
1128
    outbuf_size = 0;
 
1129
    outfile = 0;
 
1130
    picture = 0;
 
1131
    input_picture = 0;
 
1132
    picbuf = 0;
 
1133
    video_st = 0;
 
1134
    input_pix_fmt = 0;
 
1135
    memset(&temp_image, 0, sizeof(temp_image));
 
1136
    img_convert_ctx = 0;
 
1137
    frame_width = frame_height = 0;
 
1138
    frame_idx = 0;
 
1139
    ok = false;
 
1140
}
 
1141
 
 
1142
/**
 
1143
 * the following function is a modified version of code
 
1144
 * found in ffmpeg-0.4.9-pre1/output_example.c
 
1145
 */
 
1146
static AVFrame * icv_alloc_picture_FFMPEG(int pix_fmt, int width, int height, bool alloc)
 
1147
{
 
1148
    AVFrame * picture;
 
1149
    uint8_t * picture_buf;
 
1150
    int size;
 
1151
 
 
1152
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
 
1153
    ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
 
1154
    picture = av_frame_alloc();
 
1155
#else
 
1156
    picture = avcodec_alloc_frame();
 
1157
#endif
 
1158
    if (!picture)
 
1159
        return NULL;
 
1160
 
 
1161
    picture->format = pix_fmt;
 
1162
    picture->width = width;
 
1163
    picture->height = height;
 
1164
 
 
1165
    size = avpicture_get_size( (AVPixelFormat) pix_fmt, width, height);
 
1166
    if(alloc){
 
1167
        picture_buf = (uint8_t *) malloc(size);
 
1168
        if (!picture_buf)
 
1169
        {
 
1170
            av_free(picture);
 
1171
            return NULL;
 
1172
        }
 
1173
        avpicture_fill((AVPicture *)picture, picture_buf,
 
1174
                       (AVPixelFormat) pix_fmt, width, height);
 
1175
    }
 
1176
    else {
 
1177
    }
 
1178
    return picture;
 
1179
}
 
1180
 
 
1181
/* add a video output stream to the container */
 
1182
static AVStream *icv_add_video_stream_FFMPEG(AVFormatContext *oc,
 
1183
                                             CV_CODEC_ID codec_id,
 
1184
                                             int w, int h, int bitrate,
 
1185
                                             double fps, int pixel_format)
 
1186
{
 
1187
    AVCodecContext *c;
 
1188
    AVStream *st;
 
1189
    int frame_rate, frame_rate_base;
 
1190
    AVCodec *codec;
 
1191
 
 
1192
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 10, 0)
 
1193
    st = avformat_new_stream(oc, 0);
 
1194
#else
 
1195
    st = av_new_stream(oc, 0);
 
1196
#endif
 
1197
 
 
1198
    if (!st) {
 
1199
        CV_WARN("Could not allocate stream");
 
1200
        return NULL;
 
1201
    }
 
1202
 
 
1203
#if LIBAVFORMAT_BUILD > 4628
 
1204
    c = st->codec;
 
1205
#else
 
1206
    c = &(st->codec);
 
1207
#endif
 
1208
 
 
1209
#if LIBAVFORMAT_BUILD > 4621
 
1210
    c->codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
 
1211
#else
 
1212
    c->codec_id = oc->oformat->video_codec;
 
1213
#endif
 
1214
 
 
1215
    if(codec_id != CV_CODEC(CODEC_ID_NONE)){
 
1216
        c->codec_id = codec_id;
 
1217
    }
 
1218
 
 
1219
    //if(codec_tag) c->codec_tag=codec_tag;
 
1220
    codec = avcodec_find_encoder(c->codec_id);
 
1221
 
 
1222
    c->codec_type = AVMEDIA_TYPE_VIDEO;
 
1223
 
 
1224
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54,25,0)
 
1225
    // Set per-codec defaults
 
1226
    AVCodecID c_id = c->codec_id;
 
1227
    avcodec_get_context_defaults3(c, codec);
 
1228
    // avcodec_get_context_defaults3 erases codec_id for some reason
 
1229
    c->codec_id = c_id;
 
1230
#endif
 
1231
 
 
1232
    /* put sample parameters */
 
1233
    int64_t lbit_rate = (int64_t)bitrate;
 
1234
    lbit_rate += (bitrate / 2);
 
1235
    lbit_rate = std::min(lbit_rate, (int64_t)INT_MAX);
 
1236
    c->bit_rate = lbit_rate;
 
1237
 
 
1238
    // took advice from
 
1239
    // http://ffmpeg-users.933282.n4.nabble.com/warning-clipping-1-dct-coefficients-to-127-127-td934297.html
 
1240
    c->qmin = 3;
 
1241
 
 
1242
    /* resolution must be a multiple of two */
 
1243
    c->width = w;
 
1244
    c->height = h;
 
1245
 
 
1246
    /* time base: this is the fundamental unit of time (in seconds) in terms
 
1247
       of which frame timestamps are represented. for fixed-fps content,
 
1248
       timebase should be 1/framerate and timestamp increments should be
 
1249
       identically 1. */
 
1250
    frame_rate=(int)(fps+0.5);
 
1251
    frame_rate_base=1;
 
1252
    while (fabs((double)frame_rate/frame_rate_base) - fps > 0.001){
 
1253
        frame_rate_base*=10;
 
1254
        frame_rate=(int)(fps*frame_rate_base + 0.5);
 
1255
    }
 
1256
#if LIBAVFORMAT_BUILD > 4752
 
1257
    c->time_base.den = frame_rate;
 
1258
    c->time_base.num = frame_rate_base;
 
1259
    /* adjust time base for supported framerates */
 
1260
    if(codec && codec->supported_framerates){
 
1261
        const AVRational *p= codec->supported_framerates;
 
1262
        AVRational req = {frame_rate, frame_rate_base};
 
1263
        const AVRational *best=NULL;
 
1264
        AVRational best_error= {INT_MAX, 1};
 
1265
        for(; p->den!=0; p++){
 
1266
            AVRational error= av_sub_q(req, *p);
 
1267
            if(error.num <0) error.num *= -1;
 
1268
            if(av_cmp_q(error, best_error) < 0){
 
1269
                best_error= error;
 
1270
                best= p;
 
1271
            }
 
1272
        }
 
1273
        c->time_base.den= best->num;
 
1274
        c->time_base.num= best->den;
 
1275
    }
 
1276
#else
 
1277
    c->frame_rate = frame_rate;
 
1278
    c->frame_rate_base = frame_rate_base;
 
1279
#endif
 
1280
 
 
1281
    c->gop_size = 12; /* emit one intra frame every twelve frames at most */
 
1282
    c->pix_fmt = (AVPixelFormat) pixel_format;
 
1283
 
 
1284
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG2VIDEO)) {
 
1285
        c->max_b_frames = 2;
 
1286
    }
 
1287
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG1VIDEO) || c->codec_id == CV_CODEC(CODEC_ID_MSMPEG4V3)){
 
1288
        /* needed to avoid using macroblocks in which some coeffs overflow
 
1289
           this doesnt happen with normal video, it just happens here as the
 
1290
           motion of the chroma plane doesnt match the luma plane */
 
1291
        /* avoid FFMPEG warning 'clipping 1 dct coefficients...' */
 
1292
        c->mb_decision=2;
 
1293
    }
 
1294
 
 
1295
#if LIBAVUTIL_BUILD > CALC_FFMPEG_VERSION(51,11,0)
 
1296
    /* Some settings for libx264 encoding, restore dummy values for gop_size
 
1297
     and qmin since they will be set to reasonable defaults by the libx264
 
1298
     preset system. Also, use a crf encode with the default quality rating,
 
1299
     this seems easier than finding an appropriate default bitrate. */
 
1300
    if (c->codec_id == AV_CODEC_ID_H264) {
 
1301
      c->gop_size = -1;
 
1302
      c->qmin = -1;
 
1303
      c->bit_rate = 0;
 
1304
      if (c->priv_data)
 
1305
          av_opt_set(c->priv_data,"crf","23", 0);
 
1306
    }
 
1307
#endif
 
1308
 
 
1309
#if LIBAVCODEC_VERSION_INT>0x000409
 
1310
    // some formats want stream headers to be seperate
 
1311
    if(oc->oformat->flags & AVFMT_GLOBALHEADER)
 
1312
    {
 
1313
        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
 
1314
    }
 
1315
#endif
 
1316
 
 
1317
    return st;
 
1318
}
 
1319
 
 
1320
static const int OPENCV_NO_FRAMES_WRITTEN_CODE = 1000;
 
1321
 
 
1322
static int icv_av_write_frame_FFMPEG( AVFormatContext * oc, AVStream * video_st,
 
1323
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54, 1, 0)
 
1324
                                      uint8_t *, uint32_t,
 
1325
#else
 
1326
                                      uint8_t * outbuf, uint32_t outbuf_size,
 
1327
#endif
 
1328
                                      AVFrame * picture )
 
1329
{
 
1330
#if LIBAVFORMAT_BUILD > 4628
 
1331
    AVCodecContext * c = video_st->codec;
 
1332
#else
 
1333
    AVCodecContext * c = &(video_st->codec);
 
1334
#endif
 
1335
    int ret = OPENCV_NO_FRAMES_WRITTEN_CODE;
 
1336
 
 
1337
    if (oc->oformat->flags & AVFMT_RAWPICTURE) {
 
1338
        /* raw video case. The API will change slightly in the near
 
1339
           futur for that */
 
1340
        AVPacket pkt;
 
1341
        av_init_packet(&pkt);
 
1342
 
 
1343
#ifndef PKT_FLAG_KEY
 
1344
#define PKT_FLAG_KEY AV_PKT_FLAG_KEY
 
1345
#endif
 
1346
 
 
1347
        pkt.flags |= PKT_FLAG_KEY;
 
1348
        pkt.stream_index= video_st->index;
 
1349
        pkt.data= (uint8_t *)picture;
 
1350
        pkt.size= sizeof(AVPicture);
 
1351
 
 
1352
        ret = av_write_frame(oc, &pkt);
 
1353
    } else {
 
1354
        /* encode the image */
 
1355
        AVPacket pkt;
 
1356
        av_init_packet(&pkt);
 
1357
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54, 1, 0)
 
1358
        int got_output = 0;
 
1359
        pkt.data = NULL;
 
1360
        pkt.size = 0;
 
1361
        ret = avcodec_encode_video2(c, &pkt, picture, &got_output);
 
1362
        if (ret < 0)
 
1363
            ;
 
1364
        else if (got_output) {
 
1365
            if (pkt.pts != (int64_t)AV_NOPTS_VALUE)
 
1366
                pkt.pts = av_rescale_q(pkt.pts, c->time_base, video_st->time_base);
 
1367
            if (pkt.dts != (int64_t)AV_NOPTS_VALUE)
 
1368
                pkt.dts = av_rescale_q(pkt.dts, c->time_base, video_st->time_base);
 
1369
            if (pkt.duration)
 
1370
                pkt.duration = av_rescale_q(pkt.duration, c->time_base, video_st->time_base);
 
1371
            pkt.stream_index= video_st->index;
 
1372
            ret = av_write_frame(oc, &pkt);
 
1373
            av_free_packet(&pkt);
 
1374
        }
 
1375
        else
 
1376
            ret = OPENCV_NO_FRAMES_WRITTEN_CODE;
 
1377
#else
 
1378
        int out_size = avcodec_encode_video(c, outbuf, outbuf_size, picture);
 
1379
        /* if zero size, it means the image was buffered */
 
1380
        if (out_size > 0) {
 
1381
#if LIBAVFORMAT_BUILD > 4752
 
1382
            if(c->coded_frame->pts != (int64_t)AV_NOPTS_VALUE)
 
1383
                pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st->time_base);
 
1384
#else
 
1385
            pkt.pts = c->coded_frame->pts;
 
1386
#endif
 
1387
            if(c->coded_frame->key_frame)
 
1388
                pkt.flags |= PKT_FLAG_KEY;
 
1389
            pkt.stream_index= video_st->index;
 
1390
            pkt.data= outbuf;
 
1391
            pkt.size= out_size;
 
1392
 
 
1393
            /* write the compressed frame in the media file */
 
1394
            ret = av_write_frame(oc, &pkt);
 
1395
        }
 
1396
#endif
 
1397
    }
 
1398
    return ret;
 
1399
}
 
1400
 
 
1401
/// write a frame with FFMPEG
 
1402
bool CvVideoWriter_FFMPEG::writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin )
 
1403
{
 
1404
    bool ret = false;
 
1405
 
 
1406
    if( (width & -2) != frame_width || (height & -2) != frame_height || !data )
 
1407
        return false;
 
1408
    width = frame_width;
 
1409
    height = frame_height;
 
1410
 
 
1411
    // typecast from opaque data type to implemented struct
 
1412
#if LIBAVFORMAT_BUILD > 4628
 
1413
    AVCodecContext *c = video_st->codec;
 
1414
#else
 
1415
    AVCodecContext *c = &(video_st->codec);
 
1416
#endif
 
1417
 
 
1418
#if LIBAVFORMAT_BUILD < 5231
 
1419
    // It is not needed in the latest versions of the ffmpeg
 
1420
    if( c->codec_id == CV_CODEC(CODEC_ID_RAWVIDEO) && origin != 1 )
 
1421
    {
 
1422
        if( !temp_image.data )
 
1423
        {
 
1424
            temp_image.step = (width*cn + 3) & -4;
 
1425
            temp_image.width = width;
 
1426
            temp_image.height = height;
 
1427
            temp_image.cn = cn;
 
1428
            temp_image.data = (unsigned char*)malloc(temp_image.step*temp_image.height);
 
1429
        }
 
1430
        for( int y = 0; y < height; y++ )
 
1431
            memcpy(temp_image.data + y*temp_image.step, data + (height-1-y)*step, width*cn);
 
1432
        data = temp_image.data;
 
1433
        step = temp_image.step;
 
1434
    }
 
1435
#else
 
1436
    if( width*cn != step )
 
1437
    {
 
1438
        if( !temp_image.data )
 
1439
        {
 
1440
            temp_image.step = width*cn;
 
1441
            temp_image.width = width;
 
1442
            temp_image.height = height;
 
1443
            temp_image.cn = cn;
 
1444
            temp_image.data = (unsigned char*)malloc(temp_image.step*temp_image.height);
 
1445
        }
 
1446
        if (origin == 1)
 
1447
            for( int y = 0; y < height; y++ )
 
1448
                memcpy(temp_image.data + y*temp_image.step, data + (height-1-y)*step, temp_image.step);
 
1449
        else
 
1450
            for( int y = 0; y < height; y++ )
 
1451
                memcpy(temp_image.data + y*temp_image.step, data + y*step, temp_image.step);
 
1452
        data = temp_image.data;
 
1453
        step = temp_image.step;
 
1454
    }
 
1455
#endif
 
1456
 
 
1457
    // check parameters
 
1458
    if (input_pix_fmt == AV_PIX_FMT_BGR24) {
 
1459
        if (cn != 3) {
 
1460
            return false;
 
1461
        }
 
1462
    }
 
1463
    else if (input_pix_fmt == AV_PIX_FMT_GRAY8) {
 
1464
        if (cn != 1) {
 
1465
            return false;
 
1466
        }
 
1467
    }
 
1468
    else {
 
1469
        assert(false);
 
1470
    }
 
1471
 
 
1472
    if ( c->pix_fmt != input_pix_fmt ) {
 
1473
        assert( input_picture );
 
1474
        // let input_picture point to the raw data buffer of 'image'
 
1475
        avpicture_fill((AVPicture *)input_picture, (uint8_t *) data,
 
1476
                       (AVPixelFormat)input_pix_fmt, width, height);
 
1477
 
 
1478
        if( !img_convert_ctx )
 
1479
        {
 
1480
            img_convert_ctx = sws_getContext(width,
 
1481
                                             height,
 
1482
                                             (AVPixelFormat)input_pix_fmt,
 
1483
                                             c->width,
 
1484
                                             c->height,
 
1485
                                             c->pix_fmt,
 
1486
                                             SWS_BICUBIC,
 
1487
                                             NULL, NULL, NULL);
 
1488
            if( !img_convert_ctx )
 
1489
                return false;
 
1490
        }
 
1491
 
 
1492
        if ( sws_scale(img_convert_ctx, input_picture->data,
 
1493
                       input_picture->linesize, 0,
 
1494
                       height,
 
1495
                       picture->data, picture->linesize) < 0 )
 
1496
            return false;
 
1497
    }
 
1498
    else{
 
1499
        avpicture_fill((AVPicture *)picture, (uint8_t *) data,
 
1500
                       (AVPixelFormat)input_pix_fmt, width, height);
 
1501
    }
 
1502
 
 
1503
    picture->pts = frame_idx;
 
1504
    ret = icv_av_write_frame_FFMPEG( oc, video_st, outbuf, outbuf_size, picture) >= 0;
 
1505
    frame_idx++;
 
1506
 
 
1507
    return ret;
 
1508
}
 
1509
 
 
1510
/// close video output stream and free associated memory
 
1511
void CvVideoWriter_FFMPEG::close()
 
1512
{
 
1513
    // nothing to do if already released
 
1514
    if ( !picture )
 
1515
        return;
 
1516
 
 
1517
    /* no more frame to compress. The codec has a latency of a few
 
1518
       frames if using B frames, so we get the last frames by
 
1519
       passing the same picture again */
 
1520
    // TODO -- do we need to account for latency here?
 
1521
 
 
1522
    /* write the trailer, if any */
 
1523
    if(ok && oc)
 
1524
    {
 
1525
        if( (oc->oformat->flags & AVFMT_RAWPICTURE) == 0 )
 
1526
        {
 
1527
            for(;;)
 
1528
            {
 
1529
                int ret = icv_av_write_frame_FFMPEG( oc, video_st, outbuf, outbuf_size, NULL);
 
1530
                if( ret == OPENCV_NO_FRAMES_WRITTEN_CODE || ret < 0 )
 
1531
                    break;
 
1532
            }
 
1533
        }
 
1534
        av_write_trailer(oc);
 
1535
    }
 
1536
 
 
1537
    if( img_convert_ctx )
 
1538
    {
 
1539
        sws_freeContext(img_convert_ctx);
 
1540
        img_convert_ctx = 0;
 
1541
    }
 
1542
 
 
1543
    // free pictures
 
1544
#if LIBAVFORMAT_BUILD > 4628
 
1545
    if( video_st->codec->pix_fmt != input_pix_fmt)
 
1546
#else
 
1547
    if( video_st->codec.pix_fmt != input_pix_fmt)
 
1548
#endif
 
1549
    {
 
1550
        if(picture->data[0])
 
1551
            free(picture->data[0]);
 
1552
        picture->data[0] = 0;
 
1553
    }
 
1554
    av_free(picture);
 
1555
 
 
1556
    if (input_picture)
 
1557
        av_free(input_picture);
 
1558
 
 
1559
    /* close codec */
 
1560
#if LIBAVFORMAT_BUILD > 4628
 
1561
    avcodec_close(video_st->codec);
 
1562
#else
 
1563
    avcodec_close(&(video_st->codec));
 
1564
#endif
 
1565
 
 
1566
    av_free(outbuf);
 
1567
 
 
1568
    if (!(fmt->flags & AVFMT_NOFILE))
 
1569
    {
 
1570
        /* close the output file */
 
1571
 
 
1572
#if LIBAVCODEC_VERSION_INT < ((52<<16)+(123<<8)+0)
 
1573
#if LIBAVCODEC_VERSION_INT >= ((51<<16)+(49<<8)+0)
 
1574
        url_fclose(oc->pb);
 
1575
#else
 
1576
        url_fclose(&oc->pb);
 
1577
#endif
 
1578
#else
 
1579
        avio_close(oc->pb);
 
1580
#endif
 
1581
 
 
1582
    }
 
1583
 
 
1584
    /* free the stream */
 
1585
    avformat_free_context(oc);
 
1586
 
 
1587
    if( temp_image.data )
 
1588
    {
 
1589
        free(temp_image.data);
 
1590
        temp_image.data = 0;
 
1591
    }
 
1592
 
 
1593
    init();
 
1594
}
 
1595
 
 
1596
#define CV_PRINTABLE_CHAR(ch) ((ch) < 32 ? '?' : (ch))
 
1597
#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)
 
1598
 
 
1599
static inline bool cv_ff_codec_tag_match(const AVCodecTag *tags, CV_CODEC_ID id, unsigned int tag)
 
1600
{
 
1601
    while (tags->id != AV_CODEC_ID_NONE)
 
1602
    {
 
1603
        if (tags->id == id && tags->tag == tag)
 
1604
            return true;
 
1605
        tags++;
 
1606
    }
 
1607
    return false;
 
1608
}
 
1609
static inline bool cv_ff_codec_tag_list_match(const AVCodecTag *const *tags, CV_CODEC_ID id, unsigned int tag)
 
1610
{
 
1611
    int i;
 
1612
    for (i = 0; tags && tags[i]; i++) {
 
1613
        bool res = cv_ff_codec_tag_match(tags[i], id, tag);
 
1614
        if (res)
 
1615
            return res;
 
1616
    }
 
1617
    return false;
 
1618
}
 
1619
 
 
1620
/// Create a video writer object that uses FFMPEG
 
1621
bool CvVideoWriter_FFMPEG::open( const char * filename, int fourcc,
 
1622
                                 double fps, int width, int height, bool is_color )
 
1623
{
 
1624
    CV_CODEC_ID codec_id = CV_CODEC(CODEC_ID_NONE);
 
1625
    int err, codec_pix_fmt;
 
1626
    double bitrate_scale = 1;
 
1627
 
 
1628
    close();
 
1629
 
 
1630
    // check arguments
 
1631
    if( !filename )
 
1632
        return false;
 
1633
    if(fps <= 0)
 
1634
        return false;
 
1635
 
 
1636
    // we allow frames of odd width or height, but in this case we truncate
 
1637
    // the rightmost column/the bottom row. Probably, this should be handled more elegantly,
 
1638
    // but some internal functions inside FFMPEG swscale require even width/height.
 
1639
    width &= -2;
 
1640
    height &= -2;
 
1641
    if( width <= 0 || height <= 0 )
 
1642
        return false;
 
1643
 
 
1644
    /* auto detect the output format from the name and fourcc code. */
 
1645
 
 
1646
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
 
1647
    fmt = av_guess_format(NULL, filename, NULL);
 
1648
#else
 
1649
    fmt = guess_format(NULL, filename, NULL);
 
1650
#endif
 
1651
 
 
1652
    if (!fmt)
 
1653
        return false;
 
1654
 
 
1655
    /* determine optimal pixel format */
 
1656
    if (is_color) {
 
1657
        input_pix_fmt = AV_PIX_FMT_BGR24;
 
1658
    }
 
1659
    else {
 
1660
        input_pix_fmt = AV_PIX_FMT_GRAY8;
 
1661
    }
 
1662
 
 
1663
    /* Lookup codec_id for given fourcc */
 
1664
#if LIBAVCODEC_VERSION_INT<((51<<16)+(49<<8)+0)
 
1665
    if( (codec_id = codec_get_bmp_id( fourcc )) == CV_CODEC(CODEC_ID_NONE) )
 
1666
        return false;
 
1667
#else
 
1668
    if( (codec_id = av_codec_get_id(fmt->codec_tag, fourcc)) == CV_CODEC(CODEC_ID_NONE) )
 
1669
    {
 
1670
        const struct AVCodecTag * fallback_tags[] = {
 
1671
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(54, 1, 0)
 
1672
// APIchanges:
 
1673
// 2012-01-31 - dd6d3b0 - lavf 54.01.0
 
1674
//   Add avformat_get_riff_video_tags() and avformat_get_riff_audio_tags().
 
1675
                avformat_get_riff_video_tags(),
 
1676
#endif
 
1677
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 25, 100) && defined LIBAVFORMAT_VERSION_MICRO && LIBAVFORMAT_VERSION_MICRO >= 100
 
1678
// APIchanges: ffmpeg only
 
1679
// 2014-01-19 - 1a193c4 - lavf 55.25.100 - avformat.h
 
1680
//   Add avformat_get_mov_video_tags() and avformat_get_mov_audio_tags().
 
1681
                avformat_get_mov_video_tags(),
 
1682
#endif
 
1683
                codec_bmp_tags, // fallback for avformat < 54.1
 
1684
                NULL };
 
1685
        if( (codec_id = av_codec_get_id(fallback_tags, fourcc)) == CV_CODEC(CODEC_ID_NONE) )
 
1686
        {
 
1687
            fflush(stdout);
 
1688
            fprintf(stderr, "OpenCV: FFMPEG: tag 0x%08x/'%c%c%c%c' is not found (format '%s / %s')'\n",
 
1689
                    fourcc, CV_TAG_TO_PRINTABLE_CHAR4(fourcc),
 
1690
                    fmt->name, fmt->long_name);
 
1691
            return false;
 
1692
        }
 
1693
    }
 
1694
    // validate tag
 
1695
    if (cv_ff_codec_tag_list_match(fmt->codec_tag, codec_id, fourcc) == false)
 
1696
    {
 
1697
        fflush(stdout);
 
1698
        fprintf(stderr, "OpenCV: FFMPEG: tag 0x%08x/'%c%c%c%c' is not supported with codec id %d and format '%s / %s'\n",
 
1699
                fourcc, CV_TAG_TO_PRINTABLE_CHAR4(fourcc),
 
1700
                codec_id, fmt->name, fmt->long_name);
 
1701
        int supported_tag;
 
1702
        if( (supported_tag = av_codec_get_tag(fmt->codec_tag, codec_id)) != 0 )
 
1703
        {
 
1704
            fprintf(stderr, "OpenCV: FFMPEG: fallback to use tag 0x%08x/'%c%c%c%c'\n",
 
1705
                    supported_tag, CV_TAG_TO_PRINTABLE_CHAR4(supported_tag));
 
1706
            fourcc = supported_tag;
 
1707
        }
 
1708
    }
 
1709
#endif
 
1710
 
 
1711
    // alloc memory for context
 
1712
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
 
1713
    oc = avformat_alloc_context();
 
1714
#else
 
1715
    oc = av_alloc_format_context();
 
1716
#endif
 
1717
    assert (oc);
 
1718
 
 
1719
    /* set file name */
 
1720
    oc->oformat = fmt;
 
1721
    snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
 
1722
 
 
1723
    /* set some options */
 
1724
    oc->max_delay = (int)(0.7*AV_TIME_BASE);  /* This reduces buffer underrun warnings with MPEG */
 
1725
 
 
1726
    // set a few optimal pixel formats for lossless codecs of interest..
 
1727
    switch (codec_id) {
 
1728
#if LIBAVCODEC_VERSION_INT>((50<<16)+(1<<8)+0)
 
1729
    case CV_CODEC(CODEC_ID_JPEGLS):
 
1730
        // BGR24 or GRAY8 depending on is_color...
 
1731
        codec_pix_fmt = input_pix_fmt;
 
1732
        break;
 
1733
#endif
 
1734
    case CV_CODEC(CODEC_ID_HUFFYUV):
 
1735
        codec_pix_fmt = AV_PIX_FMT_YUV422P;
 
1736
        break;
 
1737
    case CV_CODEC(CODEC_ID_MJPEG):
 
1738
    case CV_CODEC(CODEC_ID_LJPEG):
 
1739
        codec_pix_fmt = AV_PIX_FMT_YUVJ420P;
 
1740
        bitrate_scale = 3;
 
1741
        break;
 
1742
    case CV_CODEC(CODEC_ID_RAWVIDEO):
 
1743
        codec_pix_fmt = input_pix_fmt == AV_PIX_FMT_GRAY8 ||
 
1744
                        input_pix_fmt == AV_PIX_FMT_GRAY16LE ||
 
1745
                        input_pix_fmt == AV_PIX_FMT_GRAY16BE ? input_pix_fmt : AV_PIX_FMT_YUV420P;
 
1746
        break;
 
1747
    default:
 
1748
        // good for lossy formats, MPEG, etc.
 
1749
        codec_pix_fmt = AV_PIX_FMT_YUV420P;
 
1750
        break;
 
1751
    }
 
1752
 
 
1753
    double bitrate = MIN(bitrate_scale*fps*width*height, (double)INT_MAX/2);
 
1754
 
 
1755
    // TODO -- safe to ignore output audio stream?
 
1756
    video_st = icv_add_video_stream_FFMPEG(oc, codec_id,
 
1757
                                           width, height, (int)(bitrate + 0.5),
 
1758
                                           fps, codec_pix_fmt);
 
1759
 
 
1760
    /* set the output parameters (must be done even if no
 
1761
   parameters). */
 
1762
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
 
1763
    if (av_set_parameters(oc, NULL) < 0) {
 
1764
        return false;
 
1765
    }
 
1766
#endif
 
1767
 
 
1768
#if 0
 
1769
#if FF_API_DUMP_FORMAT
 
1770
    dump_format(oc, 0, filename, 1);
 
1771
#else
 
1772
    av_dump_format(oc, 0, filename, 1);
 
1773
#endif
 
1774
#endif
 
1775
 
 
1776
    /* now that all the parameters are set, we can open the audio and
 
1777
     video codecs and allocate the necessary encode buffers */
 
1778
    if (!video_st){
 
1779
        return false;
 
1780
    }
 
1781
 
 
1782
    AVCodec *codec;
 
1783
    AVCodecContext *c;
 
1784
 
 
1785
#if LIBAVFORMAT_BUILD > 4628
 
1786
    c = (video_st->codec);
 
1787
#else
 
1788
    c = &(video_st->codec);
 
1789
#endif
 
1790
 
 
1791
    c->codec_tag = fourcc;
 
1792
    /* find the video encoder */
 
1793
    codec = avcodec_find_encoder(c->codec_id);
 
1794
    if (!codec) {
 
1795
        fprintf(stderr, "Could not find encoder for codec id %d: %s\n", c->codec_id, icvFFMPEGErrStr(
 
1796
        #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
 
1797
                AVERROR_ENCODER_NOT_FOUND
 
1798
        #else
 
1799
                -1
 
1800
        #endif
 
1801
                ));
 
1802
        return false;
 
1803
    }
 
1804
 
 
1805
    int64_t lbit_rate = (int64_t)c->bit_rate;
 
1806
    lbit_rate += (bitrate / 2);
 
1807
    lbit_rate = std::min(lbit_rate, (int64_t)INT_MAX);
 
1808
    c->bit_rate_tolerance = (int)lbit_rate;
 
1809
    c->bit_rate = (int)lbit_rate;
 
1810
 
 
1811
    /* open the codec */
 
1812
    if ((err=
 
1813
#if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
 
1814
         avcodec_open2(c, codec, NULL)
 
1815
#else
 
1816
         avcodec_open(c, codec)
 
1817
#endif
 
1818
         ) < 0) {
 
1819
        fprintf(stderr, "Could not open codec '%s': %s\n", codec->name, icvFFMPEGErrStr(err));
 
1820
        return false;
 
1821
    }
 
1822
 
 
1823
    outbuf = NULL;
 
1824
 
 
1825
    if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
 
1826
        /* allocate output buffer */
 
1827
        /* assume we will never get codec output with more than 4 bytes per pixel... */
 
1828
        outbuf_size = width*height*4;
 
1829
        outbuf = (uint8_t *) av_malloc(outbuf_size);
 
1830
    }
 
1831
 
 
1832
    bool need_color_convert;
 
1833
    need_color_convert = (c->pix_fmt != input_pix_fmt);
 
1834
 
 
1835
    /* allocate the encoded raw picture */
 
1836
    picture = icv_alloc_picture_FFMPEG(c->pix_fmt, c->width, c->height, need_color_convert);
 
1837
    if (!picture) {
 
1838
        return false;
 
1839
    }
 
1840
 
 
1841
    /* if the output format is not our input format, then a temporary
 
1842
   picture of the input format is needed too. It is then converted
 
1843
   to the required output format */
 
1844
    input_picture = NULL;
 
1845
    if ( need_color_convert ) {
 
1846
        input_picture = icv_alloc_picture_FFMPEG(input_pix_fmt, c->width, c->height, false);
 
1847
        if (!input_picture) {
 
1848
            return false;
 
1849
        }
 
1850
    }
 
1851
 
 
1852
    /* open the output file, if needed */
 
1853
    if (!(fmt->flags & AVFMT_NOFILE)) {
 
1854
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
 
1855
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0)
 
1856
#else
 
1857
            if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0)
 
1858
#endif
 
1859
            {
 
1860
            return false;
 
1861
        }
 
1862
    }
 
1863
 
 
1864
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
 
1865
    /* write the stream header, if any */
 
1866
    err=avformat_write_header(oc, NULL);
 
1867
#else
 
1868
    err=av_write_header( oc );
 
1869
#endif
 
1870
 
 
1871
    if(err < 0)
 
1872
    {
 
1873
        close();
 
1874
        remove(filename);
 
1875
        return false;
 
1876
    }
 
1877
    frame_width = width;
 
1878
    frame_height = height;
 
1879
    frame_idx = 0;
 
1880
    ok = true;
 
1881
 
 
1882
    return true;
 
1883
}
 
1884
 
 
1885
 
 
1886
 
 
1887
CvCapture_FFMPEG* cvCreateFileCapture_FFMPEG( const char* filename )
 
1888
{
 
1889
    CvCapture_FFMPEG* capture = (CvCapture_FFMPEG*)malloc(sizeof(*capture));
 
1890
    capture->init();
 
1891
    if( capture->open( filename ))
 
1892
        return capture;
 
1893
 
 
1894
    capture->close();
 
1895
    free(capture);
 
1896
    return 0;
 
1897
}
 
1898
 
 
1899
 
 
1900
void cvReleaseCapture_FFMPEG(CvCapture_FFMPEG** capture)
 
1901
{
 
1902
    if( capture && *capture )
 
1903
    {
 
1904
        (*capture)->close();
 
1905
        free(*capture);
 
1906
        *capture = 0;
 
1907
    }
 
1908
}
 
1909
 
 
1910
int cvSetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id, double value)
 
1911
{
 
1912
    return capture->setProperty(prop_id, value);
 
1913
}
 
1914
 
 
1915
double cvGetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id)
 
1916
{
 
1917
    return capture->getProperty(prop_id);
 
1918
}
 
1919
 
 
1920
int cvGrabFrame_FFMPEG(CvCapture_FFMPEG* capture)
 
1921
{
 
1922
    return capture->grabFrame();
 
1923
}
 
1924
 
 
1925
int cvRetrieveFrame_FFMPEG(CvCapture_FFMPEG* capture, unsigned char** data, int* step, int* width, int* height, int* cn)
 
1926
{
 
1927
    return capture->retrieveFrame(0, data, step, width, height, cn);
 
1928
}
 
1929
 
 
1930
CvVideoWriter_FFMPEG* cvCreateVideoWriter_FFMPEG( const char* filename, int fourcc, double fps,
 
1931
                                                  int width, int height, int isColor )
 
1932
{
 
1933
    CvVideoWriter_FFMPEG* writer = (CvVideoWriter_FFMPEG*)malloc(sizeof(*writer));
 
1934
    writer->init();
 
1935
    if( writer->open( filename, fourcc, fps, width, height, isColor != 0 ))
 
1936
        return writer;
 
1937
    writer->close();
 
1938
    free(writer);
 
1939
    return 0;
 
1940
}
 
1941
 
 
1942
void cvReleaseVideoWriter_FFMPEG( CvVideoWriter_FFMPEG** writer )
 
1943
{
 
1944
    if( writer && *writer )
 
1945
    {
 
1946
        (*writer)->close();
 
1947
        free(*writer);
 
1948
        *writer = 0;
 
1949
    }
 
1950
}
 
1951
 
 
1952
 
 
1953
int cvWriteFrame_FFMPEG( CvVideoWriter_FFMPEG* writer,
 
1954
                         const unsigned char* data, int step,
 
1955
                         int width, int height, int cn, int origin)
 
1956
{
 
1957
    return writer->writeFrame(data, step, width, height, cn, origin);
 
1958
}
 
1959
 
 
1960
 
 
1961
 
 
1962
/*
 
1963
 * For CUDA encoder
 
1964
 */
 
1965
 
 
1966
struct OutputMediaStream_FFMPEG
 
1967
{
 
1968
    bool open(const char* fileName, int width, int height, double fps);
 
1969
    void close();
 
1970
 
 
1971
    void write(unsigned char* data, int size, int keyFrame);
 
1972
 
 
1973
    // add a video output stream to the container
 
1974
    static AVStream* addVideoStream(AVFormatContext *oc, CV_CODEC_ID codec_id, int w, int h, int bitrate, double fps, AVPixelFormat pixel_format);
 
1975
 
 
1976
    AVOutputFormat* fmt_;
 
1977
    AVFormatContext* oc_;
 
1978
    AVStream* video_st_;
 
1979
};
 
1980
 
 
1981
void OutputMediaStream_FFMPEG::close()
 
1982
{
 
1983
    // no more frame to compress. The codec has a latency of a few
 
1984
    // frames if using B frames, so we get the last frames by
 
1985
    // passing the same picture again
 
1986
 
 
1987
    // TODO -- do we need to account for latency here?
 
1988
 
 
1989
    if (oc_)
 
1990
    {
 
1991
        // write the trailer, if any
 
1992
        av_write_trailer(oc_);
 
1993
 
 
1994
        // free the streams
 
1995
        for (unsigned int i = 0; i < oc_->nb_streams; ++i)
 
1996
        {
 
1997
            av_freep(&oc_->streams[i]->codec);
 
1998
            av_freep(&oc_->streams[i]);
 
1999
        }
 
2000
 
 
2001
        if (!(fmt_->flags & AVFMT_NOFILE) && oc_->pb)
 
2002
        {
 
2003
            // close the output file
 
2004
 
 
2005
            #if LIBAVCODEC_VERSION_INT < ((52<<16)+(123<<8)+0)
 
2006
                #if LIBAVCODEC_VERSION_INT >= ((51<<16)+(49<<8)+0)
 
2007
                    url_fclose(oc_->pb);
 
2008
                #else
 
2009
                    url_fclose(&oc_->pb);
 
2010
                #endif
 
2011
            #else
 
2012
                avio_close(oc_->pb);
 
2013
            #endif
 
2014
        }
 
2015
 
 
2016
        // free the stream
 
2017
        av_free(oc_);
 
2018
    }
 
2019
}
 
2020
 
 
2021
AVStream* OutputMediaStream_FFMPEG::addVideoStream(AVFormatContext *oc, CV_CODEC_ID codec_id, int w, int h, int bitrate, double fps, AVPixelFormat pixel_format)
 
2022
{
 
2023
    AVCodec* codec = avcodec_find_encoder(codec_id);
 
2024
    if (!codec)
 
2025
    {
 
2026
        fprintf(stderr, "Could not find encoder for codec id %d\n", codec_id);
 
2027
        return NULL;
 
2028
    }
 
2029
 
 
2030
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 10, 0)
 
2031
        AVStream* st = avformat_new_stream(oc, 0);
 
2032
    #else
 
2033
        AVStream* st = av_new_stream(oc, 0);
 
2034
    #endif
 
2035
    if (!st)
 
2036
        return 0;
 
2037
 
 
2038
    #if LIBAVFORMAT_BUILD > 4628
 
2039
        AVCodecContext* c = st->codec;
 
2040
    #else
 
2041
        AVCodecContext* c = &(st->codec);
 
2042
    #endif
 
2043
 
 
2044
    c->codec_id = codec_id;
 
2045
    c->codec_type = AVMEDIA_TYPE_VIDEO;
 
2046
 
 
2047
    // put sample parameters
 
2048
    unsigned long long lbit_rate = static_cast<unsigned long long>(bitrate);
 
2049
    lbit_rate += (bitrate / 4);
 
2050
    lbit_rate = std::min(lbit_rate, static_cast<unsigned long long>(std::numeric_limits<int>::max()));
 
2051
    c->bit_rate = bitrate;
 
2052
 
 
2053
    // took advice from
 
2054
    // http://ffmpeg-users.933282.n4.nabble.com/warning-clipping-1-dct-coefficients-to-127-127-td934297.html
 
2055
    c->qmin = 3;
 
2056
 
 
2057
    // resolution must be a multiple of two
 
2058
    c->width = w;
 
2059
    c->height = h;
 
2060
 
 
2061
    // time base: this is the fundamental unit of time (in seconds) in terms
 
2062
    // of which frame timestamps are represented. for fixed-fps content,
 
2063
    // timebase should be 1/framerate and timestamp increments should be
 
2064
    // identically 1
 
2065
 
 
2066
    int frame_rate = static_cast<int>(fps+0.5);
 
2067
    int frame_rate_base = 1;
 
2068
    while (fabs(static_cast<double>(frame_rate)/frame_rate_base) - fps > 0.001)
 
2069
    {
 
2070
        frame_rate_base *= 10;
 
2071
        frame_rate = static_cast<int>(fps*frame_rate_base + 0.5);
 
2072
    }
 
2073
    c->time_base.den = frame_rate;
 
2074
    c->time_base.num = frame_rate_base;
 
2075
 
 
2076
    #if LIBAVFORMAT_BUILD > 4752
 
2077
        // adjust time base for supported framerates
 
2078
        if (codec && codec->supported_framerates)
 
2079
        {
 
2080
            AVRational req = {frame_rate, frame_rate_base};
 
2081
            const AVRational* best = NULL;
 
2082
            AVRational best_error = {INT_MAX, 1};
 
2083
 
 
2084
            for (const AVRational* p = codec->supported_framerates; p->den!=0; ++p)
 
2085
            {
 
2086
                AVRational error = av_sub_q(req, *p);
 
2087
 
 
2088
                if (error.num < 0)
 
2089
                    error.num *= -1;
 
2090
 
 
2091
                if (av_cmp_q(error, best_error) < 0)
 
2092
                {
 
2093
                    best_error= error;
 
2094
                    best= p;
 
2095
                }
 
2096
            }
 
2097
 
 
2098
            c->time_base.den= best->num;
 
2099
            c->time_base.num= best->den;
 
2100
        }
 
2101
    #endif
 
2102
 
 
2103
    c->gop_size = 12; // emit one intra frame every twelve frames at most
 
2104
    c->pix_fmt = pixel_format;
 
2105
 
 
2106
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG2VIDEO))
 
2107
        c->max_b_frames = 2;
 
2108
 
 
2109
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG1VIDEO) || c->codec_id == CV_CODEC(CODEC_ID_MSMPEG4V3))
 
2110
    {
 
2111
        // needed to avoid using macroblocks in which some coeffs overflow
 
2112
        // this doesnt happen with normal video, it just happens here as the
 
2113
        // motion of the chroma plane doesnt match the luma plane
 
2114
 
 
2115
        // avoid FFMPEG warning 'clipping 1 dct coefficients...'
 
2116
 
 
2117
        c->mb_decision = 2;
 
2118
    }
 
2119
 
 
2120
    #if LIBAVCODEC_VERSION_INT > 0x000409
 
2121
        // some formats want stream headers to be seperate
 
2122
        if (oc->oformat->flags & AVFMT_GLOBALHEADER)
 
2123
        {
 
2124
            c->flags |= CODEC_FLAG_GLOBAL_HEADER;
 
2125
        }
 
2126
    #endif
 
2127
 
 
2128
    return st;
 
2129
}
 
2130
 
 
2131
bool OutputMediaStream_FFMPEG::open(const char* fileName, int width, int height, double fps)
 
2132
{
 
2133
    fmt_ = 0;
 
2134
    oc_ = 0;
 
2135
    video_st_ = 0;
 
2136
 
 
2137
    // auto detect the output format from the name and fourcc code
 
2138
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
 
2139
        fmt_ = av_guess_format(NULL, fileName, NULL);
 
2140
    #else
 
2141
        fmt_ = guess_format(NULL, fileName, NULL);
 
2142
    #endif
 
2143
    if (!fmt_)
 
2144
        return false;
 
2145
 
 
2146
    CV_CODEC_ID codec_id = CV_CODEC(CODEC_ID_H264);
 
2147
 
 
2148
    // alloc memory for context
 
2149
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
 
2150
        oc_ = avformat_alloc_context();
 
2151
    #else
 
2152
        oc_ = av_alloc_format_context();
 
2153
    #endif
 
2154
    if (!oc_)
 
2155
        return false;
 
2156
 
 
2157
    // set some options
 
2158
    oc_->oformat = fmt_;
 
2159
    snprintf(oc_->filename, sizeof(oc_->filename), "%s", fileName);
 
2160
 
 
2161
    oc_->max_delay = (int)(0.7 * AV_TIME_BASE); // This reduces buffer underrun warnings with MPEG
 
2162
 
 
2163
    // set a few optimal pixel formats for lossless codecs of interest..
 
2164
    AVPixelFormat codec_pix_fmt = AV_PIX_FMT_YUV420P;
 
2165
    int bitrate_scale = 64;
 
2166
 
 
2167
    // TODO -- safe to ignore output audio stream?
 
2168
    video_st_ = addVideoStream(oc_, codec_id, width, height, width * height * bitrate_scale, fps, codec_pix_fmt);
 
2169
    if (!video_st_)
 
2170
        return false;
 
2171
 
 
2172
    // set the output parameters (must be done even if no parameters)
 
2173
    #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
 
2174
        if (av_set_parameters(oc_, NULL) < 0)
 
2175
            return false;
 
2176
    #endif
 
2177
 
 
2178
    // now that all the parameters are set, we can open the audio and
 
2179
    // video codecs and allocate the necessary encode buffers
 
2180
 
 
2181
    #if LIBAVFORMAT_BUILD > 4628
 
2182
        AVCodecContext* c = (video_st_->codec);
 
2183
    #else
 
2184
        AVCodecContext* c = &(video_st_->codec);
 
2185
    #endif
 
2186
 
 
2187
    c->codec_tag = MKTAG('H', '2', '6', '4');
 
2188
    c->bit_rate_tolerance = c->bit_rate;
 
2189
 
 
2190
    // open the output file, if needed
 
2191
    if (!(fmt_->flags & AVFMT_NOFILE))
 
2192
    {
 
2193
        #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
 
2194
            int err = url_fopen(&oc_->pb, fileName, URL_WRONLY);
 
2195
        #else
 
2196
            int err = avio_open(&oc_->pb, fileName, AVIO_FLAG_WRITE);
 
2197
        #endif
 
2198
 
 
2199
        if (err != 0)
 
2200
            return false;
 
2201
    }
 
2202
 
 
2203
    // write the stream header, if any
 
2204
    #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
 
2205
        av_write_header(oc_);
 
2206
    #else
 
2207
        avformat_write_header(oc_, NULL);
 
2208
    #endif
 
2209
 
 
2210
    return true;
 
2211
}
 
2212
 
 
2213
void OutputMediaStream_FFMPEG::write(unsigned char* data, int size, int keyFrame)
 
2214
{
 
2215
    // if zero size, it means the image was buffered
 
2216
    if (size > 0)
 
2217
    {
 
2218
        AVPacket pkt;
 
2219
        av_init_packet(&pkt);
 
2220
 
 
2221
        if (keyFrame)
 
2222
            pkt.flags |= PKT_FLAG_KEY;
 
2223
 
 
2224
        pkt.stream_index = video_st_->index;
 
2225
        pkt.data = data;
 
2226
        pkt.size = size;
 
2227
 
 
2228
        // write the compressed frame in the media file
 
2229
        av_write_frame(oc_, &pkt);
 
2230
    }
 
2231
}
 
2232
 
 
2233
struct OutputMediaStream_FFMPEG* create_OutputMediaStream_FFMPEG(const char* fileName, int width, int height, double fps)
 
2234
{
 
2235
    OutputMediaStream_FFMPEG* stream = (OutputMediaStream_FFMPEG*) malloc(sizeof(OutputMediaStream_FFMPEG));
 
2236
 
 
2237
    if (stream->open(fileName, width, height, fps))
 
2238
        return stream;
 
2239
 
 
2240
    stream->close();
 
2241
    free(stream);
 
2242
 
 
2243
    return 0;
 
2244
}
 
2245
 
 
2246
void release_OutputMediaStream_FFMPEG(struct OutputMediaStream_FFMPEG* stream)
 
2247
{
 
2248
    stream->close();
 
2249
    free(stream);
 
2250
}
 
2251
 
 
2252
void write_OutputMediaStream_FFMPEG(struct OutputMediaStream_FFMPEG* stream, unsigned char* data, int size, int keyFrame)
 
2253
{
 
2254
    stream->write(data, size, keyFrame);
 
2255
}
 
2256
 
 
2257
/*
 
2258
 * For CUDA decoder
 
2259
 */
 
2260
 
 
2261
enum
 
2262
{
 
2263
    VideoCodec_MPEG1 = 0,
 
2264
    VideoCodec_MPEG2,
 
2265
    VideoCodec_MPEG4,
 
2266
    VideoCodec_VC1,
 
2267
    VideoCodec_H264,
 
2268
    VideoCodec_JPEG,
 
2269
    VideoCodec_H264_SVC,
 
2270
    VideoCodec_H264_MVC,
 
2271
 
 
2272
    // Uncompressed YUV
 
2273
    VideoCodec_YUV420 = (('I'<<24)|('Y'<<16)|('U'<<8)|('V')),   // Y,U,V (4:2:0)
 
2274
    VideoCodec_YV12   = (('Y'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,V,U (4:2:0)
 
2275
    VideoCodec_NV12   = (('N'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,UV  (4:2:0)
 
2276
    VideoCodec_YUYV   = (('Y'<<24)|('U'<<16)|('Y'<<8)|('V')),   // YUYV/YUY2 (4:2:2)
 
2277
    VideoCodec_UYVY   = (('U'<<24)|('Y'<<16)|('V'<<8)|('Y'))    // UYVY (4:2:2)
 
2278
};
 
2279
 
 
2280
enum
 
2281
{
 
2282
    VideoChromaFormat_Monochrome = 0,
 
2283
    VideoChromaFormat_YUV420,
 
2284
    VideoChromaFormat_YUV422,
 
2285
    VideoChromaFormat_YUV444
 
2286
};
 
2287
 
 
2288
struct InputMediaStream_FFMPEG
 
2289
{
 
2290
public:
 
2291
    bool open(const char* fileName, int* codec, int* chroma_format, int* width, int* height);
 
2292
    void close();
 
2293
 
 
2294
    bool read(unsigned char** data, int* size, int* endOfFile);
 
2295
 
 
2296
private:
 
2297
    InputMediaStream_FFMPEG(const InputMediaStream_FFMPEG&);
 
2298
    InputMediaStream_FFMPEG& operator =(const InputMediaStream_FFMPEG&);
 
2299
 
 
2300
    AVFormatContext* ctx_;
 
2301
    int video_stream_id_;
 
2302
    AVPacket pkt_;
 
2303
};
 
2304
 
 
2305
bool InputMediaStream_FFMPEG::open(const char* fileName, int* codec, int* chroma_format, int* width, int* height)
 
2306
{
 
2307
    int err;
 
2308
 
 
2309
    ctx_ = 0;
 
2310
    video_stream_id_ = -1;
 
2311
    memset(&pkt_, 0, sizeof(AVPacket));
 
2312
 
 
2313
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 13, 0)
 
2314
        avformat_network_init();
 
2315
    #endif
 
2316
 
 
2317
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
 
2318
        err = avformat_open_input(&ctx_, fileName, 0, 0);
 
2319
    #else
 
2320
        err = av_open_input_file(&ctx_, fileName, 0, 0, 0);
 
2321
    #endif
 
2322
    if (err < 0)
 
2323
        return false;
 
2324
 
 
2325
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
 
2326
        err = avformat_find_stream_info(ctx_, 0);
 
2327
    #else
 
2328
        err = av_find_stream_info(ctx_);
 
2329
    #endif
 
2330
    if (err < 0)
 
2331
        return false;
 
2332
 
 
2333
    for (unsigned int i = 0; i < ctx_->nb_streams; ++i)
 
2334
    {
 
2335
        #if LIBAVFORMAT_BUILD > 4628
 
2336
            AVCodecContext *enc = ctx_->streams[i]->codec;
 
2337
        #else
 
2338
            AVCodecContext *enc = &ctx_->streams[i]->codec;
 
2339
        #endif
 
2340
 
 
2341
        if (enc->codec_type == AVMEDIA_TYPE_VIDEO)
 
2342
        {
 
2343
            video_stream_id_ = static_cast<int>(i);
 
2344
 
 
2345
            switch (enc->codec_id)
 
2346
            {
 
2347
            case CV_CODEC(CODEC_ID_MPEG1VIDEO):
 
2348
                *codec = ::VideoCodec_MPEG1;
 
2349
                break;
 
2350
 
 
2351
            case CV_CODEC(CODEC_ID_MPEG2VIDEO):
 
2352
                *codec = ::VideoCodec_MPEG2;
 
2353
                break;
 
2354
 
 
2355
            case CV_CODEC(CODEC_ID_MPEG4):
 
2356
                *codec = ::VideoCodec_MPEG4;
 
2357
                break;
 
2358
 
 
2359
            case CV_CODEC(CODEC_ID_VC1):
 
2360
                *codec = ::VideoCodec_VC1;
 
2361
                break;
 
2362
 
 
2363
            case CV_CODEC(CODEC_ID_H264):
 
2364
                *codec = ::VideoCodec_H264;
 
2365
                break;
 
2366
 
 
2367
            default:
 
2368
                return false;
 
2369
            };
 
2370
 
 
2371
            switch (enc->pix_fmt)
 
2372
            {
 
2373
            case AV_PIX_FMT_YUV420P:
 
2374
                *chroma_format = ::VideoChromaFormat_YUV420;
 
2375
                break;
 
2376
 
 
2377
            case AV_PIX_FMT_YUV422P:
 
2378
                *chroma_format = ::VideoChromaFormat_YUV422;
 
2379
                break;
 
2380
 
 
2381
            case AV_PIX_FMT_YUV444P:
 
2382
                *chroma_format = ::VideoChromaFormat_YUV444;
 
2383
                break;
 
2384
 
 
2385
            default:
 
2386
                return false;
 
2387
            }
 
2388
 
 
2389
            *width = enc->coded_width;
 
2390
            *height = enc->coded_height;
 
2391
 
 
2392
            break;
 
2393
        }
 
2394
    }
 
2395
 
 
2396
    if (video_stream_id_ < 0)
 
2397
        return false;
 
2398
 
 
2399
    av_init_packet(&pkt_);
 
2400
 
 
2401
    return true;
 
2402
}
 
2403
 
 
2404
void InputMediaStream_FFMPEG::close()
 
2405
{
 
2406
    if (ctx_)
 
2407
    {
 
2408
        #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 24, 2)
 
2409
            avformat_close_input(&ctx_);
 
2410
        #else
 
2411
            av_close_input_file(ctx_);
 
2412
        #endif
 
2413
    }
 
2414
 
 
2415
    // free last packet if exist
 
2416
    if (pkt_.data)
 
2417
        av_free_packet(&pkt_);
 
2418
}
 
2419
 
 
2420
bool InputMediaStream_FFMPEG::read(unsigned char** data, int* size, int* endOfFile)
 
2421
{
 
2422
    // free last packet if exist
 
2423
    if (pkt_.data)
 
2424
        av_free_packet(&pkt_);
 
2425
 
 
2426
    // get the next frame
 
2427
    for (;;)
 
2428
    {
 
2429
        int ret = av_read_frame(ctx_, &pkt_);
 
2430
 
 
2431
        if (ret == AVERROR(EAGAIN))
 
2432
            continue;
 
2433
 
 
2434
        if (ret < 0)
 
2435
        {
 
2436
            if (ret == (int)AVERROR_EOF)
 
2437
                *endOfFile = true;
 
2438
            return false;
 
2439
        }
 
2440
 
 
2441
        if (pkt_.stream_index != video_stream_id_)
 
2442
        {
 
2443
            av_free_packet(&pkt_);
 
2444
            continue;
 
2445
        }
 
2446
 
 
2447
        break;
 
2448
    }
 
2449
 
 
2450
    *data = pkt_.data;
 
2451
    *size = pkt_.size;
 
2452
    *endOfFile = false;
 
2453
 
 
2454
    return true;
 
2455
}
 
2456
 
 
2457
InputMediaStream_FFMPEG* create_InputMediaStream_FFMPEG(const char* fileName, int* codec, int* chroma_format, int* width, int* height)
 
2458
{
 
2459
    InputMediaStream_FFMPEG* stream = (InputMediaStream_FFMPEG*) malloc(sizeof(InputMediaStream_FFMPEG));
 
2460
 
 
2461
    if (stream && stream->open(fileName, codec, chroma_format, width, height))
 
2462
        return stream;
 
2463
 
 
2464
    stream->close();
 
2465
    free(stream);
 
2466
 
 
2467
    return 0;
 
2468
}
 
2469
 
 
2470
void release_InputMediaStream_FFMPEG(InputMediaStream_FFMPEG* stream)
 
2471
{
 
2472
    stream->close();
 
2473
    free(stream);
 
2474
}
 
2475
 
 
2476
int read_InputMediaStream_FFMPEG(InputMediaStream_FFMPEG* stream, unsigned char** data, int* size, int* endOfFile)
 
2477
{
 
2478
    return stream->read(data, size, endOfFile);
 
2479
}