cap_ffmpeg_impl.hpp 98.4 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
//     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*/

43
#include <opencv2/core/utils/configuration.private.hpp>
44
#include "cap_ffmpeg_legacy_api.hpp"
45 46
#include "opencv2/core/utils/logger.hpp"
#include "cap_interface.hpp"
47 48 49

using namespace cv;

50
#if !(defined(_WIN32) || defined(WINCE))
51 52
# include <pthread.h>
#endif
53
#include <algorithm>
V
Vadim Pisarevsky 已提交
54
#include <limits>
55
#include <string.h>
56

57 58 59 60
#ifndef __OPENCV_BUILD
#define CV_FOURCC(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24))
#endif

61 62
#define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c )

63
#if defined _MSC_VER && _MSC_VER >= 1200
T
Tomoaki Teshima 已提交
64
#pragma warning( disable: 4244 4510 4610 )
65 66
#endif

A
Andrey Kamaev 已提交
67 68 69
#ifdef __GNUC__
#  pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
70 71 72
#ifdef _MSC_VER
#pragma warning(disable: 4996)  // was declared deprecated
#endif
A
Andrey Kamaev 已提交
73

A
Alexander Alekhin 已提交
74 75 76 77
#ifndef CV_UNUSED  // Required for standalone compilation mode (OpenCV defines this in base.hpp)
#define CV_UNUSED(name) (void)name
#endif

78 79 80 81
#ifdef __cplusplus
extern "C" {
#endif

82 83
#include "ffmpeg_codecs.hpp"

V
Vadim Pisarevsky 已提交
84
#include <libavutil/mathematics.h>
85
#include <libavutil/opt.h>
86 87 88
// https://github.com/FFmpeg/FFmpeg/blame/d79c240196f43b93bd204363f1facc270029f113/doc/APIchanges#L1689-L1695
#if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(52, 85, 100) : CALC_FFMPEG_VERSION(53, 15, 0))
89
#include <libavutil/display.h>
90
#endif
91

P
Peter Rekdal Sunde 已提交
92 93 94 95 96
#if LIBAVUTIL_BUILD >= (LIBAVUTIL_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(51, 63, 100) : CALC_FFMPEG_VERSION(54, 6, 0))
#include <libavutil/imgutils.h>
#endif

97 98
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
99 100 101
#ifdef HAVE_FFMPEG_LIBAVDEVICE
#include <libavdevice/avdevice.h>
#endif
102

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
// https://github.com/FFmpeg/FFmpeg/blob/b6af56c034759b81985f8ea094e41cbd5f7fecfb/doc/APIchanges#L602-L605
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(58, 9, 100)
#  define CV_FFMPEG_REGISTER
#endif

// https://github.com/FFmpeg/FFmpeg/blob/b6af56c034759b81985f8ea094e41cbd5f7fecfb/doc/APIchanges#L654-L657
#if LIBAVCODEC_BUILD < CALC_FFMPEG_VERSION(58, 9, 100)
#  define CV_FFMPEG_LOCKMGR
#endif

// https://github.com/FFmpeg/FFmpeg/blob/b6af56c034759b81985f8ea094e41cbd5f7fecfb/doc/APIchanges#L390-L392
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(58, 87, 100)
#include <libavcodec/bsf.h>
#endif

118 119
#include <libavutil/pixdesc.h>

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
// https://github.com/FFmpeg/FFmpeg/blob/b6af56c034759b81985f8ea094e41cbd5f7fecfb/doc/APIchanges#L208-L210
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(59, 0, 100)
#  define CV_FFMPEG_FMT_CONST const
#else
#  define CV_FFMPEG_FMT_CONST
#endif

// https://github.com/FFmpeg/FFmpeg/blob/b6af56c034759b81985f8ea094e41cbd5f7fecfb/doc/APIchanges#L623-L624
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(58, 7, 100)
#  define CV_FFMPEG_URL
#endif

// AVStream.codec deprecated in favor of AVStream.codecpar
// https://github.com/FFmpeg/FFmpeg/blob/b6af56c034759b81985f8ea094e41cbd5f7fecfb/doc/APIchanges#L1039-L1040
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(59, 16, 100)
//#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(57, 33, 100)
#  define CV_FFMPEG_CODECPAR
#  define CV_FFMPEG_CODEC_FIELD codecpar
#else
#  define CV_FFMPEG_CODEC_FIELD codec
#endif

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(59, 16, 100)
#  define CV_FFMPEG_PTS_FIELD pts
#else
#  define CV_FFMPEG_PTS_FIELD pkt_pts
#endif

// https://github.com/FFmpeg/FFmpeg/blob/b6af56c034759b81985f8ea094e41cbd5f7fecfb/doc/APIchanges#L1757-L1758
#if LIBAVUTIL_BUILD < CALC_FFMPEG_VERSION(52, 63, 100)
inline static AVRational av_make_q(int num, int den)
{
    AVRational res;
    res.num = num;
    res.den = den;
    return res;
}
#endif



161 162 163 164
#ifdef __cplusplus
}
#endif

165 166 167 168 169 170
// GCC 4.x compilation bug. Details: https://github.com/opencv/opencv/issues/20292
#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__)
#undef USE_AV_HW_CODECS
#define USE_AV_HW_CODECS 0
#endif

171 172 173 174 175 176 177 178 179 180
//#define USE_AV_HW_CODECS 0
#ifndef USE_AV_HW_CODECS
#if LIBAVUTIL_VERSION_MAJOR >= 56 // FFMPEG 4.0+
#define USE_AV_HW_CODECS 1
#include "cap_ffmpeg_hw.hpp"
#else
#define USE_AV_HW_CODECS 0
#endif
#endif

181
#if defined _MSC_VER && _MSC_VER >= 1200
T
Tomoaki Teshima 已提交
182
#pragma warning( default: 4244 4510 4610 )
183 184 185 186 187 188 189 190
#endif

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

191
#if defined _WIN32
192
    #include <windows.h>
193 194 195 196 197 198 199
    #if defined _MSC_VER && _MSC_VER < 1900
    struct timespec
    {
        time_t tv_sec;
        long   tv_nsec;
    };
  #endif
200
#elif defined __linux__ || defined __APPLE__ || defined __HAIKU__
201 202
    #include <unistd.h>
    #include <stdio.h>
V
Vadim Pisarevsky 已提交
203
    #include <sys/types.h>
204
    #include <sys/time.h>
205
#if defined __APPLE__
206
    #include <sys/sysctl.h>
207 208
    #include <mach/clock.h>
    #include <mach/mach.h>
209
#endif
210
#endif
211

V
Vadim Pisarevsky 已提交
212 213 214 215 216 217 218

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

219 220 221 222
#ifndef AVERROR_EOF
#define AVERROR_EOF (-MKTAG( 'E','O','F',' '))
#endif

223 224 225 226 227 228 229 230
#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

231 232 233 234
#ifndef PKT_FLAG_KEY
#define PKT_FLAG_KEY AV_PKT_FLAG_KEY
#endif

235 236 237 238 239 240 241 242 243 244
#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

245

246 247 248 249
#ifndef USE_AV_INTERRUPT_CALLBACK
#define USE_AV_INTERRUPT_CALLBACK 1
#endif

250 251 252 253 254 255 256 257 258 259
#ifndef USE_AV_SEND_FRAME_API
// https://github.com/FFmpeg/FFmpeg/commit/7fc329e2dd6226dfecaa4a1d7adf353bf2773726
#if LIBAVCODEC_VERSION_MICRO >= 100 \
    && LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(57, 37, 100)
#define USE_AV_SEND_FRAME_API 1
#else
#define USE_AV_SEND_FRAME_API 0
#endif
#endif

260
#if USE_AV_INTERRUPT_CALLBACK
261 262
#define LIBAVFORMAT_INTERRUPT_OPEN_DEFAULT_TIMEOUT_MS 30000
#define LIBAVFORMAT_INTERRUPT_READ_DEFAULT_TIMEOUT_MS 30000
263

264
#ifdef _WIN32
265 266
// http://stackoverflow.com/questions/5404277/porting-clock-gettime-to-windows

267
static
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
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;
}

288
static
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
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;
328
    t.QuadPart = (LONGLONG)microseconds;
329 330 331 332
    tv->tv_sec = t.QuadPart / 1000000;
    tv->tv_nsec = (t.QuadPart % 1000000) * 1000;
}
#else
333
static
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
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

350
static
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
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;
}

367
static
368 369 370 371 372 373 374
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;
}
375
#endif // USE_AV_INTERRUPT_CALLBACK
376

377

378 379 380 381 382 383 384 385 386
struct Image_FFMPEG
{
    unsigned char* data;
    int step;
    int width;
    int height;
};


387
#if USE_AV_INTERRUPT_CALLBACK
388 389 390 391 392 393 394
struct AVInterruptCallbackMetadata
{
    timespec value;
    unsigned int timeout_after_ms;
    int timeout;
};

395 396
// https://github.com/opencv/opencv/pull/12693#issuecomment-426236731
static
397
inline const char* _opencv_avcodec_get_name(CV_CODEC_ID id)
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
{
#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
}

430

431
static
432 433 434
inline int _opencv_ffmpeg_interrupt_callback(void *ptr)
{
    AVInterruptCallbackMetadata* metadata = (AVInterruptCallbackMetadata*)ptr;
435
    CV_Assert(metadata);
436

437 438 439 440 441
    if (metadata->timeout_after_ms == 0)
    {
        return 0; // timeout is disabled
    }

442 443 444 445 446 447 448
    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;
}
449
#endif
450

P
Peter Rekdal Sunde 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
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
};

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
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
}

507 508 509 510 511 512 513 514 515
inline static std::string _opencv_ffmpeg_get_error_string(int error_code)
{
    char buf[255] = {0};
    const int err = av_strerror(error_code, buf, 254);
    if (err == 0)
        return std::string(buf);
    else
        return std::string("Unknown error");
}
516

517 518
struct CvCapture_FFMPEG
{
519
    bool open(const char* filename, const VideoCaptureParameters& params);
520 521
    void close();

522
    double getProperty(int) const;
523 524
    bool setProperty(int, double);
    bool grabFrame();
525
    bool retrieveFrame(int flag, unsigned char** data, int* step, int* width, int* height, int* cn, int* depth);
526
    bool retrieveHWFrame(cv::OutputArray output);
527
    void rotateFrame(cv::Mat &mat) const;
528 529

    void init();
V
Vadim Pisarevsky 已提交
530 531 532

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

535 536 537
    int64_t get_total_frames() const;
    double  get_duration_sec() const;
    double  get_fps() const;
538
    int64_t get_bitrate() const;
V
Vadim Pisarevsky 已提交
539

540
    double  r2d(AVRational r) const;
V
Vadim Pisarevsky 已提交
541
    int64_t dts_to_frame_number(int64_t dts);
542
    double  dts_to_sec(int64_t dts) const;
543
    void    get_rotation_angle();
V
Vadim Pisarevsky 已提交
544 545 546

    AVFormatContext * ic;
    AVCodec         * avcodec;
547
    AVCodecContext  * context;
V
Vadim Pisarevsky 已提交
548 549
    int               video_stream;
    AVStream        * video_st;
550 551
    AVFrame         * picture;
    AVFrame           rgb_picture;
V
Vadim Pisarevsky 已提交
552 553 554 555
    int64_t           picture_pts;

    AVPacket          packet;
    Image_FFMPEG      frame;
556
    struct SwsContext *img_convert_ctx;
V
Vadim Pisarevsky 已提交
557 558 559

    int64_t frame_number, first_frame_number;

560 561
    bool   rotation_auto;
    int    rotation_angle; // valid 0, 90, 180, 270
V
Vadim Pisarevsky 已提交
562
    double eps_zero;
563 564 565 566 567 568 569 570
/*
   '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 已提交
571 572

    AVDictionary *dict;
573
#if USE_AV_INTERRUPT_CALLBACK
574 575
    int open_timeout;
    int read_timeout;
576
    AVInterruptCallbackMetadata interrupt_metadata;
577
#endif
578 579 580 581 582

    bool setRaw();
    bool processRawPacket();
    bool rawMode;
    bool rawModeInitialized;
583
    bool convertRGB;
584 585 586 587 588 589
    AVPacket packet_filtered;
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(58, 20, 100)
    AVBSFContext* bsfc;
 #else
    AVBitStreamFilterContext* bsfc;
#endif
590 591
    VideoAccelerationType va_type;
    int hw_device;
592
    int use_opencl;
593
    int extraDataIdx;
594 595 596 597
};

void CvCapture_FFMPEG::init()
{
598 599 600 601
#ifdef HAVE_FFMPEG_LIBAVDEVICE
    //libavdevice is available, so let's register all input and output devices (e.g v4l2)
    avdevice_register_all();
#endif
602 603 604 605
    ic = 0;
    video_stream = -1;
    video_st = 0;
    picture = 0;
V
Vadim Pisarevsky 已提交
606 607
    picture_pts = AV_NOPTS_VALUE_;
    first_frame_number = -1;
608 609 610
    memset( &rgb_picture, 0, sizeof(rgb_picture) );
    memset( &frame, 0, sizeof(frame) );
    filename = 0;
V
Vadim Pisarevsky 已提交
611 612
    memset(&packet, 0, sizeof(packet));
    av_init_packet(&packet);
613
    img_convert_ctx = 0;
V
Vadim Pisarevsky 已提交
614 615

    avcodec = 0;
616
    context = 0;
V
Vadim Pisarevsky 已提交
617 618
    frame_number = 0;
    eps_zero = 0.000025;
I
Ilya Lavrenov 已提交
619

620 621
    rotation_angle = 0;

622 623 624 625 626
#if (LIBAVUTIL_BUILD >= CALC_FFMPEG_VERSION(52, 92, 100))
    rotation_auto = true;
#else
    rotation_auto = false;
#endif
I
Ilya Lavrenov 已提交
627
    dict = NULL;
628

629 630 631 632 633
#if USE_AV_INTERRUPT_CALLBACK
    open_timeout = LIBAVFORMAT_INTERRUPT_OPEN_DEFAULT_TIMEOUT_MS;
    read_timeout = LIBAVFORMAT_INTERRUPT_READ_DEFAULT_TIMEOUT_MS;
#endif

634 635
    rawMode = false;
    rawModeInitialized = false;
636
    convertRGB = true;
637 638 639
    memset(&packet_filtered, 0, sizeof(packet_filtered));
    av_init_packet(&packet_filtered);
    bsfc = NULL;
640
    va_type = cv::VIDEO_ACCELERATION_NONE;  // TODO OpenCV 5.0: change to _ANY?
641
    hw_device = -1;
642
    use_opencl = 0;
643
    extraDataIdx = 1;
644 645 646 647 648
}


void CvCapture_FFMPEG::close()
{
V
Vadim Pisarevsky 已提交
649 650 651 652 653
    if( img_convert_ctx )
    {
        sws_freeContext(img_convert_ctx);
        img_convert_ctx = 0;
    }
654

655
    if( picture )
656 657
    {
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
J
jisli 已提交
658 659 660
    ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
        av_frame_free(&picture);
#elif LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
661 662 663
    ? CALC_FFMPEG_VERSION(54, 59, 100) : CALC_FFMPEG_VERSION(54, 28, 0))
        avcodec_free_frame(&picture);
#else
664
        av_free(picture);
665 666
#endif
    }
667 668 669

    if( video_st )
    {
670 671 672
#ifdef CV_FFMPEG_CODECPAR
        avcodec_close( context );
#endif
673 674 675
        video_st = NULL;
    }

676 677 678 679 680 681 682
    if (context)
    {
#ifdef CV_FFMPEG_CODECPAR
        avcodec_free_context(&context);
#endif
    }

683 684
    if( ic )
    {
685
        avformat_close_input(&ic);
686 687 688
        ic = NULL;
    }

689 690 691
#if USE_AV_FRAME_GET_BUFFER
    av_frame_unref(&rgb_picture);
#else
692 693 694 695 696
    if( rgb_picture.data[0] )
    {
        free( rgb_picture.data[0] );
        rgb_picture.data[0] = 0;
    }
697
#endif
698 699 700

    // free last packet if exist
    if (packet.data) {
P
Peter Rekdal Sunde 已提交
701
        _opencv_ffmpeg_av_packet_unref (&packet);
V
Vadim Pisarevsky 已提交
702
        packet.data = NULL;
703 704
    }

I
Ilya Lavrenov 已提交
705 706 707
    if (dict != NULL)
       av_dict_free(&dict);

708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
    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
    }

723 724 725 726 727
    init();
}


#ifndef AVSEEK_FLAG_FRAME
728
#define AVSEEK_FLAG_FRAME 0
729
#endif
A
Andrey Morozov 已提交
730
#ifndef AVSEEK_FLAG_ANY
731
#define AVSEEK_FLAG_ANY 1
732
#endif
V
Vadim Pisarevsky 已提交
733

734 735 736
#if defined(__OPENCV_BUILD) || defined(BUILD_PLUGIN)
typedef cv::Mutex ImplMutex;
#else
I
Ilya Lavrenov 已提交
737
class ImplMutex
V
Vadim Pisarevsky 已提交
738
{
I
Ilya Lavrenov 已提交
739
public:
A
Andrey Kamaev 已提交
740 741 742
    ImplMutex() { init(); }
    ~ImplMutex() { destroy(); }

I
Ilya Lavrenov 已提交
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
    void init();
    void destroy();

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

    struct Impl;
protected:
    Impl* impl;

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

759
#if defined _WIN32 || defined WINCE
I
Ilya Lavrenov 已提交
760 761 762

struct ImplMutex::Impl
{
763 764 765 766 767 768 769 770 771
    void init()
    {
#if (_WIN32_WINNT >= 0x0600)
        ::InitializeCriticalSectionEx(&cs, 1000, 0);
#else
        ::InitializeCriticalSection(&cs);
#endif
        refcount = 1;
    }
I
Ilya Lavrenov 已提交
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
    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;
};

800
#elif defined __linux__ && !defined __ANDROID__
I
Ilya Lavrenov 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833

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()
{
834
    impl = new Impl();
A
Andrey Kamaev 已提交
835
    impl->init();
I
Ilya Lavrenov 已提交
836
}
A
Andrey Kamaev 已提交
837
void ImplMutex::destroy()
I
Ilya Lavrenov 已提交
838
{
A
Andrey Kamaev 已提交
839
    impl->destroy();
840
    delete(impl);
A
Andrey Kamaev 已提交
841
    impl = NULL;
I
Ilya Lavrenov 已提交
842 843 844 845 846
}
void ImplMutex::lock() { impl->lock(); }
void ImplMutex::unlock() { impl->unlock(); }
bool ImplMutex::trylock() { return impl->trylock(); }

847 848 849 850 851 852 853 854 855 856 857 858 859
class AutoLock
{
public:
    AutoLock(ImplMutex& m) : mutex(&m) { mutex->lock(); }
    ~AutoLock() { mutex->unlock(); }
protected:
    ImplMutex* mutex;
private:
    AutoLock(const AutoLock&); // disabled
    AutoLock& operator = (const AutoLock&); // disabled
};
#endif

860

861 862
static ImplMutex _mutex;

863
#ifdef CV_FFMPEG_LOCKMGR
I
Ilya Lavrenov 已提交
864 865 866 867
static int LockCallBack(void **mutex, AVLockOp op)
{
    ImplMutex* localMutex = reinterpret_cast<ImplMutex*>(*mutex);
    switch (op)
868
    {
I
Ilya Lavrenov 已提交
869
        case AV_LOCK_CREATE:
870
            localMutex = new ImplMutex();
C
cyy 已提交
871 872
            if (!localMutex)
                return 1;
I
Ilya Lavrenov 已提交
873 874 875 876 877 878 879 880 881 882 883 884 885 886
            *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:
887
            delete localMutex;
I
Ilya Lavrenov 已提交
888
            localMutex = NULL;
889
            *mutex = NULL;
I
Ilya Lavrenov 已提交
890 891 892 893
        break;
    }
    return 0;
}
894
#endif
895

896 897 898 899
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 已提交
900
    CV_UNUSED(ptr);
901
    if (level>av_log_get_level()) return;
902 903 904 905 906 907
    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;
}
908

I
Ilya Lavrenov 已提交
909 910 911
class InternalFFMpegRegister
{
public:
912
    static void init(const bool threadSafe)
913
    {
914 915 916
        std::unique_lock<cv::Mutex> lock(_mutex, std::defer_lock);
        if(!threadSafe)
            lock.lock();
917
        static InternalFFMpegRegister instance;
918
        initLogger_();  // update logger setup unconditionally (GStreamer's libav plugin may override these settings)
919
    }
920
    static void initLogger_()
921
    {
922
#ifndef NO_GETENV
923
        char* debug_option = getenv("OPENCV_FFMPEG_DEBUG");
924 925 926
        char* level_option = getenv("OPENCV_FFMPEG_LOGLEVEL");
        int level = AV_LOG_VERBOSE;
        if (level_option != NULL)
927
        {
928 929 930 931 932
            level = atoi(level_option);
        }
        if ( (debug_option != NULL) || (level_option != NULL) )
        {
            av_log_set_level(level);
933 934 935
            av_log_set_callback(ffmpeg_log_callback);
        }
        else
936
#endif
937 938
        {
            av_log_set_level(AV_LOG_ERROR);
I
Ilya Lavrenov 已提交
939
        }
V
Vadim Pisarevsky 已提交
940 941
    }

942 943 944 945
public:
    InternalFFMpegRegister()
    {
        avformat_network_init();
V
Vadim Pisarevsky 已提交
946

947
#ifdef CV_FFMPEG_REGISTER
948 949
        /* register all codecs, demux and protocols */
        av_register_all();
950
#endif
951

952
#ifdef CV_FFMPEG_LOCKMGR
953 954
        /* register a callback function for synchronization */
        av_lockmgr_register(&LockCallBack);
955
#endif
V
Vadim Pisarevsky 已提交
956
    }
I
Ilya Lavrenov 已提交
957 958
    ~InternalFFMpegRegister()
    {
959
#ifdef CV_FFMPEG_LOCKMGR
I
Ilya Lavrenov 已提交
960
        av_lockmgr_register(NULL);
961
#endif
962
        av_log_set_callback(NULL);
V
Vadim Pisarevsky 已提交
963
    }
I
Ilya Lavrenov 已提交
964 965
};

966 967
inline void fill_codec_context(AVCodecContext * enc, AVDictionary * dict)
{
968 969 970 971 972 973 974 975 976 977 978
    if (!enc->thread_count)
    {
        int nCpus = cv::getNumberOfCPUs();
        int requestedThreads = std::min(nCpus, 16);  // [OPENCV:FFMPEG:24] Application has requested XX threads. Using a thread count greater than 16 is not recommended.
        char* threads_option = getenv("OPENCV_FFMPEG_THREADS");
        if (threads_option != NULL)
        {
            requestedThreads = atoi(threads_option);
        }
        enc->thread_count = requestedThreads;
    }
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005

    AVDictionaryEntry* avdiscard_entry = av_dict_get(dict, "avdiscard", NULL, 0);

    if (avdiscard_entry)
    {
        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;
        // 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)
        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;
    }
}

1006 1007 1008 1009 1010 1011 1012 1013
static bool isThreadSafe() {
    const bool threadSafe = utils::getConfigurationParameterBool("OPENCV_FFMPEG_IS_THREAD_SAFE", false);
    if (threadSafe) {
        CV_LOG_WARNING(NULL, "VIDEOIO/FFMPEG: OPENCV_FFMPEG_IS_THREAD_SAFE == 1, all OpenCV locks removed, relying on FFmpeg to provide thread safety.  If FFmpeg is not thread safe isOpened() may return false when multiple threads try to call open() at the same time.");
    }
    return threadSafe;
}

1014
bool CvCapture_FFMPEG::open(const char* _filename, const VideoCaptureParameters& params)
1015
{
1016 1017
    const bool threadSafe = isThreadSafe();
    InternalFFMpegRegister::init(threadSafe);
1018

1019 1020 1021
    std::unique_lock<cv::Mutex> lock(_mutex, std::defer_lock);
    if(!threadSafe)
        lock.lock();
1022

1023 1024
    unsigned i;
    bool valid = false;
1025
    int nThreads = 0;
1026 1027

    close();
1028

1029 1030
    if (!params.empty())
    {
1031 1032 1033 1034 1035 1036 1037 1038 1039
        convertRGB = params.get<bool>(CAP_PROP_CONVERT_RGB, true);
        if (!convertRGB)
        {
            CV_LOG_WARNING(NULL, "VIDEOIO/FFMPEG: BGR conversion turned OFF, decoded frame will be "
                                 "returned in its original format. "
                                 "Multiplanar formats are not supported by the backend. "
                                 "Only GRAY8/GRAY16LE pixel formats have been tested. "
                                 "Use at your own risk.");
        }
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
        if (params.has(CAP_PROP_FORMAT))
        {
            int value = params.get<int>(CAP_PROP_FORMAT);
            if (value == -1)
            {
                CV_LOG_INFO(NULL, "VIDEOIO/FFMPEG: enabled demuxer only mode: '" << (_filename ? _filename : "<NULL>") << "'");
                rawMode = true;
            }
            else
            {
                CV_LOG_ERROR(NULL, "VIDEOIO/FFMPEG: CAP_PROP_FORMAT parameter value is invalid/unsupported: " << value);
                return false;
            }
        }
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
        if (params.has(CAP_PROP_HW_ACCELERATION))
        {
            va_type = params.get<VideoAccelerationType>(CAP_PROP_HW_ACCELERATION);
#if !USE_AV_HW_CODECS
            if (va_type != VIDEO_ACCELERATION_NONE && va_type != VIDEO_ACCELERATION_ANY)
            {
                CV_LOG_ERROR(NULL, "VIDEOIO/FFMPEG: FFmpeg backend is build without acceleration support. Can't handle CAP_PROP_HW_ACCELERATION parameter. Bailout");
                return false;
            }
#endif
        }
        if (params.has(CAP_PROP_HW_DEVICE))
        {
            hw_device = params.get<int>(CAP_PROP_HW_DEVICE);
            if (va_type == VIDEO_ACCELERATION_NONE && hw_device != -1)
            {
                CV_LOG_ERROR(NULL, "VIDEOIO/FFMPEG: Invalid usage of CAP_PROP_HW_DEVICE without requested H/W acceleration. Bailout");
                return false;
            }
            if (va_type == VIDEO_ACCELERATION_ANY && hw_device != -1)
            {
                CV_LOG_ERROR(NULL, "VIDEOIO/FFMPEG: Invalid usage of CAP_PROP_HW_DEVICE with 'ANY' H/W acceleration. Bailout");
                return false;
            }
        }
1079 1080 1081
        if (params.has(CAP_PROP_HW_ACCELERATION_USE_OPENCL)) {
            use_opencl = params.get<int>(CAP_PROP_HW_ACCELERATION_USE_OPENCL);
        }
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
#if USE_AV_INTERRUPT_CALLBACK
        if (params.has(CAP_PROP_OPEN_TIMEOUT_MSEC))
        {
            open_timeout = params.get<int>(CAP_PROP_OPEN_TIMEOUT_MSEC);
        }
        if (params.has(CAP_PROP_READ_TIMEOUT_MSEC))
        {
            read_timeout = params.get<int>(CAP_PROP_READ_TIMEOUT_MSEC);
        }
#endif
1092 1093 1094 1095
        if (params.has(CAP_PROP_N_THREADS))
        {
            nThreads = params.get<int>(CAP_PROP_N_THREADS);
        }
1096 1097
        if (params.warnUnusedParameters())
        {
1098
            CV_LOG_ERROR(NULL, "VIDEOIO/FFMPEG: unsupported parameters in .open(), see logger INFO channel for details. Bailout");
1099 1100 1101 1102
            return false;
        }
    }

1103
#if USE_AV_INTERRUPT_CALLBACK
1104
    /* interrupt callback */
1105
    interrupt_metadata.timeout_after_ms = open_timeout;
1106 1107 1108 1109 1110
    get_monotonic_time(&interrupt_metadata.value);

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

1113 1114 1115 1116
#ifndef NO_GETENV
    char* options = getenv("OPENCV_FFMPEG_CAPTURE_OPTIONS");
    if(options == NULL)
    {
1117 1118 1119
#if LIBAVFORMAT_VERSION_MICRO >= 100  && LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 48, 100)
        av_dict_set(&dict, "rtsp_flags", "prefer_tcp", 0);
#else
1120
        av_dict_set(&dict, "rtsp_transport", "tcp", 0);
1121
#endif
1122 1123 1124
    }
    else
    {
1125
        CV_LOG_DEBUG(NULL, "VIDEOIO/FFMPEG: using capture options from environment: " << options);
1126 1127 1128 1129 1130 1131 1132
#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 已提交
1133
    av_dict_set(&dict, "rtsp_transport", "tcp", 0);
1134
#endif
1135
    CV_FFMPEG_FMT_CONST AVInputFormat* input_format = NULL;
1136 1137 1138 1139 1140 1141 1142
    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);
1143

I
Ilya Lavrenov 已提交
1144 1145
    if (err < 0)
    {
V
Vadim Pisarevsky 已提交
1146
        CV_WARN("Error opening file");
1147
        CV_WARN(_filename);
V
Vadim Pisarevsky 已提交
1148
        goto exit_func;
1149
    }
1150
    err = avformat_find_stream_info(ic, NULL);
I
Ilya Lavrenov 已提交
1151 1152
    if (err < 0)
    {
1153
        CV_LOG_WARNING(NULL, "Unable to read codec parameters from stream (" << _opencv_ffmpeg_get_error_string(err) << ")");
V
Vadim Pisarevsky 已提交
1154
        goto exit_func;
1155
    }
V
Vadim Pisarevsky 已提交
1156 1157
    for(i = 0; i < ic->nb_streams; i++)
    {
1158 1159 1160 1161 1162 1163 1164 1165
#ifndef CV_FFMPEG_CODECPAR
        context = ic->streams[i]->codec;
        AVCodecID codec_id = context->codec_id;
        AVMediaType codec_type = context->codec_type;
#else
        AVCodecParameters* par = ic->streams[i]->codecpar;
        AVCodecID codec_id = par->codec_id;
        AVMediaType codec_type = par->codec_type;
1166
#endif
V
Vadim Pisarevsky 已提交
1167

1168
        if( AVMEDIA_TYPE_VIDEO == codec_type && video_stream < 0)
I
Ilya Lavrenov 已提交
1169
        {
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
            // backup encoder' width/height
#ifndef CV_FFMPEG_CODECPAR
            int enc_width = context->width;
            int enc_height = context->height;
#else
            int enc_width = par->width;
            int enc_height = par->height;
#endif

            CV_LOG_DEBUG(NULL, "FFMPEG: stream[" << i << "] is video stream with codecID=" << (int)codec_id
                    << " width=" << enc_width
                    << " height=" << enc_height
1182 1183
            );

G
gferry 已提交
1184

1185 1186 1187 1188 1189
#if !USE_AV_HW_CODECS
            va_type = VIDEO_ACCELERATION_NONE;
#endif

            // find and open decoder, try HW acceleration types specified in 'hw_acceleration' list (in order)
1190
            const AVCodec *codec = NULL;
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
            err = -1;
#if USE_AV_HW_CODECS
            HWAccelIterator accel_iter(va_type, false/*isEncoder*/, dict);
            while (accel_iter.good())
            {
#else
            do {
#endif
#if USE_AV_HW_CODECS
                accel_iter.parse_next();
                AVHWDeviceType hw_type = accel_iter.hw_type();
                if (hw_type != AV_HWDEVICE_TYPE_NONE)
                {
                    CV_LOG_DEBUG(NULL, "FFMPEG: trying to configure H/W acceleration: '" << accel_iter.hw_type_device_string() << "'");
                    AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE;
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
                    codec = hw_find_codec(codec_id, hw_type, av_codec_is_decoder, accel_iter.disabled_codecs().c_str(), &hw_pix_fmt);
                    if (codec)
                    {
#ifdef CV_FFMPEG_CODECPAR
                        context = avcodec_alloc_context3(codec);
#endif
                        CV_Assert(context);
                        context->get_format = avcodec_default_get_format;
                        if (context->hw_device_ctx) {
                            av_buffer_unref(&context->hw_device_ctx);
                        }
1217
                        if (hw_pix_fmt != AV_PIX_FMT_NONE)
1218 1219 1220
                            context->get_format = hw_get_format_callback; // set callback to select HW pixel format, not SW format
                        context->hw_device_ctx = hw_create_device(hw_type, hw_device, accel_iter.device_subname(), use_opencl != 0);
                        if (!context->hw_device_ctx)
1221
                        {
1222
                            context->get_format = avcodec_default_get_format;
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
                            CV_LOG_DEBUG(NULL, "FFMPEG: ... can't create H/W device: '" << accel_iter.hw_type_device_string() << "'");
                            codec = NULL;
                        }
                    }
                }
                else if (hw_type == AV_HWDEVICE_TYPE_NONE)
#endif // USE_AV_HW_CODECS
                {
                    AVDictionaryEntry* video_codec_param = av_dict_get(dict, "video_codec", NULL, 0);
                    if (video_codec_param == NULL)
                    {
1234
                        codec = avcodec_find_decoder(codec_id);
1235 1236
                        if (!codec)
                        {
1237
                            CV_LOG_ERROR(NULL, "Could not find decoder for codec_id=" << (int)codec_id);
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
                        }
                    }
                    else
                    {
                        CV_LOG_DEBUG(NULL, "FFMPEG: Using video_codec='" << video_codec_param->value << "'");
                        codec = avcodec_find_decoder_by_name(video_codec_param->value);
                        if (!codec)
                        {
                            CV_LOG_ERROR(NULL, "Could not find decoder '" << video_codec_param->value << "'");
                        }
                    }
1249 1250 1251 1252 1253 1254 1255
                    if (codec)
                    {
#ifdef CV_FFMPEG_CODECPAR
                        context = avcodec_alloc_context3(codec);
#endif
                        CV_Assert(context);
                    }
1256 1257
                }
                if (!codec)
1258 1259 1260 1261
                {
#ifdef CV_FFMPEG_CODECPAR
                    avcodec_free_context(&context);
#endif
1262
                    continue;
1263
                }
1264
                context->thread_count = nThreads;
1265 1266 1267 1268 1269
                fill_codec_context(context, dict);
#ifdef CV_FFMPEG_CODECPAR
                avcodec_parameters_to_context(context, par);
#endif
                err = avcodec_open2(context, codec, NULL);
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
                if (err >= 0) {
#if USE_AV_HW_CODECS
                    va_type = hw_type_to_va_type(hw_type);
                    if (hw_type != AV_HWDEVICE_TYPE_NONE && hw_device < 0)
                        hw_device = 0;
#endif
                    break;
                } else {
                    CV_LOG_ERROR(NULL, "Could not open codec " << codec->name << ", error: " << err);
                }
#if USE_AV_HW_CODECS
            }  // while (accel_iter.good())
#else
            } while (0);
#endif
            if (err < 0) {
                CV_LOG_ERROR(NULL, "VIDEOIO/FFMPEG: Failed to initialize VideoCapture");
I
Ilya Lavrenov 已提交
1287
                goto exit_func;
1288
            }
V
Vadim Pisarevsky 已提交
1289

G
gferry 已提交
1290
            // checking width/height (since decoder can sometimes alter it, eg. vp6f)
1291 1292 1293 1294
            if (enc_width && (context->width != enc_width))
                context->width = enc_width;
            if (enc_height && (context->height != enc_height))
                context->height = enc_height;
G
gferry 已提交
1295

1296 1297
            video_stream = i;
            video_st = ic->streams[i];
J
jisli 已提交
1298 1299 1300 1301
#if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
    ? CALC_FFMPEG_VERSION(55, 45, 101) : CALC_FFMPEG_VERSION(55, 28, 1))
            picture = av_frame_alloc();
#else
1302
            picture = avcodec_alloc_frame();
J
jisli 已提交
1303
#endif
1304

1305 1306
            frame.width = context->width;
            frame.height = context->height;
1307 1308
            frame.step = 0;
            frame.data = NULL;
1309
            get_rotation_angle();
1310 1311 1312 1313
            break;
        }
    }

1314 1315
    if (video_stream >= 0)
        valid = true;
1316

V
Vadim Pisarevsky 已提交
1317
exit_func:
1318

1319 1320 1321 1322 1323
#if USE_AV_INTERRUPT_CALLBACK
    // deactivate interrupt callback
    interrupt_metadata.timeout_after_ms = 0;
#endif

1324 1325 1326 1327 1328 1329
    if( !valid )
        close();

    return valid;
}

1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
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;
}

1344 1345 1346 1347
static inline bool h26xContainer(const char* formatLongName) {
    return !strcmp(formatLongName, "QuickTime / MOV") || !strcmp(formatLongName, "FLV (Flash Video)") || !strcmp(formatLongName, "Matroska / WebM");
}

1348 1349 1350 1351 1352 1353 1354 1355
bool CvCapture_FFMPEG::processRawPacket()
{
    if (packet.data == NULL)  // EOF
        return false;
    if (!rawModeInitialized)
    {
        rawModeInitialized = true;
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(58, 20, 100)
1356
        CV_CODEC_ID eVideoCodec = ic->streams[video_stream]->codecpar->codec_id;
1357
#else
1358
        CV_CODEC_ID eVideoCodec = video_st->codec->codec_id;
1359 1360
#endif
        const char* filterName = NULL;
1361 1362 1363 1364 1365 1366 1367 1368 1369
        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
        )
1370
        {
1371
            if(h26xContainer(ic->iformat->long_name))
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
                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)
            {
                CV_WARN(cv::format("Bitstream filter is not available: %s", filterName).c_str());
                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)
            {
                CV_WARN(cv::format("Bitstream filter is not available: %s", filterName).c_str());
                return false;
            }
#endif
        }
    }
    if (bsfc)
    {
        if (packet_filtered.data)
        {
1410
            _opencv_ffmpeg_av_packet_unref(&packet_filtered);
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
        }

#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
        AVCodecContext* ctx = ic->streams[video_stream]->codec;
        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;
}
1440 1441 1442 1443 1444

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

1445 1446 1447 1448
    static const size_t max_read_attempts = cv::utils::getConfigurationParameterSizeT("OPENCV_FFMPEG_READ_ATTEMPTS", 4096);
    static const size_t max_decode_attempts = cv::utils::getConfigurationParameterSizeT("OPENCV_FFMPEG_DECODE_ATTEMPTS", 64);
    size_t cur_read_attempts = 0;
    size_t cur_decode_attempts = 0;
1449

1450
    if( !ic || !video_st || !context )  return false;
1451

1452 1453 1454
    if( ic->streams[video_stream]->nb_frames > 0 &&
        frame_number > ic->streams[video_stream]->nb_frames )
        return false;
1455

V
Vadim Pisarevsky 已提交
1456
    picture_pts = AV_NOPTS_VALUE_;
1457

1458 1459
#if USE_AV_INTERRUPT_CALLBACK
    // activate interrupt callback
1460
    interrupt_metadata.timeout = 0;
1461
    get_monotonic_time(&interrupt_metadata.value);
1462
    interrupt_metadata.timeout_after_ms = read_timeout;
1463 1464
#endif

1465 1466
#if USE_AV_SEND_FRAME_API
    // check if we can receive frame from previously decoded packet
1467
    valid = avcodec_receive_frame(context, picture) >= 0;
1468 1469
#endif

1470
    // get the next frame
V
Vadim Pisarevsky 已提交
1471 1472
    while (!valid)
    {
H
hahne 已提交
1473

P
Peter Rekdal Sunde 已提交
1474
        _opencv_ffmpeg_av_packet_unref (&packet);
1475

1476
#if USE_AV_INTERRUPT_CALLBACK
1477 1478 1479 1480 1481
        if (interrupt_metadata.timeout)
        {
            valid = false;
            break;
        }
1482
#endif
1483

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

1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
        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 已提交
1499 1500 1501

        if( packet.stream_index != video_stream )
        {
P
Peter Rekdal Sunde 已提交
1502
            _opencv_ffmpeg_av_packet_unref (&packet);
1503 1504 1505 1506 1507 1508 1509
            if (++cur_read_attempts > max_read_attempts)
            {
                CV_LOG_WARNING(NULL,
                    "packet read max attempts exceeded, if your video have "
                    "multiple streams (video, audio) try to increase attempt "
                    "limit by setting environment variable OPENCV_FFMPEG_READ_ATTEMPTS "
                    "(current value is " << max_read_attempts << ")");
V
Vadim Pisarevsky 已提交
1510
                break;
1511
            }
1512 1513
            continue;
        }
1514

1515 1516 1517 1518 1519 1520
        if (rawMode)
        {
            valid = processRawPacket();
            break;
        }

V
Vadim Pisarevsky 已提交
1521
        // Decode video frame
1522
#if USE_AV_SEND_FRAME_API
1523
        if (avcodec_send_packet(context, &packet) < 0) {
1524 1525
            break;
        }
1526
        ret = avcodec_receive_frame(context, picture);
1527 1528
#else
        int got_picture = 0;
1529
        avcodec_decode_video2(context, picture, &got_picture, &packet);
1530 1531 1532
        ret = got_picture ? 0 : -1;
#endif
        if (ret >= 0) {
V
Vadim Pisarevsky 已提交
1533
            valid = true;
1534 1535
        } else if (ret == AVERROR(EAGAIN)) {
            continue;
V
Vadim Pisarevsky 已提交
1536 1537 1538
        }
        else
        {
1539 1540 1541 1542 1543 1544
            if (++cur_decode_attempts > max_decode_attempts)
            {
                CV_LOG_WARNING(NULL,
                    "frame decode max attempts exceeded, try to increase attempt "
                    "limit by setting environment variable OPENCV_FFMPEG_DECODE_ATTEMPTS "
                    "(current value is " << max_decode_attempts << ")");
V
Vadim Pisarevsky 已提交
1545
                break;
1546
            }
1547 1548 1549
        }
    }

D
dan 已提交
1550 1551 1552
    if (valid) {
        if( picture_pts == AV_NOPTS_VALUE_ )
            picture_pts = picture->CV_FFMPEG_PTS_FIELD != AV_NOPTS_VALUE_ && picture->CV_FFMPEG_PTS_FIELD != 0 ? picture->CV_FFMPEG_PTS_FIELD : picture->pkt_dts;
1553
        frame_number++;
D
dan 已提交
1554
    }
1555 1556

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

1559 1560 1561 1562 1563
#if USE_AV_INTERRUPT_CALLBACK
    // deactivate interrupt callback
    interrupt_metadata.timeout_after_ms = 0;
#endif

1564
    // return if we have a new frame or not
1565 1566 1567
    return valid;
}

1568
bool CvCapture_FFMPEG::retrieveFrame(int flag, unsigned char** data, int* step, int* width, int* height, int* cn, int* depth)
1569
{
1570
    if (!video_st || !context)
1571 1572
        return false;

1573
    if (rawMode || flag == extraDataIdx)
1574
    {
1575 1576 1577 1578 1579 1580 1581 1582
        bool ret = true;
        if (flag == 0) {
            AVPacket& p = bsfc ? packet_filtered : packet;
            *data = p.data;
            *step = p.size;
            ret = p.data != NULL;
        }
        else if (flag == extraDataIdx) {
1583 1584
            *data = ic->streams[video_stream]->CV_FFMPEG_CODEC_FIELD->extradata;
            *step = ic->streams[video_stream]->CV_FFMPEG_CODEC_FIELD->extradata_size;
1585 1586
        }
        *width = *step;
1587 1588
        *height = 1;
        *cn = 1;
1589
        *depth = CV_8U;
1590
        return  ret;
1591 1592
    }

1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
    AVFrame* sw_picture = picture;
#if USE_AV_HW_CODECS
    // if hardware frame, copy it to system memory
    if (picture && picture->hw_frames_ctx) {
        sw_picture = av_frame_alloc();
        //if (av_hwframe_map(sw_picture, picture, AV_HWFRAME_MAP_READ) < 0) {
        if (av_hwframe_transfer_data(sw_picture, picture, 0) < 0) {
            CV_LOG_ERROR(NULL, "Error copying data from GPU to CPU (av_hwframe_transfer_data)");
            return false;
        }
    }
#endif

    if (!sw_picture || !sw_picture->data[0])
1607 1608
        return false;

1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
    CV_LOG_DEBUG(NULL, "Input picture format: " << av_get_pix_fmt_name((AVPixelFormat)sw_picture->format));
    const AVPixelFormat result_format = convertRGB ? AV_PIX_FMT_BGR24 : (AVPixelFormat)sw_picture->format;
    switch (result_format)
    {
    case AV_PIX_FMT_BGR24: *depth = CV_8U; *cn = 3; break;
    case AV_PIX_FMT_GRAY8: *depth = CV_8U; *cn = 1; break;
    case AV_PIX_FMT_GRAY16LE: *depth = CV_16U; *cn = 1; break;
    default:
        CV_LOG_WARNING(NULL, "Unknown/unsupported picture format: " << av_get_pix_fmt_name(result_format)
                       << ", will be treated as 8UC1.");
        *depth = CV_8U;
        *cn = 1;
        break; // TODO: return false?
    }

V
Vadim Pisarevsky 已提交
1624
    if( img_convert_ctx == NULL ||
1625 1626
        frame.width != video_st->CV_FFMPEG_CODEC_FIELD->width ||
        frame.height != video_st->CV_FFMPEG_CODEC_FIELD->height ||
1627
        frame.data == NULL )
V
Vadim Pisarevsky 已提交
1628
    {
1629 1630
        // 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)
1631
        int buffer_width = context->coded_width, buffer_height = context->coded_height;
V
Vadim Pisarevsky 已提交
1632 1633

        img_convert_ctx = sws_getCachedContext(
1634 1635
                img_convert_ctx,
                buffer_width, buffer_height,
1636
                (AVPixelFormat)sw_picture->format,
1637
                buffer_width, buffer_height,
1638
                result_format,
V
Vadim Pisarevsky 已提交
1639 1640 1641 1642 1643 1644
                SWS_BICUBIC,
                NULL, NULL, NULL
                );

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

1646 1647
#if USE_AV_FRAME_GET_BUFFER
        av_frame_unref(&rgb_picture);
1648
        rgb_picture.format = result_format;
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
        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);
1659
        rgb_picture.data[0] = (uint8_t*)realloc(rgb_picture.data[0],
1660
                _opencv_ffmpeg_av_image_get_buffer_size( result_format,
1661
                                    buffer_width, buffer_height ));
P
Peter Rekdal Sunde 已提交
1662
        _opencv_ffmpeg_av_image_fill_arrays(&rgb_picture, rgb_picture.data[0],
1663
                        result_format, buffer_width, buffer_height );
1664
#endif
1665 1666
        frame.width = video_st->CV_FFMPEG_CODEC_FIELD->width;
        frame.height = video_st->CV_FFMPEG_CODEC_FIELD->height;
1667
        frame.data = rgb_picture.data[0];
1668
        frame.step = rgb_picture.linesize[0];
V
Vadim Pisarevsky 已提交
1669 1670 1671 1672
    }

    sws_scale(
            img_convert_ctx,
1673 1674
            sw_picture->data,
            sw_picture->linesize,
1675
            0, sw_picture->height,
V
Vadim Pisarevsky 已提交
1676 1677 1678 1679
            rgb_picture.data,
            rgb_picture.linesize
            );

1680 1681 1682 1683 1684
    *data = frame.data;
    *step = frame.step;
    *width = frame.width;
    *height = frame.height;

1685 1686 1687
#if USE_AV_HW_CODECS
    if (sw_picture != picture)
    {
1688
        av_frame_free(&sw_picture);
1689
    }
1690
#endif
1691 1692 1693
    return true;
}

1694 1695 1696 1697
bool CvCapture_FFMPEG::retrieveHWFrame(cv::OutputArray output)
{
#if USE_AV_HW_CODECS
    // check that we have HW frame in GPU memory
1698
    if (!picture || !picture->hw_frames_ctx || !context) {
1699 1700 1701 1702
        return false;
    }

    // GPU color conversion NV12->BGRA, from GPU media buffer to GPU OpenCL buffer
1703
    return hw_copy_frame_to_umat(context->hw_device_ctx, picture, output);
1704 1705 1706 1707 1708 1709
#else
    CV_UNUSED(output);
    return false;
#endif
}

1710
double CvCapture_FFMPEG::getProperty( int property_id ) const
1711
{
1712
    if( !video_st || !context ) return 0;
1713

1714
    double codec_tag = 0;
1715
    CV_CODEC_ID codec_id = AV_CODEC_ID_NONE;
1716 1717
    const char* codec_fourcc = NULL;

1718 1719
    switch( property_id )
    {
1720
    case CAP_PROP_POS_MSEC:
1721 1722 1723 1724 1725
        if (picture_pts == AV_NOPTS_VALUE_)
        {
            return 0;
        }
        return (dts_to_sec(picture_pts) * 1000);
1726
    case CAP_PROP_POS_FRAMES:
V
Vadim Pisarevsky 已提交
1727
        return (double)frame_number;
1728
    case CAP_PROP_POS_AVI_RATIO:
V
Vadim Pisarevsky 已提交
1729
        return r2d(ic->streams[video_stream]->time_base);
1730
    case CAP_PROP_FRAME_COUNT:
V
Vadim Pisarevsky 已提交
1731
        return (double)get_total_frames();
1732
    case CAP_PROP_FRAME_WIDTH:
1733
        return (double)((rotation_auto && ((rotation_angle%180) != 0)) ? frame.height : frame.width);
1734
    case CAP_PROP_FRAME_HEIGHT:
1735
        return (double)((rotation_auto && ((rotation_angle%180) != 0)) ? frame.width : frame.height);
1736 1737
    case CAP_PROP_FRAME_TYPE:
        return (double)av_get_picture_type_char(picture->pict_type);
1738
    case CAP_PROP_FPS:
1739
        return get_fps();
1740
    case CAP_PROP_FOURCC: {
1741 1742
        codec_id = video_st->CV_FFMPEG_CODEC_FIELD->codec_id;
        codec_tag = (double) video_st->CV_FFMPEG_CODEC_FIELD->codec_tag;
1743 1744 1745 1746 1747 1748 1749

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

        codec_fourcc = _opencv_avcodec_get_name(codec_id);
1750
        if (!codec_fourcc || strcmp(codec_fourcc, "unknown_codec") == 0 || strlen(codec_fourcc) != 4)
1751
        {
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
            const struct AVCodecTag* fallback_tags[] = {
            // APIchanges:
            // 2012-01-31 - dd6d3b0 - lavf 54.01.0
            //   Add avformat_get_riff_video_tags() and avformat_get_riff_audio_tags().
                avformat_get_riff_video_tags(),
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 25, 100) && defined LIBAVFORMAT_VERSION_MICRO && LIBAVFORMAT_VERSION_MICRO >= 100
            // 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().
                avformat_get_mov_video_tags(),
#endif
                codec_bmp_tags, // fallback for avformat < 54.1
                NULL };
            return av_codec_get_tag(fallback_tags, codec_id);
1766 1767
        }

1768
        return (double) CV_FOURCC(codec_fourcc[0], codec_fourcc[1], codec_fourcc[2], codec_fourcc[3]);
1769
    }
1770
    case CAP_PROP_SAR_NUM:
1771
        return _opencv_ffmpeg_get_sample_aspect_ratio(ic->streams[video_stream]).num;
1772
    case CAP_PROP_SAR_DEN:
1773
        return _opencv_ffmpeg_get_sample_aspect_ratio(ic->streams[video_stream]).den;
1774 1775
    case CAP_PROP_CODEC_PIXEL_FORMAT:
    {
1776 1777 1778
#ifdef CV_FFMPEG_CODECPAR
        AVPixelFormat pix_fmt = (AVPixelFormat)video_st->codecpar->format;
#else
1779
        AVPixelFormat pix_fmt = video_st->codec->pix_fmt;
1780
#endif
1781 1782 1783 1784 1785 1786 1787
        unsigned int fourcc_tag = avcodec_pix_fmt_to_codec_tag(pix_fmt);
        return (fourcc_tag == 0) ? (double)-1 : (double)fourcc_tag;
    }
    case CAP_PROP_FORMAT:
        if (rawMode)
            return -1;
        break;
1788 1789
    case CAP_PROP_CONVERT_RGB:
        return convertRGB;
1790 1791 1792 1793 1794 1795
    case CAP_PROP_LRF_HAS_KEY_FRAME: {
        const AVPacket& p = bsfc ? packet_filtered : packet;
        return ((p.flags & AV_PKT_FLAG_KEY) != 0) ? 1 : 0;
    }
    case CAP_PROP_CODEC_EXTRADATA_INDEX:
            return extraDataIdx;
1796
    case CAP_PROP_BITRATE:
1797
        return static_cast<double>(get_bitrate());
1798
    case CAP_PROP_ORIENTATION_META:
1799
        return static_cast<double>(rotation_angle);
1800
    case CAP_PROP_ORIENTATION_AUTO:
1801
#if LIBAVUTIL_BUILD >= CALC_FFMPEG_VERSION(52, 94, 100)
1802
        return static_cast<double>(rotation_auto);
1803 1804 1805
#else
        return 0;
#endif
1806 1807 1808 1809 1810
#if USE_AV_HW_CODECS
    case CAP_PROP_HW_ACCELERATION:
        return static_cast<double>(va_type);
    case CAP_PROP_HW_DEVICE:
        return static_cast<double>(hw_device);
1811 1812
    case CAP_PROP_HW_ACCELERATION_USE_OPENCL:
        return static_cast<double>(use_opencl);
1813
#endif  // USE_AV_HW_CODECS
1814 1815 1816
    case CAP_PROP_STREAM_OPEN_TIME_USEC:
        //ic->start_time_realtime is in microseconds
        return ((double)ic->start_time_realtime);
1817 1818
    case CAP_PROP_N_THREADS:
        return static_cast<double>(context->thread_count);
V
Vadim Pisarevsky 已提交
1819
    default:
1820
        break;
1821
    }
V
Vadim Pisarevsky 已提交
1822

1823 1824 1825
    return 0;
}

1826
double CvCapture_FFMPEG::r2d(AVRational r) const
V
Vadim Pisarevsky 已提交
1827 1828 1829 1830
{
    return r.num == 0 || r.den == 0 ? 0. : (double)r.num / (double)r.den;
}

1831
double CvCapture_FFMPEG::get_duration_sec() const
1832
{
V
Vadim Pisarevsky 已提交
1833 1834 1835
    double sec = (double)ic->duration / (double)AV_TIME_BASE;

    if (sec < eps_zero)
1836
    {
V
Vadim Pisarevsky 已提交
1837
        sec = (double)ic->streams[video_stream]->duration * r2d(ic->streams[video_stream]->time_base);
1838
    }
V
Vadim Pisarevsky 已提交
1839 1840

    return sec;
1841 1842
}

1843
int64_t CvCapture_FFMPEG::get_bitrate() const
1844
{
1845
    return ic->bit_rate / 1000;
V
Vadim Pisarevsky 已提交
1846 1847
}

1848
double CvCapture_FFMPEG::get_fps() const
V
Vadim Pisarevsky 已提交
1849
{
1850
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 1, 100) && LIBAVFORMAT_VERSION_MICRO >= 100
A
Alexander Alekhin 已提交
1851 1852 1853
    double fps = r2d(av_guess_frame_rate(ic, ic->streams[video_stream], NULL));
#else
    double fps = r2d(ic->streams[video_stream]->avg_frame_rate);
V
Vadim Pisarevsky 已提交
1854 1855 1856 1857 1858

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    if (fps < eps_zero)
    {
        fps = r2d(ic->streams[video_stream]->avg_frame_rate);
1859
    }
1860
#endif
V
Vadim Pisarevsky 已提交
1861 1862 1863

    if (fps < eps_zero)
    {
1864
        fps = 1.0 / r2d(ic->streams[video_stream]->time_base);
V
Vadim Pisarevsky 已提交
1865
    }
A
Alexander Alekhin 已提交
1866
#endif
V
Vadim Pisarevsky 已提交
1867 1868 1869
    return fps;
}

1870
int64_t CvCapture_FFMPEG::get_total_frames() const
V
Vadim Pisarevsky 已提交
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
{
    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);
}

1887
double CvCapture_FFMPEG::dts_to_sec(int64_t dts) const
V
Vadim Pisarevsky 已提交
1888 1889 1890 1891 1892
{
    return (double)(dts - ic->streams[video_stream]->start_time) *
        r2d(ic->streams[video_stream]->time_base);
}

1893 1894 1895
void CvCapture_FFMPEG::get_rotation_angle()
{
    rotation_angle = 0;
1896 1897 1898 1899 1900
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(57, 68, 100)
    const uint8_t *data = 0;
    data = av_stream_get_side_data(video_st, AV_PKT_DATA_DISPLAYMATRIX, NULL);
    if (data)
    {
1901
        rotation_angle = -cvRound(av_display_rotation_get((const int32_t*)data));
1902 1903 1904 1905
        if (rotation_angle < 0)
            rotation_angle += 360;
    }
#elif LIBAVUTIL_BUILD >= CALC_FFMPEG_VERSION(52, 94, 100)
1906 1907 1908
    AVDictionaryEntry *rotate_tag = av_dict_get(video_st->metadata, "rotate", NULL, 0);
    if (rotate_tag != NULL)
        rotation_angle = atoi(rotate_tag->value);
1909
#endif
1910 1911
}

V
Vadim Pisarevsky 已提交
1912 1913
void CvCapture_FFMPEG::seek(int64_t _frame_number)
{
1914
    CV_Assert(context);
V
Vadim Pisarevsky 已提交
1915 1916
    _frame_number = std::min(_frame_number, get_total_frames());
    int delta = 16;
1917

V
Vadim Pisarevsky 已提交
1918 1919
    // 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
1920
    if( first_frame_number < 0 && get_total_frames() > 1 )
1921
        grabFrame();
1922

V
Vadim Pisarevsky 已提交
1923 1924 1925 1926 1927 1928 1929
    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);
1930
        if (get_total_frames() > 1) av_seek_frame(ic, video_stream, time_stamp, AVSEEK_FLAG_BACKWARD);
1931
        avcodec_flush_buffers(context);
V
Vadim Pisarevsky 已提交
1932 1933 1934
        if( _frame_number > 0 )
        {
            grabFrame();
1935

V
Vadim Pisarevsky 已提交
1936 1937 1938 1939 1940
            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);
1941

V
Vadim Pisarevsky 已提交
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
                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;
        }
1968
    }
V
Vadim Pisarevsky 已提交
1969 1970 1971 1972 1973
}

void CvCapture_FFMPEG::seek(double sec)
{
    seek((int64_t)(sec * get_fps() + 0.5));
1974
}
1975 1976 1977 1978 1979 1980 1981

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

    switch( property_id )
    {
1982 1983 1984
    case CAP_PROP_POS_MSEC:
    case CAP_PROP_POS_FRAMES:
    case CAP_PROP_POS_AVI_RATIO:
1985 1986 1987
        {
            switch( property_id )
            {
1988
            case CAP_PROP_POS_FRAMES:
V
Vadim Pisarevsky 已提交
1989
                seek((int64_t)value);
1990 1991
                break;

1992
            case CAP_PROP_POS_MSEC:
V
Vadim Pisarevsky 已提交
1993
                seek(value/1000.0);
1994 1995
                break;

1996
            case CAP_PROP_POS_AVI_RATIO:
V
Vadim Pisarevsky 已提交
1997
                seek((int64_t)(value*ic->duration));
1998 1999 2000 2001 2002 2003
                break;
            }

            picture_pts=(int64_t)value;
        }
        break;
2004 2005 2006 2007
    case CAP_PROP_FORMAT:
        if (value == -1)
            return setRaw();
        return false;
2008 2009 2010
    case CAP_PROP_CONVERT_RGB:
        convertRGB = (value != 0);
        return true;
2011
    case CAP_PROP_ORIENTATION_AUTO:
2012
#if LIBAVUTIL_BUILD >= CALC_FFMPEG_VERSION(52, 94, 100)
2013
        rotation_auto = value != 0 ? true : false;
2014 2015
        return true;
#else
2016
        rotation_auto = false;
2017 2018
        return false;
#endif
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
    default:
        return false;
    }

    return true;
}


///////////////// FFMPEG CvVideoWriter implementation //////////////////////////
struct CvVideoWriter_FFMPEG
{
    bool open( const char* filename, int fourcc,
2031
               double fps, int width, int height, const VideoWriterParameters& params );
2032 2033
    void close();
    bool writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin );
2034
    bool writeHWFrame(cv::InputArray input);
2035
    double getProperty(int propId) const;
2036 2037 2038

    void init();

2039
    CV_FFMPEG_FMT_CONST AVOutputFormat  * fmt;
V
Vadim Pisarevsky 已提交
2040
    AVFormatContext * oc;
2041 2042 2043 2044 2045 2046 2047
    uint8_t         * outbuf;
    uint32_t          outbuf_size;
    FILE            * outfile;
    AVFrame         * picture;
    AVFrame         * input_picture;
    uint8_t         * picbuf;
    AVStream        * video_st;
2048
    AVCodecContext  * context;
2049
    AVPixelFormat     input_pix_fmt;
2050
    unsigned char   * aligned_input;
2051
    size_t            aligned_input_size;
V
Vadim Pisarevsky 已提交
2052
    int               frame_width, frame_height;
2053
    int               frame_idx;
V
Vadim Pisarevsky 已提交
2054
    bool              ok;
2055
    struct SwsContext *img_convert_ctx;
2056 2057
    VideoAccelerationType va_type;
    int               hw_device;
2058
    int               use_opencl;
2059 2060 2061 2062
};

static const char * icvFFMPEGErrStr(int err)
{
2063
    switch(err) {
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
    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 已提交
2092
    }
2093

V
Vadim Pisarevsky 已提交
2094
    return "Unspecified error";
2095 2096 2097 2098
}

/* function internal to FFMPEG (libavformat/riff.c) to lookup codec id by fourcc tag*/
extern "C" {
2099
    enum CV_CODEC_ID codec_get_bmp_id(unsigned int tag);
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
}

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;
2113
    context = 0;
2114
    input_pix_fmt = AV_PIX_FMT_NONE;
2115
    aligned_input = NULL;
2116
    aligned_input_size = 0;
2117
    img_convert_ctx = 0;
V
Vadim Pisarevsky 已提交
2118
    frame_width = frame_height = 0;
2119
    frame_idx = 0;
2120 2121
    va_type = VIDEO_ACCELERATION_NONE;
    hw_device = -1;
2122
    use_opencl = 0;
V
Vadim Pisarevsky 已提交
2123
    ok = false;
2124 2125 2126 2127 2128 2129 2130 2131
}

/**
 * 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 已提交
2132
    AVFrame * picture;
2133
    uint8_t * picture_buf = 0;
V
Vadim Pisarevsky 已提交
2134 2135
    int size;

J
jisli 已提交
2136 2137 2138 2139
#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 已提交
2140
    picture = avcodec_alloc_frame();
J
jisli 已提交
2141
#endif
V
Vadim Pisarevsky 已提交
2142 2143
    if (!picture)
        return NULL;
2144 2145 2146 2147 2148

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

P
Peter Rekdal Sunde 已提交
2149
    size = _opencv_ffmpeg_av_image_get_buffer_size( (AVPixelFormat) pix_fmt, width, height);
V
Vadim Pisarevsky 已提交
2150 2151 2152 2153 2154 2155 2156
    if(alloc){
        picture_buf = (uint8_t *) malloc(size);
        if (!picture_buf)
        {
            av_free(picture);
            return NULL;
        }
P
Peter Rekdal Sunde 已提交
2157
        _opencv_ffmpeg_av_image_fill_arrays(picture, picture_buf,
J
jisli 已提交
2158
                       (AVPixelFormat) pix_fmt, width, height);
V
Vadim Pisarevsky 已提交
2159
    }
2160

V
Vadim Pisarevsky 已提交
2161
    return picture;
2162 2163
}

2164
/* configure video stream */
2165
static AVCodecContext * icv_configure_video_stream_FFMPEG(AVFormatContext *oc,
2166 2167 2168
                                                   AVStream *st,
                                                   const AVCodec* codec,
                                                   int w, int h, int bitrate,
2169
                                                   double fps, AVPixelFormat pixel_format, int fourcc)
2170
{
2171 2172 2173
#ifdef CV_FFMPEG_CODECPAR
    AVCodecContext *c = avcodec_alloc_context3(codec);
#else
2174
    AVCodecContext *c = st->codec;
2175 2176 2177
#endif
    CV_Assert(c);

V
Vadim Pisarevsky 已提交
2178
    int frame_rate, frame_rate_base;
2179

2180
    c->codec_id = codec->id;
V
Vadim Pisarevsky 已提交
2181
    c->codec_type = AVMEDIA_TYPE_VIDEO;
2182
    c->codec_tag = fourcc;
2183

2184
#ifndef CV_FFMPEG_CODECPAR
2185
    // Set per-codec defaults
2186
    CV_CODEC_ID c_id = c->codec_id;
2187 2188 2189
    avcodec_get_context_defaults3(c, codec);
    // avcodec_get_context_defaults3 erases codec_id for some reason
    c->codec_id = c_id;
2190
#endif
2191

V
Vadim Pisarevsky 已提交
2192 2193 2194 2195 2196
    /* 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;
2197

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

V
Vadim Pisarevsky 已提交
2202 2203 2204 2205 2206 2207
    /* 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,
2208 2209
       timebase should be 1/framerate and timestamp increments should be
       identically 1. */
V
Vadim Pisarevsky 已提交
2210 2211
    frame_rate=(int)(fps+0.5);
    frame_rate_base=1;
2212
    while (fabs(((double)frame_rate/frame_rate_base) - fps) > 0.001){
V
Vadim Pisarevsky 已提交
2213 2214 2215
        frame_rate_base*=10;
        frame_rate=(int)(fps*frame_rate_base + 0.5);
    }
2216 2217
    c->time_base.den = frame_rate;
    c->time_base.num = frame_rate_base;
V
Vadim Pisarevsky 已提交
2218 2219 2220
    /* adjust time base for supported framerates */
    if(codec && codec->supported_framerates){
        const AVRational *p= codec->supported_framerates;
2221
        AVRational req = {frame_rate, frame_rate_base};
V
Vadim Pisarevsky 已提交
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231
        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;
            }
        }
2232
        if (best == NULL)
2233 2234 2235 2236 2237 2238
        {
#ifdef CV_FFMPEG_CODECPAR
            avcodec_free_context(&c);
#endif
            return NULL;
        }
V
Vadim Pisarevsky 已提交
2239 2240 2241
        c->time_base.den= best->num;
        c->time_base.num= best->den;
    }
2242

V
Vadim Pisarevsky 已提交
2243
    c->gop_size = 12; /* emit one intra frame every twelve frames at most */
2244
    c->pix_fmt = pixel_format;
2245
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG2VIDEO)) {
2246 2247
        c->max_b_frames = 2;
    }
2248
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG1VIDEO) || c->codec_id == CV_CODEC(CODEC_ID_MSMPEG4V3)){
2249
        /* needed to avoid using macroblocks in which some coeffs overflow
L
luz.paz 已提交
2250 2251
           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 已提交
2252
        /* avoid FFMPEG warning 'clipping 1 dct coefficients...' */
2253 2254
        c->mb_decision=2;
    }
2255

2256 2257
    /* Some settings for libx264 encoding, restore dummy values for gop_size
     and qmin since they will be set to reasonable defaults by the libx264
2258
     preset system. Also, use a crf encode with the default quality rating,
2259
     this seems easier than finding an appropriate default bitrate. */
2260
    if (c->codec_id == AV_CODEC_ID_H264) {
2261 2262 2263
      c->gop_size = -1;
      c->qmin = -1;
      c->bit_rate = 0;
2264 2265
      if (c->priv_data)
          av_opt_set(c->priv_data,"crf","23", 0);
2266
    }
2267

L
luz.paz 已提交
2268
    // some formats want stream headers to be separate
2269 2270
    if(oc->oformat->flags & AVFMT_GLOBALHEADER)
    {
2271 2272 2273
        // 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))
2274 2275
        c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
#else
2276
        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
2277
#endif
2278 2279
    }

2280
    st->avg_frame_rate = av_make_q(frame_rate, frame_rate_base);
2281 2282 2283
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 20, 0)
    st->time_base = c->time_base;
#endif
A
Alexander Alekhin 已提交
2284

2285
    return c;
2286 2287
}

V
Vadim Pisarevsky 已提交
2288 2289
static const int OPENCV_NO_FRAMES_WRITTEN_CODE = 1000;

2290
static int icv_av_write_frame_FFMPEG( AVFormatContext * oc, AVStream * video_st, AVCodecContext * c,
2291
                                      uint8_t *, uint32_t,
2292
                                      AVFrame * picture, int frame_idx)
2293
{
2294
    int ret = OPENCV_NO_FRAMES_WRITTEN_CODE;
2295

2296 2297 2298
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(57, 0, 0)
    if (oc->oformat->flags & AVFMT_RAWPICTURE)
    {
2299 2300 2301 2302 2303
        /* raw video case. The API will change slightly in the near
           futur for that */
        AVPacket pkt;
        av_init_packet(&pkt);

V
Vadim Pisarevsky 已提交
2304
        pkt.flags |= PKT_FLAG_KEY;
2305 2306 2307 2308 2309
        pkt.stream_index= video_st->index;
        pkt.data= (uint8_t *)picture;
        pkt.size= sizeof(AVPicture);

        ret = av_write_frame(oc, &pkt);
2310 2311 2312 2313
    }
    else
#endif
    {
2314
        /* encode the image */
2315
#if USE_AV_SEND_FRAME_API
2316 2317 2318 2319 2320 2321 2322
        if (picture == NULL && frame_idx == 0) {
            ret = 0;
        } else {
            ret = avcodec_send_frame(c, picture);
            if (ret < 0)
                CV_LOG_ERROR(NULL, "Error sending frame to encoder (avcodec_send_frame)");
        }
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
        while (ret >= 0)
        {
            AVPacket* pkt = av_packet_alloc();
            pkt->stream_index = video_st->index;
            ret = avcodec_receive_packet(c, pkt);

            if(!ret)
            {
                av_packet_rescale_ts(pkt, c->time_base, video_st->time_base);
                ret = av_write_frame(oc, pkt);
                av_packet_free(&pkt);
                continue;
            }

            av_packet_free(&pkt);
            break;
        }
#else
2341
        CV_UNUSED(frame_idx);
2342 2343 2344 2345 2346 2347 2348
        AVPacket pkt;
        av_init_packet(&pkt);
        int got_output = 0;
        pkt.data = NULL;
        pkt.size = 0;
        ret = avcodec_encode_video2(c, &pkt, picture, &got_output);
        if (ret < 0)
2349
            ;
2350
        else if (got_output) {
2351 2352 2353 2354 2355 2356
            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);
2357 2358
            pkt.stream_index= video_st->index;
            ret = av_write_frame(oc, &pkt);
P
Peter Rekdal Sunde 已提交
2359
            _opencv_ffmpeg_av_packet_unref(&pkt);
2360 2361 2362 2363
        }
        else
            ret = OPENCV_NO_FRAMES_WRITTEN_CODE;
#endif
2364
    }
V
Vadim Pisarevsky 已提交
2365
    return ret;
2366 2367 2368 2369 2370
}

/// write a frame with FFMPEG
bool CvVideoWriter_FFMPEG::writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin )
{
2371 2372 2373 2374 2375 2376
    // check parameters
    if (input_pix_fmt == AV_PIX_FMT_BGR24) {
        if (cn != 3) {
            return false;
        }
    }
2377
    else if (input_pix_fmt == AV_PIX_FMT_GRAY8 || input_pix_fmt == AV_PIX_FMT_GRAY16LE) {
2378 2379 2380 2381 2382
        if (cn != 1) {
            return false;
        }
    }
    else {
2383 2384 2385
        CV_LOG_WARNING(NULL, "Input data does not match selected pixel format: "
                       << av_get_pix_fmt_name(input_pix_fmt)
                       << ", number of channels: " << cn);
2386
        CV_Assert(false);
2387
    }
2388

V
Vadim Pisarevsky 已提交
2389 2390 2391 2392
    if( (width & -2) != frame_width || (height & -2) != frame_height || !data )
        return false;
    width = frame_width;
    height = frame_height;
2393

2394
    // FFmpeg contains SIMD optimizations which can sometimes read data past
2395 2396 2397 2398 2399 2400 2401
    // 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;
2402
    const size_t CV_PAGE_MASK = ~(size_t)(4096 - 1);
A
Alexander Alekhin 已提交
2403
    const unsigned char* dataend = data + ((size_t)height * step);
2404 2405
    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 已提交
2406
    {
2407
        int aligned_step = (step + CV_STEP_ALIGNMENT - 1) & ~(CV_STEP_ALIGNMENT - 1);
2408

2409 2410 2411
        size_t new_size = (aligned_step * height + CV_SIMD_SIZE);

        if (!aligned_input || aligned_input_size < new_size)
A
Alexander Shishkov 已提交
2412
        {
2413 2414 2415 2416
            if (aligned_input)
                av_freep(&aligned_input);
            aligned_input_size = new_size;
            aligned_input = (unsigned char*)av_mallocz(aligned_input_size);
A
Alexander Shishkov 已提交
2417
        }
2418

A
Alexander Shishkov 已提交
2419 2420
        if (origin == 1)
            for( int y = 0; y < height; y++ )
2421
                memcpy(aligned_input + y*aligned_step, data + (height-1-y)*step, step);
A
Alexander Shishkov 已提交
2422 2423
        else
            for( int y = 0; y < height; y++ )
2424
                memcpy(aligned_input + y*aligned_step, data + y*step, step);
2425

2426 2427
        data = aligned_input;
        step = aligned_step;
2428 2429
    }

2430
    AVPixelFormat sw_pix_fmt = context->pix_fmt;
2431
#if USE_AV_HW_CODECS
2432 2433
    if (context->hw_frames_ctx)
        sw_pix_fmt = ((AVHWFramesContext*)context->hw_frames_ctx->data)->sw_format;
2434 2435
#endif
    if ( sw_pix_fmt != input_pix_fmt ) {
2436
        CV_Assert( input_picture );
V
Vadim Pisarevsky 已提交
2437
        // let input_picture point to the raw data buffer of 'image'
P
Peter Rekdal Sunde 已提交
2438
        _opencv_ffmpeg_av_image_fill_arrays(input_picture, (uint8_t *) data,
J
jisli 已提交
2439
                       (AVPixelFormat)input_pix_fmt, width, height);
2440
        input_picture->linesize[0] = step;
2441

V
Vadim Pisarevsky 已提交
2442 2443 2444 2445
        if( !img_convert_ctx )
        {
            img_convert_ctx = sws_getContext(width,
                                             height,
J
jisli 已提交
2446
                                             (AVPixelFormat)input_pix_fmt,
2447 2448
                                             context->width,
                                             context->height,
2449
                                             sw_pix_fmt,
V
Vadim Pisarevsky 已提交
2450 2451 2452 2453 2454
                                             SWS_BICUBIC,
                                             NULL, NULL, NULL);
            if( !img_convert_ctx )
                return false;
        }
2455 2456 2457 2458 2459 2460

        if ( sws_scale(img_convert_ctx, input_picture->data,
                       input_picture->linesize, 0,
                       height,
                       picture->data, picture->linesize) < 0 )
            return false;
V
Vadim Pisarevsky 已提交
2461 2462
    }
    else{
P
Peter Rekdal Sunde 已提交
2463
        _opencv_ffmpeg_av_image_fill_arrays(picture, (uint8_t *) data,
J
jisli 已提交
2464
                       (AVPixelFormat)input_pix_fmt, width, height);
2465
        picture->linesize[0] = step;
V
Vadim Pisarevsky 已提交
2466
    }
2467

2468 2469
    bool ret;
#if USE_AV_HW_CODECS
2470
    if (context->hw_device_ctx) {
2471 2472 2473 2474 2475 2476
        // copy data to HW frame
        AVFrame* hw_frame = av_frame_alloc();
        if (!hw_frame) {
            CV_LOG_ERROR(NULL, "Error allocating AVFrame (av_frame_alloc)");
            return false;
        }
2477
        if (av_hwframe_get_buffer(context->hw_frames_ctx, hw_frame, 0) < 0) {
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
            CV_LOG_ERROR(NULL, "Error obtaining HW frame (av_hwframe_get_buffer)");
            av_frame_free(&hw_frame);
            return false;
        }
        if (av_hwframe_transfer_data(hw_frame, picture, 0) < 0) {
            CV_LOG_ERROR(NULL, "Error copying data from CPU to GPU (av_hwframe_transfer_data)");
            av_frame_free(&hw_frame);
            return false;
        }
        hw_frame->pts = frame_idx;
2488
        int ret_write = icv_av_write_frame_FFMPEG(oc, video_st, context, outbuf, outbuf_size, hw_frame, frame_idx);
2489 2490 2491 2492 2493 2494
        ret = ret_write >= 0 ? true : false;
        av_frame_free(&hw_frame);
    } else
#endif
    {
        picture->pts = frame_idx;
2495
        int ret_write = icv_av_write_frame_FFMPEG(oc, video_st, context, outbuf, outbuf_size, picture, frame_idx);
2496 2497 2498
        ret = ret_write >= 0 ? true : false;
    }

2499
    frame_idx++;
2500

V
Vadim Pisarevsky 已提交
2501
    return ret;
2502 2503
}

2504 2505
bool CvVideoWriter_FFMPEG::writeHWFrame(cv::InputArray input) {
#if USE_AV_HW_CODECS
2506
    if (!video_st || !context || !context->hw_frames_ctx || !context->hw_device_ctx)
2507 2508 2509 2510 2511 2512 2513
        return false;

    // Get hardware frame from frame pool
    AVFrame* hw_frame = av_frame_alloc();
    if (!hw_frame) {
        return false;
    }
2514
    if (av_hwframe_get_buffer(context->hw_frames_ctx, hw_frame, 0) < 0) {
2515 2516 2517 2518 2519
        av_frame_free(&hw_frame);
        return false;
    }

    // GPU to GPU copy
2520
    if (!hw_copy_umat_to_frame(context->hw_device_ctx, input, hw_frame)) {
2521 2522 2523 2524 2525 2526
        av_frame_free(&hw_frame);
        return false;
    }

    // encode
    hw_frame->pts = frame_idx;
2527
    icv_av_write_frame_FFMPEG( oc, video_st, context, outbuf, outbuf_size, hw_frame, frame_idx);
2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
    frame_idx++;

    av_frame_free(&hw_frame);

    return true;
#else
    CV_UNUSED(input);
    return false;
#endif
}

2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
double CvVideoWriter_FFMPEG::getProperty(int propId) const
{
    CV_UNUSED(propId);
#if USE_AV_HW_CODECS
    if (propId == VIDEOWRITER_PROP_HW_ACCELERATION)
    {
        return static_cast<double>(va_type);
    }
    else if (propId == VIDEOWRITER_PROP_HW_DEVICE)
    {
        return static_cast<double>(hw_device);
    }
2551 2552 2553 2554
    else if (propId == VIDEOWRITER_PROP_HW_ACCELERATION_USE_OPENCL)
    {
        return static_cast<double>(use_opencl);
    }
2555 2556 2557 2558
#endif
    return 0;
}

2559 2560 2561
/// close video output stream and free associated memory
void CvVideoWriter_FFMPEG::close()
{
V
Vadim Pisarevsky 已提交
2562 2563 2564 2565
    /* 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?
2566

V
Vadim Pisarevsky 已提交
2567
    /* write the trailer, if any */
2568
    if (picture && ok && oc)
V
Vadim Pisarevsky 已提交
2569
    {
2570 2571 2572
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(57, 0, 0)
        if (!(oc->oformat->flags & AVFMT_RAWPICTURE))
#endif
V
Vadim Pisarevsky 已提交
2573 2574 2575
        {
            for(;;)
            {
2576
                int ret = icv_av_write_frame_FFMPEG( oc, video_st, context, outbuf, outbuf_size, NULL, frame_idx);
V
Vadim Pisarevsky 已提交
2577 2578 2579 2580 2581 2582
                if( ret == OPENCV_NO_FRAMES_WRITTEN_CODE || ret < 0 )
                    break;
            }
        }
        av_write_trailer(oc);
    }
2583

V
Vadim Pisarevsky 已提交
2584 2585 2586 2587 2588
    if( img_convert_ctx )
    {
        sws_freeContext(img_convert_ctx);
        img_convert_ctx = 0;
    }
2589

V
Vadim Pisarevsky 已提交
2590
    // free pictures
2591
    if (picture && context && context->pix_fmt != input_pix_fmt)
V
Vadim Pisarevsky 已提交
2592 2593 2594 2595 2596 2597
    {
        if(picture->data[0])
            free(picture->data[0]);
        picture->data[0] = 0;
    }
    av_free(picture);
2598

V
Vadim Pisarevsky 已提交
2599 2600
    if (input_picture)
        av_free(input_picture);
2601

2602 2603 2604
#ifdef CV_FFMPEG_CODECPAR
    avcodec_free_context(&context);
#else
V
Vadim Pisarevsky 已提交
2605
    /* close codec */
2606 2607 2608 2609
    if (context)  // fixed after https://github.com/FFmpeg/FFmpeg/commit/3e1f507f3e8f16b716aa115552d243b48ae809bd
        avcodec_close(context);
    context = NULL;
#endif
2610

V
Vadim Pisarevsky 已提交
2611
    av_free(outbuf);
2612

2613
    if (oc)
V
Vadim Pisarevsky 已提交
2614
    {
2615 2616 2617 2618 2619
        if (!(fmt->flags & AVFMT_NOFILE))
        {
            /* close the output file */
            avio_close(oc->pb);
        }
2620

2621 2622 2623
        /* free the stream */
        avformat_free_context(oc);
    }
2624

2625
    av_freep(&aligned_input);
2626

V
Vadim Pisarevsky 已提交
2627 2628
    init();
}
2629

2630 2631 2632
#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)

2633
static inline bool cv_ff_codec_tag_match(const AVCodecTag *tags, CV_CODEC_ID id, unsigned int tag)
2634 2635 2636 2637 2638 2639 2640 2641 2642
{
    while (tags->id != AV_CODEC_ID_NONE)
    {
        if (tags->id == id && tags->tag == tag)
            return true;
        tags++;
    }
    return false;
}
E
Emanuele Ruffaldi 已提交
2643

2644
static inline bool cv_ff_codec_tag_list_match(const AVCodecTag *const *tags, CV_CODEC_ID id, unsigned int tag)
2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
{
    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 已提交
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669

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 已提交
2670 2671
/// Create a video writer object that uses FFMPEG
bool CvVideoWriter_FFMPEG::open( const char * filename, int fourcc,
2672
                                 double fps, int width, int height, const VideoWriterParameters& params)
V
Vadim Pisarevsky 已提交
2673
{
2674 2675
    const bool threadSafe = isThreadSafe();
    InternalFFMpegRegister::init(threadSafe);
2676

2677 2678 2679
    std::unique_lock<cv::Mutex> lock(_mutex, std::defer_lock);
    if (!threadSafe)
        lock.lock();
2680

2681
    CV_CODEC_ID codec_id = CV_CODEC(CODEC_ID_NONE);
2682
    AVPixelFormat codec_pix_fmt;
V
Vadim Pisarevsky 已提交
2683
    double bitrate_scale = 1;
2684

V
Vadim Pisarevsky 已提交
2685
    close();
2686

2687
    const bool is_color = params.get(VIDEOWRITER_PROP_IS_COLOR, true);
2688 2689 2690 2691 2692 2693 2694 2695
    const int depth = params.get(VIDEOWRITER_PROP_DEPTH, CV_8U);
    const bool is_supported = depth == CV_8U || (depth == CV_16U && !is_color);
    if (!is_supported)
    {
        CV_LOG_WARNING(NULL, "Unsupported depth/isColor combination is selected, "
                             "only CV_8UC1/CV_8UC3/CV_16UC1 are supported.");
        return false;
    }
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
    if (params.has(VIDEOWRITER_PROP_HW_ACCELERATION))
    {
        va_type = params.get<VideoAccelerationType>(VIDEOWRITER_PROP_HW_ACCELERATION, VIDEO_ACCELERATION_NONE);
#if !USE_AV_HW_CODECS
        if (va_type != VIDEO_ACCELERATION_NONE && va_type != VIDEO_ACCELERATION_ANY)
        {
            CV_LOG_ERROR(NULL, "VIDEOIO/FFMPEG: FFmpeg backend is build without acceleration support. Can't handle VIDEOWRITER_PROP_HW_ACCELERATION parameter. Bailout");
            return false;
        }
#endif
    }
    if (params.has(VIDEOWRITER_PROP_HW_DEVICE))
    {
        hw_device = params.get<int>(VIDEOWRITER_PROP_HW_DEVICE, -1);
        if (va_type == VIDEO_ACCELERATION_NONE && hw_device != -1)
        {
            CV_LOG_ERROR(NULL, "VIDEOIO/FFMPEG: Invalid usage of VIDEOWRITER_PROP_HW_DEVICE without requested H/W acceleration. Bailout");
            return false;
        }
        if (va_type == VIDEO_ACCELERATION_ANY && hw_device != -1)
        {
            CV_LOG_ERROR(NULL, "VIDEOIO/FFMPEG: Invalid usage of VIDEOWRITER_PROP_HW_DEVICE with 'ANY' H/W acceleration. Bailout");
            return false;
        }
    }
2721 2722 2723
    if (params.has(VIDEOWRITER_PROP_HW_ACCELERATION_USE_OPENCL)) {
        use_opencl = params.get<int>(VIDEOWRITER_PROP_HW_ACCELERATION_USE_OPENCL);
    }
2724 2725 2726 2727 2728 2729 2730

    if (params.warnUnusedParameters())
    {
        CV_LOG_ERROR(NULL, "VIDEOIO/FFMPEG: unsupported parameters in VideoWriter, see logger INFO channel for details");
        return false;
    }

V
Vadim Pisarevsky 已提交
2731 2732 2733 2734 2735
    // check arguments
    if( !filename )
        return false;
    if(fps <= 0)
        return false;
2736

V
Vadim Pisarevsky 已提交
2737 2738 2739 2740 2741 2742 2743
    // 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;
2744

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

V
Vadim Pisarevsky 已提交
2747
    fmt = av_guess_format(NULL, filename, NULL);
2748

V
Vadim Pisarevsky 已提交
2749 2750
    if (!fmt)
        return false;
2751

V
Vadim Pisarevsky 已提交
2752
    /* determine optimal pixel format */
2753 2754 2755 2756 2757 2758 2759 2760 2761
    if (is_color)
    {
        switch (depth)
        {
        case CV_8U: input_pix_fmt = AV_PIX_FMT_BGR24; break;
        default:
            CV_LOG_WARNING(NULL, "Unsupported input depth for color image: " << depth);
            return false;
        }
V
Vadim Pisarevsky 已提交
2762
    }
2763 2764 2765 2766 2767 2768 2769 2770 2771 2772
    else
    {
        switch (depth)
        {
        case CV_8U: input_pix_fmt = AV_PIX_FMT_GRAY8; break;
        case CV_16U: input_pix_fmt = AV_PIX_FMT_GRAY16LE; break;
        default:
            CV_LOG_WARNING(NULL, "Unsupported input depth for grayscale image: " << depth);
            return false;
        }
V
Vadim Pisarevsky 已提交
2773
    }
2774
    CV_LOG_DEBUG(NULL, "Selected pixel format: " << av_get_pix_fmt_name(input_pix_fmt));
2775

E
Emanuele Ruffaldi 已提交
2776 2777 2778 2779 2780 2781 2782
    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 已提交
2783
    /* Lookup codec_id for given fourcc */
2784 2785 2786
    if( (codec_id = av_codec_get_id(fmt->codec_tag, fourcc)) == CV_CODEC(CODEC_ID_NONE) )
    {
        const struct AVCodecTag * fallback_tags[] = {
2787 2788 2789
// APIchanges:
// 2012-01-31 - dd6d3b0 - lavf 54.01.0
//   Add avformat_get_riff_video_tags() and avformat_get_riff_audio_tags().
2790
                avformat_get_riff_video_tags(),
2791
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(55, 25, 100) && defined LIBAVFORMAT_VERSION_MICRO && LIBAVFORMAT_VERSION_MICRO >= 100
2792 2793 2794
// 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().
2795
                avformat_get_mov_video_tags(),
2796
#endif
2797 2798
                codec_bmp_tags, // fallback for avformat < 54.1
                NULL };
2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
        if (codec_id == CV_CODEC(CODEC_ID_NONE)) {
            codec_id = av_codec_get_id(fallback_tags, fourcc);
        }
        if (codec_id == CV_CODEC(CODEC_ID_NONE)) {
            char *p = (char *) &fourcc;
            char name[] = {(char)tolower(p[0]), (char)tolower(p[1]), (char)tolower(p[2]), (char)tolower(p[3]), 0};
            const AVCodecDescriptor *desc = avcodec_descriptor_get_by_name(name);
            if (desc)
                codec_id = desc->id;
        }

        if (codec_id == CV_CODEC(CODEC_ID_NONE))
2811 2812 2813 2814 2815 2816 2817 2818
        {
            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 已提交
2819 2820


2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
    // 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;
        }
    }
2836

V
Vadim Pisarevsky 已提交
2837 2838
    // alloc memory for context
    oc = avformat_alloc_context();
2839
    CV_Assert(oc);
2840

V
Vadim Pisarevsky 已提交
2841 2842
    /* set file name */
    oc->oformat = fmt;
2843
#ifndef CV_FFMPEG_URL
V
Vadim Pisarevsky 已提交
2844
    snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
2845 2846 2847 2848 2849 2850 2851
#else
    size_t name_len = strlen(filename);
    oc->url = (char*)av_malloc(name_len + 1);
    CV_Assert(oc->url);
    memcpy((void*)oc->url, filename, name_len + 1);
    oc->url[name_len] = '\0';
#endif
V
Vadim Pisarevsky 已提交
2852 2853
    /* set some options */
    oc->max_delay = (int)(0.7*AV_TIME_BASE);  /* This reduces buffer underrun warnings with MPEG */
2854

V
Vadim Pisarevsky 已提交
2855 2856
    // set a few optimal pixel formats for lossless codecs of interest..
    switch (codec_id) {
2857
    case CV_CODEC(CODEC_ID_JPEGLS):
V
Vadim Pisarevsky 已提交
2858
        // BGR24 or GRAY8 depending on is_color...
E
Emanuele Ruffaldi 已提交
2859 2860
        // supported: bgr24 rgb24 gray gray16le
        // as of version 3.4.1
V
Vadim Pisarevsky 已提交
2861 2862
        codec_pix_fmt = input_pix_fmt;
        break;
2863
    case CV_CODEC(CODEC_ID_HUFFYUV):
E
Emanuele Ruffaldi 已提交
2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929
        // 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 已提交
2930
        break;
2931 2932
    case CV_CODEC(CODEC_ID_MJPEG):
    case CV_CODEC(CODEC_ID_LJPEG):
J
jisli 已提交
2933
        codec_pix_fmt = AV_PIX_FMT_YUVJ420P;
V
Vadim Pisarevsky 已提交
2934 2935
        bitrate_scale = 3;
        break;
2936
    case CV_CODEC(CODEC_ID_RAWVIDEO):
E
Emanuele Ruffaldi 已提交
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955
        // 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 已提交
2956 2957 2958
        break;
    default:
        // good for lossy formats, MPEG, etc.
J
jisli 已提交
2959
        codec_pix_fmt = AV_PIX_FMT_YUV420P;
V
Vadim Pisarevsky 已提交
2960 2961
        break;
    }
2962

2963
    double bitrate = std::min(bitrate_scale*fps*width*height, (double)INT_MAX/2);
2964

2965
    if (codec_id == AV_CODEC_ID_NONE) {
2966
        codec_id = av_guess_codec(oc->oformat, NULL, filename, NULL, AVMEDIA_TYPE_VIDEO);
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
    }

    // Add video stream to output file
    video_st = avformat_new_stream(oc, 0);
    if (!video_st) {
        CV_WARN("Could not allocate stream");
        return false;
    }

    AVDictionary *dict = NULL;
#if !defined(NO_GETENV) && (LIBAVUTIL_VERSION_MAJOR >= 53)
    char* options = getenv("OPENCV_FFMPEG_WRITER_OPTIONS");
2979 2980 2981
    if (options)
    {
        CV_LOG_DEBUG(NULL, "VIDEOIO/FFMPEG: using writer options from environment: " << options);
2982 2983 2984 2985 2986 2987
        av_dict_parse_string(&dict, options, ";", "|", 0);
    }
#endif

    // find and open encoder, try HW acceleration types specified in 'hw_acceleration' list (in order)
    int err = -1;
2988
    const AVCodec* codec = NULL;
2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009
#if USE_AV_HW_CODECS
    AVBufferRef* hw_device_ctx = NULL;
    HWAccelIterator accel_iter(va_type, true/*isEncoder*/, dict);
    while (accel_iter.good())
    {
#else
    do {
#endif
#if USE_AV_HW_CODECS
        accel_iter.parse_next();
        AVHWDeviceType hw_type = accel_iter.hw_type();
        codec = NULL;
        AVPixelFormat hw_format = AV_PIX_FMT_NONE;
        if (hw_device_ctx)
            av_buffer_unref(&hw_device_ctx);
        if (hw_type != AV_HWDEVICE_TYPE_NONE)
        {
            codec = hw_find_codec(codec_id, hw_type, av_codec_is_encoder, accel_iter.disabled_codecs().c_str(), &hw_format);
            if (!codec)
                continue;

3010
            hw_device_ctx = hw_create_device(hw_type, hw_device, accel_iter.device_subname(), use_opencl != 0);
3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030
            if (!hw_device_ctx)
                continue;
        }
        else if (hw_type == AV_HWDEVICE_TYPE_NONE)
#endif
        {
            codec = avcodec_find_encoder(codec_id);
            if (!codec) {
                CV_LOG_ERROR(NULL, "Could not find encoder for codec_id=" << (int)codec_id << ", error: "
                        << icvFFMPEGErrStr(AVERROR_ENCODER_NOT_FOUND));
            }
        }
        if (!codec)
            continue;
#if USE_AV_HW_CODECS
        AVPixelFormat format = (hw_format != AV_PIX_FMT_NONE) ? hw_format : codec_pix_fmt;
#else
        AVPixelFormat format = codec_pix_fmt;
#endif

3031
#ifdef CV_FFMPEG_CODECPAR
3032
        avcodec_free_context(&context);
3033 3034 3035 3036 3037 3038
#endif
        context = icv_configure_video_stream_FFMPEG(oc, video_st, codec,
                                              width, height, (int) (bitrate + 0.5),
                                              fps, format, fourcc);
        if (!context)
        {
3039 3040
            continue;
        }
3041

V
Vadim Pisarevsky 已提交
3042 3043
#if 0
#if FF_API_DUMP_FORMAT
3044
        dump_format(oc, 0, filename, 1);
3045
#else
3046
        av_dump_format(oc, 0, filename, 1);
V
Vadim Pisarevsky 已提交
3047
#endif
3048 3049
#endif

3050 3051
#if USE_AV_HW_CODECS
        if (hw_device_ctx) {
3052
            context->hw_device_ctx = av_buffer_ref(hw_device_ctx);
3053
            if (hw_format != AV_PIX_FMT_NONE) {
3054 3055
                context->hw_frames_ctx = hw_create_frames(NULL, hw_device_ctx, width, height, hw_format);
                if (!context->hw_frames_ctx)
3056 3057 3058 3059
                    continue;
            }
        }
#endif
3060

3061
        int64_t lbit_rate = (int64_t) context->bit_rate;
3062 3063
        lbit_rate += (int64_t)(bitrate / 2);
        lbit_rate = std::min(lbit_rate, (int64_t) INT_MAX);
3064 3065
        context->bit_rate_tolerance = (int) lbit_rate;
        context->bit_rate = (int) lbit_rate;
3066

3067
        /* open the codec */
3068
        err = avcodec_open2(context, codec, NULL);
3069 3070 3071 3072 3073 3074 3075 3076
        if (err >= 0) {
#if USE_AV_HW_CODECS
            va_type = hw_type_to_va_type(hw_type);
            if (hw_type != AV_HWDEVICE_TYPE_NONE && hw_device < 0)
                hw_device = 0;
#endif
            break;
        } else {
3077
            CV_LOG_ERROR(NULL, "Could not open codec " << codec->name << ", error: " << icvFFMPEGErrStr(err) << " (" << err << ")");
3078 3079 3080 3081 3082 3083
        }
#if USE_AV_HW_CODECS
    }  // while (accel_iter.good())
#else
    } while (0);
#endif
3084

3085 3086 3087 3088 3089 3090 3091 3092 3093 3094
#if USE_AV_HW_CODECS
    if (hw_device_ctx)
        av_buffer_unref(&hw_device_ctx);
#endif

    if (dict != NULL)
        av_dict_free(&dict);

    if (err < 0) {
        CV_LOG_ERROR(NULL, "VIDEOIO/FFMPEG: Failed to initialize VideoWriter");
V
Vadim Pisarevsky 已提交
3095
        return false;
3096
    }
3097

3098 3099 3100 3101 3102 3103
#ifdef CV_FFMPEG_CODECPAR
    // Copy all to codecpar...
    // !!! https://stackoverflow.com/questions/15897849/c-ffmpeg-not-writing-avcc-box-information
    avcodec_parameters_from_context(video_st->codecpar, context);
#endif

V
Vadim Pisarevsky 已提交
3104
    outbuf = NULL;
3105

3106 3107 3108 3109 3110

#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(57, 0, 0)
    if (!(oc->oformat->flags & AVFMT_RAWPICTURE))
#endif
    {
V
Vadim Pisarevsky 已提交
3111 3112 3113 3114
        /* 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);
3115
    }
3116

V
Vadim Pisarevsky 已提交
3117
    bool need_color_convert;
3118
    AVPixelFormat sw_pix_fmt = context->pix_fmt;
3119
#if USE_AV_HW_CODECS
3120 3121
    if (context->hw_frames_ctx)
        sw_pix_fmt = ((AVHWFramesContext*)context->hw_frames_ctx->data)->sw_format;
3122 3123 3124
#endif

    need_color_convert = (sw_pix_fmt != input_pix_fmt);
3125

V
Vadim Pisarevsky 已提交
3126
    /* allocate the encoded raw picture */
3127
    picture = icv_alloc_picture_FFMPEG(sw_pix_fmt, context->width, context->height, need_color_convert);
V
Vadim Pisarevsky 已提交
3128 3129
    if (!picture) {
        return false;
3130
    }
3131

V
Vadim Pisarevsky 已提交
3132 3133 3134 3135 3136
    /* 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 ) {
3137
        input_picture = icv_alloc_picture_FFMPEG(input_pix_fmt, context->width, context->height, false);
V
Vadim Pisarevsky 已提交
3138 3139
        if (!input_picture) {
            return false;
3140
        }
3141 3142
    }

V
Vadim Pisarevsky 已提交
3143
    /* open the output file, if needed */
3144 3145 3146 3147
    if (!(fmt->flags & AVFMT_NOFILE))
    {
        if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0)
        {
V
Vadim Pisarevsky 已提交
3148 3149
            return false;
        }
3150
    }
3151

V
Vadim Pisarevsky 已提交
3152 3153
    /* write the stream header, if any */
    err=avformat_write_header(oc, NULL);
3154

V
Vadim Pisarevsky 已提交
3155
    if(err < 0)
V
Vladislav Vinogradov 已提交
3156
    {
V
Vadim Pisarevsky 已提交
3157 3158 3159
        close();
        remove(filename);
        return false;
V
Vladislav Vinogradov 已提交
3160
    }
V
Vadim Pisarevsky 已提交
3161 3162
    frame_width = width;
    frame_height = height;
3163
    frame_idx = 0;
V
Vadim Pisarevsky 已提交
3164
    ok = true;
I
Ilya Lavrenov 已提交
3165

V
Vadim Pisarevsky 已提交
3166
    return true;
V
Vladislav Vinogradov 已提交
3167 3168 3169 3170
}



3171 3172
static
CvCapture_FFMPEG* cvCreateFileCaptureWithParams_FFMPEG(const char* filename, const VideoCaptureParameters& params)
V
Vladislav Vinogradov 已提交
3173
{
3174
    // FIXIT: remove unsafe malloc() approach
V
Vadim Pisarevsky 已提交
3175
    CvCapture_FFMPEG* capture = (CvCapture_FFMPEG*)malloc(sizeof(*capture));
3176 3177
    if (!capture)
        return 0;
V
Vadim Pisarevsky 已提交
3178
    capture->init();
3179
    if (capture->open(filename, params))
V
Vadim Pisarevsky 已提交
3180
        return capture;
I
Ilya Lavrenov 已提交
3181

V
Vadim Pisarevsky 已提交
3182 3183 3184
    capture->close();
    free(capture);
    return 0;
V
Vladislav Vinogradov 已提交
3185 3186
}

V
Vadim Pisarevsky 已提交
3187
void cvReleaseCapture_FFMPEG(CvCapture_FFMPEG** capture)
V
Vladislav Vinogradov 已提交
3188
{
V
Vadim Pisarevsky 已提交
3189
    if( capture && *capture )
V
Vladislav Vinogradov 已提交
3190
    {
V
Vadim Pisarevsky 已提交
3191 3192 3193
        (*capture)->close();
        free(*capture);
        *capture = 0;
V
Vladislav Vinogradov 已提交
3194 3195 3196
    }
}

V
Vadim Pisarevsky 已提交
3197
int cvSetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id, double value)
V
Vladislav Vinogradov 已提交
3198
{
V
Vadim Pisarevsky 已提交
3199
    return capture->setProperty(prop_id, value);
V
Vladislav Vinogradov 已提交
3200 3201
}

V
Vadim Pisarevsky 已提交
3202
double cvGetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id)
V
Vladislav Vinogradov 已提交
3203
{
V
Vadim Pisarevsky 已提交
3204
    return capture->getProperty(prop_id);
V
Vladislav Vinogradov 已提交
3205 3206
}

V
Vadim Pisarevsky 已提交
3207
int cvGrabFrame_FFMPEG(CvCapture_FFMPEG* capture)
V
Vladislav Vinogradov 已提交
3208
{
V
Vadim Pisarevsky 已提交
3209
    return capture->grabFrame();
V
Vladislav Vinogradov 已提交
3210
}
V
Vladislav Vinogradov 已提交
3211

V
Vadim Pisarevsky 已提交
3212
int cvRetrieveFrame_FFMPEG(CvCapture_FFMPEG* capture, unsigned char** data, int* step, int* width, int* height, int* cn)
V
Vladislav Vinogradov 已提交
3213
{
3214 3215 3216 3217 3218 3219 3220
    int depth = CV_8U;
    return cvRetrieveFrame2_FFMPEG(capture, data, step, width, height, cn, &depth);
}

int cvRetrieveFrame2_FFMPEG(CvCapture_FFMPEG* capture, unsigned char** data, int* step, int* width, int* height, int* cn, int* depth)
{
    return capture->retrieveFrame(0, data, step, width, height, cn, depth);
V
Vladislav Vinogradov 已提交
3221 3222
}

3223 3224
static CvVideoWriter_FFMPEG* cvCreateVideoWriterWithParams_FFMPEG( const char* filename, int fourcc, double fps,
                                                  int width, int height, const VideoWriterParameters& params )
V
Vladislav Vinogradov 已提交
3225
{
V
Vadim Pisarevsky 已提交
3226
    CvVideoWriter_FFMPEG* writer = (CvVideoWriter_FFMPEG*)malloc(sizeof(*writer));
3227 3228
    if (!writer)
        return 0;
V
Vadim Pisarevsky 已提交
3229
    writer->init();
3230
    if( writer->open( filename, fourcc, fps, width, height, params ))
V
Vadim Pisarevsky 已提交
3231 3232 3233 3234
        return writer;
    writer->close();
    free(writer);
    return 0;
V
Vladislav Vinogradov 已提交
3235 3236
}

3237 3238 3239 3240 3241 3242 3243 3244
CvVideoWriter_FFMPEG* cvCreateVideoWriter_FFMPEG( const char* filename, int fourcc, double fps,
                                                  int width, int height, int isColor )
{
    VideoWriterParameters params;
    params.add(VIDEOWRITER_PROP_IS_COLOR, isColor);
    return cvCreateVideoWriterWithParams_FFMPEG(filename, fourcc, fps, width, height, params);
}

V
Vadim Pisarevsky 已提交
3245 3246 3247
void cvReleaseVideoWriter_FFMPEG( CvVideoWriter_FFMPEG** writer )
{
    if( writer && *writer )
V
Vladislav Vinogradov 已提交
3248
    {
V
Vadim Pisarevsky 已提交
3249 3250 3251
        (*writer)->close();
        free(*writer);
        *writer = 0;
V
Vladislav Vinogradov 已提交
3252 3253 3254 3255
    }
}


V
Vadim Pisarevsky 已提交
3256 3257 3258
int cvWriteFrame_FFMPEG( CvVideoWriter_FFMPEG* writer,
                         const unsigned char* data, int step,
                         int width, int height, int cn, int origin)
V
Vladislav Vinogradov 已提交
3259
{
V
Vadim Pisarevsky 已提交
3260
    return writer->writeFrame(data, step, width, height, cn, origin);
V
Vladislav Vinogradov 已提交
3261
}