cap_ffmpeg_impl.hpp 92.8 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
#if !(defined(_WIN32) || defined(WINCE))
45 46
# include <pthread.h>
#endif
47
#include <assert.h>
48
#include <algorithm>
V
Vadim Pisarevsky 已提交
49
#include <limits>
50

51 52 53 54
#ifndef __OPENCV_BUILD
#define CV_FOURCC(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24))
#endif

55 56
#define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c )

57
#if defined _MSC_VER && _MSC_VER >= 1200
T
Tomoaki Teshima 已提交
58
#pragma warning( disable: 4244 4510 4610 )
59 60
#endif

A
Andrey Kamaev 已提交
61 62 63
#ifdef __GNUC__
#  pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
64 65 66
#ifdef _MSC_VER
#pragma warning(disable: 4996)  // was declared deprecated
#endif
A
Andrey Kamaev 已提交
67

A
Alexander Alekhin 已提交
68 69 70 71
#ifndef CV_UNUSED  // Required for standalone compilation mode (OpenCV defines this in base.hpp)
#define CV_UNUSED(name) (void)name
#endif

72 73 74 75
#ifdef __cplusplus
extern "C" {
#endif

76 77
#include "ffmpeg_codecs.hpp"

V
Vadim Pisarevsky 已提交
78 79
#include <libavutil/mathematics.h>

80 81 82 83
#if LIBAVUTIL_BUILD > CALC_FFMPEG_VERSION(51,11,0)
  #include <libavutil/opt.h>
#endif

P
Peter Rekdal Sunde 已提交
84 85 86 87 88
#if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(51, 63, 100) : CALC_FFMPEG_VERSION(54, 6, 0))
#include <libavutil/imgutils.h>
#endif

89 90
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
91 92 93 94 95 96

#ifdef __cplusplus
}
#endif

#if defined _MSC_VER && _MSC_VER >= 1200
T
Tomoaki Teshima 已提交
97
#pragma warning( default: 4244 4510 4610 )
98 99 100 101 102 103 104 105
#endif

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

106
#if defined _WIN32
107
    #include <windows.h>
108 109 110 111 112 113 114
    #if defined _MSC_VER && _MSC_VER < 1900
    struct timespec
    {
        time_t tv_sec;
        long   tv_nsec;
    };
  #endif
115
#elif defined __linux__ || defined __APPLE__ || defined __HAIKU__
116 117
    #include <unistd.h>
    #include <stdio.h>
V
Vadim Pisarevsky 已提交
118
    #include <sys/types.h>
119
    #include <sys/time.h>
120
#if defined __APPLE__
121
    #include <sys/sysctl.h>
122 123
    #include <mach/clock.h>
    #include <mach/mach.h>
124
#endif
125
#endif
126

V
Vadim Pisarevsky 已提交
127 128 129 130 131 132 133 134 135 136
#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

137 138 139 140
#ifndef AVERROR_EOF
#define AVERROR_EOF (-MKTAG( 'E','O','F',' '))
#endif

141 142 143 144 145 146 147 148
#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 已提交
149 150 151 152 153 154
#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
155 156
#define AV_PIX_FMT_BGRA PIX_FMT_BGRA
#define AV_PIX_FMT_RGBA PIX_FMT_RGBA
J
jisli 已提交
157 158 159 160 161 162 163 164
#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

165 166 167 168
#ifndef PKT_FLAG_KEY
#define PKT_FLAG_KEY AV_PKT_FLAG_KEY
#endif

169 170 171 172 173 174 175 176 177 178
#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

179

180 181 182 183 184 185 186 187 188
#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
189 190
#define LIBAVFORMAT_INTERRUPT_OPEN_DEFAULT_TIMEOUT_MS 30000
#define LIBAVFORMAT_INTERRUPT_READ_DEFAULT_TIMEOUT_MS 30000
191

192
#ifdef _WIN32
193 194
// http://stackoverflow.com/questions/5404277/porting-clock-gettime-to-windows

195
static
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
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;
}

216
static
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
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;
256
    t.QuadPart = (LONGLONG)microseconds;
257 258 259 260
    tv->tv_sec = t.QuadPart / 1000000;
    tv->tv_nsec = (t.QuadPart % 1000000) * 1000;
}
#else
261
static
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
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

278
static
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
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;
}

295
static
296 297 298 299 300 301 302
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;
}
303
#endif // USE_AV_INTERRUPT_CALLBACK
304

305
static int get_number_of_cpus(void)
306
{
V
Vadim Pisarevsky 已提交
307 308
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(52, 111, 0)
    return 1;
309
#elif defined _WIN32
310 311
    SYSTEM_INFO sysinfo;
    GetSystemInfo( &sysinfo );
V
Vadim Pisarevsky 已提交
312

313
    return (int)sysinfo.dwNumberOfProcessors;
314
#elif defined __linux__ || defined __HAIKU__
315 316 317 318
    return (int)sysconf( _SC_NPROCESSORS_ONLN );
#elif defined __APPLE__
    int numCPU=0;
    int mib[4];
V
Vadim Pisarevsky 已提交
319 320 321
    size_t len = sizeof(numCPU);

    // set the mib for hw.ncpu
322 323
    mib[0] = CTL_HW;
    mib[1] = HW_AVAILCPU;  // alternatively, try HW_NCPU;
V
Vadim Pisarevsky 已提交
324 325

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

    if( numCPU < 1 )
329 330 331
    {
        mib[1] = HW_NCPU;
        sysctl( mib, 2, &numCPU, &len, NULL, 0 );
V
Vadim Pisarevsky 已提交
332

333 334 335 336 337 338 339 340 341 342 343
        if( numCPU < 1 )
            numCPU = 1;
    }

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


344 345 346 347 348 349 350 351 352 353
struct Image_FFMPEG
{
    unsigned char* data;
    int step;
    int width;
    int height;
    int cn;
};


354
#if USE_AV_INTERRUPT_CALLBACK
355 356 357 358 359 360 361
struct AVInterruptCallbackMetadata
{
    timespec value;
    unsigned int timeout_after_ms;
    int timeout;
};

362 363
// https://github.com/opencv/opencv/pull/12693#issuecomment-426236731
static
364
inline const char* _opencv_avcodec_get_name(CV_CODEC_ID id)
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
{
#if LIBAVCODEC_VERSION_MICRO >= 100 \
    && LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(53, 47, 100)
    return avcodec_get_name(id);
#else
    const AVCodecDescriptor *cd;
    AVCodec *codec;

    if (id == AV_CODEC_ID_NONE)
    {
        return "none";
    }
    cd = avcodec_descriptor_get(id);
    if (cd)
    {
        return cd->name;
    }
    codec = avcodec_find_decoder(id);
    if (codec)
    {
        return codec->name;
    }
    codec = avcodec_find_encoder(id);
    if (codec)
    {
        return codec->name;
    }

    return "unknown_codec";
#endif
}

397
static
398 399 400 401 402 403
inline void _opencv_ffmpeg_free(void** ptr)
{
    if(*ptr) free(*ptr);
    *ptr = 0;
}

404
static
405 406 407 408 409
inline int _opencv_ffmpeg_interrupt_callback(void *ptr)
{
    AVInterruptCallbackMetadata* metadata = (AVInterruptCallbackMetadata*)ptr;
    assert(metadata);

410 411 412 413 414
    if (metadata->timeout_after_ms == 0)
    {
        return 0; // timeout is disabled
    }

415 416 417 418 419 420 421
    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;
}
422
#endif
423

P
Peter Rekdal Sunde 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
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
};

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
static AVRational _opencv_ffmpeg_get_sample_aspect_ratio(AVStream *stream)
{
#if LIBAVUTIL_VERSION_MICRO >= 100 && LIBAVUTIL_BUILD >= CALC_FFMPEG_VERSION(54, 5, 100)
    return av_guess_sample_aspect_ratio(NULL, stream, NULL);
#else
    AVRational undef = {0, 1};

    // stream
    AVRational ratio = stream ? stream->sample_aspect_ratio : undef;
    av_reduce(&ratio.num, &ratio.den, ratio.num, ratio.den, INT_MAX);
    if (ratio.num > 0 && ratio.den > 0)
        return ratio;

    // codec
    ratio  = stream && stream->codec ? stream->codec->sample_aspect_ratio : undef;
    av_reduce(&ratio.num, &ratio.den, ratio.num, ratio.den, INT_MAX);
    if (ratio.num > 0 && ratio.den > 0)
        return ratio;

    return undef;
#endif
}

480

481 482 483 484 485
struct CvCapture_FFMPEG
{
    bool open( const char* filename );
    void close();

486
    double getProperty(int) const;
487 488 489 490 491
    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 已提交
492 493 494

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

497 498 499
    int64_t get_total_frames() const;
    double  get_duration_sec() const;
    double  get_fps() const;
500
    int64_t get_bitrate() const;
V
Vadim Pisarevsky 已提交
501

502
    double  r2d(AVRational r) const;
V
Vadim Pisarevsky 已提交
503
    int64_t dts_to_frame_number(int64_t dts);
504
    double  dts_to_sec(int64_t dts) const;
505
    void    get_rotation_angle();
V
Vadim Pisarevsky 已提交
506 507 508 509 510

    AVFormatContext * ic;
    AVCodec         * avcodec;
    int               video_stream;
    AVStream        * video_st;
511 512
    AVFrame         * picture;
    AVFrame           rgb_picture;
V
Vadim Pisarevsky 已提交
513 514 515 516
    int64_t           picture_pts;

    AVPacket          packet;
    Image_FFMPEG      frame;
517
    struct SwsContext *img_convert_ctx;
V
Vadim Pisarevsky 已提交
518 519 520

    int64_t frame_number, first_frame_number;

521 522
    bool   rotation_auto;
    int    rotation_angle; // valid 0, 90, 180, 270
V
Vadim Pisarevsky 已提交
523
    double eps_zero;
524 525 526 527 528 529 530 531
/*
   '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 已提交
532 533 534 535

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    AVDictionary *dict;
#endif
536
#if USE_AV_INTERRUPT_CALLBACK
537 538
    int open_timeout_ms;
    int read_timeout_ms;
539
    AVInterruptCallbackMetadata interrupt_metadata;
540
#endif
541 542 543 544 545 546 547 548 549 550 551

    bool setRaw();
    bool processRawPacket();
    bool rawMode;
    bool rawModeInitialized;
    AVPacket packet_filtered;
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(58, 20, 100)
    AVBSFContext* bsfc;
 #else
    AVBitStreamFilterContext* bsfc;
#endif
552 553 554 555 556 557 558 559
};

void CvCapture_FFMPEG::init()
{
    ic = 0;
    video_stream = -1;
    video_st = 0;
    picture = 0;
V
Vadim Pisarevsky 已提交
560 561
    picture_pts = AV_NOPTS_VALUE_;
    first_frame_number = -1;
562 563 564
    memset( &rgb_picture, 0, sizeof(rgb_picture) );
    memset( &frame, 0, sizeof(frame) );
    filename = 0;
V
Vadim Pisarevsky 已提交
565 566
    memset(&packet, 0, sizeof(packet));
    av_init_packet(&packet);
567
    img_convert_ctx = 0;
V
Vadim Pisarevsky 已提交
568 569 570 571

    avcodec = 0;
    frame_number = 0;
    eps_zero = 0.000025;
I
Ilya Lavrenov 已提交
572

573 574 575 576 577
#if USE_AV_INTERRUPT_CALLBACK
    open_timeout_ms = LIBAVFORMAT_INTERRUPT_OPEN_DEFAULT_TIMEOUT_MS;
    read_timeout_ms = LIBAVFORMAT_INTERRUPT_READ_DEFAULT_TIMEOUT_MS;
#endif

578 579
    rotation_angle = 0;

580 581 582 583 584 585
#if (LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0))
#if (LIBAVUTIL_BUILD >= CALC_FFMPEG_VERSION(52, 92, 100))
    rotation_auto = true;
#else
    rotation_auto = false;
#endif
I
Ilya Lavrenov 已提交
586
    dict = NULL;
587 588
#else
    rotation_auto = false;
I
Ilya Lavrenov 已提交
589
#endif
590 591 592 593 594 595

    rawMode = false;
    rawModeInitialized = false;
    memset(&packet_filtered, 0, sizeof(packet_filtered));
    av_init_packet(&packet_filtered);
    bsfc = NULL;
596 597 598 599 600
}


void CvCapture_FFMPEG::close()
{
V
Vadim Pisarevsky 已提交
601 602 603 604 605
    if( img_convert_ctx )
    {
        sws_freeContext(img_convert_ctx);
        img_convert_ctx = 0;
    }
606

607
    if( picture )
608 609
    {
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
J
jisli 已提交
610 611 612
    ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
        av_frame_free(&picture);
#elif LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
613 614 615
    ? CALC_FFMPEG_VERSION(54, 59, 100) : CALC_FFMPEG_VERSION(54, 28, 0))
        avcodec_free_frame(&picture);
#else
616
        av_free(picture);
617 618
#endif
    }
619 620 621 622 623

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

625
#else
V
Vadim Pisarevsky 已提交
626 627
        avcodec_close( &(video_st->codec) );

628 629 630 631 632 633
#endif
        video_st = NULL;
    }

    if( ic )
    {
V
Vadim Pisarevsky 已提交
634
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 24, 2)
635
        av_close_input_file(ic);
V
Vadim Pisarevsky 已提交
636
#else
637
        avformat_close_input(&ic);
V
Vadim Pisarevsky 已提交
638 639
#endif

640 641 642
        ic = NULL;
    }

643 644 645
#if USE_AV_FRAME_GET_BUFFER
    av_frame_unref(&rgb_picture);
#else
646 647 648 649 650
    if( rgb_picture.data[0] )
    {
        free( rgb_picture.data[0] );
        rgb_picture.data[0] = 0;
    }
651
#endif
652 653 654

    // free last packet if exist
    if (packet.data) {
P
Peter Rekdal Sunde 已提交
655
        _opencv_ffmpeg_av_packet_unref (&packet);
V
Vadim Pisarevsky 已提交
656
        packet.data = NULL;
657 658
    }

I
Ilya Lavrenov 已提交
659 660 661 662 663
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    if (dict != NULL)
       av_dict_free(&dict);
#endif

664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
    if (packet_filtered.data)
    {
        _opencv_ffmpeg_av_packet_unref(&packet_filtered);
        packet_filtered.data = NULL;
    }

    if (bsfc)
    {
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(58, 20, 100)
        av_bsf_free(&bsfc);
#else
        av_bitstream_filter_close(bsfc);
#endif
    }

679 680 681 682 683
    init();
}


#ifndef AVSEEK_FLAG_FRAME
684
#define AVSEEK_FLAG_FRAME 0
685
#endif
A
Andrey Morozov 已提交
686
#ifndef AVSEEK_FLAG_ANY
687
#define AVSEEK_FLAG_ANY 1
688
#endif
V
Vadim Pisarevsky 已提交
689

I
Ilya Lavrenov 已提交
690
class ImplMutex
V
Vadim Pisarevsky 已提交
691
{
I
Ilya Lavrenov 已提交
692
public:
A
Andrey Kamaev 已提交
693 694 695
    ImplMutex() { init(); }
    ~ImplMutex() { destroy(); }

I
Ilya Lavrenov 已提交
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
    void init();
    void destroy();

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

    struct Impl;
protected:
    Impl* impl;

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

712
#if defined _WIN32 || defined WINCE
I
Ilya Lavrenov 已提交
713 714 715

struct ImplMutex::Impl
{
716 717 718 719 720 721 722 723 724
    void init()
    {
#if (_WIN32_WINNT >= 0x0600)
        ::InitializeCriticalSectionEx(&cs, 1000, 0);
#else
        ::InitializeCriticalSection(&cs);
#endif
        refcount = 1;
    }
I
Ilya Lavrenov 已提交
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
    void destroy() { DeleteCriticalSection(&cs); }

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

    CRITICAL_SECTION cs;
    int refcount;
};


#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;
};

753
#elif defined __linux__ && !defined __ANDROID__
I
Ilya Lavrenov 已提交
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786

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()
{
787
    impl = new Impl();
A
Andrey Kamaev 已提交
788
    impl->init();
I
Ilya Lavrenov 已提交
789
}
A
Andrey Kamaev 已提交
790
void ImplMutex::destroy()
I
Ilya Lavrenov 已提交
791
{
A
Andrey Kamaev 已提交
792
    impl->destroy();
793
    delete(impl);
A
Andrey Kamaev 已提交
794
    impl = NULL;
I
Ilya Lavrenov 已提交
795 796 797 798 799 800 801 802 803
}
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)
804
    {
I
Ilya Lavrenov 已提交
805 806
        case AV_LOCK_CREATE:
            localMutex = reinterpret_cast<ImplMutex*>(malloc(sizeof(ImplMutex)));
C
cyy 已提交
807 808
            if (!localMutex)
                return 1;
I
Ilya Lavrenov 已提交
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
            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;
827
            *mutex = NULL;
I
Ilya Lavrenov 已提交
828 829 830 831 832 833 834 835
        break;
    }
    return 0;
}

static ImplMutex _mutex;
static bool _initialized = false;

836 837 838 839 840 841 842 843 844 845 846 847
class AutoLock
{
public:
    AutoLock(ImplMutex& m) : mutex(&m) { mutex->lock(); }
    ~AutoLock() { mutex->unlock(); }
protected:
    ImplMutex* mutex;
private:
    AutoLock(const AutoLock&); // disabled
    AutoLock& operator = (const AutoLock&); // disabled
};

848 849 850 851
static void ffmpeg_log_callback(void *ptr, int level, const char *fmt, va_list vargs)
{
    static bool skip_header = false;
    static int prev_level = -1;
H
Hamdi Sahloul 已提交
852
    CV_UNUSED(ptr);
853
    if (level>av_log_get_level()) return;
854 855 856 857 858 859
    if (!skip_header || level != prev_level) printf("[OPENCV:FFMPEG:%02d] ", level);
    vprintf(fmt, vargs);
    size_t fmt_len = strlen(fmt);
    skip_header = fmt_len > 0 && fmt[fmt_len - 1] != '\n';
    prev_level = level;
}
860

I
Ilya Lavrenov 已提交
861 862
class InternalFFMpegRegister
{
863
    static void init_()
864
    {
865 866 867 868 869
        static InternalFFMpegRegister instance;
    }

    static void initLogger_()
    {
870
#ifndef NO_GETENV
871
        char* debug_option = getenv("OPENCV_FFMPEG_DEBUG");
872 873 874
        char* level_option = getenv("OPENCV_FFMPEG_LOGLEVEL");
        int level = AV_LOG_VERBOSE;
        if (level_option != NULL)
I
Ilya Lavrenov 已提交
875
        {
876 877 878 879 880
            level = atoi(level_option);
        }
        if ( (debug_option != NULL) || (level_option != NULL) )
        {
            av_log_set_level(level);
881 882 883
            av_log_set_callback(ffmpeg_log_callback);
        }
        else
884
#endif
885 886 887 888
        {
            av_log_set_level(AV_LOG_ERROR);
        }
    }
V
Vadim Pisarevsky 已提交
889

890 891 892 893 894 895 896
public:
    static void init()
    {
        if (!_initialized)
        {
            AutoLock lock(_mutex);
            if (!_initialized)
897
            {
898
                init_();
899
            }
900 901 902 903 904 905 906 907
        }
        initLogger_();  // update logger setup unconditionally (GStreamer's libav plugin may override these settings)
    }

    InternalFFMpegRegister()
    {
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 13, 0)
        avformat_network_init();
908
#endif
V
Vadim Pisarevsky 已提交
909

910 911 912 913 914 915 916
        /* register all codecs, demux and protocols */
        av_register_all();

        /* register a callback function for synchronization */
        av_lockmgr_register(&LockCallBack);

        _initialized = true;
V
Vadim Pisarevsky 已提交
917
    }
918

I
Ilya Lavrenov 已提交
919 920 921 922
    ~InternalFFMpegRegister()
    {
        _initialized = false;
        av_lockmgr_register(NULL);
923
        av_log_set_callback(NULL);
V
Vadim Pisarevsky 已提交
924
    }
I
Ilya Lavrenov 已提交
925 926
};

927 928
bool CvCapture_FFMPEG::open( const char* _filename )
{
929 930
    InternalFFMpegRegister::init();

931
    AutoLock lock(_mutex);
932

933 934 935 936
    unsigned i;
    bool valid = false;

    close();
937

938
#if USE_AV_INTERRUPT_CALLBACK
939
    /* interrupt callback */
940
    interrupt_metadata.timeout_after_ms = open_timeout_ms;
941 942 943 944 945
    get_monotonic_time(&interrupt_metadata.value);

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

V
Vadim Pisarevsky 已提交
948
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
#ifndef NO_GETENV
    char* options = getenv("OPENCV_FFMPEG_CAPTURE_OPTIONS");
    if(options == NULL)
    {
        av_dict_set(&dict, "rtsp_transport", "tcp", 0);
    }
    else
    {
#if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 ? CALC_FFMPEG_VERSION(52, 17, 100) : CALC_FFMPEG_VERSION(52, 7, 0))
        av_dict_parse_string(&dict, options, ";", "|", 0);
#else
        av_dict_set(&dict, "rtsp_transport", "tcp", 0);
#endif
    }
#else
I
Ilya Lavrenov 已提交
964
    av_dict_set(&dict, "rtsp_transport", "tcp", 0);
965
#endif
966 967 968 969 970 971 972 973
    AVInputFormat* input_format = NULL;
    AVDictionaryEntry* entry = av_dict_get(dict, "input_format", NULL, 0);
    if (entry != 0)
    {
      input_format = av_find_input_format(entry->value);
    }

    int err = avformat_open_input(&ic, _filename, input_format, &dict);
V
Vadim Pisarevsky 已提交
974
#else
975
    int err = av_open_input_file(&ic, _filename, NULL, 0, NULL);
976 977
#endif

I
Ilya Lavrenov 已提交
978 979
    if (err < 0)
    {
V
Vadim Pisarevsky 已提交
980
        CV_WARN("Error opening file");
981
        CV_WARN(_filename);
V
Vadim Pisarevsky 已提交
982
        goto exit_func;
983
    }
V
Vadim Pisarevsky 已提交
984
    err =
R
Roman Donchenko 已提交
985
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
V
Vadim Pisarevsky 已提交
986 987 988 989
    avformat_find_stream_info(ic, NULL);
#else
    av_find_stream_info(ic);
#endif
I
Ilya Lavrenov 已提交
990 991
    if (err < 0)
    {
V
Vadim Pisarevsky 已提交
992 993
        CV_WARN("Could not find codec parameters");
        goto exit_func;
994
    }
V
Vadim Pisarevsky 已提交
995 996
    for(i = 0; i < ic->nb_streams; i++)
    {
997 998 999 1000 1001 1002
#if LIBAVFORMAT_BUILD > 4628
        AVCodecContext *enc = ic->streams[i]->codec;
#else
        AVCodecContext *enc = &ic->streams[i]->codec;
#endif

I
Ilya Lavrenov 已提交
1003 1004 1005
//#ifdef FF_API_THREAD_INIT
//        avcodec_thread_init(enc, get_number_of_cpus());
//#else
V
Vadim Pisarevsky 已提交
1006
        enc->thread_count = get_number_of_cpus();
I
Ilya Lavrenov 已提交
1007
//#endif
1008

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(52, 123, 0)
        AVDictionaryEntry* avdiscard_entry = av_dict_get(dict, "avdiscard", NULL, 0);

        if (avdiscard_entry != 0) {
            if(strcmp(avdiscard_entry->value, "all") == 0)
                enc->skip_frame = AVDISCARD_ALL;
            else if (strcmp(avdiscard_entry->value, "bidir") == 0)
                enc->skip_frame = AVDISCARD_BIDIR;
            else if (strcmp(avdiscard_entry->value, "default") == 0)
                enc->skip_frame = AVDISCARD_DEFAULT;
            else if (strcmp(avdiscard_entry->value, "none") == 0)
                enc->skip_frame = AVDISCARD_NONE;
1021 1022 1023 1024
            // NONINTRA flag was introduced with version bump at revision:
            // https://github.com/FFmpeg/FFmpeg/commit/b152152df3b778d0a86dcda5d4f5d065b4175a7b
            // This key is supported only for FFMPEG version
#if LIBAVCODEC_VERSION_MICRO >= 100 && LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(55, 67, 100)
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
            else if (strcmp(avdiscard_entry->value, "nonintra") == 0)
                enc->skip_frame = AVDISCARD_NONINTRA;
#endif
            else if (strcmp(avdiscard_entry->value, "nonkey") == 0)
                enc->skip_frame = AVDISCARD_NONKEY;
            else if (strcmp(avdiscard_entry->value, "nonref") == 0)
                enc->skip_frame = AVDISCARD_NONREF;
        }
#endif

1035 1036 1037
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
#define AVMEDIA_TYPE_VIDEO CODEC_TYPE_VIDEO
#endif
V
Vadim Pisarevsky 已提交
1038

I
Ilya Lavrenov 已提交
1039 1040
        if( AVMEDIA_TYPE_VIDEO == enc->codec_type && video_stream < 0)
        {
G
gferry 已提交
1041 1042 1043 1044
            // backup encoder' width/height
            int enc_width = enc->width;
            int enc_height = enc->height;

1045 1046 1047 1048 1049 1050
            AVCodec *codec;
            if(av_dict_get(dict, "video_codec", NULL, 0) == NULL) {
                codec = avcodec_find_decoder(enc->codec_id);
            } else {
                codec = avcodec_find_decoder_by_name(av_dict_get(dict, "video_codec", NULL, 0)->value);
            }
1051
            if (!codec ||
V
Vadim Pisarevsky 已提交
1052 1053 1054 1055 1056
#if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
                avcodec_open2(enc, codec, NULL)
#else
                avcodec_open(enc, codec)
#endif
I
Ilya Lavrenov 已提交
1057 1058
                < 0)
                goto exit_func;
V
Vadim Pisarevsky 已提交
1059

G
gferry 已提交
1060 1061 1062 1063
            // 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; }

1064 1065
            video_stream = i;
            video_st = ic->streams[i];
J
jisli 已提交
1066 1067 1068 1069
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
            picture = av_frame_alloc();
#else
1070
            picture = avcodec_alloc_frame();
J
jisli 已提交
1071
#endif
1072 1073 1074 1075

            frame.width = enc->width;
            frame.height = enc->height;
            frame.cn = 3;
1076 1077
            frame.step = 0;
            frame.data = NULL;
1078
            get_rotation_angle();
1079 1080 1081 1082 1083 1084
            break;
        }
    }

    if(video_stream >= 0) valid = true;

V
Vadim Pisarevsky 已提交
1085
exit_func:
1086

1087 1088 1089 1090 1091
#if USE_AV_INTERRUPT_CALLBACK
    // deactivate interrupt callback
    interrupt_metadata.timeout_after_ms = 0;
#endif

1092 1093 1094 1095 1096 1097
    if( !valid )
        close();

    return valid;
}

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
bool CvCapture_FFMPEG::setRaw()
{
    if (!rawMode)
    {
        if (frame_number != 0)
        {
            CV_WARN("Incorrect usage: do not grab frames before .set(CAP_PROP_FORMAT, -1)");
        }
        // binary stream filter creation is moved into processRawPacket()
        rawMode = true;
    }
    return true;
}

bool CvCapture_FFMPEG::processRawPacket()
{
    if (packet.data == NULL)  // EOF
        return false;
    if (!rawModeInitialized)
    {
        rawModeInitialized = true;
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(58, 20, 100)
1120
        CV_CODEC_ID eVideoCodec = ic->streams[video_stream]->codecpar->codec_id;
1121
#elif LIBAVFORMAT_BUILD > 4628
1122
        CV_CODEC_ID eVideoCodec = video_st->codec->codec_id;
1123
#else
1124
        CV_CODEC_ID eVideoCodec = video_st->codec.codec_id;
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
#endif
        const char* filterName = NULL;
        if (eVideoCodec == CV_CODEC(CODEC_ID_H264)
#if LIBAVCODEC_VERSION_MICRO >= 100 \
    && LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(57, 24, 102)  // FFmpeg 3.0
            || eVideoCodec == CV_CODEC(CODEC_ID_H265)
#elif LIBAVCODEC_VERSION_MICRO < 100 \
    && LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(55, 34, 1)  // libav v10+
            || eVideoCodec == CV_CODEC(CODEC_ID_HEVC)
#endif
        )
        {
            // check start code prefixed mode (as defined in the Annex B H.264 / H.265 specification)
            if (packet.size >= 5
                 && !(packet.data[0] == 0 && packet.data[1] == 0 && packet.data[2] == 0 && packet.data[3] == 1)
                 && !(packet.data[0] == 0 && packet.data[1] == 0 && packet.data[2] == 1)
            )
            {
                filterName = eVideoCodec == CV_CODEC(CODEC_ID_H264) ? "h264_mp4toannexb" : "hevc_mp4toannexb";
            }
        }
        if (filterName)
        {
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(58, 20, 100)
            const AVBitStreamFilter * bsf = av_bsf_get_by_name(filterName);
            if (!bsf)
            {
1152
#ifdef __OPENCV_BUILD
1153
                CV_WARN(cv::format("Bitstream filter is not available: %s", filterName).c_str());
1154 1155 1156
#else
                CV_WARN("Bitstream filter is not available");
#endif
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
                return false;
            }
            int err = av_bsf_alloc(bsf, &bsfc);
            if (err < 0)
            {
                CV_WARN("Error allocating context for bitstream buffer");
                return false;
            }
            avcodec_parameters_copy(bsfc->par_in, ic->streams[video_stream]->codecpar);
            err = av_bsf_init(bsfc);
            if (err < 0)
            {
                CV_WARN("Error initializing bitstream buffer");
                return false;
            }
#else
            bsfc = av_bitstream_filter_init(filterName);
            if (!bsfc)
            {
1176
#ifdef __OPENCV_BUILD
1177
                CV_WARN(cv::format("Bitstream filter is not available: %s", filterName).c_str());
1178 1179 1180
#else
                CV_WARN("Bitstream filter is not available");
#endif
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
                return false;
            }
#endif
        }
    }
    if (bsfc)
    {
        if (packet_filtered.data)
        {
            _opencv_ffmpeg_av_packet_unref(&packet_filtered);
        }

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(58, 20, 100)
        int err = av_bsf_send_packet(bsfc, &packet);
        if (err < 0)
        {
            CV_WARN("Packet submission for filtering failed");
            return false;
        }
        err = av_bsf_receive_packet(bsfc, &packet_filtered);
        if (err < 0)
        {
            CV_WARN("Filtered packet retrieve failed");
            return false;
        }
#else
#if LIBAVFORMAT_BUILD > 4628
        AVCodecContext* ctx = ic->streams[video_stream]->codec;
#else
        AVCodecContext* ctx = &ic->streams[video_stream]->codec;
#endif
        int err = av_bitstream_filter_filter(bsfc, ctx, NULL, &packet_filtered.data,
            &packet_filtered.size, packet.data, packet.size, packet_filtered.flags & AV_PKT_FLAG_KEY);
        if (err < 0)
        {
            CV_WARN("Packet filtering failed");
            return false;
        }
#endif
        return packet_filtered.data != NULL;
    }
    return packet.data != NULL;
}
1224 1225 1226 1227 1228 1229

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

V
Vadim Pisarevsky 已提交
1230
    int count_errs = 0;
J
jormansa 已提交
1231
    const int max_number_of_attempts = 1 << 9;
1232

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

1235 1236 1237
    if( ic->streams[video_stream]->nb_frames > 0 &&
        frame_number > ic->streams[video_stream]->nb_frames )
        return false;
1238

V
Vadim Pisarevsky 已提交
1239
    picture_pts = AV_NOPTS_VALUE_;
1240

1241 1242 1243
#if USE_AV_INTERRUPT_CALLBACK
    // activate interrupt callback
    get_monotonic_time(&interrupt_metadata.value);
1244
    interrupt_metadata.timeout_after_ms = read_timeout_ms;
1245 1246
#endif

1247
    // get the next frame
V
Vadim Pisarevsky 已提交
1248 1249
    while (!valid)
    {
H
hahne 已提交
1250

P
Peter Rekdal Sunde 已提交
1251
        _opencv_ffmpeg_av_packet_unref (&packet);
1252

1253
#if USE_AV_INTERRUPT_CALLBACK
1254 1255 1256 1257 1258
        if (interrupt_metadata.timeout)
        {
            valid = false;
            break;
        }
1259
#endif
1260

1261
        int ret = av_read_frame(ic, &packet);
V
Vadim Pisarevsky 已提交
1262

1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
        if (ret == AVERROR(EAGAIN))
            continue;

        if (ret == AVERROR_EOF)
        {
            if (rawMode)
                break;

            // flush cached frames from video decoder
            packet.data = NULL;
            packet.size = 0;
            packet.stream_index = video_stream;
        }
V
Vadim Pisarevsky 已提交
1276 1277 1278

        if( packet.stream_index != video_stream )
        {
P
Peter Rekdal Sunde 已提交
1279
            _opencv_ffmpeg_av_packet_unref (&packet);
V
Vadim Pisarevsky 已提交
1280 1281 1282
            count_errs++;
            if (count_errs > max_number_of_attempts)
                break;
1283 1284
            continue;
        }
1285

1286 1287 1288 1289 1290 1291
        if (rawMode)
        {
            valid = processRawPacket();
            break;
        }

V
Vadim Pisarevsky 已提交
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
        // 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
1304

V
Vadim Pisarevsky 已提交
1305 1306 1307 1308 1309
        // Did we get a video frame?
        if(got_picture)
        {
            //picture_pts = picture->best_effort_timestamp;
            if( picture_pts == AV_NOPTS_VALUE_ )
1310 1311
                picture_pts = picture->pkt_pts != AV_NOPTS_VALUE_ && picture->pkt_pts != 0 ? picture->pkt_pts : picture->pkt_dts;

V
Vadim Pisarevsky 已提交
1312 1313 1314 1315 1316 1317 1318
            valid = true;
        }
        else
        {
            count_errs++;
            if (count_errs > max_number_of_attempts)
                break;
1319 1320 1321
        }
    }

1322 1323 1324 1325
    if (valid)
        frame_number++;

    if (!rawMode && valid && first_frame_number < 0)
V
Vadim Pisarevsky 已提交
1326
        first_frame_number = dts_to_frame_number(picture_pts);
1327

1328 1329 1330 1331 1332
#if USE_AV_INTERRUPT_CALLBACK
    // deactivate interrupt callback
    interrupt_metadata.timeout_after_ms = 0;
#endif

1333
    // return if we have a new frame or not
1334 1335 1336 1337 1338
    return valid;
}

bool CvCapture_FFMPEG::retrieveFrame(int, unsigned char** data, int* step, int* width, int* height, int* cn)
{
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
    if (!video_st)
        return false;

    if (rawMode)
    {
        AVPacket& p = bsfc ? packet_filtered : packet;
        *data = p.data;
        *step = p.size;
        *width = p.size;
        *height = 1;
        *cn = 1;
        return p.data != NULL;
    }

    if (!picture->data[0])
1354 1355
        return false;

V
Vadim Pisarevsky 已提交
1356 1357
    if( img_convert_ctx == NULL ||
        frame.width != video_st->codec->width ||
1358 1359
        frame.height != video_st->codec->height ||
        frame.data == NULL )
V
Vadim Pisarevsky 已提交
1360
    {
1361 1362 1363
        // 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 已提交
1364 1365

        img_convert_ctx = sws_getCachedContext(
1366 1367
                img_convert_ctx,
                buffer_width, buffer_height,
V
Vadim Pisarevsky 已提交
1368
                video_st->codec->pix_fmt,
1369
                buffer_width, buffer_height,
J
jisli 已提交
1370
                AV_PIX_FMT_BGR24,
V
Vadim Pisarevsky 已提交
1371 1372 1373 1374 1375 1376
                SWS_BICUBIC,
                NULL, NULL, NULL
                );

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

1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
#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);
1391
        rgb_picture.data[0] = (uint8_t*)realloc(rgb_picture.data[0],
P
Peter Rekdal Sunde 已提交
1392
                _opencv_ffmpeg_av_image_get_buffer_size( AV_PIX_FMT_BGR24,
1393
                                    buffer_width, buffer_height ));
P
Peter Rekdal Sunde 已提交
1394
        _opencv_ffmpeg_av_image_fill_arrays(&rgb_picture, rgb_picture.data[0],
1395 1396 1397 1398 1399
                        AV_PIX_FMT_BGR24, buffer_width, buffer_height );
#endif
        frame.width = video_st->codec->width;
        frame.height = video_st->codec->height;
        frame.cn = 3;
1400
        frame.data = rgb_picture.data[0];
1401
        frame.step = rgb_picture.linesize[0];
V
Vadim Pisarevsky 已提交
1402 1403 1404 1405 1406 1407
    }

    sws_scale(
            img_convert_ctx,
            picture->data,
            picture->linesize,
1408
            0, video_st->codec->coded_height,
V
Vadim Pisarevsky 已提交
1409 1410 1411 1412
            rgb_picture.data,
            rgb_picture.linesize
            );

1413 1414 1415 1416 1417 1418 1419 1420 1421
    *data = frame.data;
    *step = frame.step;
    *width = frame.width;
    *height = frame.height;
    *cn = frame.cn;

    return true;
}

1422
double CvCapture_FFMPEG::getProperty( int property_id ) const
1423 1424 1425
{
    if( !video_st ) return 0;

1426
    double codec_tag = 0;
1427
    CV_CODEC_ID codec_id = AV_CODEC_ID_NONE;
1428 1429
    const char* codec_fourcc = NULL;

1430 1431
    switch( property_id )
    {
V
Vadim Pisarevsky 已提交
1432
    case CV_FFMPEG_CAP_PROP_POS_MSEC:
1433 1434 1435 1436 1437
        if (picture_pts == AV_NOPTS_VALUE_)
        {
            return 0;
        }
        return (dts_to_sec(picture_pts) * 1000);
1438
    case CV_FFMPEG_CAP_PROP_POS_FRAMES:
V
Vadim Pisarevsky 已提交
1439
        return (double)frame_number;
1440
    case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
V
Vadim Pisarevsky 已提交
1441
        return r2d(ic->streams[video_stream]->time_base);
1442
    case CV_FFMPEG_CAP_PROP_FRAME_COUNT:
V
Vadim Pisarevsky 已提交
1443
        return (double)get_total_frames();
1444
    case CV_FFMPEG_CAP_PROP_FRAME_WIDTH:
1445
        return (double)((rotation_auto && ((rotation_angle%180) != 0)) ? frame.height : frame.width);
1446
    case CV_FFMPEG_CAP_PROP_FRAME_HEIGHT:
1447
        return (double)((rotation_auto && ((rotation_angle%180) != 0)) ? frame.width : frame.height);
1448
    case CV_FFMPEG_CAP_PROP_FPS:
1449
        return get_fps();
1450 1451
    case CV_FFMPEG_CAP_PROP_FOURCC:
#if LIBAVFORMAT_BUILD > 4628
1452 1453
        codec_id = video_st->codec->codec_id;
        codec_tag = (double) video_st->codec->codec_tag;
1454
#else
1455 1456
        codec_id = video_st->codec.codec_id;
        codec_tag = (double)video_st->codec.codec_tag;
1457
#endif
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469

        if(codec_tag || codec_id == AV_CODEC_ID_NONE)
        {
            return codec_tag;
        }

        codec_fourcc = _opencv_avcodec_get_name(codec_id);
        if(!codec_fourcc || strlen(codec_fourcc) < 4 || strcmp(codec_fourcc, "unknown_codec") == 0)
        {
            return codec_tag;
        }

1470
        return (double) CV_FOURCC(codec_fourcc[0], codec_fourcc[1], codec_fourcc[2], codec_fourcc[3]);
1471
    case CV_FFMPEG_CAP_PROP_SAR_NUM:
1472
        return _opencv_ffmpeg_get_sample_aspect_ratio(ic->streams[video_stream]).num;
1473
    case CV_FFMPEG_CAP_PROP_SAR_DEN:
1474
        return _opencv_ffmpeg_get_sample_aspect_ratio(ic->streams[video_stream]).den;
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
    case CV_FFMPEG_CAP_PROP_CODEC_PIXEL_FORMAT:
    {
#if LIBAVFORMAT_BUILD > 4628
        AVPixelFormat pix_fmt = video_st->codec->pix_fmt;
#else
        AVPixelFormat pix_fmt = video_st->codec.pix_fmt;
#endif
        unsigned int fourcc_tag = avcodec_pix_fmt_to_codec_tag(pix_fmt);
        return (fourcc_tag == 0) ? (double)-1 : (double)fourcc_tag;
    }
    case CV_FFMPEG_CAP_PROP_FORMAT:
        if (rawMode)
            return -1;
        break;
1489 1490
    case CV_FFMPEG_CAP_PROP_BITRATE:
        return static_cast<double>(get_bitrate());
1491 1492 1493
    case CV_FFMPEG_CAP_PROP_ORIENTATION_META:
        return static_cast<double>(rotation_angle);
    case CV_FFMPEG_CAP_PROP_ORIENTATION_AUTO:
1494 1495
#if ((LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)) && \
     (LIBAVUTIL_BUILD >= CALC_FFMPEG_VERSION(52, 94, 100)))
1496
        return static_cast<double>(rotation_auto);
1497 1498 1499
#else
        return 0;
#endif
1500 1501 1502 1503 1504 1505
#if USE_AV_INTERRUPT_CALLBACK
    case CV_FFMPEG_CAP_PROP_OPEN_TIMEOUT_MSEC:
        return static_cast<double>(open_timeout_ms);
    case CV_FFMPEG_CAP_PROP_READ_TIMEOUT_MSEC:
        return static_cast<double>(read_timeout_ms);
#endif // USE_AV_INTERRUPT_CALLBACK
V
Vadim Pisarevsky 已提交
1506
    default:
1507
        break;
1508
    }
V
Vadim Pisarevsky 已提交
1509

1510 1511 1512
    return 0;
}

1513
double CvCapture_FFMPEG::r2d(AVRational r) const
V
Vadim Pisarevsky 已提交
1514 1515 1516 1517
{
    return r.num == 0 || r.den == 0 ? 0. : (double)r.num / (double)r.den;
}

1518
double CvCapture_FFMPEG::get_duration_sec() const
1519
{
V
Vadim Pisarevsky 已提交
1520 1521 1522
    double sec = (double)ic->duration / (double)AV_TIME_BASE;

    if (sec < eps_zero)
1523
    {
V
Vadim Pisarevsky 已提交
1524
        sec = (double)ic->streams[video_stream]->duration * r2d(ic->streams[video_stream]->time_base);
1525
    }
V
Vadim Pisarevsky 已提交
1526 1527

    return sec;
1528 1529
}

1530
int64_t CvCapture_FFMPEG::get_bitrate() const
1531
{
1532
    return ic->bit_rate / 1000;
V
Vadim Pisarevsky 已提交
1533 1534
}

1535
double CvCapture_FFMPEG::get_fps() const
V
Vadim Pisarevsky 已提交
1536
{
A
Alexander Alekhin 已提交
1537 1538 1539 1540 1541 1542
#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 已提交
1543
    double fps = r2d(ic->streams[video_stream]->r_frame_rate);
A
Alexander Alekhin 已提交
1544
#endif
V
Vadim Pisarevsky 已提交
1545 1546 1547 1548 1549

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    if (fps < eps_zero)
    {
        fps = r2d(ic->streams[video_stream]->avg_frame_rate);
1550
    }
1551
#endif
V
Vadim Pisarevsky 已提交
1552 1553 1554 1555 1556

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

1561
int64_t CvCapture_FFMPEG::get_total_frames() const
V
Vadim Pisarevsky 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
{
    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);
}

1578
double CvCapture_FFMPEG::dts_to_sec(int64_t dts) const
V
Vadim Pisarevsky 已提交
1579 1580 1581 1582 1583
{
    return (double)(dts - ic->streams[video_stream]->start_time) *
        r2d(ic->streams[video_stream]->time_base);
}

1584 1585 1586
void CvCapture_FFMPEG::get_rotation_angle()
{
    rotation_angle = 0;
1587 1588
#if ((LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)) && \
     (LIBAVUTIL_BUILD >= CALC_FFMPEG_VERSION(52, 94, 100)))
1589 1590 1591
    AVDictionaryEntry *rotate_tag = av_dict_get(video_st->metadata, "rotate", NULL, 0);
    if (rotate_tag != NULL)
        rotation_angle = atoi(rotate_tag->value);
1592
#endif
1593 1594
}

V
Vadim Pisarevsky 已提交
1595 1596 1597 1598
void CvCapture_FFMPEG::seek(int64_t _frame_number)
{
    _frame_number = std::min(_frame_number, get_total_frames());
    int delta = 16;
1599

V
Vadim Pisarevsky 已提交
1600 1601
    // 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
1602
    if( first_frame_number < 0 && get_total_frames() > 1 )
1603
        grabFrame();
1604

V
Vadim Pisarevsky 已提交
1605 1606 1607 1608 1609 1610 1611
    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);
1612
        if (get_total_frames() > 1) av_seek_frame(ic, video_stream, time_stamp, AVSEEK_FLAG_BACKWARD);
V
Vadim Pisarevsky 已提交
1613 1614 1615 1616
        avcodec_flush_buffers(ic->streams[video_stream]->codec);
        if( _frame_number > 0 )
        {
            grabFrame();
1617

V
Vadim Pisarevsky 已提交
1618 1619 1620 1621 1622
            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);
1623

V
Vadim Pisarevsky 已提交
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
                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;
        }
1650
    }
V
Vadim Pisarevsky 已提交
1651 1652 1653 1654 1655
}

void CvCapture_FFMPEG::seek(double sec)
{
    seek((int64_t)(sec * get_fps() + 0.5));
1656
}
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670

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 已提交
1671
                seek((int64_t)value);
1672 1673 1674
                break;

            case CV_FFMPEG_CAP_PROP_POS_MSEC:
V
Vadim Pisarevsky 已提交
1675
                seek(value/1000.0);
1676 1677 1678
                break;

            case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
V
Vadim Pisarevsky 已提交
1679
                seek((int64_t)(value*ic->duration));
1680 1681 1682 1683 1684 1685
                break;
            }

            picture_pts=(int64_t)value;
        }
        break;
1686 1687 1688 1689
    case CV_FFMPEG_CAP_PROP_FORMAT:
        if (value == -1)
            return setRaw();
        return false;
1690
    case CV_FFMPEG_CAP_PROP_ORIENTATION_AUTO:
1691 1692
#if ((LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)) && \
     (LIBAVUTIL_BUILD >= CALC_FFMPEG_VERSION(52, 94, 100)))
1693
        rotation_auto = value != 0 ? true : false;
1694 1695
        return true;
#else
1696
        rotation_auto = false;
1697 1698
        return false;
#endif
1699
        break;
1700 1701 1702 1703 1704 1705 1706 1707
#if USE_AV_INTERRUPT_CALLBACK
    case CV_FFMPEG_CAP_PROP_OPEN_TIMEOUT_MSEC:
        open_timeout_ms = (int)value;
        break;
    case CV_FFMPEG_CAP_PROP_READ_TIMEOUT_MSEC:
        read_timeout_ms = (int)value;
        break;
#endif  // USE_AV_INTERRUPT_CALLBACK
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
    default:
        return false;
    }

    return true;
}


///////////////// FFMPEG CvVideoWriter implementation //////////////////////////
struct CvVideoWriter_FFMPEG
{
    bool open( const char* filename, int fourcc,
1720
               double fps, int width, int height, bool isColor );
1721 1722 1723 1724 1725
    void close();
    bool writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin );

    void init();

1726
    AVOutputFormat  * fmt;
V
Vadim Pisarevsky 已提交
1727
    AVFormatContext * oc;
1728 1729 1730 1731 1732 1733 1734 1735
    uint8_t         * outbuf;
    uint32_t          outbuf_size;
    FILE            * outfile;
    AVFrame         * picture;
    AVFrame         * input_picture;
    uint8_t         * picbuf;
    AVStream        * video_st;
    int               input_pix_fmt;
1736
    unsigned char   * aligned_input;
1737
    size_t            aligned_input_size;
V
Vadim Pisarevsky 已提交
1738
    int               frame_width, frame_height;
1739
    int               frame_idx;
V
Vadim Pisarevsky 已提交
1740
    bool              ok;
1741 1742 1743 1744 1745
    struct SwsContext *img_convert_ctx;
};

static const char * icvFFMPEGErrStr(int err)
{
1746
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
1747
    switch(err) {
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
    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 已提交
1776
    }
1777
#else
1778 1779
    switch(err) {
    case AVERROR_NUMEXPECTED:
V
Vadim Pisarevsky 已提交
1780
        return "Incorrect filename syntax";
1781
    case AVERROR_INVALIDDATA:
V
Vadim Pisarevsky 已提交
1782
        return "Invalid data in header";
1783
    case AVERROR_NOFMT:
V
Vadim Pisarevsky 已提交
1784
        return "Unknown format";
1785
    case AVERROR_IO:
V
Vadim Pisarevsky 已提交
1786
        return "I/O error occurred";
1787
    case AVERROR_NOMEM:
V
Vadim Pisarevsky 已提交
1788
        return "Memory allocation error";
1789
    default:
V
Vadim Pisarevsky 已提交
1790
        break;
1791
    }
1792 1793
#endif

V
Vadim Pisarevsky 已提交
1794
    return "Unspecified error";
1795 1796 1797 1798
}

/* function internal to FFMPEG (libavformat/riff.c) to lookup codec id by fourcc tag*/
extern "C" {
1799
    enum CV_CODEC_ID codec_get_bmp_id(unsigned int tag);
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
}

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;
1814
    aligned_input = NULL;
1815
    aligned_input_size = 0;
1816
    img_convert_ctx = 0;
V
Vadim Pisarevsky 已提交
1817
    frame_width = frame_height = 0;
1818
    frame_idx = 0;
V
Vadim Pisarevsky 已提交
1819
    ok = false;
1820 1821 1822 1823 1824 1825 1826 1827
}

/**
 * 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 已提交
1828
    AVFrame * picture;
1829
    uint8_t * picture_buf = 0;
V
Vadim Pisarevsky 已提交
1830 1831
    int size;

J
jisli 已提交
1832 1833 1834 1835
#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 已提交
1836
    picture = avcodec_alloc_frame();
J
jisli 已提交
1837
#endif
V
Vadim Pisarevsky 已提交
1838 1839
    if (!picture)
        return NULL;
1840 1841 1842 1843 1844

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

P
Peter Rekdal Sunde 已提交
1845
    size = _opencv_ffmpeg_av_image_get_buffer_size( (AVPixelFormat) pix_fmt, width, height);
V
Vadim Pisarevsky 已提交
1846 1847 1848 1849 1850 1851 1852
    if(alloc){
        picture_buf = (uint8_t *) malloc(size);
        if (!picture_buf)
        {
            av_free(picture);
            return NULL;
        }
P
Peter Rekdal Sunde 已提交
1853
        _opencv_ffmpeg_av_image_fill_arrays(picture, picture_buf,
J
jisli 已提交
1854
                       (AVPixelFormat) pix_fmt, width, height);
V
Vadim Pisarevsky 已提交
1855
    }
1856

V
Vadim Pisarevsky 已提交
1857
    return picture;
1858 1859 1860 1861
}

/* add a video output stream to the container */
static AVStream *icv_add_video_stream_FFMPEG(AVFormatContext *oc,
1862
                                             CV_CODEC_ID codec_id,
V
Vadim Pisarevsky 已提交
1863 1864
                                             int w, int h, int bitrate,
                                             double fps, int pixel_format)
1865
{
V
Vadim Pisarevsky 已提交
1866 1867 1868 1869
    AVCodecContext *c;
    AVStream *st;
    int frame_rate, frame_rate_base;
    AVCodec *codec;
1870

V
Vadim Pisarevsky 已提交
1871 1872 1873 1874 1875
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 10, 0)
    st = avformat_new_stream(oc, 0);
#else
    st = av_new_stream(oc, 0);
#endif
1876

V
Vadim Pisarevsky 已提交
1877 1878 1879 1880
    if (!st) {
        CV_WARN("Could not allocate stream");
        return NULL;
    }
1881 1882

#if LIBAVFORMAT_BUILD > 4628
V
Vadim Pisarevsky 已提交
1883
    c = st->codec;
1884
#else
V
Vadim Pisarevsky 已提交
1885
    c = &(st->codec);
1886 1887 1888
#endif

#if LIBAVFORMAT_BUILD > 4621
V
Vadim Pisarevsky 已提交
1889
    c->codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
1890
#else
V
Vadim Pisarevsky 已提交
1891
    c->codec_id = oc->oformat->video_codec;
1892 1893
#endif

1894
    if(codec_id != CV_CODEC(CODEC_ID_NONE)){
V
Vadim Pisarevsky 已提交
1895 1896
        c->codec_id = codec_id;
    }
1897 1898

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

V
Vadim Pisarevsky 已提交
1901
    c->codec_type = AVMEDIA_TYPE_VIDEO;
1902

1903
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54,25,0)
1904
    // Set per-codec defaults
1905
    CV_CODEC_ID c_id = c->codec_id;
1906 1907 1908
    avcodec_get_context_defaults3(c, codec);
    // avcodec_get_context_defaults3 erases codec_id for some reason
    c->codec_id = c_id;
1909
#endif
1910

V
Vadim Pisarevsky 已提交
1911 1912 1913 1914 1915
    /* 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;
1916

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

V
Vadim Pisarevsky 已提交
1921 1922 1923 1924 1925 1926
    /* 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,
1927 1928
       timebase should be 1/framerate and timestamp increments should be
       identically 1. */
V
Vadim Pisarevsky 已提交
1929 1930
    frame_rate=(int)(fps+0.5);
    frame_rate_base=1;
1931
    while (fabs(((double)frame_rate/frame_rate_base) - fps) > 0.001){
V
Vadim Pisarevsky 已提交
1932 1933 1934
        frame_rate_base*=10;
        frame_rate=(int)(fps*frame_rate_base + 0.5);
    }
1935 1936 1937
#if LIBAVFORMAT_BUILD > 4752
    c->time_base.den = frame_rate;
    c->time_base.num = frame_rate_base;
V
Vadim Pisarevsky 已提交
1938 1939 1940
    /* adjust time base for supported framerates */
    if(codec && codec->supported_framerates){
        const AVRational *p= codec->supported_framerates;
1941
        AVRational req = {frame_rate, frame_rate_base};
V
Vadim Pisarevsky 已提交
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
        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;
            }
        }
1952 1953
        if (best == NULL)
            return NULL;
V
Vadim Pisarevsky 已提交
1954 1955 1956
        c->time_base.den= best->num;
        c->time_base.num= best->den;
    }
1957
#else
V
Vadim Pisarevsky 已提交
1958 1959
    c->frame_rate = frame_rate;
    c->frame_rate_base = frame_rate_base;
1960 1961
#endif

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

1965
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG2VIDEO)) {
1966 1967
        c->max_b_frames = 2;
    }
1968
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG1VIDEO) || c->codec_id == CV_CODEC(CODEC_ID_MSMPEG4V3)){
1969
        /* needed to avoid using macroblocks in which some coeffs overflow
L
luz.paz 已提交
1970 1971
           this doesn't happen with normal video, it just happens here as the
           motion of the chroma plane doesn't match the luma plane */
V
Vadim Pisarevsky 已提交
1972
        /* avoid FFMPEG warning 'clipping 1 dct coefficients...' */
1973 1974
        c->mb_decision=2;
    }
1975 1976

#if LIBAVUTIL_BUILD > CALC_FFMPEG_VERSION(51,11,0)
1977 1978
    /* Some settings for libx264 encoding, restore dummy values for gop_size
     and qmin since they will be set to reasonable defaults by the libx264
1979
     preset system. Also, use a crf encode with the default quality rating,
1980
     this seems easier than finding an appropriate default bitrate. */
1981
    if (c->codec_id == AV_CODEC_ID_H264) {
1982 1983 1984
      c->gop_size = -1;
      c->qmin = -1;
      c->bit_rate = 0;
1985 1986
      if (c->priv_data)
          av_opt_set(c->priv_data,"crf","23", 0);
1987
    }
1988 1989
#endif

1990
#if LIBAVCODEC_VERSION_INT>0x000409
L
luz.paz 已提交
1991
    // some formats want stream headers to be separate
1992 1993
    if(oc->oformat->flags & AVFMT_GLOBALHEADER)
    {
1994 1995 1996
        // flags were renamed: https://github.com/libav/libav/commit/7c6eb0a1b7bf1aac7f033a7ec6d8cacc3b5c2615
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
     ? CALC_FFMPEG_VERSION(56, 60, 100) : CALC_FFMPEG_VERSION(56, 35, 0))
1997 1998
        c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
#else
1999
        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
2000
#endif
2001 2002 2003
    }
#endif

A
Alexander Alekhin 已提交
2004
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(52, 42, 0)
2005 2006 2007 2008
#if defined(_MSC_VER)
    AVRational avg_frame_rate = {frame_rate, frame_rate_base};
    st->avg_frame_rate = avg_frame_rate;
#else
A
Alexander Alekhin 已提交
2009 2010
    st->avg_frame_rate = (AVRational){frame_rate, frame_rate_base};
#endif
2011
#endif
2012 2013 2014
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 20, 0)
    st->time_base = c->time_base;
#endif
A
Alexander Alekhin 已提交
2015

2016 2017 2018
    return st;
}

V
Vadim Pisarevsky 已提交
2019 2020
static const int OPENCV_NO_FRAMES_WRITTEN_CODE = 1000;

2021 2022 2023 2024 2025 2026 2027
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 )
2028 2029
{
#if LIBAVFORMAT_BUILD > 4628
V
Vadim Pisarevsky 已提交
2030
    AVCodecContext * c = video_st->codec;
2031
#else
V
Vadim Pisarevsky 已提交
2032
    AVCodecContext * c = &(video_st->codec);
2033
#endif
2034
    int ret = OPENCV_NO_FRAMES_WRITTEN_CODE;
2035

2036 2037 2038
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(57, 0, 0)
    if (oc->oformat->flags & AVFMT_RAWPICTURE)
    {
2039 2040 2041 2042 2043
        /* raw video case. The API will change slightly in the near
           futur for that */
        AVPacket pkt;
        av_init_packet(&pkt);

V
Vadim Pisarevsky 已提交
2044
        pkt.flags |= PKT_FLAG_KEY;
2045 2046 2047 2048 2049
        pkt.stream_index= video_st->index;
        pkt.data= (uint8_t *)picture;
        pkt.size= sizeof(AVPicture);

        ret = av_write_frame(oc, &pkt);
2050 2051 2052 2053
    }
    else
#endif
    {
2054
        /* encode the image */
2055 2056 2057 2058 2059 2060 2061 2062
        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)
2063
            ;
2064
        else if (got_output) {
2065 2066 2067 2068 2069 2070
            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);
2071 2072
            pkt.stream_index= video_st->index;
            ret = av_write_frame(oc, &pkt);
P
Peter Rekdal Sunde 已提交
2073
            _opencv_ffmpeg_av_packet_unref(&pkt);
2074 2075 2076 2077 2078
        }
        else
            ret = OPENCV_NO_FRAMES_WRITTEN_CODE;
#else
        int out_size = avcodec_encode_video(c, outbuf, outbuf_size, picture);
2079 2080 2081
        /* if zero size, it means the image was buffered */
        if (out_size > 0) {
#if LIBAVFORMAT_BUILD > 4752
2082
            if(c->coded_frame->pts != (int64_t)AV_NOPTS_VALUE)
2083
                pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st->time_base);
2084
#else
V
Vadim Pisarevsky 已提交
2085
            pkt.pts = c->coded_frame->pts;
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
#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);
        }
2096
#endif
2097
    }
V
Vadim Pisarevsky 已提交
2098
    return ret;
2099 2100 2101 2102 2103
}

/// write a frame with FFMPEG
bool CvVideoWriter_FFMPEG::writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin )
{
2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
    // 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);
    }
2118

V
Vadim Pisarevsky 已提交
2119 2120 2121 2122
    if( (width & -2) != frame_width || (height & -2) != frame_height || !data )
        return false;
    width = frame_width;
    height = frame_height;
2123

V
Vadim Pisarevsky 已提交
2124
    // typecast from opaque data type to implemented struct
2125 2126 2127
#if LIBAVFORMAT_BUILD > 4628
    AVCodecContext *c = video_st->codec;
#else
A
Alexander Shishkov 已提交
2128
    AVCodecContext *c = &(video_st->codec);
2129 2130
#endif

2131
    // FFmpeg contains SIMD optimizations which can sometimes read data past
2132 2133 2134 2135 2136 2137 2138
    // the supplied input buffer.
    // Related info: https://trac.ffmpeg.org/ticket/6763
    // 1. 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).
    // 2. (dataend - SIMD_SIZE) and (dataend + SIMD_SIZE) is from the same 4k page
    const int CV_STEP_ALIGNMENT = 32;
    const size_t CV_SIMD_SIZE = 32;
2139
    const size_t CV_PAGE_MASK = ~(size_t)(4096 - 1);
A
Alexander Alekhin 已提交
2140
    const unsigned char* dataend = data + ((size_t)height * step);
2141 2142
    if (step % CV_STEP_ALIGNMENT != 0 ||
        (((size_t)dataend - CV_SIMD_SIZE) & CV_PAGE_MASK) != (((size_t)dataend + CV_SIMD_SIZE) & CV_PAGE_MASK))
A
Alexander Shishkov 已提交
2143
    {
2144
        int aligned_step = (step + CV_STEP_ALIGNMENT - 1) & ~(CV_STEP_ALIGNMENT - 1);
2145

2146 2147 2148
        size_t new_size = (aligned_step * height + CV_SIMD_SIZE);

        if (!aligned_input || aligned_input_size < new_size)
A
Alexander Shishkov 已提交
2149
        {
2150 2151 2152 2153
            if (aligned_input)
                av_freep(&aligned_input);
            aligned_input_size = new_size;
            aligned_input = (unsigned char*)av_mallocz(aligned_input_size);
A
Alexander Shishkov 已提交
2154
        }
2155

A
Alexander Shishkov 已提交
2156 2157
        if (origin == 1)
            for( int y = 0; y < height; y++ )
2158
                memcpy(aligned_input + y*aligned_step, data + (height-1-y)*step, step);
A
Alexander Shishkov 已提交
2159 2160
        else
            for( int y = 0; y < height; y++ )
2161
                memcpy(aligned_input + y*aligned_step, data + y*step, step);
2162

2163 2164
        data = aligned_input;
        step = aligned_step;
2165 2166
    }

V
Vadim Pisarevsky 已提交
2167 2168 2169
    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 已提交
2170
        _opencv_ffmpeg_av_image_fill_arrays(input_picture, (uint8_t *) data,
J
jisli 已提交
2171
                       (AVPixelFormat)input_pix_fmt, width, height);
2172
        input_picture->linesize[0] = step;
2173

V
Vadim Pisarevsky 已提交
2174 2175 2176 2177
        if( !img_convert_ctx )
        {
            img_convert_ctx = sws_getContext(width,
                                             height,
J
jisli 已提交
2178
                                             (AVPixelFormat)input_pix_fmt,
V
Vadim Pisarevsky 已提交
2179 2180 2181 2182 2183 2184 2185 2186
                                             c->width,
                                             c->height,
                                             c->pix_fmt,
                                             SWS_BICUBIC,
                                             NULL, NULL, NULL);
            if( !img_convert_ctx )
                return false;
        }
2187 2188 2189 2190 2191 2192

        if ( sws_scale(img_convert_ctx, input_picture->data,
                       input_picture->linesize, 0,
                       height,
                       picture->data, picture->linesize) < 0 )
            return false;
V
Vadim Pisarevsky 已提交
2193 2194
    }
    else{
P
Peter Rekdal Sunde 已提交
2195
        _opencv_ffmpeg_av_image_fill_arrays(picture, (uint8_t *) data,
J
jisli 已提交
2196
                       (AVPixelFormat)input_pix_fmt, width, height);
2197
        picture->linesize[0] = step;
V
Vadim Pisarevsky 已提交
2198
    }
2199

2200
    picture->pts = frame_idx;
2201
    bool ret = icv_av_write_frame_FFMPEG( oc, video_st, outbuf, outbuf_size, picture) >= 0;
2202
    frame_idx++;
2203

V
Vadim Pisarevsky 已提交
2204
    return ret;
2205 2206 2207 2208 2209
}

/// close video output stream and free associated memory
void CvVideoWriter_FFMPEG::close()
{
V
Vadim Pisarevsky 已提交
2210 2211 2212
    // nothing to do if already released
    if ( !picture )
        return;
2213

V
Vadim Pisarevsky 已提交
2214 2215 2216 2217
    /* 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?
2218

V
Vadim Pisarevsky 已提交
2219 2220 2221
    /* write the trailer, if any */
    if(ok && oc)
    {
2222 2223 2224
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(57, 0, 0)
        if (!(oc->oformat->flags & AVFMT_RAWPICTURE))
#endif
V
Vadim Pisarevsky 已提交
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
        {
            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);
    }
2235

V
Vadim Pisarevsky 已提交
2236 2237 2238 2239 2240
    if( img_convert_ctx )
    {
        sws_freeContext(img_convert_ctx);
        img_convert_ctx = 0;
    }
2241

V
Vadim Pisarevsky 已提交
2242
    // free pictures
2243
#if LIBAVFORMAT_BUILD > 4628
V
Vadim Pisarevsky 已提交
2244
    if( video_st->codec->pix_fmt != input_pix_fmt)
2245
#else
V
Vadim Pisarevsky 已提交
2246
    if( video_st->codec.pix_fmt != input_pix_fmt)
2247
#endif
V
Vadim Pisarevsky 已提交
2248 2249 2250 2251 2252 2253
    {
        if(picture->data[0])
            free(picture->data[0]);
        picture->data[0] = 0;
    }
    av_free(picture);
2254

V
Vadim Pisarevsky 已提交
2255 2256
    if (input_picture)
        av_free(input_picture);
2257

V
Vadim Pisarevsky 已提交
2258
    /* close codec */
2259
#if LIBAVFORMAT_BUILD > 4628
V
Vadim Pisarevsky 已提交
2260
    avcodec_close(video_st->codec);
2261
#else
V
Vadim Pisarevsky 已提交
2262
    avcodec_close(&(video_st->codec));
2263 2264
#endif

V
Vadim Pisarevsky 已提交
2265
    av_free(outbuf);
2266

2267
    if (oc)
V
Vadim Pisarevsky 已提交
2268
    {
2269 2270 2271
        if (!(fmt->flags & AVFMT_NOFILE))
        {
            /* close the output file */
2272

V
Vadim Pisarevsky 已提交
2273
#if LIBAVCODEC_VERSION_INT < ((52<<16)+(123<<8)+0)
2274
#if LIBAVCODEC_VERSION_INT >= ((51<<16)+(49<<8)+0)
2275
            url_fclose(oc->pb);
2276
#else
2277
            url_fclose(&oc->pb);
V
Vadim Pisarevsky 已提交
2278 2279
#endif
#else
2280
            avio_close(oc->pb);
2281 2282
#endif

2283
        }
2284

2285 2286 2287
        /* free the stream */
        avformat_free_context(oc);
    }
2288

2289
    av_freep(&aligned_input);
2290

V
Vadim Pisarevsky 已提交
2291 2292
    init();
}
2293

2294 2295 2296
#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)

2297
static inline bool cv_ff_codec_tag_match(const AVCodecTag *tags, CV_CODEC_ID id, unsigned int tag)
2298 2299 2300 2301 2302 2303 2304 2305 2306
{
    while (tags->id != AV_CODEC_ID_NONE)
    {
        if (tags->id == id && tags->tag == tag)
            return true;
        tags++;
    }
    return false;
}
E
Emanuele Ruffaldi 已提交
2307

2308
static inline bool cv_ff_codec_tag_list_match(const AVCodecTag *const *tags, CV_CODEC_ID id, unsigned int tag)
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
{
    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;
}

E
Emanuele Ruffaldi 已提交
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333

static inline void cv_ff_codec_tag_dump(const AVCodecTag *const *tags)
{
    int i;
    for (i = 0; tags && tags[i]; i++) {
        const AVCodecTag * ptags = tags[i];
        while (ptags->id != AV_CODEC_ID_NONE)
        {
            unsigned int tag = ptags->tag;
            printf("fourcc tag 0x%08x/'%c%c%c%c' codec_id %04X\n", tag, CV_TAG_TO_PRINTABLE_CHAR4(tag), ptags->id);
            ptags++;
        }
    }
}

V
Vadim Pisarevsky 已提交
2334 2335 2336 2337
/// 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 )
{
2338 2339 2340 2341
    InternalFFMpegRegister::init();

    AutoLock lock(_mutex);

2342
    CV_CODEC_ID codec_id = CV_CODEC(CODEC_ID_NONE);
V
Vadim Pisarevsky 已提交
2343 2344
    int err, codec_pix_fmt;
    double bitrate_scale = 1;
2345

V
Vadim Pisarevsky 已提交
2346
    close();
2347

V
Vadim Pisarevsky 已提交
2348 2349 2350 2351 2352
    // check arguments
    if( !filename )
        return false;
    if(fps <= 0)
        return false;
2353

V
Vadim Pisarevsky 已提交
2354 2355 2356 2357 2358 2359 2360
    // 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;
2361

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

2364
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
V
Vadim Pisarevsky 已提交
2365
    fmt = av_guess_format(NULL, filename, NULL);
2366
#else
V
Vadim Pisarevsky 已提交
2367
    fmt = guess_format(NULL, filename, NULL);
2368
#endif
2369

V
Vadim Pisarevsky 已提交
2370 2371
    if (!fmt)
        return false;
2372

V
Vadim Pisarevsky 已提交
2373 2374
    /* determine optimal pixel format */
    if (is_color) {
J
jisli 已提交
2375
        input_pix_fmt = AV_PIX_FMT_BGR24;
V
Vadim Pisarevsky 已提交
2376 2377
    }
    else {
J
jisli 已提交
2378
        input_pix_fmt = AV_PIX_FMT_GRAY8;
V
Vadim Pisarevsky 已提交
2379
    }
2380

E
Emanuele Ruffaldi 已提交
2381 2382 2383 2384 2385 2386 2387
    if (fourcc == -1)
    {
        fprintf(stderr,"OpenCV: FFMPEG: format %s / %s\n", fmt->name, fmt->long_name);
        cv_ff_codec_tag_dump(fmt->codec_tag);
        return false;
    }

V
Vadim Pisarevsky 已提交
2388
    /* Lookup codec_id for given fourcc */
2389
#if LIBAVCODEC_VERSION_INT<((51<<16)+(49<<8)+0)
2390
    if( (codec_id = codec_get_bmp_id( fourcc )) == CV_CODEC(CODEC_ID_NONE) )
V
Vadim Pisarevsky 已提交
2391
        return false;
2392
#else
2393 2394 2395
    if( (codec_id = av_codec_get_id(fmt->codec_tag, fourcc)) == CV_CODEC(CODEC_ID_NONE) )
    {
        const struct AVCodecTag * fallback_tags[] = {
2396 2397 2398 2399
#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().
2400
                avformat_get_riff_video_tags(),
2401 2402
#endif
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 25, 100) && defined LIBAVFORMAT_VERSION_MICRO && LIBAVFORMAT_VERSION_MICRO >= 100
2403 2404 2405
// 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().
2406
                avformat_get_mov_video_tags(),
2407
#endif
2408 2409
                codec_bmp_tags, // fallback for avformat < 54.1
                NULL };
2410 2411 2412 2413 2414 2415 2416 2417 2418
        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;
        }
    }
E
Emanuele Ruffaldi 已提交
2419 2420


2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
    // 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;
        }
    }
2436 2437
#endif

V
Vadim Pisarevsky 已提交
2438
    // alloc memory for context
2439
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
V
Vadim Pisarevsky 已提交
2440
    oc = avformat_alloc_context();
2441
#else
V
Vadim Pisarevsky 已提交
2442
    oc = av_alloc_format_context();
2443
#endif
V
Vadim Pisarevsky 已提交
2444
    assert (oc);
2445

V
Vadim Pisarevsky 已提交
2446 2447 2448
    /* set file name */
    oc->oformat = fmt;
    snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
2449

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

V
Vadim Pisarevsky 已提交
2453 2454
    // set a few optimal pixel formats for lossless codecs of interest..
    switch (codec_id) {
2455
#if LIBAVCODEC_VERSION_INT>((50<<16)+(1<<8)+0)
2456
    case CV_CODEC(CODEC_ID_JPEGLS):
V
Vadim Pisarevsky 已提交
2457
        // BGR24 or GRAY8 depending on is_color...
E
Emanuele Ruffaldi 已提交
2458 2459
        // supported: bgr24 rgb24 gray gray16le
        // as of version 3.4.1
V
Vadim Pisarevsky 已提交
2460 2461
        codec_pix_fmt = input_pix_fmt;
        break;
2462
#endif
2463
    case CV_CODEC(CODEC_ID_HUFFYUV):
E
Emanuele Ruffaldi 已提交
2464 2465 2466 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 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 2527 2528 2529
        // supported: yuv422p rgb24 bgra
        // as of version 3.4.1
        switch(input_pix_fmt)
        {
            case AV_PIX_FMT_RGB24:
            case AV_PIX_FMT_BGRA:
                codec_pix_fmt = input_pix_fmt;
                break;
            case AV_PIX_FMT_BGR24:
                codec_pix_fmt = AV_PIX_FMT_RGB24;
                break;
            default:
                codec_pix_fmt = AV_PIX_FMT_YUV422P;
                break;
        }
        break;
    case CV_CODEC(CODEC_ID_PNG):
        // supported: rgb24 rgba rgb48be rgba64be pal8 gray ya8 gray16be ya16be monob
        // as of version 3.4.1
        switch(input_pix_fmt)
        {
            case AV_PIX_FMT_GRAY8:
            case AV_PIX_FMT_GRAY16BE:
            case AV_PIX_FMT_RGB24:
            case AV_PIX_FMT_BGRA:
                codec_pix_fmt = input_pix_fmt;
                break;
            case AV_PIX_FMT_GRAY16LE:
                codec_pix_fmt = AV_PIX_FMT_GRAY16BE;
                break;
            case AV_PIX_FMT_BGR24:
                codec_pix_fmt = AV_PIX_FMT_RGB24;
                break;
            default:
                codec_pix_fmt = AV_PIX_FMT_YUV422P;
                break;
        }
        break;
    case CV_CODEC(CODEC_ID_FFV1):
        // supported: MANY
        // as of version 3.4.1
        switch(input_pix_fmt)
        {
            case AV_PIX_FMT_GRAY8:
            case AV_PIX_FMT_GRAY16LE:
#ifdef AV_PIX_FMT_BGR0
            case AV_PIX_FMT_BGR0:
#endif
            case AV_PIX_FMT_BGRA:
                codec_pix_fmt = input_pix_fmt;
                break;
            case AV_PIX_FMT_GRAY16BE:
                codec_pix_fmt = AV_PIX_FMT_GRAY16LE;
                break;
            case AV_PIX_FMT_BGR24:
            case AV_PIX_FMT_RGB24:
#ifdef AV_PIX_FMT_BGR0
                codec_pix_fmt = AV_PIX_FMT_BGR0;
#else
                codec_pix_fmt = AV_PIX_FMT_BGRA;
#endif
                break;
            default:
                codec_pix_fmt = AV_PIX_FMT_YUV422P;
                break;
        }
V
Vadim Pisarevsky 已提交
2530
        break;
2531 2532
    case CV_CODEC(CODEC_ID_MJPEG):
    case CV_CODEC(CODEC_ID_LJPEG):
J
jisli 已提交
2533
        codec_pix_fmt = AV_PIX_FMT_YUVJ420P;
V
Vadim Pisarevsky 已提交
2534 2535
        bitrate_scale = 3;
        break;
2536
    case CV_CODEC(CODEC_ID_RAWVIDEO):
E
Emanuele Ruffaldi 已提交
2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555
        // RGBA is the only RGB fourcc supported by AVI and MKV format
        if(fourcc == CV_FOURCC('R','G','B','A'))
        {
            codec_pix_fmt = AV_PIX_FMT_RGBA;
        }
        else
        {
            switch(input_pix_fmt)
            {
                case AV_PIX_FMT_GRAY8:
                case AV_PIX_FMT_GRAY16LE:
                case AV_PIX_FMT_GRAY16BE:
                    codec_pix_fmt = input_pix_fmt;
                    break;
                default:
                    codec_pix_fmt = AV_PIX_FMT_YUV420P;
                    break;
            }
        }
V
Vadim Pisarevsky 已提交
2556 2557 2558
        break;
    default:
        // good for lossy formats, MPEG, etc.
J
jisli 已提交
2559
        codec_pix_fmt = AV_PIX_FMT_YUV420P;
V
Vadim Pisarevsky 已提交
2560 2561
        break;
    }
2562

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

V
Vadim Pisarevsky 已提交
2565 2566 2567 2568
    // 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);
2569

V
Vadim Pisarevsky 已提交
2570 2571 2572 2573 2574 2575 2576
    /* 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
2577

V
Vadim Pisarevsky 已提交
2578 2579 2580
#if 0
#if FF_API_DUMP_FORMAT
    dump_format(oc, 0, filename, 1);
2581
#else
V
Vadim Pisarevsky 已提交
2582 2583
    av_dump_format(oc, 0, filename, 1);
#endif
2584 2585
#endif

V
Vadim Pisarevsky 已提交
2586 2587 2588 2589
    /* 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;
2590
    }
2591

V
Vadim Pisarevsky 已提交
2592 2593
    AVCodec *codec;
    AVCodecContext *c;
2594

V
Vadim Pisarevsky 已提交
2595 2596 2597 2598 2599
#if LIBAVFORMAT_BUILD > 4628
    c = (video_st->codec);
#else
    c = &(video_st->codec);
#endif
2600

V
Vadim Pisarevsky 已提交
2601 2602 2603 2604
    c->codec_tag = fourcc;
    /* find the video encoder */
    codec = avcodec_find_encoder(c->codec_id);
    if (!codec) {
2605
        fprintf(stderr, "Could not find encoder for codec id %d: %s\n", c->codec_id, icvFFMPEGErrStr(
V
Vadim Pisarevsky 已提交
2606 2607 2608 2609 2610 2611 2612
        #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
                AVERROR_ENCODER_NOT_FOUND
        #else
                -1
        #endif
                ));
        return false;
2613
    }
2614

V
Vadim Pisarevsky 已提交
2615
    int64_t lbit_rate = (int64_t)c->bit_rate;
2616
    lbit_rate += (int64_t)(bitrate / 2);
V
Vadim Pisarevsky 已提交
2617 2618 2619
    lbit_rate = std::min(lbit_rate, (int64_t)INT_MAX);
    c->bit_rate_tolerance = (int)lbit_rate;
    c->bit_rate = (int)lbit_rate;
2620

V
Vadim Pisarevsky 已提交
2621 2622 2623 2624 2625 2626 2627 2628
    /* 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) {
2629
        fprintf(stderr, "Could not open codec '%s': %s\n", codec->name, icvFFMPEGErrStr(err));
V
Vadim Pisarevsky 已提交
2630
        return false;
2631
    }
2632

V
Vadim Pisarevsky 已提交
2633
    outbuf = NULL;
2634

2635 2636 2637 2638 2639

#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(57, 0, 0)
    if (!(oc->oformat->flags & AVFMT_RAWPICTURE))
#endif
    {
V
Vadim Pisarevsky 已提交
2640 2641 2642 2643
        /* 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);
2644
    }
2645

V
Vadim Pisarevsky 已提交
2646 2647
    bool need_color_convert;
    need_color_convert = (c->pix_fmt != input_pix_fmt);
2648

V
Vadim Pisarevsky 已提交
2649 2650 2651 2652
    /* allocate the encoded raw picture */
    picture = icv_alloc_picture_FFMPEG(c->pix_fmt, c->width, c->height, need_color_convert);
    if (!picture) {
        return false;
2653
    }
2654

V
Vadim Pisarevsky 已提交
2655 2656 2657 2658 2659 2660 2661 2662
    /* 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;
2663
        }
2664 2665
    }

V
Vadim Pisarevsky 已提交
2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
    /* 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;
        }
2676
    }
2677

V
Vadim Pisarevsky 已提交
2678 2679 2680 2681 2682
#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 );
2683 2684
#endif

V
Vadim Pisarevsky 已提交
2685
    if(err < 0)
V
Vladislav Vinogradov 已提交
2686
    {
V
Vadim Pisarevsky 已提交
2687 2688 2689
        close();
        remove(filename);
        return false;
V
Vladislav Vinogradov 已提交
2690
    }
V
Vadim Pisarevsky 已提交
2691 2692
    frame_width = width;
    frame_height = height;
2693
    frame_idx = 0;
V
Vadim Pisarevsky 已提交
2694
    ok = true;
I
Ilya Lavrenov 已提交
2695

V
Vadim Pisarevsky 已提交
2696
    return true;
V
Vladislav Vinogradov 已提交
2697 2698 2699 2700
}



V
Vadim Pisarevsky 已提交
2701
CvCapture_FFMPEG* cvCreateFileCapture_FFMPEG( const char* filename )
V
Vladislav Vinogradov 已提交
2702
{
V
Vadim Pisarevsky 已提交
2703
    CvCapture_FFMPEG* capture = (CvCapture_FFMPEG*)malloc(sizeof(*capture));
2704 2705
    if (!capture)
        return 0;
V
Vadim Pisarevsky 已提交
2706 2707 2708
    capture->init();
    if( capture->open( filename ))
        return capture;
I
Ilya Lavrenov 已提交
2709

V
Vadim Pisarevsky 已提交
2710 2711 2712
    capture->close();
    free(capture);
    return 0;
V
Vladislav Vinogradov 已提交
2713 2714
}

V
Vadim Pisarevsky 已提交
2715 2716

void cvReleaseCapture_FFMPEG(CvCapture_FFMPEG** capture)
V
Vladislav Vinogradov 已提交
2717
{
V
Vadim Pisarevsky 已提交
2718
    if( capture && *capture )
V
Vladislav Vinogradov 已提交
2719
    {
V
Vadim Pisarevsky 已提交
2720 2721 2722
        (*capture)->close();
        free(*capture);
        *capture = 0;
V
Vladislav Vinogradov 已提交
2723 2724 2725
    }
}

V
Vadim Pisarevsky 已提交
2726
int cvSetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id, double value)
V
Vladislav Vinogradov 已提交
2727
{
V
Vadim Pisarevsky 已提交
2728
    return capture->setProperty(prop_id, value);
V
Vladislav Vinogradov 已提交
2729 2730
}

V
Vadim Pisarevsky 已提交
2731
double cvGetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id)
V
Vladislav Vinogradov 已提交
2732
{
V
Vadim Pisarevsky 已提交
2733
    return capture->getProperty(prop_id);
V
Vladislav Vinogradov 已提交
2734 2735
}

V
Vadim Pisarevsky 已提交
2736
int cvGrabFrame_FFMPEG(CvCapture_FFMPEG* capture)
V
Vladislav Vinogradov 已提交
2737
{
V
Vadim Pisarevsky 已提交
2738
    return capture->grabFrame();
V
Vladislav Vinogradov 已提交
2739
}
V
Vladislav Vinogradov 已提交
2740

V
Vadim Pisarevsky 已提交
2741
int cvRetrieveFrame_FFMPEG(CvCapture_FFMPEG* capture, unsigned char** data, int* step, int* width, int* height, int* cn)
V
Vladislav Vinogradov 已提交
2742
{
V
Vadim Pisarevsky 已提交
2743
    return capture->retrieveFrame(0, data, step, width, height, cn);
V
Vladislav Vinogradov 已提交
2744 2745
}

V
Vadim Pisarevsky 已提交
2746 2747
CvVideoWriter_FFMPEG* cvCreateVideoWriter_FFMPEG( const char* filename, int fourcc, double fps,
                                                  int width, int height, int isColor )
V
Vladislav Vinogradov 已提交
2748
{
V
Vadim Pisarevsky 已提交
2749
    CvVideoWriter_FFMPEG* writer = (CvVideoWriter_FFMPEG*)malloc(sizeof(*writer));
2750 2751
    if (!writer)
        return 0;
V
Vadim Pisarevsky 已提交
2752 2753 2754 2755 2756 2757
    writer->init();
    if( writer->open( filename, fourcc, fps, width, height, isColor != 0 ))
        return writer;
    writer->close();
    free(writer);
    return 0;
V
Vladislav Vinogradov 已提交
2758 2759
}

V
Vadim Pisarevsky 已提交
2760 2761 2762
void cvReleaseVideoWriter_FFMPEG( CvVideoWriter_FFMPEG** writer )
{
    if( writer && *writer )
V
Vladislav Vinogradov 已提交
2763
    {
V
Vadim Pisarevsky 已提交
2764 2765 2766
        (*writer)->close();
        free(*writer);
        *writer = 0;
V
Vladislav Vinogradov 已提交
2767 2768 2769 2770
    }
}


V
Vadim Pisarevsky 已提交
2771 2772 2773
int cvWriteFrame_FFMPEG( CvVideoWriter_FFMPEG* writer,
                         const unsigned char* data, int step,
                         int width, int height, int cn, int origin)
V
Vladislav Vinogradov 已提交
2774
{
V
Vadim Pisarevsky 已提交
2775
    return writer->writeFrame(data, step, width, height, cn, origin);
V
Vladislav Vinogradov 已提交
2776 2777
}

2778 2779 2780 2781 2782 2783 2784 2785 2786 2787


/*
 * For CUDA encoder
 */

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

2789 2790 2791
    void write(unsigned char* data, int size, int keyFrame);

    // add a video output stream to the container
J
jisli 已提交
2792
    static AVStream* addVideoStream(AVFormatContext *oc, CV_CODEC_ID codec_id, int w, int h, int bitrate, double fps, AVPixelFormat pixel_format);
2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838

    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 已提交
2839
AVStream* OutputMediaStream_FFMPEG::addVideoStream(AVFormatContext *oc, CV_CODEC_ID codec_id, int w, int h, int bitrate, double fps, AVPixelFormat pixel_format)
2840
{
2841 2842 2843 2844 2845 2846 2847
    AVCodec* codec = avcodec_find_encoder(codec_id);
    if (!codec)
    {
        fprintf(stderr, "Could not find encoder for codec id %d\n", codec_id);
        return NULL;
    }

2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882
    #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
    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;
2883
    while (fabs((static_cast<double>(frame_rate)/frame_rate_base) - fps) > 0.001)
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902
    {
        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);

2903
                if (error.num < 0)
2904 2905 2906 2907 2908 2909 2910 2911 2912
                    error.num *= -1;

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

2913 2914
            if (best == NULL)
                return NULL;
2915 2916 2917 2918 2919 2920 2921 2922
            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;

2923
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG2VIDEO))
2924 2925
        c->max_b_frames = 2;

2926
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG1VIDEO) || c->codec_id == CV_CODEC(CODEC_ID_MSMPEG4V3))
2927 2928
    {
        // needed to avoid using macroblocks in which some coeffs overflow
L
luz.paz 已提交
2929 2930
        // this doesn't happen with normal video, it just happens here as the
        // motion of the chroma plane doesn't match the luma plane
2931 2932 2933 2934 2935 2936 2937

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

        c->mb_decision = 2;
    }

    #if LIBAVCODEC_VERSION_INT > 0x000409
L
luz.paz 已提交
2938
        // some formats want stream headers to be separate
2939 2940
        if (oc->oformat->flags & AVFMT_GLOBALHEADER)
        {
2941 2942 2943 2944 2945
            #if LIBAVCODEC_BUILD > CALC_FFMPEG_VERSION(56, 35, 0)
                c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
            #else
                c->flags |= CODEC_FLAG_GLOBAL_HEADER;
            #endif
2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966
        }
    #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;

2967
    CV_CODEC_ID codec_id = CV_CODEC(CODEC_ID_H264);
2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984

    // 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 已提交
2985
    AVPixelFormat codec_pix_fmt = AV_PIX_FMT_YUV420P;
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
    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');
3009
    c->bit_rate_tolerance = (int)(c->bit_rate);
3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024

    // 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
A
Alexander Alekhin 已提交
3025
    int header_err =
3026 3027 3028 3029 3030
    #if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
        av_write_header(oc_);
    #else
        avformat_write_header(oc_, NULL);
    #endif
A
Alexander Alekhin 已提交
3031 3032
    if (header_err != 0)
        return false;
3033 3034 3035 3036 3037 3038 3039

    return true;
}

void OutputMediaStream_FFMPEG::write(unsigned char* data, int size, int keyFrame)
{
    // if zero size, it means the image was buffered
3040
    if (size > 0)
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059
    {
        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));
3060 3061
    if (!stream)
        return 0;
3062 3063 3064 3065 3066 3067

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

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

3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102
    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 已提交
3103
    VideoCodec_UYVY   = (('U'<<24)|('Y'<<16)|('V'<<8)|('Y'))    // UYVY (4:2:2)
3104 3105 3106 3107 3108 3109 3110
};

enum
{
    VideoChromaFormat_Monochrome = 0,
    VideoChromaFormat_YUV420,
    VideoChromaFormat_YUV422,
I
Ilya Lavrenov 已提交
3111
    VideoChromaFormat_YUV444
3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
};

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_;
3129

3130
#if USE_AV_INTERRUPT_CALLBACK
3131
    AVInterruptCallbackMetadata interrupt_metadata;
3132
#endif
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142
};

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));

3143
#if USE_AV_INTERRUPT_CALLBACK
3144
    /* interrupt callback */
3145
    interrupt_metadata.timeout_after_ms = LIBAVFORMAT_INTERRUPT_OPEN_DEFAULT_TIMEOUT_MS;
3146 3147 3148 3149 3150
    get_monotonic_time(&interrupt_metadata.value);

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

3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164
    #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 已提交
3165
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
        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)
            {
3187
            case CV_CODEC(CODEC_ID_MPEG1VIDEO):
3188 3189 3190
                *codec = ::VideoCodec_MPEG1;
                break;

3191
            case CV_CODEC(CODEC_ID_MPEG2VIDEO):
3192 3193 3194
                *codec = ::VideoCodec_MPEG2;
                break;

3195
            case CV_CODEC(CODEC_ID_MPEG4):
3196 3197 3198
                *codec = ::VideoCodec_MPEG4;
                break;

3199
            case CV_CODEC(CODEC_ID_VC1):
3200 3201 3202
                *codec = ::VideoCodec_VC1;
                break;

3203
            case CV_CODEC(CODEC_ID_H264):
3204 3205 3206 3207 3208 3209 3210 3211 3212
                *codec = ::VideoCodec_H264;
                break;

            default:
                return false;
            };

            switch (enc->pix_fmt)
            {
J
jisli 已提交
3213
            case AV_PIX_FMT_YUV420P:
3214 3215 3216
                *chroma_format = ::VideoChromaFormat_YUV420;
                break;

J
jisli 已提交
3217
            case AV_PIX_FMT_YUV422P:
3218 3219 3220
                *chroma_format = ::VideoChromaFormat_YUV422;
                break;

J
jisli 已提交
3221
            case AV_PIX_FMT_YUV444P:
3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
                *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_);

3241 3242 3243 3244 3245
#if USE_AV_INTERRUPT_CALLBACK
    // deactivate interrupt callback
    interrupt_metadata.timeout_after_ms = 0;
#endif

3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261
    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 已提交
3262
        _opencv_ffmpeg_av_packet_unref(&pkt_);
3263 3264 3265 3266
}

bool InputMediaStream_FFMPEG::read(unsigned char** data, int* size, int* endOfFile)
{
3267 3268 3269 3270 3271
    bool result = false;

#if USE_AV_INTERRUPT_CALLBACK
    // activate interrupt callback
    get_monotonic_time(&interrupt_metadata.value);
3272
    interrupt_metadata.timeout_after_ms = LIBAVFORMAT_INTERRUPT_READ_DEFAULT_TIMEOUT_MS;
3273 3274
#endif

3275 3276
    // free last packet if exist
    if (pkt_.data)
P
Peter Rekdal Sunde 已提交
3277
        _opencv_ffmpeg_av_packet_unref(&pkt_);
3278 3279 3280 3281

    // get the next frame
    for (;;)
    {
3282
#if USE_AV_INTERRUPT_CALLBACK
3283 3284 3285 3286
        if(interrupt_metadata.timeout)
        {
            break;
        }
3287
#endif
3288

3289 3290 3291 3292 3293 3294 3295
        int ret = av_read_frame(ctx_, &pkt_);

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

        if (ret < 0)
        {
A
Andrey Kamaev 已提交
3296
            if (ret == (int)AVERROR_EOF)
3297
                *endOfFile = true;
3298
            break;
3299 3300 3301 3302
        }

        if (pkt_.stream_index != video_stream_id_)
        {
P
Peter Rekdal Sunde 已提交
3303
            _opencv_ffmpeg_av_packet_unref(&pkt_);
3304 3305 3306
            continue;
        }

3307
        result = true;
3308 3309 3310
        break;
    }

3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321
#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;
    }
3322

3323
    return result;
3324 3325 3326 3327 3328
}

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));
3329 3330
    if (!stream)
        return 0;
3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350

    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);
}