cap_ffmpeg_impl.hpp 75.7 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
V
Vadim Pisarevsky 已提交
10
//                          License Agreement
11 12
//                For Open Source Computer Vision Library
//
V
Vadim Pisarevsky 已提交
13 14
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 16 17 18 19 20 21 22 23 24 25 26
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
V
Vadim Pisarevsky 已提交
27
//   * The name of the copyright holders may not be used to endorse or promote products
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "cap_ffmpeg_api.hpp"
44 45 46
#if !(defined(WIN32) || defined(_WIN32) || defined(WINCE))
# include <pthread.h>
#endif
47
#include <assert.h>
48
#include <algorithm>
V
Vadim Pisarevsky 已提交
49
#include <limits>
50

51 52
#define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c )

53 54 55 56
#if defined _MSC_VER && _MSC_VER >= 1200
#pragma warning( disable: 4244 4510 4512 4610 )
#endif

A
Andrey Kamaev 已提交
57 58 59 60
#ifdef __GNUC__
#  pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif

61 62 63 64
#ifdef __cplusplus
extern "C" {
#endif

65 66
#include "ffmpeg_codecs.hpp"

V
Vadim Pisarevsky 已提交
67 68
#include <libavutil/mathematics.h>

69 70 71 72
#if LIBAVUTIL_BUILD > CALC_FFMPEG_VERSION(51,11,0)
  #include <libavutil/opt.h>
#endif

P
Peter Rekdal Sunde 已提交
73 74 75 76 77
#if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(51, 63, 100) : CALC_FFMPEG_VERSION(54, 6, 0))
#include <libavutil/imgutils.h>
#endif

78 79 80 81 82 83
#ifdef WIN32
  #define HAVE_FFMPEG_SWSCALE 1
  #include <libavcodec/avcodec.h>
  #include <libswscale/swscale.h>
#else

V
Vadim Pisarevsky 已提交
84 85 86
#ifndef HAVE_FFMPEG_SWSCALE
    #error "libswscale is necessary to build the newer OpenCV ffmpeg wrapper"
#endif
87

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
// if the header path is not specified explicitly, let's deduce it
#if !defined HAVE_FFMPEG_AVCODEC_H && !defined HAVE_LIBAVCODEC_AVCODEC_H

#if defined(HAVE_GENTOO_FFMPEG)
  #define HAVE_LIBAVCODEC_AVCODEC_H 1
  #if defined(HAVE_FFMPEG_SWSCALE)
    #define HAVE_LIBSWSCALE_SWSCALE_H 1
  #endif
#elif defined HAVE_FFMPEG
  #define HAVE_FFMPEG_AVCODEC_H 1
  #if defined(HAVE_FFMPEG_SWSCALE)
    #define HAVE_FFMPEG_SWSCALE_H 1
  #endif
#endif

#endif

#if defined(HAVE_FFMPEG_AVCODEC_H)
  #include <ffmpeg/avcodec.h>
#endif
#if defined(HAVE_FFMPEG_SWSCALE_H)
  #include <ffmpeg/swscale.h>
#endif

#if defined(HAVE_LIBAVCODEC_AVCODEC_H)
  #include <libavcodec/avcodec.h>
#endif
#if defined(HAVE_LIBSWSCALE_SWSCALE_H)
  #include <libswscale/swscale.h>
#endif

#endif

#ifdef __cplusplus
}
#endif

#if defined _MSC_VER && _MSC_VER >= 1200
#pragma warning( default: 4244 4510 4512 4610 )
#endif

#ifdef NDEBUG
#define CV_WARN(message)
#else
#define CV_WARN(message) fprintf(stderr, "warning: %s (%s:%d)\n", message, __FILE__, __LINE__)
#endif

135 136
#if defined WIN32 || defined _WIN32
    #include <windows.h>
137 138 139 140 141 142 143
    #if defined _MSC_VER && _MSC_VER < 1900
    struct timespec
    {
        time_t tv_sec;
        long   tv_nsec;
    };
  #endif
144 145 146
#elif defined __linux__ || defined __APPLE__
    #include <unistd.h>
    #include <stdio.h>
V
Vadim Pisarevsky 已提交
147
    #include <sys/types.h>
148
    #include <sys/time.h>
149
#if defined __APPLE__
150
    #include <sys/sysctl.h>
151 152
    #include <mach/clock.h>
    #include <mach/mach.h>
153
#endif
154
#endif
155

V
Vadim Pisarevsky 已提交
156 157 158 159 160 161 162 163 164 165
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif

#if defined(__APPLE__)
#define AV_NOPTS_VALUE_ ((int64_t)0x8000000000000000LL)
#else
#define AV_NOPTS_VALUE_ ((int64_t)AV_NOPTS_VALUE)
#endif

166 167 168 169
#ifndef AVERROR_EOF
#define AVERROR_EOF (-MKTAG( 'E','O','F',' '))
#endif

170 171 172 173 174 175 176 177
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54,25,0)
#  define CV_CODEC_ID AVCodecID
#  define CV_CODEC(name) AV_##name
#else
#  define CV_CODEC_ID CodecID
#  define CV_CODEC(name) name
#endif

J
jisli 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191
#if LIBAVUTIL_BUILD < (LIBAVUTIL_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(51, 74, 100) : CALC_FFMPEG_VERSION(51, 42, 0))
#define AVPixelFormat PixelFormat
#define AV_PIX_FMT_BGR24 PIX_FMT_BGR24
#define AV_PIX_FMT_RGB24 PIX_FMT_RGB24
#define AV_PIX_FMT_GRAY8 PIX_FMT_GRAY8
#define AV_PIX_FMT_YUV422P PIX_FMT_YUV422P
#define AV_PIX_FMT_YUV420P PIX_FMT_YUV420P
#define AV_PIX_FMT_YUV444P PIX_FMT_YUV444P
#define AV_PIX_FMT_YUVJ420P PIX_FMT_YUVJ420P
#define AV_PIX_FMT_GRAY16LE PIX_FMT_GRAY16LE
#define AV_PIX_FMT_GRAY16BE PIX_FMT_GRAY16BE
#endif

192 193 194 195 196 197 198 199 200 201
#if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(52, 38, 100) : CALC_FFMPEG_VERSION(52, 13, 0))
#define USE_AV_FRAME_GET_BUFFER 1
#else
#define USE_AV_FRAME_GET_BUFFER 0
#ifndef AV_NUM_DATA_POINTERS // required for 0.7.x/0.8.x ffmpeg releases
#define AV_NUM_DATA_POINTERS 4
#endif
#endif

202

203 204 205 206 207 208 209 210 211
#ifndef USE_AV_INTERRUPT_CALLBACK
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 21, 0)
#define USE_AV_INTERRUPT_CALLBACK 1
#else
#define USE_AV_INTERRUPT_CALLBACK 0
#endif
#endif

#if USE_AV_INTERRUPT_CALLBACK
212 213
#define LIBAVFORMAT_INTERRUPT_OPEN_TIMEOUT_MS 30000
#define LIBAVFORMAT_INTERRUPT_READ_TIMEOUT_MS 30000
214 215 216 217

#ifdef WIN32
// http://stackoverflow.com/questions/5404277/porting-clock-gettime-to-windows

218
static
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
inline LARGE_INTEGER get_filetime_offset()
{
    SYSTEMTIME s;
    FILETIME f;
    LARGE_INTEGER t;

    s.wYear = 1970;
    s.wMonth = 1;
    s.wDay = 1;
    s.wHour = 0;
    s.wMinute = 0;
    s.wSecond = 0;
    s.wMilliseconds = 0;
    SystemTimeToFileTime(&s, &f);
    t.QuadPart = f.dwHighDateTime;
    t.QuadPart <<= 32;
    t.QuadPart |= f.dwLowDateTime;
    return t;
}

239
static
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
inline void get_monotonic_time(timespec *tv)
{
    LARGE_INTEGER           t;
    FILETIME				f;
    double                  microseconds;
    static LARGE_INTEGER    offset;
    static double           frequencyToMicroseconds;
    static int              initialized = 0;
    static BOOL             usePerformanceCounter = 0;

    if (!initialized)
    {
        LARGE_INTEGER performanceFrequency;
        initialized = 1;
        usePerformanceCounter = QueryPerformanceFrequency(&performanceFrequency);
        if (usePerformanceCounter)
        {
            QueryPerformanceCounter(&offset);
            frequencyToMicroseconds = (double)performanceFrequency.QuadPart / 1000000.;
        }
        else
        {
            offset = get_filetime_offset();
            frequencyToMicroseconds = 10.;
        }
    }

    if (usePerformanceCounter)
    {
        QueryPerformanceCounter(&t);
    } else {
        GetSystemTimeAsFileTime(&f);
        t.QuadPart = f.dwHighDateTime;
        t.QuadPart <<= 32;
        t.QuadPart |= f.dwLowDateTime;
    }

    t.QuadPart -= offset.QuadPart;
    microseconds = (double)t.QuadPart / frequencyToMicroseconds;
    t.QuadPart = microseconds;
    tv->tv_sec = t.QuadPart / 1000000;
    tv->tv_nsec = (t.QuadPart % 1000000) * 1000;
}
#else
284
static
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
inline void get_monotonic_time(timespec *time)
{
#if defined(__APPLE__) && defined(__MACH__)
    clock_serv_t cclock;
    mach_timespec_t mts;
    host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
    clock_get_time(cclock, &mts);
    mach_port_deallocate(mach_task_self(), cclock);
    time->tv_sec = mts.tv_sec;
    time->tv_nsec = mts.tv_nsec;
#else
    clock_gettime(CLOCK_MONOTONIC, time);
#endif
}
#endif

301
static
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
inline timespec get_monotonic_time_diff(timespec start, timespec end)
{
    timespec temp;
    if (end.tv_nsec - start.tv_nsec < 0)
    {
        temp.tv_sec = end.tv_sec - start.tv_sec - 1;
        temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
    }
    else
    {
        temp.tv_sec = end.tv_sec - start.tv_sec;
        temp.tv_nsec = end.tv_nsec - start.tv_nsec;
    }
    return temp;
}

318
static
319 320 321 322 323 324 325
inline double get_monotonic_time_diff_ms(timespec time1, timespec time2)
{
    timespec delta = get_monotonic_time_diff(time1, time2);
    double milliseconds = delta.tv_sec * 1000 + (double)delta.tv_nsec / 1000000.0;

    return milliseconds;
}
326
#endif // USE_AV_INTERRUPT_CALLBACK
327

328
static int get_number_of_cpus(void)
329
{
V
Vadim Pisarevsky 已提交
330 331 332
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(52, 111, 0)
    return 1;
#elif defined WIN32 || defined _WIN32
333 334
    SYSTEM_INFO sysinfo;
    GetSystemInfo( &sysinfo );
V
Vadim Pisarevsky 已提交
335

336 337 338 339 340 341
    return (int)sysinfo.dwNumberOfProcessors;
#elif defined __linux__
    return (int)sysconf( _SC_NPROCESSORS_ONLN );
#elif defined __APPLE__
    int numCPU=0;
    int mib[4];
V
Vadim Pisarevsky 已提交
342 343 344
    size_t len = sizeof(numCPU);

    // set the mib for hw.ncpu
345 346
    mib[0] = CTL_HW;
    mib[1] = HW_AVAILCPU;  // alternatively, try HW_NCPU;
V
Vadim Pisarevsky 已提交
347 348

    // get the number of CPUs from the system
349
    sysctl(mib, 2, &numCPU, &len, NULL, 0);
V
Vadim Pisarevsky 已提交
350 351

    if( numCPU < 1 )
352 353 354
    {
        mib[1] = HW_NCPU;
        sysctl( mib, 2, &numCPU, &len, NULL, 0 );
V
Vadim Pisarevsky 已提交
355

356 357 358 359 360 361 362 363 364 365 366
        if( numCPU < 1 )
            numCPU = 1;
    }

    return (int)numCPU;
#else
    return 1;
#endif
}


367 368 369 370 371 372 373 374 375 376
struct Image_FFMPEG
{
    unsigned char* data;
    int step;
    int width;
    int height;
    int cn;
};


377
#if USE_AV_INTERRUPT_CALLBACK
378 379 380 381 382 383 384
struct AVInterruptCallbackMetadata
{
    timespec value;
    unsigned int timeout_after_ms;
    int timeout;
};

385
static
386 387 388 389 390 391
inline void _opencv_ffmpeg_free(void** ptr)
{
    if(*ptr) free(*ptr);
    *ptr = 0;
}

392
static
393 394 395 396 397
inline int _opencv_ffmpeg_interrupt_callback(void *ptr)
{
    AVInterruptCallbackMetadata* metadata = (AVInterruptCallbackMetadata*)ptr;
    assert(metadata);

398 399 400 401 402
    if (metadata->timeout_after_ms == 0)
    {
        return 0; // timeout is disabled
    }

403 404 405 406 407 408 409
    timespec now;
    get_monotonic_time(&now);

    metadata->timeout = get_monotonic_time_diff_ms(metadata->value, now) > metadata->timeout_after_ms;

    return metadata->timeout ? -1 : 0;
}
410
#endif
411

P
Peter Rekdal Sunde 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
static
inline void _opencv_ffmpeg_av_packet_unref(AVPacket *pkt)
{
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(55, 25, 100) : CALC_FFMPEG_VERSION(55, 16, 0))
    av_packet_unref(pkt);
#else
    av_free_packet(pkt);
#endif
};

static
inline void _opencv_ffmpeg_av_image_fill_arrays(void *frame, uint8_t *ptr, enum AVPixelFormat pix_fmt, int width, int height)
{
#if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(51, 63, 100) : CALC_FFMPEG_VERSION(54, 6, 0))
    av_image_fill_arrays(((AVFrame*)frame)->data, ((AVFrame*)frame)->linesize, ptr, pix_fmt, width, height, 1);
#else
    avpicture_fill((AVPicture*)frame, ptr, pix_fmt, width, height);
#endif
};

static
inline int _opencv_ffmpeg_av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height)
{
#if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(51, 63, 100) : CALC_FFMPEG_VERSION(54, 6, 0))
    return av_image_get_buffer_size(pix_fmt, width, height, 1);
#else
    return avpicture_get_size(pix_fmt, width, height);
#endif
};

445

446 447 448 449 450
struct CvCapture_FFMPEG
{
    bool open( const char* filename );
    void close();

451
    double getProperty(int) const;
452 453 454 455 456
    bool setProperty(int, double);
    bool grabFrame();
    bool retrieveFrame(int, unsigned char** data, int* step, int* width, int* height, int* cn);

    void init();
V
Vadim Pisarevsky 已提交
457 458 459

    void    seek(int64_t frame_number);
    void    seek(double sec);
460
    bool    slowSeek( int framenumber );
V
Vadim Pisarevsky 已提交
461

462 463 464 465
    int64_t get_total_frames() const;
    double  get_duration_sec() const;
    double  get_fps() const;
    int     get_bitrate() const;
466
    AVRational get_sample_aspect_ratio(AVStream *stream) const;
V
Vadim Pisarevsky 已提交
467

468
    double  r2d(AVRational r) const;
V
Vadim Pisarevsky 已提交
469 470 471 472 473 474 475
    int64_t dts_to_frame_number(int64_t dts);
    double  dts_to_sec(int64_t dts);

    AVFormatContext * ic;
    AVCodec         * avcodec;
    int               video_stream;
    AVStream        * video_st;
476 477
    AVFrame         * picture;
    AVFrame           rgb_picture;
V
Vadim Pisarevsky 已提交
478 479 480 481
    int64_t           picture_pts;

    AVPacket          packet;
    Image_FFMPEG      frame;
482
    struct SwsContext *img_convert_ctx;
V
Vadim Pisarevsky 已提交
483 484 485 486

    int64_t frame_number, first_frame_number;

    double eps_zero;
487 488 489 490 491 492 493 494
/*
   'filename' contains the filename of the videosource,
   'filename==NULL' indicates that ffmpeg's seek support works
   for the particular file.
   'filename!=NULL' indicates that the slow fallback function is used for seeking,
   and so the filename is needed to reopen the file on backward seeking.
*/
    char              * filename;
I
Ilya Lavrenov 已提交
495 496 497 498

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    AVDictionary *dict;
#endif
499
#if USE_AV_INTERRUPT_CALLBACK
500
    AVInterruptCallbackMetadata interrupt_metadata;
501
#endif
502 503 504 505 506 507 508 509
};

void CvCapture_FFMPEG::init()
{
    ic = 0;
    video_stream = -1;
    video_st = 0;
    picture = 0;
V
Vadim Pisarevsky 已提交
510 511
    picture_pts = AV_NOPTS_VALUE_;
    first_frame_number = -1;
512 513 514
    memset( &rgb_picture, 0, sizeof(rgb_picture) );
    memset( &frame, 0, sizeof(frame) );
    filename = 0;
V
Vadim Pisarevsky 已提交
515 516
    memset(&packet, 0, sizeof(packet));
    av_init_packet(&packet);
517
    img_convert_ctx = 0;
V
Vadim Pisarevsky 已提交
518 519 520 521

    avcodec = 0;
    frame_number = 0;
    eps_zero = 0.000025;
I
Ilya Lavrenov 已提交
522 523 524 525

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    dict = NULL;
#endif
526 527 528 529 530
}


void CvCapture_FFMPEG::close()
{
V
Vadim Pisarevsky 已提交
531 532 533 534 535
    if( img_convert_ctx )
    {
        sws_freeContext(img_convert_ctx);
        img_convert_ctx = 0;
    }
536

537
    if( picture )
538 539
    {
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
J
jisli 已提交
540 541 542
    ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
        av_frame_free(&picture);
#elif LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
543 544 545
    ? CALC_FFMPEG_VERSION(54, 59, 100) : CALC_FFMPEG_VERSION(54, 28, 0))
        avcodec_free_frame(&picture);
#else
546
        av_free(picture);
547 548
#endif
    }
549 550 551 552 553

    if( video_st )
    {
#if LIBAVFORMAT_BUILD > 4628
        avcodec_close( video_st->codec );
V
Vadim Pisarevsky 已提交
554

555
#else
V
Vadim Pisarevsky 已提交
556 557
        avcodec_close( &(video_st->codec) );

558 559 560 561 562 563
#endif
        video_st = NULL;
    }

    if( ic )
    {
V
Vadim Pisarevsky 已提交
564
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 24, 2)
565
        av_close_input_file(ic);
V
Vadim Pisarevsky 已提交
566
#else
567
        avformat_close_input(&ic);
V
Vadim Pisarevsky 已提交
568 569
#endif

570 571 572
        ic = NULL;
    }

573 574 575
#if USE_AV_FRAME_GET_BUFFER
    av_frame_unref(&rgb_picture);
#else
576 577 578 579 580
    if( rgb_picture.data[0] )
    {
        free( rgb_picture.data[0] );
        rgb_picture.data[0] = 0;
    }
581
#endif
582 583 584

    // free last packet if exist
    if (packet.data) {
P
Peter Rekdal Sunde 已提交
585
        _opencv_ffmpeg_av_packet_unref (&packet);
V
Vadim Pisarevsky 已提交
586
        packet.data = NULL;
587 588
    }

I
Ilya Lavrenov 已提交
589 590 591 592 593
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    if (dict != NULL)
       av_dict_free(&dict);
#endif

594 595 596 597 598
    init();
}


#ifndef AVSEEK_FLAG_FRAME
599
#define AVSEEK_FLAG_FRAME 0
600
#endif
A
Andrey Morozov 已提交
601
#ifndef AVSEEK_FLAG_ANY
602
#define AVSEEK_FLAG_ANY 1
603
#endif
V
Vadim Pisarevsky 已提交
604

I
Ilya Lavrenov 已提交
605
class ImplMutex
V
Vadim Pisarevsky 已提交
606
{
I
Ilya Lavrenov 已提交
607
public:
A
Andrey Kamaev 已提交
608 609 610
    ImplMutex() { init(); }
    ~ImplMutex() { destroy(); }

I
Ilya Lavrenov 已提交
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
    void init();
    void destroy();

    void lock();
    bool trylock();
    void unlock();

    struct Impl;
protected:
    Impl* impl;

private:
    ImplMutex(const ImplMutex&);
    ImplMutex& operator = (const ImplMutex& m);
};

#if defined WIN32 || defined _WIN32 || defined WINCE

struct ImplMutex::Impl
{
631 632 633 634 635 636 637 638 639
    void init()
    {
#if (_WIN32_WINNT >= 0x0600)
        ::InitializeCriticalSectionEx(&cs, 1000, 0);
#else
        ::InitializeCriticalSection(&cs);
#endif
        refcount = 1;
    }
I
Ilya Lavrenov 已提交
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
    void destroy() { DeleteCriticalSection(&cs); }

    void lock() { EnterCriticalSection(&cs); }
    bool trylock() { return TryEnterCriticalSection(&cs) != 0; }
    void unlock() { LeaveCriticalSection(&cs); }

    CRITICAL_SECTION cs;
    int refcount;
};

#ifndef __GNUC__
static int _interlockedExchangeAdd(int* addr, int delta)
{
#if defined _MSC_VER && _MSC_VER >= 1500
    return (int)_InterlockedExchangeAdd((long volatile*)addr, delta);
#else
    return (int)InterlockedExchangeAdd((long volatile*)addr, delta);
#endif
}
#endif // __GNUC__

#elif defined __APPLE__

#include <libkern/OSAtomic.h>

struct ImplMutex::Impl
{
    void init() { sl = OS_SPINLOCK_INIT; refcount = 1; }
    void destroy() { }

    void lock() { OSSpinLockLock(&sl); }
    bool trylock() { return OSSpinLockTry(&sl); }
    void unlock() { OSSpinLockUnlock(&sl); }

    OSSpinLock sl;
    int refcount;
};

#elif defined __linux__ && !defined ANDROID

struct ImplMutex::Impl
{
    void init() { pthread_spin_init(&sl, 0); refcount = 1; }
    void destroy() { pthread_spin_destroy(&sl); }

    void lock() { pthread_spin_lock(&sl); }
    bool trylock() { return pthread_spin_trylock(&sl) == 0; }
    void unlock() { pthread_spin_unlock(&sl); }

    pthread_spinlock_t sl;
    int refcount;
};

#else

struct ImplMutex::Impl
{
    void init() { pthread_mutex_init(&sl, 0); refcount = 1; }
    void destroy() { pthread_mutex_destroy(&sl); }

    void lock() { pthread_mutex_lock(&sl); }
    bool trylock() { return pthread_mutex_trylock(&sl) == 0; }
    void unlock() { pthread_mutex_unlock(&sl); }

    pthread_mutex_t sl;
    int refcount;
};

#endif

void ImplMutex::init()
{
A
Andrey Kamaev 已提交
712 713
    impl = (Impl*)malloc(sizeof(Impl));
    impl->init();
I
Ilya Lavrenov 已提交
714
}
A
Andrey Kamaev 已提交
715
void ImplMutex::destroy()
I
Ilya Lavrenov 已提交
716
{
A
Andrey Kamaev 已提交
717 718 719
    impl->destroy();
    free(impl);
    impl = NULL;
I
Ilya Lavrenov 已提交
720 721 722 723 724 725 726 727 728
}
void ImplMutex::lock() { impl->lock(); }
void ImplMutex::unlock() { impl->unlock(); }
bool ImplMutex::trylock() { return impl->trylock(); }

static int LockCallBack(void **mutex, AVLockOp op)
{
    ImplMutex* localMutex = reinterpret_cast<ImplMutex*>(*mutex);
    switch (op)
729
    {
I
Ilya Lavrenov 已提交
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
        case AV_LOCK_CREATE:
            localMutex = reinterpret_cast<ImplMutex*>(malloc(sizeof(ImplMutex)));
            localMutex->init();
            *mutex = localMutex;
            if (!*mutex)
                return 1;
        break;

        case AV_LOCK_OBTAIN:
            localMutex->lock();
        break;

        case AV_LOCK_RELEASE:
            localMutex->unlock();
        break;

        case AV_LOCK_DESTROY:
            localMutex->destroy();
            free(localMutex);
            localMutex = NULL;
750
            *mutex = NULL;
I
Ilya Lavrenov 已提交
751 752 753 754 755 756 757 758 759 760 761 762
        break;
    }
    return 0;
}

static ImplMutex _mutex;
static bool _initialized = false;

class InternalFFMpegRegister
{
public:
    InternalFFMpegRegister()
763
    {
I
Ilya Lavrenov 已提交
764 765 766
        _mutex.lock();
        if (!_initialized)
        {
767
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 13, 0)
I
Ilya Lavrenov 已提交
768
            avformat_network_init();
769
    #endif
V
Vadim Pisarevsky 已提交
770

I
Ilya Lavrenov 已提交
771 772
            /* register all codecs, demux and protocols */
            av_register_all();
V
Vadim Pisarevsky 已提交
773

I
Ilya Lavrenov 已提交
774 775
            /* register a callback function for synchronization */
            av_lockmgr_register(&LockCallBack);
776

I
Ilya Lavrenov 已提交
777
            av_log_set_level(AV_LOG_ERROR);
V
Vadim Pisarevsky 已提交
778

I
Ilya Lavrenov 已提交
779 780 781
            _initialized = true;
        }
        _mutex.unlock();
V
Vadim Pisarevsky 已提交
782
    }
783

I
Ilya Lavrenov 已提交
784 785 786 787
    ~InternalFFMpegRegister()
    {
        _initialized = false;
        av_lockmgr_register(NULL);
V
Vadim Pisarevsky 已提交
788
    }
I
Ilya Lavrenov 已提交
789 790 791
};

static InternalFFMpegRegister _init;
792 793 794 795 796 797 798

bool CvCapture_FFMPEG::open( const char* _filename )
{
    unsigned i;
    bool valid = false;

    close();
799

800
#if USE_AV_INTERRUPT_CALLBACK
801
    /* interrupt callback */
802
    interrupt_metadata.timeout_after_ms = LIBAVFORMAT_INTERRUPT_OPEN_TIMEOUT_MS;
803 804 805 806 807
    get_monotonic_time(&interrupt_metadata.value);

    ic = avformat_alloc_context();
    ic->interrupt_callback.callback = _opencv_ffmpeg_interrupt_callback;
    ic->interrupt_callback.opaque = &interrupt_metadata;
808
#endif
809

V
Vadim Pisarevsky 已提交
810
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
I
Ilya Lavrenov 已提交
811
    av_dict_set(&dict, "rtsp_transport", "tcp", 0);
812
    int err = avformat_open_input(&ic, _filename, NULL, &dict);
V
Vadim Pisarevsky 已提交
813
#else
814
    int err = av_open_input_file(&ic, _filename, NULL, 0, NULL);
815 816
#endif

I
Ilya Lavrenov 已提交
817 818
    if (err < 0)
    {
V
Vadim Pisarevsky 已提交
819
        CV_WARN("Error opening file");
820
        CV_WARN(_filename);
V
Vadim Pisarevsky 已提交
821
        goto exit_func;
822
    }
V
Vadim Pisarevsky 已提交
823
    err =
R
Roman Donchenko 已提交
824
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
V
Vadim Pisarevsky 已提交
825 826 827 828
    avformat_find_stream_info(ic, NULL);
#else
    av_find_stream_info(ic);
#endif
I
Ilya Lavrenov 已提交
829 830
    if (err < 0)
    {
V
Vadim Pisarevsky 已提交
831 832
        CV_WARN("Could not find codec parameters");
        goto exit_func;
833
    }
V
Vadim Pisarevsky 已提交
834 835
    for(i = 0; i < ic->nb_streams; i++)
    {
836 837 838 839 840 841
#if LIBAVFORMAT_BUILD > 4628
        AVCodecContext *enc = ic->streams[i]->codec;
#else
        AVCodecContext *enc = &ic->streams[i]->codec;
#endif

I
Ilya Lavrenov 已提交
842 843 844
//#ifdef FF_API_THREAD_INIT
//        avcodec_thread_init(enc, get_number_of_cpus());
//#else
V
Vadim Pisarevsky 已提交
845
        enc->thread_count = get_number_of_cpus();
I
Ilya Lavrenov 已提交
846
//#endif
847

848 849 850
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
#define AVMEDIA_TYPE_VIDEO CODEC_TYPE_VIDEO
#endif
V
Vadim Pisarevsky 已提交
851

I
Ilya Lavrenov 已提交
852 853
        if( AVMEDIA_TYPE_VIDEO == enc->codec_type && video_stream < 0)
        {
G
gferry 已提交
854 855 856 857
            // backup encoder' width/height
            int enc_width = enc->width;
            int enc_height = enc->height;

A
Andrey Morozov 已提交
858
            AVCodec *codec = avcodec_find_decoder(enc->codec_id);
859
            if (!codec ||
V
Vadim Pisarevsky 已提交
860 861 862 863 864
#if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
                avcodec_open2(enc, codec, NULL)
#else
                avcodec_open(enc, codec)
#endif
I
Ilya Lavrenov 已提交
865 866
                < 0)
                goto exit_func;
V
Vadim Pisarevsky 已提交
867

G
gferry 已提交
868 869 870 871
            // checking width/height (since decoder can sometimes alter it, eg. vp6f)
            if (enc_width && (enc->width != enc_width)) { enc->width = enc_width; }
            if (enc_height && (enc->height != enc_height)) { enc->height = enc_height; }

872 873
            video_stream = i;
            video_st = ic->streams[i];
J
jisli 已提交
874 875 876 877
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
            picture = av_frame_alloc();
#else
878
            picture = avcodec_alloc_frame();
J
jisli 已提交
879
#endif
880 881 882 883

            frame.width = enc->width;
            frame.height = enc->height;
            frame.cn = 3;
884 885
            frame.step = 0;
            frame.data = NULL;
886 887 888 889 890 891
            break;
        }
    }

    if(video_stream >= 0) valid = true;

V
Vadim Pisarevsky 已提交
892
exit_func:
893

894 895 896 897 898
#if USE_AV_INTERRUPT_CALLBACK
    // deactivate interrupt callback
    interrupt_metadata.timeout_after_ms = 0;
#endif

899 900 901 902 903 904 905 906 907 908 909 910
    if( !valid )
        close();

    return valid;
}


bool CvCapture_FFMPEG::grabFrame()
{
    bool valid = false;
    int got_picture;

V
Vadim Pisarevsky 已提交
911
    int count_errs = 0;
J
jormansa 已提交
912
    const int max_number_of_attempts = 1 << 9;
913

V
Vadim Pisarevsky 已提交
914
    if( !ic || !video_st )  return false;
915

916 917 918
    if( ic->streams[video_stream]->nb_frames > 0 &&
        frame_number > ic->streams[video_stream]->nb_frames )
        return false;
919

V
Vadim Pisarevsky 已提交
920
    picture_pts = AV_NOPTS_VALUE_;
921

922 923 924 925 926 927
#if USE_AV_INTERRUPT_CALLBACK
    // activate interrupt callback
    get_monotonic_time(&interrupt_metadata.value);
    interrupt_metadata.timeout_after_ms = LIBAVFORMAT_INTERRUPT_READ_TIMEOUT_MS;
#endif

928
    // get the next frame
V
Vadim Pisarevsky 已提交
929 930
    while (!valid)
    {
H
hahne 已提交
931

P
Peter Rekdal Sunde 已提交
932
        _opencv_ffmpeg_av_packet_unref (&packet);
933

934
#if USE_AV_INTERRUPT_CALLBACK
935 936 937 938 939
        if (interrupt_metadata.timeout)
        {
            valid = false;
            break;
        }
940
#endif
941

942
        int ret = av_read_frame(ic, &packet);
V
Vadim Pisarevsky 已提交
943 944 945 946 947 948
        if (ret == AVERROR(EAGAIN)) continue;

        /* else if (ret < 0) break; */

        if( packet.stream_index != video_stream )
        {
P
Peter Rekdal Sunde 已提交
949
            _opencv_ffmpeg_av_packet_unref (&packet);
V
Vadim Pisarevsky 已提交
950 951 952
            count_errs++;
            if (count_errs > max_number_of_attempts)
                break;
953 954
            continue;
        }
955

V
Vadim Pisarevsky 已提交
956 957 958 959 960 961 962 963 964 965 966 967
        // Decode video frame
        #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
            avcodec_decode_video2(video_st->codec, picture, &got_picture, &packet);
        #elif LIBAVFORMAT_BUILD > 4628
                avcodec_decode_video(video_st->codec,
                                     picture, &got_picture,
                                     packet.data, packet.size);
        #else
                avcodec_decode_video(&video_st->codec,
                                     picture, &got_picture,
                                     packet.data, packet.size);
        #endif
968

V
Vadim Pisarevsky 已提交
969 970 971 972 973
        // Did we get a video frame?
        if(got_picture)
        {
            //picture_pts = picture->best_effort_timestamp;
            if( picture_pts == AV_NOPTS_VALUE_ )
974 975
                picture_pts = picture->pkt_pts != AV_NOPTS_VALUE_ && picture->pkt_pts != 0 ? picture->pkt_pts : picture->pkt_dts;

V
Vadim Pisarevsky 已提交
976 977 978 979 980 981 982 983
            frame_number++;
            valid = true;
        }
        else
        {
            count_errs++;
            if (count_errs > max_number_of_attempts)
                break;
984 985 986
        }
    }

V
Vadim Pisarevsky 已提交
987 988
    if( valid && first_frame_number < 0 )
        first_frame_number = dts_to_frame_number(picture_pts);
989

990 991 992 993 994
#if USE_AV_INTERRUPT_CALLBACK
    // deactivate interrupt callback
    interrupt_metadata.timeout_after_ms = 0;
#endif

995 996 997 998 999 1000 1001 1002 1003 1004
    // return if we have a new picture or not
    return valid;
}


bool CvCapture_FFMPEG::retrieveFrame(int, unsigned char** data, int* step, int* width, int* height, int* cn)
{
    if( !video_st || !picture->data[0] )
        return false;

V
Vadim Pisarevsky 已提交
1005 1006
    if( img_convert_ctx == NULL ||
        frame.width != video_st->codec->width ||
1007 1008
        frame.height != video_st->codec->height ||
        frame.data == NULL )
V
Vadim Pisarevsky 已提交
1009
    {
1010 1011 1012
        // Some sws_scale optimizations have some assumptions about alignment of data/step/width/height
        // Also we use coded_width/height to workaround problem with legacy ffmpeg versions (like n0.8)
        int buffer_width = video_st->codec->coded_width, buffer_height = video_st->codec->coded_height;
V
Vadim Pisarevsky 已提交
1013 1014

        img_convert_ctx = sws_getCachedContext(
1015 1016
                img_convert_ctx,
                buffer_width, buffer_height,
V
Vadim Pisarevsky 已提交
1017
                video_st->codec->pix_fmt,
1018
                buffer_width, buffer_height,
J
jisli 已提交
1019
                AV_PIX_FMT_BGR24,
V
Vadim Pisarevsky 已提交
1020 1021 1022 1023 1024 1025
                SWS_BICUBIC,
                NULL, NULL, NULL
                );

        if (img_convert_ctx == NULL)
            return false;//CV_Error(0, "Cannot initialize the conversion context!");
1026

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
#if USE_AV_FRAME_GET_BUFFER
        av_frame_unref(&rgb_picture);
        rgb_picture.format = AV_PIX_FMT_BGR24;
        rgb_picture.width = buffer_width;
        rgb_picture.height = buffer_height;
        if (0 != av_frame_get_buffer(&rgb_picture, 32))
        {
            CV_WARN("OutOfMemory");
            return false;
        }
#else
        int aligns[AV_NUM_DATA_POINTERS];
        avcodec_align_dimensions2(video_st->codec, &buffer_width, &buffer_height, aligns);
1040
        rgb_picture.data[0] = (uint8_t*)realloc(rgb_picture.data[0],
P
Peter Rekdal Sunde 已提交
1041
                _opencv_ffmpeg_av_image_get_buffer_size( AV_PIX_FMT_BGR24,
1042
                                    buffer_width, buffer_height ));
P
Peter Rekdal Sunde 已提交
1043
        _opencv_ffmpeg_av_image_fill_arrays(&rgb_picture, rgb_picture.data[0],
1044 1045 1046 1047 1048
                        AV_PIX_FMT_BGR24, buffer_width, buffer_height );
#endif
        frame.width = video_st->codec->width;
        frame.height = video_st->codec->height;
        frame.cn = 3;
1049
        frame.data = rgb_picture.data[0];
1050
        frame.step = rgb_picture.linesize[0];
V
Vadim Pisarevsky 已提交
1051 1052 1053 1054 1055 1056
    }

    sws_scale(
            img_convert_ctx,
            picture->data,
            picture->linesize,
1057
            0, video_st->codec->coded_height,
V
Vadim Pisarevsky 已提交
1058 1059 1060 1061
            rgb_picture.data,
            rgb_picture.linesize
            );

1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    *data = frame.data;
    *step = frame.step;
    *width = frame.width;
    *height = frame.height;
    *cn = frame.cn;

    return true;
}


1072
double CvCapture_FFMPEG::getProperty( int property_id ) const
1073 1074 1075 1076 1077
{
    if( !video_st ) return 0;

    switch( property_id )
    {
V
Vadim Pisarevsky 已提交
1078 1079
    case CV_FFMPEG_CAP_PROP_POS_MSEC:
        return 1000.0*(double)frame_number/get_fps();
1080
    case CV_FFMPEG_CAP_PROP_POS_FRAMES:
V
Vadim Pisarevsky 已提交
1081
        return (double)frame_number;
1082
    case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
V
Vadim Pisarevsky 已提交
1083
        return r2d(ic->streams[video_stream]->time_base);
1084
    case CV_FFMPEG_CAP_PROP_FRAME_COUNT:
V
Vadim Pisarevsky 已提交
1085
        return (double)get_total_frames();
1086 1087 1088 1089 1090
    case CV_FFMPEG_CAP_PROP_FRAME_WIDTH:
        return (double)frame.width;
    case CV_FFMPEG_CAP_PROP_FRAME_HEIGHT:
        return (double)frame.height;
    case CV_FFMPEG_CAP_PROP_FPS:
1091
        return get_fps();
1092 1093 1094 1095 1096 1097
    case CV_FFMPEG_CAP_PROP_FOURCC:
#if LIBAVFORMAT_BUILD > 4628
        return (double)video_st->codec->codec_tag;
#else
        return (double)video_st->codec.codec_tag;
#endif
1098 1099 1100 1101
    case CV_FFMPEG_CAP_PROP_SAR_NUM:
        return get_sample_aspect_ratio(ic->streams[video_stream]).num;
    case CV_FFMPEG_CAP_PROP_SAR_DEN:
        return get_sample_aspect_ratio(ic->streams[video_stream]).den;
V
Vadim Pisarevsky 已提交
1102
    default:
1103
        break;
1104
    }
V
Vadim Pisarevsky 已提交
1105

1106 1107 1108
    return 0;
}

1109
double CvCapture_FFMPEG::r2d(AVRational r) const
V
Vadim Pisarevsky 已提交
1110 1111 1112 1113
{
    return r.num == 0 || r.den == 0 ? 0. : (double)r.num / (double)r.den;
}

1114
double CvCapture_FFMPEG::get_duration_sec() const
1115
{
V
Vadim Pisarevsky 已提交
1116 1117 1118
    double sec = (double)ic->duration / (double)AV_TIME_BASE;

    if (sec < eps_zero)
1119
    {
V
Vadim Pisarevsky 已提交
1120
        sec = (double)ic->streams[video_stream]->duration * r2d(ic->streams[video_stream]->time_base);
1121
    }
V
Vadim Pisarevsky 已提交
1122 1123

    if (sec < eps_zero)
1124
    {
V
Vadim Pisarevsky 已提交
1125
        sec = (double)ic->streams[video_stream]->duration * r2d(ic->streams[video_stream]->time_base);
1126
    }
V
Vadim Pisarevsky 已提交
1127 1128

    return sec;
1129 1130
}

1131
int CvCapture_FFMPEG::get_bitrate() const
1132
{
V
Vadim Pisarevsky 已提交
1133 1134 1135
    return ic->bit_rate;
}

1136
double CvCapture_FFMPEG::get_fps() const
V
Vadim Pisarevsky 已提交
1137
{
A
Alexander Alekhin 已提交
1138 1139 1140 1141 1142 1143
#if 0 && LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 1, 100) && LIBAVFORMAT_VERSION_MICRO >= 100
    double fps = r2d(av_guess_frame_rate(ic, ic->streams[video_stream], NULL));
#else
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54, 1, 0)
    double fps = r2d(ic->streams[video_stream]->avg_frame_rate);
#else
V
Vadim Pisarevsky 已提交
1144
    double fps = r2d(ic->streams[video_stream]->r_frame_rate);
A
Alexander Alekhin 已提交
1145
#endif
V
Vadim Pisarevsky 已提交
1146 1147 1148 1149 1150

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    if (fps < eps_zero)
    {
        fps = r2d(ic->streams[video_stream]->avg_frame_rate);
1151
    }
1152
#endif
V
Vadim Pisarevsky 已提交
1153 1154 1155 1156 1157

    if (fps < eps_zero)
    {
        fps = 1.0 / r2d(ic->streams[video_stream]->codec->time_base);
    }
A
Alexander Alekhin 已提交
1158
#endif
V
Vadim Pisarevsky 已提交
1159 1160 1161
    return fps;
}

1162
int64_t CvCapture_FFMPEG::get_total_frames() const
V
Vadim Pisarevsky 已提交
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
{
    int64_t nbf = ic->streams[video_stream]->nb_frames;

    if (nbf == 0)
    {
        nbf = (int64_t)floor(get_duration_sec() * get_fps() + 0.5);
    }
    return nbf;
}

int64_t CvCapture_FFMPEG::dts_to_frame_number(int64_t dts)
{
    double sec = dts_to_sec(dts);
    return (int64_t)(get_fps() * sec + 0.5);
}

1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
AVRational CvCapture_FFMPEG::get_sample_aspect_ratio(AVStream *stream) const
{
    AVRational undef = {0, 1};
    AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
    AVRational frame_sample_aspect_ratio  = stream && stream->codec ? stream->codec->sample_aspect_ratio : undef;

    av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
        stream_sample_aspect_ratio.num,  stream_sample_aspect_ratio.den, INT_MAX);
    if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
        stream_sample_aspect_ratio = undef;

    av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
        frame_sample_aspect_ratio.num,  frame_sample_aspect_ratio.den, INT_MAX);
    if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
        frame_sample_aspect_ratio = undef;

    if (stream_sample_aspect_ratio.num)
        return stream_sample_aspect_ratio;
    else
        return frame_sample_aspect_ratio;
}

V
Vadim Pisarevsky 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
double CvCapture_FFMPEG::dts_to_sec(int64_t dts)
{
    return (double)(dts - ic->streams[video_stream]->start_time) *
        r2d(ic->streams[video_stream]->time_base);
}

void CvCapture_FFMPEG::seek(int64_t _frame_number)
{
    _frame_number = std::min(_frame_number, get_total_frames());
    int delta = 16;
1211

V
Vadim Pisarevsky 已提交
1212 1213
    // if we have not grabbed a single frame before first seek, let's read the first frame
    // and get some valuable information during the process
1214
    if( first_frame_number < 0 && get_total_frames() > 1 )
1215
        grabFrame();
1216

V
Vadim Pisarevsky 已提交
1217 1218 1219 1220 1221 1222 1223
    for(;;)
    {
        int64_t _frame_number_temp = std::max(_frame_number-delta, (int64_t)0);
        double sec = (double)_frame_number_temp / get_fps();
        int64_t time_stamp = ic->streams[video_stream]->start_time;
        double  time_base  = r2d(ic->streams[video_stream]->time_base);
        time_stamp += (int64_t)(sec / time_base + 0.5);
1224
        if (get_total_frames() > 1) av_seek_frame(ic, video_stream, time_stamp, AVSEEK_FLAG_BACKWARD);
V
Vadim Pisarevsky 已提交
1225 1226 1227 1228
        avcodec_flush_buffers(ic->streams[video_stream]->codec);
        if( _frame_number > 0 )
        {
            grabFrame();
1229

V
Vadim Pisarevsky 已提交
1230 1231 1232 1233 1234
            if( _frame_number > 1 )
            {
                frame_number = dts_to_frame_number(picture_pts) - first_frame_number;
                //printf("_frame_number = %d, frame_number = %d, delta = %d\n",
                //       (int)_frame_number, (int)frame_number, delta);
1235

V
Vadim Pisarevsky 已提交
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
                if( frame_number < 0 || frame_number > _frame_number-1 )
                {
                    if( _frame_number_temp == 0 || delta >= INT_MAX/4 )
                        break;
                    delta = delta < 16 ? delta*2 : delta*3/2;
                    continue;
                }
                while( frame_number < _frame_number-1 )
                {
                    if(!grabFrame())
                        break;
                }
                frame_number++;
                break;
            }
            else
            {
                frame_number = 1;
                break;
            }
        }
        else
        {
            frame_number = 0;
            break;
        }
1262
    }
V
Vadim Pisarevsky 已提交
1263 1264 1265 1266 1267
}

void CvCapture_FFMPEG::seek(double sec)
{
    seek((int64_t)(sec * get_fps() + 0.5));
1268
}
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282

bool CvCapture_FFMPEG::setProperty( int property_id, double value )
{
    if( !video_st ) return false;

    switch( property_id )
    {
    case CV_FFMPEG_CAP_PROP_POS_MSEC:
    case CV_FFMPEG_CAP_PROP_POS_FRAMES:
    case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
        {
            switch( property_id )
            {
            case CV_FFMPEG_CAP_PROP_POS_FRAMES:
V
Vadim Pisarevsky 已提交
1283
                seek((int64_t)value);
1284 1285 1286
                break;

            case CV_FFMPEG_CAP_PROP_POS_MSEC:
V
Vadim Pisarevsky 已提交
1287
                seek(value/1000.0);
1288 1289 1290
                break;

            case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
V
Vadim Pisarevsky 已提交
1291
                seek((int64_t)(value*ic->duration));
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
                break;
            }

            picture_pts=(int64_t)value;
        }
        break;
    default:
        return false;
    }

    return true;
}


///////////////// FFMPEG CvVideoWriter implementation //////////////////////////
struct CvVideoWriter_FFMPEG
{
    bool open( const char* filename, int fourcc,
1310
               double fps, int width, int height, bool isColor );
1311 1312 1313 1314 1315
    void close();
    bool writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin );

    void init();

1316
    AVOutputFormat  * fmt;
V
Vadim Pisarevsky 已提交
1317
    AVFormatContext * oc;
1318 1319 1320 1321 1322 1323 1324 1325
    uint8_t         * outbuf;
    uint32_t          outbuf_size;
    FILE            * outfile;
    AVFrame         * picture;
    AVFrame         * input_picture;
    uint8_t         * picbuf;
    AVStream        * video_st;
    int               input_pix_fmt;
1326
    unsigned char   * aligned_input;
V
Vadim Pisarevsky 已提交
1327
    int               frame_width, frame_height;
1328
    int               frame_idx;
V
Vadim Pisarevsky 已提交
1329
    bool              ok;
1330 1331 1332 1333 1334
    struct SwsContext *img_convert_ctx;
};

static const char * icvFFMPEGErrStr(int err)
{
1335
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
1336
    switch(err) {
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
    case AVERROR_BSF_NOT_FOUND:
        return "Bitstream filter not found";
    case AVERROR_DECODER_NOT_FOUND:
        return "Decoder not found";
    case AVERROR_DEMUXER_NOT_FOUND:
        return "Demuxer not found";
    case AVERROR_ENCODER_NOT_FOUND:
        return "Encoder not found";
    case AVERROR_EOF:
        return "End of file";
    case AVERROR_EXIT:
        return "Immediate exit was requested; the called function should not be restarted";
    case AVERROR_FILTER_NOT_FOUND:
        return "Filter not found";
    case AVERROR_INVALIDDATA:
        return "Invalid data found when processing input";
    case AVERROR_MUXER_NOT_FOUND:
        return "Muxer not found";
    case AVERROR_OPTION_NOT_FOUND:
        return "Option not found";
    case AVERROR_PATCHWELCOME:
        return "Not yet implemented in FFmpeg, patches welcome";
    case AVERROR_PROTOCOL_NOT_FOUND:
        return "Protocol not found";
    case AVERROR_STREAM_NOT_FOUND:
        return "Stream not found";
    default:
        break;
V
Vadim Pisarevsky 已提交
1365
    }
1366
#else
1367 1368
    switch(err) {
    case AVERROR_NUMEXPECTED:
V
Vadim Pisarevsky 已提交
1369
        return "Incorrect filename syntax";
1370
    case AVERROR_INVALIDDATA:
V
Vadim Pisarevsky 已提交
1371
        return "Invalid data in header";
1372
    case AVERROR_NOFMT:
V
Vadim Pisarevsky 已提交
1373
        return "Unknown format";
1374
    case AVERROR_IO:
V
Vadim Pisarevsky 已提交
1375
        return "I/O error occurred";
1376
    case AVERROR_NOMEM:
V
Vadim Pisarevsky 已提交
1377
        return "Memory allocation error";
1378
    default:
V
Vadim Pisarevsky 已提交
1379
        break;
1380
    }
1381 1382
#endif

V
Vadim Pisarevsky 已提交
1383
    return "Unspecified error";
1384 1385 1386 1387
}

/* function internal to FFMPEG (libavformat/riff.c) to lookup codec id by fourcc tag*/
extern "C" {
1388
    enum CV_CODEC_ID codec_get_bmp_id(unsigned int tag);
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
}

void CvVideoWriter_FFMPEG::init()
{
    fmt = 0;
    oc = 0;
    outbuf = 0;
    outbuf_size = 0;
    outfile = 0;
    picture = 0;
    input_picture = 0;
    picbuf = 0;
    video_st = 0;
    input_pix_fmt = 0;
1403
    aligned_input = NULL;
1404
    img_convert_ctx = 0;
V
Vadim Pisarevsky 已提交
1405
    frame_width = frame_height = 0;
1406
    frame_idx = 0;
V
Vadim Pisarevsky 已提交
1407
    ok = false;
1408 1409 1410 1411 1412 1413 1414 1415
}

/**
 * the following function is a modified version of code
 * found in ffmpeg-0.4.9-pre1/output_example.c
 */
static AVFrame * icv_alloc_picture_FFMPEG(int pix_fmt, int width, int height, bool alloc)
{
V
Vadim Pisarevsky 已提交
1416 1417 1418 1419
    AVFrame * picture;
    uint8_t * picture_buf;
    int size;

J
jisli 已提交
1420 1421 1422 1423
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
    picture = av_frame_alloc();
#else
V
Vadim Pisarevsky 已提交
1424
    picture = avcodec_alloc_frame();
J
jisli 已提交
1425
#endif
V
Vadim Pisarevsky 已提交
1426 1427
    if (!picture)
        return NULL;
1428 1429 1430 1431 1432

    picture->format = pix_fmt;
    picture->width = width;
    picture->height = height;

P
Peter Rekdal Sunde 已提交
1433
    size = _opencv_ffmpeg_av_image_get_buffer_size( (AVPixelFormat) pix_fmt, width, height);
V
Vadim Pisarevsky 已提交
1434 1435 1436 1437 1438 1439 1440
    if(alloc){
        picture_buf = (uint8_t *) malloc(size);
        if (!picture_buf)
        {
            av_free(picture);
            return NULL;
        }
P
Peter Rekdal Sunde 已提交
1441
        _opencv_ffmpeg_av_image_fill_arrays(picture, picture_buf,
J
jisli 已提交
1442
                       (AVPixelFormat) pix_fmt, width, height);
V
Vadim Pisarevsky 已提交
1443 1444 1445 1446
    }
    else {
    }
    return picture;
1447 1448 1449 1450
}

/* add a video output stream to the container */
static AVStream *icv_add_video_stream_FFMPEG(AVFormatContext *oc,
1451
                                             CV_CODEC_ID codec_id,
V
Vadim Pisarevsky 已提交
1452 1453
                                             int w, int h, int bitrate,
                                             double fps, int pixel_format)
1454
{
V
Vadim Pisarevsky 已提交
1455 1456 1457 1458
    AVCodecContext *c;
    AVStream *st;
    int frame_rate, frame_rate_base;
    AVCodec *codec;
1459

V
Vadim Pisarevsky 已提交
1460 1461 1462 1463 1464
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 10, 0)
    st = avformat_new_stream(oc, 0);
#else
    st = av_new_stream(oc, 0);
#endif
1465

V
Vadim Pisarevsky 已提交
1466 1467 1468 1469
    if (!st) {
        CV_WARN("Could not allocate stream");
        return NULL;
    }
1470 1471

#if LIBAVFORMAT_BUILD > 4628
V
Vadim Pisarevsky 已提交
1472
    c = st->codec;
1473
#else
V
Vadim Pisarevsky 已提交
1474
    c = &(st->codec);
1475 1476 1477
#endif

#if LIBAVFORMAT_BUILD > 4621
V
Vadim Pisarevsky 已提交
1478
    c->codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
1479
#else
V
Vadim Pisarevsky 已提交
1480
    c->codec_id = oc->oformat->video_codec;
1481 1482
#endif

1483
    if(codec_id != CV_CODEC(CODEC_ID_NONE)){
V
Vadim Pisarevsky 已提交
1484 1485
        c->codec_id = codec_id;
    }
1486 1487

    //if(codec_tag) c->codec_tag=codec_tag;
V
Vadim Pisarevsky 已提交
1488
    codec = avcodec_find_encoder(c->codec_id);
1489

V
Vadim Pisarevsky 已提交
1490
    c->codec_type = AVMEDIA_TYPE_VIDEO;
1491

1492
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54,25,0)
1493 1494 1495 1496 1497
    // Set per-codec defaults
    AVCodecID c_id = c->codec_id;
    avcodec_get_context_defaults3(c, codec);
    // avcodec_get_context_defaults3 erases codec_id for some reason
    c->codec_id = c_id;
1498
#endif
1499

V
Vadim Pisarevsky 已提交
1500 1501 1502 1503 1504
    /* put sample parameters */
    int64_t lbit_rate = (int64_t)bitrate;
    lbit_rate += (bitrate / 2);
    lbit_rate = std::min(lbit_rate, (int64_t)INT_MAX);
    c->bit_rate = lbit_rate;
1505

V
Vadim Pisarevsky 已提交
1506 1507 1508
    // took advice from
    // http://ffmpeg-users.933282.n4.nabble.com/warning-clipping-1-dct-coefficients-to-127-127-td934297.html
    c->qmin = 3;
1509

V
Vadim Pisarevsky 已提交
1510 1511 1512 1513 1514 1515
    /* resolution must be a multiple of two */
    c->width = w;
    c->height = h;

    /* time base: this is the fundamental unit of time (in seconds) in terms
       of which frame timestamps are represented. for fixed-fps content,
1516 1517
       timebase should be 1/framerate and timestamp increments should be
       identically 1. */
V
Vadim Pisarevsky 已提交
1518 1519 1520 1521 1522 1523
    frame_rate=(int)(fps+0.5);
    frame_rate_base=1;
    while (fabs((double)frame_rate/frame_rate_base) - fps > 0.001){
        frame_rate_base*=10;
        frame_rate=(int)(fps*frame_rate_base + 0.5);
    }
1524 1525 1526
#if LIBAVFORMAT_BUILD > 4752
    c->time_base.den = frame_rate;
    c->time_base.num = frame_rate_base;
V
Vadim Pisarevsky 已提交
1527 1528 1529
    /* adjust time base for supported framerates */
    if(codec && codec->supported_framerates){
        const AVRational *p= codec->supported_framerates;
1530
        AVRational req = {frame_rate, frame_rate_base};
V
Vadim Pisarevsky 已提交
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
        const AVRational *best=NULL;
        AVRational best_error= {INT_MAX, 1};
        for(; p->den!=0; p++){
            AVRational error= av_sub_q(req, *p);
            if(error.num <0) error.num *= -1;
            if(av_cmp_q(error, best_error) < 0){
                best_error= error;
                best= p;
            }
        }
        c->time_base.den= best->num;
        c->time_base.num= best->den;
    }
1544
#else
V
Vadim Pisarevsky 已提交
1545 1546
    c->frame_rate = frame_rate;
    c->frame_rate_base = frame_rate_base;
1547 1548
#endif

V
Vadim Pisarevsky 已提交
1549
    c->gop_size = 12; /* emit one intra frame every twelve frames at most */
J
jisli 已提交
1550
    c->pix_fmt = (AVPixelFormat) pixel_format;
1551

1552
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG2VIDEO)) {
1553 1554
        c->max_b_frames = 2;
    }
1555
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG1VIDEO) || c->codec_id == CV_CODEC(CODEC_ID_MSMPEG4V3)){
1556 1557 1558
        /* needed to avoid using macroblocks in which some coeffs overflow
           this doesnt happen with normal video, it just happens here as the
           motion of the chroma plane doesnt match the luma plane */
V
Vadim Pisarevsky 已提交
1559
        /* avoid FFMPEG warning 'clipping 1 dct coefficients...' */
1560 1561
        c->mb_decision=2;
    }
1562 1563

#if LIBAVUTIL_BUILD > CALC_FFMPEG_VERSION(51,11,0)
1564 1565
    /* Some settings for libx264 encoding, restore dummy values for gop_size
     and qmin since they will be set to reasonable defaults by the libx264
1566
     preset system. Also, use a crf encode with the default quality rating,
1567
     this seems easier than finding an appropriate default bitrate. */
1568
    if (c->codec_id == AV_CODEC_ID_H264) {
1569 1570 1571
      c->gop_size = -1;
      c->qmin = -1;
      c->bit_rate = 0;
1572 1573
      if (c->priv_data)
          av_opt_set(c->priv_data,"crf","23", 0);
1574
    }
1575 1576
#endif

1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
#if LIBAVCODEC_VERSION_INT>0x000409
    // some formats want stream headers to be seperate
    if(oc->oformat->flags & AVFMT_GLOBALHEADER)
    {
        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
    }
#endif

    return st;
}

V
Vadim Pisarevsky 已提交
1588 1589
static const int OPENCV_NO_FRAMES_WRITTEN_CODE = 1000;

1590 1591 1592 1593 1594 1595 1596
static int icv_av_write_frame_FFMPEG( AVFormatContext * oc, AVStream * video_st,
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54, 1, 0)
                                      uint8_t *, uint32_t,
#else
                                      uint8_t * outbuf, uint32_t outbuf_size,
#endif
                                      AVFrame * picture )
1597 1598
{
#if LIBAVFORMAT_BUILD > 4628
V
Vadim Pisarevsky 已提交
1599
    AVCodecContext * c = video_st->codec;
1600
#else
V
Vadim Pisarevsky 已提交
1601
    AVCodecContext * c = &(video_st->codec);
1602
#endif
1603
    int ret = OPENCV_NO_FRAMES_WRITTEN_CODE;
1604 1605 1606 1607 1608 1609 1610

    if (oc->oformat->flags & AVFMT_RAWPICTURE) {
        /* raw video case. The API will change slightly in the near
           futur for that */
        AVPacket pkt;
        av_init_packet(&pkt);

1611 1612 1613
#ifndef PKT_FLAG_KEY
#define PKT_FLAG_KEY AV_PKT_FLAG_KEY
#endif
V
Vadim Pisarevsky 已提交
1614 1615

        pkt.flags |= PKT_FLAG_KEY;
1616 1617 1618 1619 1620 1621 1622
        pkt.stream_index= video_st->index;
        pkt.data= (uint8_t *)picture;
        pkt.size= sizeof(AVPicture);

        ret = av_write_frame(oc, &pkt);
    } else {
        /* encode the image */
1623 1624 1625 1626 1627 1628 1629 1630
        AVPacket pkt;
        av_init_packet(&pkt);
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54, 1, 0)
        int got_output = 0;
        pkt.data = NULL;
        pkt.size = 0;
        ret = avcodec_encode_video2(c, &pkt, picture, &got_output);
        if (ret < 0)
1631
            ;
1632
        else if (got_output) {
1633 1634 1635 1636 1637 1638
            if (pkt.pts != (int64_t)AV_NOPTS_VALUE)
                pkt.pts = av_rescale_q(pkt.pts, c->time_base, video_st->time_base);
            if (pkt.dts != (int64_t)AV_NOPTS_VALUE)
                pkt.dts = av_rescale_q(pkt.dts, c->time_base, video_st->time_base);
            if (pkt.duration)
                pkt.duration = av_rescale_q(pkt.duration, c->time_base, video_st->time_base);
1639 1640
            pkt.stream_index= video_st->index;
            ret = av_write_frame(oc, &pkt);
P
Peter Rekdal Sunde 已提交
1641
            _opencv_ffmpeg_av_packet_unref(&pkt);
1642 1643 1644 1645 1646
        }
        else
            ret = OPENCV_NO_FRAMES_WRITTEN_CODE;
#else
        int out_size = avcodec_encode_video(c, outbuf, outbuf_size, picture);
1647 1648 1649
        /* if zero size, it means the image was buffered */
        if (out_size > 0) {
#if LIBAVFORMAT_BUILD > 4752
1650
            if(c->coded_frame->pts != (int64_t)AV_NOPTS_VALUE)
1651
                pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st->time_base);
1652
#else
V
Vadim Pisarevsky 已提交
1653
            pkt.pts = c->coded_frame->pts;
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
#endif
            if(c->coded_frame->key_frame)
                pkt.flags |= PKT_FLAG_KEY;
            pkt.stream_index= video_st->index;
            pkt.data= outbuf;
            pkt.size= out_size;

            /* write the compressed frame in the media file */
            ret = av_write_frame(oc, &pkt);
        }
1664
#endif
1665
    }
V
Vadim Pisarevsky 已提交
1666
    return ret;
1667 1668 1669 1670 1671
}

/// write a frame with FFMPEG
bool CvVideoWriter_FFMPEG::writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin )
{
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
    // check parameters
    if (input_pix_fmt == AV_PIX_FMT_BGR24) {
        if (cn != 3) {
            return false;
        }
    }
    else if (input_pix_fmt == AV_PIX_FMT_GRAY8) {
        if (cn != 1) {
            return false;
        }
    }
    else {
        assert(false);
    }
1686

V
Vadim Pisarevsky 已提交
1687 1688 1689 1690
    if( (width & -2) != frame_width || (height & -2) != frame_height || !data )
        return false;
    width = frame_width;
    height = frame_height;
1691

V
Vadim Pisarevsky 已提交
1692
    // typecast from opaque data type to implemented struct
1693 1694 1695
#if LIBAVFORMAT_BUILD > 4628
    AVCodecContext *c = video_st->codec;
#else
A
Alexander Shishkov 已提交
1696
    AVCodecContext *c = &(video_st->codec);
1697 1698
#endif

1699 1700 1701 1702 1703 1704
    // FFmpeg contains SIMD optimizations which can sometimes read data past
    // the supplied input buffer. To ensure that doesn't happen, we pad the
    // step to a multiple of 32 (that's the minimal alignment for which Valgrind
    // doesn't raise any warnings).
    const int STEP_ALIGNMENT = 32;
    if( step % STEP_ALIGNMENT != 0 )
A
Alexander Shishkov 已提交
1705
    {
1706 1707 1708
        int aligned_step = (step + STEP_ALIGNMENT - 1) & -STEP_ALIGNMENT;

        if( !aligned_input )
A
Alexander Shishkov 已提交
1709
        {
1710
            aligned_input = (unsigned char*)av_mallocz(aligned_step * height);
A
Alexander Shishkov 已提交
1711
        }
1712

A
Alexander Shishkov 已提交
1713 1714
        if (origin == 1)
            for( int y = 0; y < height; y++ )
1715
                memcpy(aligned_input + y*aligned_step, data + (height-1-y)*step, step);
A
Alexander Shishkov 已提交
1716 1717
        else
            for( int y = 0; y < height; y++ )
1718
                memcpy(aligned_input + y*aligned_step, data + y*step, step);
1719

1720 1721
        data = aligned_input;
        step = aligned_step;
1722 1723
    }

V
Vadim Pisarevsky 已提交
1724 1725 1726
    if ( c->pix_fmt != input_pix_fmt ) {
        assert( input_picture );
        // let input_picture point to the raw data buffer of 'image'
P
Peter Rekdal Sunde 已提交
1727
        _opencv_ffmpeg_av_image_fill_arrays(input_picture, (uint8_t *) data,
J
jisli 已提交
1728
                       (AVPixelFormat)input_pix_fmt, width, height);
1729
        input_picture->linesize[0] = step;
1730

V
Vadim Pisarevsky 已提交
1731 1732 1733 1734
        if( !img_convert_ctx )
        {
            img_convert_ctx = sws_getContext(width,
                                             height,
J
jisli 已提交
1735
                                             (AVPixelFormat)input_pix_fmt,
V
Vadim Pisarevsky 已提交
1736 1737 1738 1739 1740 1741 1742 1743
                                             c->width,
                                             c->height,
                                             c->pix_fmt,
                                             SWS_BICUBIC,
                                             NULL, NULL, NULL);
            if( !img_convert_ctx )
                return false;
        }
1744 1745 1746 1747 1748 1749

        if ( sws_scale(img_convert_ctx, input_picture->data,
                       input_picture->linesize, 0,
                       height,
                       picture->data, picture->linesize) < 0 )
            return false;
V
Vadim Pisarevsky 已提交
1750 1751
    }
    else{
P
Peter Rekdal Sunde 已提交
1752
        _opencv_ffmpeg_av_image_fill_arrays(picture, (uint8_t *) data,
J
jisli 已提交
1753
                       (AVPixelFormat)input_pix_fmt, width, height);
1754
        picture->linesize[0] = step;
V
Vadim Pisarevsky 已提交
1755
    }
1756

1757
    picture->pts = frame_idx;
1758
    bool ret = icv_av_write_frame_FFMPEG( oc, video_st, outbuf, outbuf_size, picture) >= 0;
1759
    frame_idx++;
1760

V
Vadim Pisarevsky 已提交
1761
    return ret;
1762 1763 1764 1765 1766
}

/// close video output stream and free associated memory
void CvVideoWriter_FFMPEG::close()
{
V
Vadim Pisarevsky 已提交
1767 1768 1769
    // nothing to do if already released
    if ( !picture )
        return;
1770

V
Vadim Pisarevsky 已提交
1771 1772 1773 1774
    /* no more frame to compress. The codec has a latency of a few
       frames if using B frames, so we get the last frames by
       passing the same picture again */
    // TODO -- do we need to account for latency here?
1775

V
Vadim Pisarevsky 已提交
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
    /* write the trailer, if any */
    if(ok && oc)
    {
        if( (oc->oformat->flags & AVFMT_RAWPICTURE) == 0 )
        {
            for(;;)
            {
                int ret = icv_av_write_frame_FFMPEG( oc, video_st, outbuf, outbuf_size, NULL);
                if( ret == OPENCV_NO_FRAMES_WRITTEN_CODE || ret < 0 )
                    break;
            }
        }
        av_write_trailer(oc);
    }
1790

V
Vadim Pisarevsky 已提交
1791 1792 1793 1794 1795
    if( img_convert_ctx )
    {
        sws_freeContext(img_convert_ctx);
        img_convert_ctx = 0;
    }
1796

V
Vadim Pisarevsky 已提交
1797
    // free pictures
1798
#if LIBAVFORMAT_BUILD > 4628
V
Vadim Pisarevsky 已提交
1799
    if( video_st->codec->pix_fmt != input_pix_fmt)
1800
#else
V
Vadim Pisarevsky 已提交
1801
    if( video_st->codec.pix_fmt != input_pix_fmt)
1802
#endif
V
Vadim Pisarevsky 已提交
1803 1804 1805 1806 1807 1808
    {
        if(picture->data[0])
            free(picture->data[0]);
        picture->data[0] = 0;
    }
    av_free(picture);
1809

V
Vadim Pisarevsky 已提交
1810 1811
    if (input_picture)
        av_free(input_picture);
1812

V
Vadim Pisarevsky 已提交
1813
    /* close codec */
1814
#if LIBAVFORMAT_BUILD > 4628
V
Vadim Pisarevsky 已提交
1815
    avcodec_close(video_st->codec);
1816
#else
V
Vadim Pisarevsky 已提交
1817
    avcodec_close(&(video_st->codec));
1818 1819
#endif

V
Vadim Pisarevsky 已提交
1820
    av_free(outbuf);
1821

V
Vadim Pisarevsky 已提交
1822 1823 1824
    if (!(fmt->flags & AVFMT_NOFILE))
    {
        /* close the output file */
1825

V
Vadim Pisarevsky 已提交
1826
#if LIBAVCODEC_VERSION_INT < ((52<<16)+(123<<8)+0)
1827
#if LIBAVCODEC_VERSION_INT >= ((51<<16)+(49<<8)+0)
V
Vadim Pisarevsky 已提交
1828
        url_fclose(oc->pb);
1829
#else
V
Vadim Pisarevsky 已提交
1830 1831 1832 1833
        url_fclose(&oc->pb);
#endif
#else
        avio_close(oc->pb);
1834 1835
#endif

V
Vadim Pisarevsky 已提交
1836
    }
1837

V
Vadim Pisarevsky 已提交
1838
    /* free the stream */
1839
    avformat_free_context(oc);
1840

1841
    av_freep(&aligned_input);
1842

V
Vadim Pisarevsky 已提交
1843 1844
    init();
}
1845

1846 1847 1848
#define CV_PRINTABLE_CHAR(ch) ((ch) < 32 ? '?' : (ch))
#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)

1849
static inline bool cv_ff_codec_tag_match(const AVCodecTag *tags, CV_CODEC_ID id, unsigned int tag)
1850 1851 1852 1853 1854 1855 1856 1857 1858
{
    while (tags->id != AV_CODEC_ID_NONE)
    {
        if (tags->id == id && tags->tag == tag)
            return true;
        tags++;
    }
    return false;
}
1859
static inline bool cv_ff_codec_tag_list_match(const AVCodecTag *const *tags, CV_CODEC_ID id, unsigned int tag)
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
{
    int i;
    for (i = 0; tags && tags[i]; i++) {
        bool res = cv_ff_codec_tag_match(tags[i], id, tag);
        if (res)
            return res;
    }
    return false;
}

V
Vadim Pisarevsky 已提交
1870 1871 1872 1873
/// Create a video writer object that uses FFMPEG
bool CvVideoWriter_FFMPEG::open( const char * filename, int fourcc,
                                 double fps, int width, int height, bool is_color )
{
1874
    CV_CODEC_ID codec_id = CV_CODEC(CODEC_ID_NONE);
V
Vadim Pisarevsky 已提交
1875 1876
    int err, codec_pix_fmt;
    double bitrate_scale = 1;
1877

V
Vadim Pisarevsky 已提交
1878
    close();
1879

V
Vadim Pisarevsky 已提交
1880 1881 1882 1883 1884
    // check arguments
    if( !filename )
        return false;
    if(fps <= 0)
        return false;
1885

V
Vadim Pisarevsky 已提交
1886 1887 1888 1889 1890 1891 1892
    // we allow frames of odd width or height, but in this case we truncate
    // the rightmost column/the bottom row. Probably, this should be handled more elegantly,
    // but some internal functions inside FFMPEG swscale require even width/height.
    width &= -2;
    height &= -2;
    if( width <= 0 || height <= 0 )
        return false;
1893

V
Vadim Pisarevsky 已提交
1894
    /* auto detect the output format from the name and fourcc code. */
1895

1896
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
V
Vadim Pisarevsky 已提交
1897
    fmt = av_guess_format(NULL, filename, NULL);
1898
#else
V
Vadim Pisarevsky 已提交
1899
    fmt = guess_format(NULL, filename, NULL);
1900
#endif
1901

V
Vadim Pisarevsky 已提交
1902 1903
    if (!fmt)
        return false;
1904

V
Vadim Pisarevsky 已提交
1905 1906
    /* determine optimal pixel format */
    if (is_color) {
J
jisli 已提交
1907
        input_pix_fmt = AV_PIX_FMT_BGR24;
V
Vadim Pisarevsky 已提交
1908 1909
    }
    else {
J
jisli 已提交
1910
        input_pix_fmt = AV_PIX_FMT_GRAY8;
V
Vadim Pisarevsky 已提交
1911
    }
1912

V
Vadim Pisarevsky 已提交
1913
    /* Lookup codec_id for given fourcc */
1914
#if LIBAVCODEC_VERSION_INT<((51<<16)+(49<<8)+0)
1915
    if( (codec_id = codec_get_bmp_id( fourcc )) == CV_CODEC(CODEC_ID_NONE) )
V
Vadim Pisarevsky 已提交
1916
        return false;
1917
#else
1918 1919 1920
    if( (codec_id = av_codec_get_id(fmt->codec_tag, fourcc)) == CV_CODEC(CODEC_ID_NONE) )
    {
        const struct AVCodecTag * fallback_tags[] = {
1921 1922 1923 1924
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(54, 1, 0)
// APIchanges:
// 2012-01-31 - dd6d3b0 - lavf 54.01.0
//   Add avformat_get_riff_video_tags() and avformat_get_riff_audio_tags().
1925
                avformat_get_riff_video_tags(),
1926 1927
#endif
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 25, 100) && defined LIBAVFORMAT_VERSION_MICRO && LIBAVFORMAT_VERSION_MICRO >= 100
1928 1929 1930
// APIchanges: ffmpeg only
// 2014-01-19 - 1a193c4 - lavf 55.25.100 - avformat.h
//   Add avformat_get_mov_video_tags() and avformat_get_mov_audio_tags().
1931
                avformat_get_mov_video_tags(),
1932
#endif
1933 1934
                codec_bmp_tags, // fallback for avformat < 54.1
                NULL };
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
        if( (codec_id = av_codec_get_id(fallback_tags, fourcc)) == CV_CODEC(CODEC_ID_NONE) )
        {
            fflush(stdout);
            fprintf(stderr, "OpenCV: FFMPEG: tag 0x%08x/'%c%c%c%c' is not found (format '%s / %s')'\n",
                    fourcc, CV_TAG_TO_PRINTABLE_CHAR4(fourcc),
                    fmt->name, fmt->long_name);
            return false;
        }
    }
    // validate tag
    if (cv_ff_codec_tag_list_match(fmt->codec_tag, codec_id, fourcc) == false)
    {
        fflush(stdout);
        fprintf(stderr, "OpenCV: FFMPEG: tag 0x%08x/'%c%c%c%c' is not supported with codec id %d and format '%s / %s'\n",
                fourcc, CV_TAG_TO_PRINTABLE_CHAR4(fourcc),
                codec_id, fmt->name, fmt->long_name);
        int supported_tag;
        if( (supported_tag = av_codec_get_tag(fmt->codec_tag, codec_id)) != 0 )
        {
            fprintf(stderr, "OpenCV: FFMPEG: fallback to use tag 0x%08x/'%c%c%c%c'\n",
                    supported_tag, CV_TAG_TO_PRINTABLE_CHAR4(supported_tag));
            fourcc = supported_tag;
        }
    }
1959 1960
#endif

V
Vadim Pisarevsky 已提交
1961
    // alloc memory for context
1962
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
V
Vadim Pisarevsky 已提交
1963
    oc = avformat_alloc_context();
1964
#else
V
Vadim Pisarevsky 已提交
1965
    oc = av_alloc_format_context();
1966
#endif
V
Vadim Pisarevsky 已提交
1967
    assert (oc);
1968

V
Vadim Pisarevsky 已提交
1969 1970 1971
    /* set file name */
    oc->oformat = fmt;
    snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
1972

V
Vadim Pisarevsky 已提交
1973 1974
    /* set some options */
    oc->max_delay = (int)(0.7*AV_TIME_BASE);  /* This reduces buffer underrun warnings with MPEG */
1975

V
Vadim Pisarevsky 已提交
1976 1977
    // set a few optimal pixel formats for lossless codecs of interest..
    switch (codec_id) {
1978
#if LIBAVCODEC_VERSION_INT>((50<<16)+(1<<8)+0)
1979
    case CV_CODEC(CODEC_ID_JPEGLS):
V
Vadim Pisarevsky 已提交
1980 1981 1982
        // BGR24 or GRAY8 depending on is_color...
        codec_pix_fmt = input_pix_fmt;
        break;
1983
#endif
1984
    case CV_CODEC(CODEC_ID_HUFFYUV):
J
jisli 已提交
1985
        codec_pix_fmt = AV_PIX_FMT_YUV422P;
V
Vadim Pisarevsky 已提交
1986
        break;
1987 1988
    case CV_CODEC(CODEC_ID_MJPEG):
    case CV_CODEC(CODEC_ID_LJPEG):
J
jisli 已提交
1989
        codec_pix_fmt = AV_PIX_FMT_YUVJ420P;
V
Vadim Pisarevsky 已提交
1990 1991
        bitrate_scale = 3;
        break;
1992
    case CV_CODEC(CODEC_ID_RAWVIDEO):
J
jisli 已提交
1993 1994 1995
        codec_pix_fmt = input_pix_fmt == AV_PIX_FMT_GRAY8 ||
                        input_pix_fmt == AV_PIX_FMT_GRAY16LE ||
                        input_pix_fmt == AV_PIX_FMT_GRAY16BE ? input_pix_fmt : AV_PIX_FMT_YUV420P;
V
Vadim Pisarevsky 已提交
1996 1997 1998
        break;
    default:
        // good for lossy formats, MPEG, etc.
J
jisli 已提交
1999
        codec_pix_fmt = AV_PIX_FMT_YUV420P;
V
Vadim Pisarevsky 已提交
2000 2001
        break;
    }
2002

V
Vadim Pisarevsky 已提交
2003
    double bitrate = MIN(bitrate_scale*fps*width*height, (double)INT_MAX/2);
2004

V
Vadim Pisarevsky 已提交
2005 2006 2007 2008
    // TODO -- safe to ignore output audio stream?
    video_st = icv_add_video_stream_FFMPEG(oc, codec_id,
                                           width, height, (int)(bitrate + 0.5),
                                           fps, codec_pix_fmt);
2009

V
Vadim Pisarevsky 已提交
2010 2011 2012 2013 2014 2015 2016
    /* set the output parameters (must be done even if no
   parameters). */
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
    if (av_set_parameters(oc, NULL) < 0) {
        return false;
    }
#endif
2017

V
Vadim Pisarevsky 已提交
2018 2019 2020
#if 0
#if FF_API_DUMP_FORMAT
    dump_format(oc, 0, filename, 1);
2021
#else
V
Vadim Pisarevsky 已提交
2022 2023
    av_dump_format(oc, 0, filename, 1);
#endif
2024 2025
#endif

V
Vadim Pisarevsky 已提交
2026 2027 2028 2029
    /* now that all the parameters are set, we can open the audio and
     video codecs and allocate the necessary encode buffers */
    if (!video_st){
        return false;
2030
    }
2031

V
Vadim Pisarevsky 已提交
2032 2033
    AVCodec *codec;
    AVCodecContext *c;
2034

V
Vadim Pisarevsky 已提交
2035 2036 2037 2038 2039
#if LIBAVFORMAT_BUILD > 4628
    c = (video_st->codec);
#else
    c = &(video_st->codec);
#endif
2040

V
Vadim Pisarevsky 已提交
2041 2042 2043 2044
    c->codec_tag = fourcc;
    /* find the video encoder */
    codec = avcodec_find_encoder(c->codec_id);
    if (!codec) {
2045
        fprintf(stderr, "Could not find encoder for codec id %d: %s\n", c->codec_id, icvFFMPEGErrStr(
V
Vadim Pisarevsky 已提交
2046 2047 2048 2049 2050 2051 2052
        #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
                AVERROR_ENCODER_NOT_FOUND
        #else
                -1
        #endif
                ));
        return false;
2053
    }
2054

V
Vadim Pisarevsky 已提交
2055 2056 2057 2058 2059
    int64_t lbit_rate = (int64_t)c->bit_rate;
    lbit_rate += (bitrate / 2);
    lbit_rate = std::min(lbit_rate, (int64_t)INT_MAX);
    c->bit_rate_tolerance = (int)lbit_rate;
    c->bit_rate = (int)lbit_rate;
2060

V
Vadim Pisarevsky 已提交
2061 2062 2063 2064 2065 2066 2067 2068
    /* open the codec */
    if ((err=
#if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
         avcodec_open2(c, codec, NULL)
#else
         avcodec_open(c, codec)
#endif
         ) < 0) {
2069
        fprintf(stderr, "Could not open codec '%s': %s\n", codec->name, icvFFMPEGErrStr(err));
V
Vadim Pisarevsky 已提交
2070
        return false;
2071
    }
2072

V
Vadim Pisarevsky 已提交
2073
    outbuf = NULL;
2074

V
Vadim Pisarevsky 已提交
2075 2076 2077 2078 2079
    if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
        /* allocate output buffer */
        /* assume we will never get codec output with more than 4 bytes per pixel... */
        outbuf_size = width*height*4;
        outbuf = (uint8_t *) av_malloc(outbuf_size);
2080
    }
2081

V
Vadim Pisarevsky 已提交
2082 2083
    bool need_color_convert;
    need_color_convert = (c->pix_fmt != input_pix_fmt);
2084

V
Vadim Pisarevsky 已提交
2085 2086 2087 2088
    /* allocate the encoded raw picture */
    picture = icv_alloc_picture_FFMPEG(c->pix_fmt, c->width, c->height, need_color_convert);
    if (!picture) {
        return false;
2089
    }
2090

V
Vadim Pisarevsky 已提交
2091 2092 2093 2094 2095 2096 2097 2098
    /* if the output format is not our input format, then a temporary
   picture of the input format is needed too. It is then converted
   to the required output format */
    input_picture = NULL;
    if ( need_color_convert ) {
        input_picture = icv_alloc_picture_FFMPEG(input_pix_fmt, c->width, c->height, false);
        if (!input_picture) {
            return false;
2099
        }
2100 2101
    }

V
Vadim Pisarevsky 已提交
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
    /* open the output file, if needed */
    if (!(fmt->flags & AVFMT_NOFILE)) {
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0)
#else
            if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0)
#endif
            {
            return false;
        }
2112
    }
2113

V
Vadim Pisarevsky 已提交
2114 2115 2116 2117 2118
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    /* write the stream header, if any */
    err=avformat_write_header(oc, NULL);
#else
    err=av_write_header( oc );
2119 2120
#endif

V
Vadim Pisarevsky 已提交
2121
    if(err < 0)
V
Vladislav Vinogradov 已提交
2122
    {
V
Vadim Pisarevsky 已提交
2123 2124 2125
        close();
        remove(filename);
        return false;
V
Vladislav Vinogradov 已提交
2126
    }
V
Vadim Pisarevsky 已提交
2127 2128
    frame_width = width;
    frame_height = height;
2129
    frame_idx = 0;
V
Vadim Pisarevsky 已提交
2130
    ok = true;
I
Ilya Lavrenov 已提交
2131

V
Vadim Pisarevsky 已提交
2132
    return true;
V
Vladislav Vinogradov 已提交
2133 2134 2135 2136
}



V
Vadim Pisarevsky 已提交
2137
CvCapture_FFMPEG* cvCreateFileCapture_FFMPEG( const char* filename )
V
Vladislav Vinogradov 已提交
2138
{
V
Vadim Pisarevsky 已提交
2139 2140 2141 2142
    CvCapture_FFMPEG* capture = (CvCapture_FFMPEG*)malloc(sizeof(*capture));
    capture->init();
    if( capture->open( filename ))
        return capture;
I
Ilya Lavrenov 已提交
2143

V
Vadim Pisarevsky 已提交
2144 2145 2146
    capture->close();
    free(capture);
    return 0;
V
Vladislav Vinogradov 已提交
2147 2148
}

V
Vadim Pisarevsky 已提交
2149 2150

void cvReleaseCapture_FFMPEG(CvCapture_FFMPEG** capture)
V
Vladislav Vinogradov 已提交
2151
{
V
Vadim Pisarevsky 已提交
2152
    if( capture && *capture )
V
Vladislav Vinogradov 已提交
2153
    {
V
Vadim Pisarevsky 已提交
2154 2155 2156
        (*capture)->close();
        free(*capture);
        *capture = 0;
V
Vladislav Vinogradov 已提交
2157 2158 2159
    }
}

V
Vadim Pisarevsky 已提交
2160
int cvSetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id, double value)
V
Vladislav Vinogradov 已提交
2161
{
V
Vadim Pisarevsky 已提交
2162
    return capture->setProperty(prop_id, value);
V
Vladislav Vinogradov 已提交
2163 2164
}

V
Vadim Pisarevsky 已提交
2165
double cvGetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id)
V
Vladislav Vinogradov 已提交
2166
{
V
Vadim Pisarevsky 已提交
2167
    return capture->getProperty(prop_id);
V
Vladislav Vinogradov 已提交
2168 2169
}

V
Vadim Pisarevsky 已提交
2170
int cvGrabFrame_FFMPEG(CvCapture_FFMPEG* capture)
V
Vladislav Vinogradov 已提交
2171
{
V
Vadim Pisarevsky 已提交
2172
    return capture->grabFrame();
V
Vladislav Vinogradov 已提交
2173
}
V
Vladislav Vinogradov 已提交
2174

V
Vadim Pisarevsky 已提交
2175
int cvRetrieveFrame_FFMPEG(CvCapture_FFMPEG* capture, unsigned char** data, int* step, int* width, int* height, int* cn)
V
Vladislav Vinogradov 已提交
2176
{
V
Vadim Pisarevsky 已提交
2177
    return capture->retrieveFrame(0, data, step, width, height, cn);
V
Vladislav Vinogradov 已提交
2178 2179
}

V
Vadim Pisarevsky 已提交
2180 2181
CvVideoWriter_FFMPEG* cvCreateVideoWriter_FFMPEG( const char* filename, int fourcc, double fps,
                                                  int width, int height, int isColor )
V
Vladislav Vinogradov 已提交
2182
{
V
Vadim Pisarevsky 已提交
2183 2184 2185 2186 2187 2188 2189
    CvVideoWriter_FFMPEG* writer = (CvVideoWriter_FFMPEG*)malloc(sizeof(*writer));
    writer->init();
    if( writer->open( filename, fourcc, fps, width, height, isColor != 0 ))
        return writer;
    writer->close();
    free(writer);
    return 0;
V
Vladislav Vinogradov 已提交
2190 2191
}

V
Vadim Pisarevsky 已提交
2192 2193 2194
void cvReleaseVideoWriter_FFMPEG( CvVideoWriter_FFMPEG** writer )
{
    if( writer && *writer )
V
Vladislav Vinogradov 已提交
2195
    {
V
Vadim Pisarevsky 已提交
2196 2197 2198
        (*writer)->close();
        free(*writer);
        *writer = 0;
V
Vladislav Vinogradov 已提交
2199 2200 2201 2202
    }
}


V
Vadim Pisarevsky 已提交
2203 2204 2205
int cvWriteFrame_FFMPEG( CvVideoWriter_FFMPEG* writer,
                         const unsigned char* data, int step,
                         int width, int height, int cn, int origin)
V
Vladislav Vinogradov 已提交
2206
{
V
Vadim Pisarevsky 已提交
2207
    return writer->writeFrame(data, step, width, height, cn, origin);
V
Vladislav Vinogradov 已提交
2208 2209
}

2210 2211 2212 2213 2214 2215 2216 2217 2218 2219


/*
 * For CUDA encoder
 */

struct OutputMediaStream_FFMPEG
{
    bool open(const char* fileName, int width, int height, double fps);
    void close();
2220

2221 2222 2223
    void write(unsigned char* data, int size, int keyFrame);

    // add a video output stream to the container
J
jisli 已提交
2224
    static AVStream* addVideoStream(AVFormatContext *oc, CV_CODEC_ID codec_id, int w, int h, int bitrate, double fps, AVPixelFormat pixel_format);
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270

    AVOutputFormat* fmt_;
    AVFormatContext* oc_;
    AVStream* video_st_;
};

void OutputMediaStream_FFMPEG::close()
{
    // no more frame to compress. The codec has a latency of a few
    // frames if using B frames, so we get the last frames by
    // passing the same picture again

    // TODO -- do we need to account for latency here?

    if (oc_)
    {
        // write the trailer, if any
        av_write_trailer(oc_);

        // free the streams
        for (unsigned int i = 0; i < oc_->nb_streams; ++i)
        {
            av_freep(&oc_->streams[i]->codec);
            av_freep(&oc_->streams[i]);
        }

        if (!(fmt_->flags & AVFMT_NOFILE) && oc_->pb)
        {
            // close the output file

            #if LIBAVCODEC_VERSION_INT < ((52<<16)+(123<<8)+0)
                #if LIBAVCODEC_VERSION_INT >= ((51<<16)+(49<<8)+0)
                    url_fclose(oc_->pb);
                #else
                    url_fclose(&oc_->pb);
                #endif
            #else
                avio_close(oc_->pb);
            #endif
        }

        // free the stream
        av_free(oc_);
    }
}

J
jisli 已提交
2271
AVStream* OutputMediaStream_FFMPEG::addVideoStream(AVFormatContext *oc, CV_CODEC_ID codec_id, int w, int h, int bitrate, double fps, AVPixelFormat pixel_format)
2272
{
2273 2274 2275 2276 2277 2278 2279
    AVCodec* codec = avcodec_find_encoder(codec_id);
    if (!codec)
    {
        fprintf(stderr, "Could not find encoder for codec id %d\n", codec_id);
        return NULL;
    }

2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 10, 0)
        AVStream* st = avformat_new_stream(oc, 0);
    #else
        AVStream* st = av_new_stream(oc, 0);
    #endif
    if (!st)
        return 0;

    #if LIBAVFORMAT_BUILD > 4628
        AVCodecContext* c = st->codec;
    #else
        AVCodecContext* c = &(st->codec);
    #endif

    c->codec_id = codec_id;
    c->codec_type = AVMEDIA_TYPE_VIDEO;

    // put sample parameters
    unsigned long long lbit_rate = static_cast<unsigned long long>(bitrate);
    lbit_rate += (bitrate / 4);
    lbit_rate = std::min(lbit_rate, static_cast<unsigned long long>(std::numeric_limits<int>::max()));
    c->bit_rate = bitrate;

    // took advice from
    // http://ffmpeg-users.933282.n4.nabble.com/warning-clipping-1-dct-coefficients-to-127-127-td934297.html
    c->qmin = 3;

    // resolution must be a multiple of two
    c->width = w;
    c->height = h;

    // time base: this is the fundamental unit of time (in seconds) in terms
    // of which frame timestamps are represented. for fixed-fps content,
    // timebase should be 1/framerate and timestamp increments should be
    // identically 1

    int frame_rate = static_cast<int>(fps+0.5);
    int frame_rate_base = 1;
    while (fabs(static_cast<double>(frame_rate)/frame_rate_base) - fps > 0.001)
    {
        frame_rate_base *= 10;
        frame_rate = static_cast<int>(fps*frame_rate_base + 0.5);
    }
    c->time_base.den = frame_rate;
    c->time_base.num = frame_rate_base;

    #if LIBAVFORMAT_BUILD > 4752
        // adjust time base for supported framerates
        if (codec && codec->supported_framerates)
        {
            AVRational req = {frame_rate, frame_rate_base};
            const AVRational* best = NULL;
            AVRational best_error = {INT_MAX, 1};

            for (const AVRational* p = codec->supported_framerates; p->den!=0; ++p)
            {
                AVRational error = av_sub_q(req, *p);

2338
                if (error.num < 0)
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
                    error.num *= -1;

                if (av_cmp_q(error, best_error) < 0)
                {
                    best_error= error;
                    best= p;
                }
            }

            c->time_base.den= best->num;
            c->time_base.num= best->den;
        }
    #endif

    c->gop_size = 12; // emit one intra frame every twelve frames at most
    c->pix_fmt = pixel_format;

2356
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG2VIDEO))
2357 2358
        c->max_b_frames = 2;

2359
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG1VIDEO) || c->codec_id == CV_CODEC(CODEC_ID_MSMPEG4V3))
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
    {
        // needed to avoid using macroblocks in which some coeffs overflow
        // this doesnt happen with normal video, it just happens here as the
        // motion of the chroma plane doesnt match the luma plane

        // avoid FFMPEG warning 'clipping 1 dct coefficients...'

        c->mb_decision = 2;
    }

    #if LIBAVCODEC_VERSION_INT > 0x000409
        // some formats want stream headers to be seperate
        if (oc->oformat->flags & AVFMT_GLOBALHEADER)
        {
            c->flags |= CODEC_FLAG_GLOBAL_HEADER;
        }
    #endif

    return st;
}

bool OutputMediaStream_FFMPEG::open(const char* fileName, int width, int height, double fps)
{
    fmt_ = 0;
    oc_ = 0;
    video_st_ = 0;

    // auto detect the output format from the name and fourcc code
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
        fmt_ = av_guess_format(NULL, fileName, NULL);
    #else
        fmt_ = guess_format(NULL, fileName, NULL);
    #endif
    if (!fmt_)
        return false;

2396
    CV_CODEC_ID codec_id = CV_CODEC(CODEC_ID_H264);
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413

    // alloc memory for context
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
        oc_ = avformat_alloc_context();
    #else
        oc_ = av_alloc_format_context();
    #endif
    if (!oc_)
        return false;

    // set some options
    oc_->oformat = fmt_;
    snprintf(oc_->filename, sizeof(oc_->filename), "%s", fileName);

    oc_->max_delay = (int)(0.7 * AV_TIME_BASE); // This reduces buffer underrun warnings with MPEG

    // set a few optimal pixel formats for lossless codecs of interest..
J
jisli 已提交
2414
    AVPixelFormat codec_pix_fmt = AV_PIX_FMT_YUV420P;
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465
    int bitrate_scale = 64;

    // TODO -- safe to ignore output audio stream?
    video_st_ = addVideoStream(oc_, codec_id, width, height, width * height * bitrate_scale, fps, codec_pix_fmt);
    if (!video_st_)
        return false;

    // set the output parameters (must be done even if no parameters)
    #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
        if (av_set_parameters(oc_, NULL) < 0)
            return false;
    #endif

    // now that all the parameters are set, we can open the audio and
    // video codecs and allocate the necessary encode buffers

    #if LIBAVFORMAT_BUILD > 4628
        AVCodecContext* c = (video_st_->codec);
    #else
        AVCodecContext* c = &(video_st_->codec);
    #endif

    c->codec_tag = MKTAG('H', '2', '6', '4');
    c->bit_rate_tolerance = c->bit_rate;

    // open the output file, if needed
    if (!(fmt_->flags & AVFMT_NOFILE))
    {
        #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
            int err = url_fopen(&oc_->pb, fileName, URL_WRONLY);
        #else
            int err = avio_open(&oc_->pb, fileName, AVIO_FLAG_WRITE);
        #endif

        if (err != 0)
            return false;
    }

    // write the stream header, if any
    #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
        av_write_header(oc_);
    #else
        avformat_write_header(oc_, NULL);
    #endif

    return true;
}

void OutputMediaStream_FFMPEG::write(unsigned char* data, int size, int keyFrame)
{
    // if zero size, it means the image was buffered
2466
    if (size > 0)
2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491
    {
        AVPacket pkt;
        av_init_packet(&pkt);

        if (keyFrame)
            pkt.flags |= PKT_FLAG_KEY;

        pkt.stream_index = video_st_->index;
        pkt.data = data;
        pkt.size = size;

        // write the compressed frame in the media file
        av_write_frame(oc_, &pkt);
    }
}

struct OutputMediaStream_FFMPEG* create_OutputMediaStream_FFMPEG(const char* fileName, int width, int height, double fps)
{
    OutputMediaStream_FFMPEG* stream = (OutputMediaStream_FFMPEG*) malloc(sizeof(OutputMediaStream_FFMPEG));

    if (stream->open(fileName, width, height, fps))
        return stream;

    stream->close();
    free(stream);
2492

2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
    return 0;
}

void release_OutputMediaStream_FFMPEG(struct OutputMediaStream_FFMPEG* stream)
{
    stream->close();
    free(stream);
}

void write_OutputMediaStream_FFMPEG(struct OutputMediaStream_FFMPEG* stream, unsigned char* data, int size, int keyFrame)
{
    stream->write(data, size, keyFrame);
}

/*
 * For CUDA decoder
 */

enum
{
    VideoCodec_MPEG1 = 0,
    VideoCodec_MPEG2,
    VideoCodec_MPEG4,
    VideoCodec_VC1,
    VideoCodec_H264,
    VideoCodec_JPEG,
    VideoCodec_H264_SVC,
    VideoCodec_H264_MVC,

    // Uncompressed YUV
    VideoCodec_YUV420 = (('I'<<24)|('Y'<<16)|('U'<<8)|('V')),   // Y,U,V (4:2:0)
    VideoCodec_YV12   = (('Y'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,V,U (4:2:0)
    VideoCodec_NV12   = (('N'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,UV  (4:2:0)
    VideoCodec_YUYV   = (('Y'<<24)|('U'<<16)|('Y'<<8)|('V')),   // YUYV/YUY2 (4:2:2)
I
Ilya Lavrenov 已提交
2527
    VideoCodec_UYVY   = (('U'<<24)|('Y'<<16)|('V'<<8)|('Y'))    // UYVY (4:2:2)
2528 2529 2530 2531 2532 2533 2534
};

enum
{
    VideoChromaFormat_Monochrome = 0,
    VideoChromaFormat_YUV420,
    VideoChromaFormat_YUV422,
I
Ilya Lavrenov 已提交
2535
    VideoChromaFormat_YUV444
2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
};

struct InputMediaStream_FFMPEG
{
public:
    bool open(const char* fileName, int* codec, int* chroma_format, int* width, int* height);
    void close();

    bool read(unsigned char** data, int* size, int* endOfFile);

private:
    InputMediaStream_FFMPEG(const InputMediaStream_FFMPEG&);
    InputMediaStream_FFMPEG& operator =(const InputMediaStream_FFMPEG&);

    AVFormatContext* ctx_;
    int video_stream_id_;
    AVPacket pkt_;
2553

2554
#if USE_AV_INTERRUPT_CALLBACK
2555
    AVInterruptCallbackMetadata interrupt_metadata;
2556
#endif
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
};

bool InputMediaStream_FFMPEG::open(const char* fileName, int* codec, int* chroma_format, int* width, int* height)
{
    int err;

    ctx_ = 0;
    video_stream_id_ = -1;
    memset(&pkt_, 0, sizeof(AVPacket));

2567
#if USE_AV_INTERRUPT_CALLBACK
2568
    /* interrupt callback */
2569
    interrupt_metadata.timeout_after_ms = LIBAVFORMAT_INTERRUPT_OPEN_TIMEOUT_MS;
2570 2571 2572 2573 2574
    get_monotonic_time(&interrupt_metadata.value);

    ctx_ = avformat_alloc_context();
    ctx_->interrupt_callback.callback = _opencv_ffmpeg_interrupt_callback;
    ctx_->interrupt_callback.opaque = &interrupt_metadata;
2575
#endif
2576

2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 13, 0)
        avformat_network_init();
    #endif

    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
        err = avformat_open_input(&ctx_, fileName, 0, 0);
    #else
        err = av_open_input_file(&ctx_, fileName, 0, 0, 0);
    #endif
    if (err < 0)
        return false;

R
Roman Donchenko 已提交
2589
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
        err = avformat_find_stream_info(ctx_, 0);
    #else
        err = av_find_stream_info(ctx_);
    #endif
    if (err < 0)
        return false;

    for (unsigned int i = 0; i < ctx_->nb_streams; ++i)
    {
        #if LIBAVFORMAT_BUILD > 4628
            AVCodecContext *enc = ctx_->streams[i]->codec;
        #else
            AVCodecContext *enc = &ctx_->streams[i]->codec;
        #endif

        if (enc->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            video_stream_id_ = static_cast<int>(i);

            switch (enc->codec_id)
            {
2611
            case CV_CODEC(CODEC_ID_MPEG1VIDEO):
2612 2613 2614
                *codec = ::VideoCodec_MPEG1;
                break;

2615
            case CV_CODEC(CODEC_ID_MPEG2VIDEO):
2616 2617 2618
                *codec = ::VideoCodec_MPEG2;
                break;

2619
            case CV_CODEC(CODEC_ID_MPEG4):
2620 2621 2622
                *codec = ::VideoCodec_MPEG4;
                break;

2623
            case CV_CODEC(CODEC_ID_VC1):
2624 2625 2626
                *codec = ::VideoCodec_VC1;
                break;

2627
            case CV_CODEC(CODEC_ID_H264):
2628 2629 2630 2631 2632 2633 2634 2635 2636
                *codec = ::VideoCodec_H264;
                break;

            default:
                return false;
            };

            switch (enc->pix_fmt)
            {
J
jisli 已提交
2637
            case AV_PIX_FMT_YUV420P:
2638 2639 2640
                *chroma_format = ::VideoChromaFormat_YUV420;
                break;

J
jisli 已提交
2641
            case AV_PIX_FMT_YUV422P:
2642 2643 2644
                *chroma_format = ::VideoChromaFormat_YUV422;
                break;

J
jisli 已提交
2645
            case AV_PIX_FMT_YUV444P:
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664
                *chroma_format = ::VideoChromaFormat_YUV444;
                break;

            default:
                return false;
            }

            *width = enc->coded_width;
            *height = enc->coded_height;

            break;
        }
    }

    if (video_stream_id_ < 0)
        return false;

    av_init_packet(&pkt_);

2665 2666 2667 2668 2669
#if USE_AV_INTERRUPT_CALLBACK
    // deactivate interrupt callback
    interrupt_metadata.timeout_after_ms = 0;
#endif

2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
    return true;
}

void InputMediaStream_FFMPEG::close()
{
    if (ctx_)
    {
        #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 24, 2)
            avformat_close_input(&ctx_);
        #else
            av_close_input_file(ctx_);
        #endif
    }

    // free last packet if exist
    if (pkt_.data)
P
Peter Rekdal Sunde 已提交
2686
        _opencv_ffmpeg_av_packet_unref(&pkt_);
2687 2688 2689 2690
}

bool InputMediaStream_FFMPEG::read(unsigned char** data, int* size, int* endOfFile)
{
2691 2692 2693 2694 2695 2696 2697 2698
    bool result = false;

#if USE_AV_INTERRUPT_CALLBACK
    // activate interrupt callback
    get_monotonic_time(&interrupt_metadata.value);
    interrupt_metadata.timeout_after_ms = LIBAVFORMAT_INTERRUPT_READ_TIMEOUT_MS;
#endif

2699 2700
    // free last packet if exist
    if (pkt_.data)
P
Peter Rekdal Sunde 已提交
2701
        _opencv_ffmpeg_av_packet_unref(&pkt_);
2702 2703 2704 2705

    // get the next frame
    for (;;)
    {
2706
#if USE_AV_INTERRUPT_CALLBACK
2707 2708 2709 2710
        if(interrupt_metadata.timeout)
        {
            break;
        }
2711
#endif
2712

2713 2714 2715 2716 2717 2718 2719
        int ret = av_read_frame(ctx_, &pkt_);

        if (ret == AVERROR(EAGAIN))
            continue;

        if (ret < 0)
        {
A
Andrey Kamaev 已提交
2720
            if (ret == (int)AVERROR_EOF)
2721
                *endOfFile = true;
2722
            break;
2723 2724 2725 2726
        }

        if (pkt_.stream_index != video_stream_id_)
        {
P
Peter Rekdal Sunde 已提交
2727
            _opencv_ffmpeg_av_packet_unref(&pkt_);
2728 2729 2730
            continue;
        }

2731
        result = true;
2732 2733 2734
        break;
    }

2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745
#if USE_AV_INTERRUPT_CALLBACK
    // deactivate interrupt callback
    interrupt_metadata.timeout_after_ms = 0;
#endif

    if (result)
    {
        *data = pkt_.data;
        *size = pkt_.size;
        *endOfFile = false;
    }
2746

2747
    return result;
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772
}

InputMediaStream_FFMPEG* create_InputMediaStream_FFMPEG(const char* fileName, int* codec, int* chroma_format, int* width, int* height)
{
    InputMediaStream_FFMPEG* stream = (InputMediaStream_FFMPEG*) malloc(sizeof(InputMediaStream_FFMPEG));

    if (stream && stream->open(fileName, codec, chroma_format, width, height))
        return stream;

    stream->close();
    free(stream);

    return 0;
}

void release_InputMediaStream_FFMPEG(InputMediaStream_FFMPEG* stream)
{
    stream->close();
    free(stream);
}

int read_InputMediaStream_FFMPEG(InputMediaStream_FFMPEG* stream, unsigned char** data, int* size, int* endOfFile)
{
    return stream->read(data, size, endOfFile);
}