cap_ffmpeg_impl.hpp 60.7 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
10
//                          License Agreement
11 12
//                For Open Source Computer Vision Library
//
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
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.
//
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
27
//   * The name of the copyright holders may not be used to endorse or promote products
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

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

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

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

57 58 59 60
#ifdef __GNUC__
#  pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif

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

65 66
#include "ffmpeg_codecs.hpp"

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
67 68
#include <libavutil/mathematics.h>

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

73 74 75 76 77 78
#ifdef WIN32
  #define HAVE_FFMPEG_SWSCALE 1
  #include <libavcodec/avcodec.h>
  #include <libswscale/swscale.h>
#else

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
79 80 81
#ifndef HAVE_FFMPEG_SWSCALE
    #error "libswscale is necessary to build the newer OpenCV ffmpeg wrapper"
#endif
82

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

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

#endif

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

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

#endif

#ifdef __cplusplus
}
#endif

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

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

/* PIX_FMT_RGBA32 macro changed in newer ffmpeg versions */
#ifndef PIX_FMT_RGBA32
#define PIX_FMT_RGBA32 PIX_FMT_RGB32
#endif


136 137 138 139 140
#if defined WIN32 || defined _WIN32
    #include <windows.h>
#elif defined __linux__ || defined __APPLE__
    #include <unistd.h>
    #include <stdio.h>
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
141
    #include <sys/types.h>
142 143 144
    #include <sys/sysctl.h>
#endif

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
145 146 147 148 149 150 151 152 153 154
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif

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

155 156 157 158
#ifndef AVERROR_EOF
#define AVERROR_EOF (-MKTAG( 'E','O','F',' '))
#endif

159 160 161 162 163 164 165 166
#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

167
static int get_number_of_cpus(void)
168
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
169 170 171
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(52, 111, 0)
    return 1;
#elif defined WIN32 || defined _WIN32
172 173
    SYSTEM_INFO sysinfo;
    GetSystemInfo( &sysinfo );
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
174

175 176 177 178 179 180
    return (int)sysinfo.dwNumberOfProcessors;
#elif defined __linux__
    return (int)sysconf( _SC_NPROCESSORS_ONLN );
#elif defined __APPLE__
    int numCPU=0;
    int mib[4];
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
181 182 183
    size_t len = sizeof(numCPU);

    // set the mib for hw.ncpu
184 185
    mib[0] = CTL_HW;
    mib[1] = HW_AVAILCPU;  // alternatively, try HW_NCPU;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
186 187

    // get the number of CPUs from the system
188
    sysctl(mib, 2, &numCPU, &len, NULL, 0);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
189 190

    if( numCPU < 1 )
191 192 193
    {
        mib[1] = HW_NCPU;
        sysctl( mib, 2, &numCPU, &len, NULL, 0 );
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
194

195 196 197 198 199 200 201 202 203 204 205
        if( numCPU < 1 )
            numCPU = 1;
    }

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


206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
struct Image_FFMPEG
{
    unsigned char* data;
    int step;
    int width;
    int height;
    int cn;
};


inline void _opencv_ffmpeg_free(void** ptr)
{
    if(*ptr) free(*ptr);
    *ptr = 0;
}


struct CvCapture_FFMPEG
{
    bool open( const char* filename );
    void close();

    double getProperty(int);
    bool setProperty(int, double);
    bool grabFrame();
    bool retrieveFrame(int, unsigned char** data, int* step, int* width, int* height, int* cn);

    void init();
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
234 235 236

    void    seek(int64_t frame_number);
    void    seek(double sec);
237
    bool    slowSeek( int framenumber );
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251

    int64_t get_total_frames();
    double  get_duration_sec();
    double  get_fps();
    int     get_bitrate();

    double  r2d(AVRational r);
    int64_t dts_to_frame_number(int64_t dts);
    double  dts_to_sec(int64_t dts);

    AVFormatContext * ic;
    AVCodec         * avcodec;
    int               video_stream;
    AVStream        * video_st;
252 253
    AVFrame         * picture;
    AVFrame           rgb_picture;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
254 255 256 257
    int64_t           picture_pts;

    AVPacket          packet;
    Image_FFMPEG      frame;
258
    struct SwsContext *img_convert_ctx;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
259 260 261 262

    int64_t frame_number, first_frame_number;

    double eps_zero;
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
/*
   '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;
};

void CvCapture_FFMPEG::init()
{
    ic = 0;
    video_stream = -1;
    video_st = 0;
    picture = 0;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
279 280
    picture_pts = AV_NOPTS_VALUE_;
    first_frame_number = -1;
281 282 283
    memset( &rgb_picture, 0, sizeof(rgb_picture) );
    memset( &frame, 0, sizeof(frame) );
    filename = 0;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
284 285
    memset(&packet, 0, sizeof(packet));
    av_init_packet(&packet);
286
    img_convert_ctx = 0;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
287 288 289 290

    avcodec = 0;
    frame_number = 0;
    eps_zero = 0.000025;
291 292 293 294 295
}


void CvCapture_FFMPEG::close()
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
296 297 298 299 300
    if( img_convert_ctx )
    {
        sws_freeContext(img_convert_ctx);
        img_convert_ctx = 0;
    }
301

302
    if( picture )
303
        av_free(picture);
304 305 306 307 308

    if( video_st )
    {
#if LIBAVFORMAT_BUILD > 4628
        avcodec_close( video_st->codec );
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
309

310
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
311 312
        avcodec_close( &(video_st->codec) );

313 314 315 316 317 318
#endif
        video_st = NULL;
    }

    if( ic )
    {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
319
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 24, 2)
320
        av_close_input_file(ic);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
321
#else
322
        avformat_close_input(&ic);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
323 324
#endif

325 326 327 328 329 330 331 332 333 334 335 336
        ic = NULL;
    }

    if( rgb_picture.data[0] )
    {
        free( rgb_picture.data[0] );
        rgb_picture.data[0] = 0;
    }

    // free last packet if exist
    if (packet.data) {
        av_free_packet (&packet);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
337
        packet.data = NULL;
338 339 340 341 342 343 344
    }

    init();
}


#ifndef AVSEEK_FLAG_FRAME
345
#define AVSEEK_FLAG_FRAME 0
346
#endif
Andrey Morozov's avatar
Andrey Morozov committed
347
#ifndef AVSEEK_FLAG_ANY
348
#define AVSEEK_FLAG_ANY 1
349
#endif
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
350

351
class ImplMutex
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
352
{
353
public:
Andrey Kamaev's avatar
Andrey Kamaev committed
354 355 356
    ImplMutex() { init(); }
    ~ImplMutex() { destroy(); }

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    void init();
    void destroy();

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

    struct Impl;
protected:
    Impl* impl;

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

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

struct ImplMutex::Impl
{
377 378 379 380 381 382 383 384 385
    void init()
    {
#if (_WIN32_WINNT >= 0x0600)
        ::InitializeCriticalSectionEx(&cs, 1000, 0);
#else
        ::InitializeCriticalSection(&cs);
#endif
        refcount = 1;
    }
386 387 388 389 390 391 392 393 394 395 396 397 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 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    void destroy() { DeleteCriticalSection(&cs); }

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

    CRITICAL_SECTION cs;
    int refcount;
};

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

#elif defined __APPLE__

#include <libkern/OSAtomic.h>

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

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

    OSSpinLock sl;
    int refcount;
};

#elif defined __linux__ && !defined ANDROID

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

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

    pthread_spinlock_t sl;
    int refcount;
};

#else

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

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

    pthread_mutex_t sl;
    int refcount;
};

#endif

void ImplMutex::init()
{
Andrey Kamaev's avatar
Andrey Kamaev committed
458 459
    impl = (Impl*)malloc(sizeof(Impl));
    impl->init();
460
}
Andrey Kamaev's avatar
Andrey Kamaev committed
461
void ImplMutex::destroy()
462
{
Andrey Kamaev's avatar
Andrey Kamaev committed
463 464 465
    impl->destroy();
    free(impl);
    impl = NULL;
466 467 468 469 470 471 472 473 474
}
void ImplMutex::lock() { impl->lock(); }
void ImplMutex::unlock() { impl->unlock(); }
bool ImplMutex::trylock() { return impl->trylock(); }

static int LockCallBack(void **mutex, AVLockOp op)
{
    ImplMutex* localMutex = reinterpret_cast<ImplMutex*>(*mutex);
    switch (op)
475
    {
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
        case AV_LOCK_CREATE:
            localMutex = reinterpret_cast<ImplMutex*>(malloc(sizeof(ImplMutex)));
            localMutex->init();
            *mutex = localMutex;
            if (!*mutex)
                return 1;
        break;

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

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

        case AV_LOCK_DESTROY:
            localMutex->destroy();
            free(localMutex);
            localMutex = NULL;
        break;
    }
    return 0;
}

static ImplMutex _mutex;
static bool _initialized = false;

class InternalFFMpegRegister
{
public:
    InternalFFMpegRegister()
508
    {
509 510 511
        _mutex.lock();
        if (!_initialized)
        {
512
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 13, 0)
513
            avformat_network_init();
514
    #endif
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
515

516 517
            /* register all codecs, demux and protocols */
            av_register_all();
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
518

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

522
            av_log_set_level(AV_LOG_ERROR);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
523

524 525 526
            _initialized = true;
        }
        _mutex.unlock();
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
527
    }
528

529 530 531 532
    ~InternalFFMpegRegister()
    {
        _initialized = false;
        av_lockmgr_register(NULL);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
533
    }
534 535 536
};

static InternalFFMpegRegister _init;
537 538 539 540 541 542 543

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

    close();
544

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
545 546 547
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    int err = avformat_open_input(&ic, _filename, NULL, NULL);
#else
548
    int err = av_open_input_file(&ic, _filename, NULL, 0, NULL);
549 550
#endif

551 552
    if (err < 0)
    {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
553 554
        CV_WARN("Error opening file");
        goto exit_func;
555
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
556
    err =
557
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
558 559 560 561
    avformat_find_stream_info(ic, NULL);
#else
    av_find_stream_info(ic);
#endif
562 563
    if (err < 0)
    {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
564 565
        CV_WARN("Could not find codec parameters");
        goto exit_func;
566
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
567 568
    for(i = 0; i < ic->nb_streams; i++)
    {
569 570 571 572 573 574
#if LIBAVFORMAT_BUILD > 4628
        AVCodecContext *enc = ic->streams[i]->codec;
#else
        AVCodecContext *enc = &ic->streams[i]->codec;
#endif

575 576 577
//#ifdef FF_API_THREAD_INIT
//        avcodec_thread_init(enc, get_number_of_cpus());
//#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
578
        enc->thread_count = get_number_of_cpus();
579
//#endif
580

581 582 583
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
#define AVMEDIA_TYPE_VIDEO CODEC_TYPE_VIDEO
#endif
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
584

585 586
        if( AVMEDIA_TYPE_VIDEO == enc->codec_type && video_stream < 0)
        {
gferry's avatar
gferry committed
587 588 589 590
            // backup encoder' width/height
            int enc_width = enc->width;
            int enc_height = enc->height;

591
            AVCodec *codec = avcodec_find_decoder(enc->codec_id);
592
            if (!codec ||
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
593 594 595 596 597
#if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
                avcodec_open2(enc, codec, NULL)
#else
                avcodec_open(enc, codec)
#endif
598 599
                < 0)
                goto exit_func;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
600

gferry's avatar
gferry committed
601 602 603 604
            // checking width/height (since decoder can sometimes alter it, eg. vp6f)
            if (enc_width && (enc->width != enc_width)) { enc->width = enc_width; }
            if (enc_height && (enc->height != enc_height)) { enc->height = enc_height; }

605 606 607 608 609
            video_stream = i;
            video_st = ic->streams[i];
            picture = avcodec_alloc_frame();

            rgb_picture.data[0] = (uint8_t*)malloc(
610 611
                    avpicture_get_size( PIX_FMT_BGR24,
                                        enc->width, enc->height ));
612
            avpicture_fill( (AVPicture*)&rgb_picture, rgb_picture.data[0],
613
                            PIX_FMT_BGR24, enc->width, enc->height );
614 615 616 617 618 619 620 621 622 623 624 625

            frame.width = enc->width;
            frame.height = enc->height;
            frame.cn = 3;
            frame.step = rgb_picture.linesize[0];
            frame.data = rgb_picture.data[0];
            break;
        }
    }

    if(video_stream >= 0) valid = true;

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
626
exit_func:
627 628 629 630 631 632 633 634 635 636 637 638 639

    if( !valid )
        close();

    return valid;
}


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

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
640 641
    int count_errs = 0;
    const int max_number_of_attempts = 1 << 16;
642

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
643
    if( !ic || !video_st )  return false;
644

645 646 647
    if( ic->streams[video_stream]->nb_frames > 0 &&
        frame_number > ic->streams[video_stream]->nb_frames )
        return false;
648

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
649
    av_free_packet (&packet);
650

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
651
    picture_pts = AV_NOPTS_VALUE_;
652 653

    // get the next frame
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
654 655
    while (!valid)
    {
656
        int ret = av_read_frame(ic, &packet);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
657 658 659 660 661 662
        if (ret == AVERROR(EAGAIN)) continue;

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

        if( packet.stream_index != video_stream )
        {
663
            av_free_packet (&packet);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
664 665 666
            count_errs++;
            if (count_errs > max_number_of_attempts)
                break;
667 668
            continue;
        }
669

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
670 671 672 673 674 675 676 677 678 679 680 681
        // Decode video frame
        #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
            avcodec_decode_video2(video_st->codec, picture, &got_picture, &packet);
        #elif LIBAVFORMAT_BUILD > 4628
                avcodec_decode_video(video_st->codec,
                                     picture, &got_picture,
                                     packet.data, packet.size);
        #else
                avcodec_decode_video(&video_st->codec,
                                     picture, &got_picture,
                                     packet.data, packet.size);
        #endif
682

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
683 684 685 686 687 688 689 690 691 692 693 694 695 696
        // Did we get a video frame?
        if(got_picture)
        {
            //picture_pts = picture->best_effort_timestamp;
            if( picture_pts == AV_NOPTS_VALUE_ )
                picture_pts = packet.pts != AV_NOPTS_VALUE_ && packet.pts != 0 ? packet.pts : packet.dts;
            frame_number++;
            valid = true;
        }
        else
        {
            count_errs++;
            if (count_errs > max_number_of_attempts)
                break;
697
        }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
698 699

        av_free_packet (&packet);
700 701
    }

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
702 703
    if( valid && first_frame_number < 0 )
        first_frame_number = dts_to_frame_number(picture_pts);
704

705 706 707 708 709 710 711 712 713 714
    // return if we have a new picture or not
    return valid;
}


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

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
715 716 717 718 719 720 721 722 723
    avpicture_fill((AVPicture*)&rgb_picture, rgb_picture.data[0], PIX_FMT_RGB24,
                   video_st->codec->width, video_st->codec->height);

    if( img_convert_ctx == NULL ||
        frame.width != video_st->codec->width ||
        frame.height != video_st->codec->height )
    {
        if( img_convert_ctx )
            sws_freeContext(img_convert_ctx);
724

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
        frame.width = video_st->codec->width;
        frame.height = video_st->codec->height;

        img_convert_ctx = sws_getCachedContext(
                NULL,
                video_st->codec->width, video_st->codec->height,
                video_st->codec->pix_fmt,
                video_st->codec->width, video_st->codec->height,
                PIX_FMT_BGR24,
                SWS_BICUBIC,
                NULL, NULL, NULL
                );

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

    sws_scale(
            img_convert_ctx,
            picture->data,
            picture->linesize,
            0, video_st->codec->height,
            rgb_picture.data,
            rgb_picture.linesize
            );

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
    *data = frame.data;
    *step = frame.step;
    *width = frame.width;
    *height = frame.height;
    *cn = frame.cn;

    return true;
}


double CvCapture_FFMPEG::getProperty( int property_id )
{
    if( !video_st ) return 0;

    switch( property_id )
    {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
767 768
    case CV_FFMPEG_CAP_PROP_POS_MSEC:
        return 1000.0*(double)frame_number/get_fps();
769
    case CV_FFMPEG_CAP_PROP_POS_FRAMES:
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
770
        return (double)frame_number;
771
    case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
772
        return r2d(ic->streams[video_stream]->time_base);
773
    case CV_FFMPEG_CAP_PROP_FRAME_COUNT:
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
774
        return (double)get_total_frames();
775 776 777 778 779 780
    case CV_FFMPEG_CAP_PROP_FRAME_WIDTH:
        return (double)frame.width;
    case CV_FFMPEG_CAP_PROP_FRAME_HEIGHT:
        return (double)frame.height;
    case CV_FFMPEG_CAP_PROP_FPS:
#if LIBAVCODEC_BUILD > 4753
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
781
        return av_q2d(video_st->r_frame_rate);
782 783
#else
        return (double)video_st->codec.frame_rate
784
                / (double)video_st->codec.frame_rate_base;
785 786 787 788 789 790 791
#endif
    case CV_FFMPEG_CAP_PROP_FOURCC:
#if LIBAVFORMAT_BUILD > 4628
        return (double)video_st->codec->codec_tag;
#else
        return (double)video_st->codec.codec_tag;
#endif
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
792
    default:
793
        break;
794
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
795

796 797 798
    return 0;
}

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
799 800 801 802 803 804
double CvCapture_FFMPEG::r2d(AVRational r)
{
    return r.num == 0 || r.den == 0 ? 0. : (double)r.num / (double)r.den;
}

double CvCapture_FFMPEG::get_duration_sec()
805
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
806 807 808
    double sec = (double)ic->duration / (double)AV_TIME_BASE;

    if (sec < eps_zero)
809
    {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
810
        sec = (double)ic->streams[video_stream]->duration * r2d(ic->streams[video_stream]->time_base);
811
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
812 813

    if (sec < eps_zero)
814
    {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
815
        sec = (double)ic->streams[video_stream]->duration * r2d(ic->streams[video_stream]->time_base);
816
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
817 818

    return sec;
819 820
}

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
821
int CvCapture_FFMPEG::get_bitrate()
822
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
823 824 825 826 827 828 829 830 831 832 833
    return ic->bit_rate;
}

double CvCapture_FFMPEG::get_fps()
{
    double fps = r2d(ic->streams[video_stream]->r_frame_rate);

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    if (fps < eps_zero)
    {
        fps = r2d(ic->streams[video_stream]->avg_frame_rate);
834
    }
835
#endif
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871

    if (fps < eps_zero)
    {
        fps = 1.0 / r2d(ic->streams[video_stream]->codec->time_base);
    }

    return fps;
}

int64_t CvCapture_FFMPEG::get_total_frames()
{
    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);
}

double CvCapture_FFMPEG::dts_to_sec(int64_t dts)
{
    return (double)(dts - ic->streams[video_stream]->start_time) *
        r2d(ic->streams[video_stream]->time_base);
}

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

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
873 874
    // 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
875
    if( first_frame_number < 0 && get_total_frames() > 1 )
876
        grabFrame();
877

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
878 879 880 881 882 883 884
    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);
885
        if (get_total_frames() > 1) av_seek_frame(ic, video_stream, time_stamp, AVSEEK_FLAG_BACKWARD);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
886 887 888 889
        avcodec_flush_buffers(ic->streams[video_stream]->codec);
        if( _frame_number > 0 )
        {
            grabFrame();
890

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
891 892 893 894 895
            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);
896

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
                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;
        }
923
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
924 925 926 927 928
}

void CvCapture_FFMPEG::seek(double sec)
{
    seek((int64_t)(sec * get_fps() + 0.5));
929
}
930 931 932 933 934 935 936 937 938 939 940 941 942 943

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

    switch( property_id )
    {
    case CV_FFMPEG_CAP_PROP_POS_MSEC:
    case CV_FFMPEG_CAP_PROP_POS_FRAMES:
    case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
        {
            switch( property_id )
            {
            case CV_FFMPEG_CAP_PROP_POS_FRAMES:
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
944
                seek((int64_t)value);
945 946 947
                break;

            case CV_FFMPEG_CAP_PROP_POS_MSEC:
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
948
                seek(value/1000.0);
949 950 951
                break;

            case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
952
                seek((int64_t)(value*ic->duration));
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
                break;
            }

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

    return true;
}


///////////////// FFMPEG CvVideoWriter implementation //////////////////////////
struct CvVideoWriter_FFMPEG
{
    bool open( const char* filename, int fourcc,
971
               double fps, int width, int height, bool isColor );
972 973 974 975 976
    void close();
    bool writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin );

    void init();

977
    AVOutputFormat  * fmt;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
978
    AVFormatContext * oc;
979 980 981 982 983 984 985 986 987
    uint8_t         * outbuf;
    uint32_t          outbuf_size;
    FILE            * outfile;
    AVFrame         * picture;
    AVFrame         * input_picture;
    uint8_t         * picbuf;
    AVStream        * video_st;
    int               input_pix_fmt;
    Image_FFMPEG      temp_image;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
988 989
    int               frame_width, frame_height;
    bool              ok;
990 991 992 993 994
    struct SwsContext *img_convert_ctx;
};

static const char * icvFFMPEGErrStr(int err)
{
995
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
996
    switch(err) {
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
    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;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1025
    }
1026
#else
1027 1028
    switch(err) {
    case AVERROR_NUMEXPECTED:
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1029
        return "Incorrect filename syntax";
1030
    case AVERROR_INVALIDDATA:
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1031
        return "Invalid data in header";
1032
    case AVERROR_NOFMT:
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1033
        return "Unknown format";
1034
    case AVERROR_IO:
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1035
        return "I/O error occurred";
1036
    case AVERROR_NOMEM:
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1037
        return "Memory allocation error";
1038
    default:
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1039
        break;
1040
    }
1041 1042
#endif

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1043
    return "Unspecified error";
1044 1045 1046 1047
}

/* function internal to FFMPEG (libavformat/riff.c) to lookup codec id by fourcc tag*/
extern "C" {
1048
    enum CV_CODEC_ID codec_get_bmp_id(unsigned int tag);
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
}

void CvVideoWriter_FFMPEG::init()
{
    fmt = 0;
    oc = 0;
    outbuf = 0;
    outbuf_size = 0;
    outfile = 0;
    picture = 0;
    input_picture = 0;
    picbuf = 0;
    video_st = 0;
    input_pix_fmt = 0;
    memset(&temp_image, 0, sizeof(temp_image));
    img_convert_ctx = 0;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1065 1066
    frame_width = frame_height = 0;
    ok = false;
1067 1068 1069 1070 1071 1072 1073 1074
}

/**
 * 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)
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    AVFrame * picture;
    uint8_t * picture_buf;
    int size;

    picture = avcodec_alloc_frame();
    if (!picture)
        return NULL;
    size = avpicture_get_size( (PixelFormat) pix_fmt, width, height);
    if(alloc){
        picture_buf = (uint8_t *) malloc(size);
        if (!picture_buf)
        {
            av_free(picture);
            return NULL;
        }
        avpicture_fill((AVPicture *)picture, picture_buf,
1091
                       (PixelFormat) pix_fmt, width, height);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1092 1093 1094 1095
    }
    else {
    }
    return picture;
1096 1097 1098 1099
}

/* add a video output stream to the container */
static AVStream *icv_add_video_stream_FFMPEG(AVFormatContext *oc,
1100
                                             CV_CODEC_ID codec_id,
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1101 1102
                                             int w, int h, int bitrate,
                                             double fps, int pixel_format)
1103
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1104 1105 1106 1107
    AVCodecContext *c;
    AVStream *st;
    int frame_rate, frame_rate_base;
    AVCodec *codec;
1108

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1109 1110 1111 1112 1113
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 10, 0)
    st = avformat_new_stream(oc, 0);
#else
    st = av_new_stream(oc, 0);
#endif
1114

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1115 1116 1117 1118
    if (!st) {
        CV_WARN("Could not allocate stream");
        return NULL;
    }
1119 1120

#if LIBAVFORMAT_BUILD > 4628
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1121
    c = st->codec;
1122
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1123
    c = &(st->codec);
1124 1125 1126
#endif

#if LIBAVFORMAT_BUILD > 4621
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1127
    c->codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
1128
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1129
    c->codec_id = oc->oformat->video_codec;
1130 1131
#endif

1132
    if(codec_id != CV_CODEC(CODEC_ID_NONE)){
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1133 1134
        c->codec_id = codec_id;
    }
1135 1136

    //if(codec_tag) c->codec_tag=codec_tag;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1137
    codec = avcodec_find_encoder(c->codec_id);
1138

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1139
    c->codec_type = AVMEDIA_TYPE_VIDEO;
1140

1141
#if LIBAVCODEC_BUILD >= CALC_FFMPEG_VERSION(54,25,0)
1142 1143 1144 1145 1146
    // Set per-codec defaults
    AVCodecID c_id = c->codec_id;
    avcodec_get_context_defaults3(c, codec);
    // avcodec_get_context_defaults3 erases codec_id for some reason
    c->codec_id = c_id;
1147
#endif
1148

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1149 1150 1151 1152 1153
    /* 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;
1154

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1155 1156 1157
    // took advice from
    // http://ffmpeg-users.933282.n4.nabble.com/warning-clipping-1-dct-coefficients-to-127-127-td934297.html
    c->qmin = 3;
1158

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1159 1160 1161 1162 1163 1164
    /* 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,
1165 1166
       timebase should be 1/framerate and timestamp increments should be
       identically 1. */
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1167 1168 1169 1170 1171 1172
    frame_rate=(int)(fps+0.5);
    frame_rate_base=1;
    while (fabs((double)frame_rate/frame_rate_base) - fps > 0.001){
        frame_rate_base*=10;
        frame_rate=(int)(fps*frame_rate_base + 0.5);
    }
1173 1174 1175
#if LIBAVFORMAT_BUILD > 4752
    c->time_base.den = frame_rate;
    c->time_base.num = frame_rate_base;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1176 1177 1178
    /* adjust time base for supported framerates */
    if(codec && codec->supported_framerates){
        const AVRational *p= codec->supported_framerates;
1179
        AVRational req = {frame_rate, frame_rate_base};
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
        const AVRational *best=NULL;
        AVRational best_error= {INT_MAX, 1};
        for(; p->den!=0; p++){
            AVRational error= av_sub_q(req, *p);
            if(error.num <0) error.num *= -1;
            if(av_cmp_q(error, best_error) < 0){
                best_error= error;
                best= p;
            }
        }
        c->time_base.den= best->num;
        c->time_base.num= best->den;
    }
1193
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1194 1195
    c->frame_rate = frame_rate;
    c->frame_rate_base = frame_rate_base;
1196 1197
#endif

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1198 1199
    c->gop_size = 12; /* emit one intra frame every twelve frames at most */
    c->pix_fmt = (PixelFormat) pixel_format;
1200

1201
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG2VIDEO)) {
1202 1203
        c->max_b_frames = 2;
    }
1204
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG1VIDEO) || c->codec_id == CV_CODEC(CODEC_ID_MSMPEG4V3)){
1205 1206 1207
        /* needed to avoid using macroblocks in which some coeffs overflow
           this doesnt happen with normal video, it just happens here as the
           motion of the chroma plane doesnt match the luma plane */
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1208
        /* avoid FFMPEG warning 'clipping 1 dct coefficients...' */
1209 1210
        c->mb_decision=2;
    }
1211 1212

#if LIBAVUTIL_BUILD > CALC_FFMPEG_VERSION(51,11,0)
1213 1214
    /* Some settings for libx264 encoding, restore dummy values for gop_size
     and qmin since they will be set to reasonable defaults by the libx264
1215
     preset system. Also, use a crf encode with the default quality rating,
1216
     this seems easier than finding an appropriate default bitrate. */
1217
    if (c->codec_id == CODEC_ID_H264) {
1218 1219 1220 1221 1222
      c->gop_size = -1;
      c->qmin = -1;
      c->bit_rate = 0;
      av_opt_set(c->priv_data,"crf","23", 0);
    }
1223 1224
#endif

1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
#if LIBAVCODEC_VERSION_INT>0x000409
    // some formats want stream headers to be seperate
    if(oc->oformat->flags & AVFMT_GLOBALHEADER)
    {
        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
    }
#endif

    return st;
}

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1236 1237
static const int OPENCV_NO_FRAMES_WRITTEN_CODE = 1000;

1238
static int icv_av_write_frame_FFMPEG( AVFormatContext * oc, AVStream * video_st, uint8_t * outbuf, uint32_t outbuf_size, AVFrame * picture )
1239 1240
{
#if LIBAVFORMAT_BUILD > 4628
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1241
    AVCodecContext * c = video_st->codec;
1242
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1243
    AVCodecContext * c = &(video_st->codec);
1244
#endif
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1245 1246
    int out_size;
    int ret = 0;
1247 1248 1249 1250 1251 1252 1253

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

1254 1255 1256
#ifndef PKT_FLAG_KEY
#define PKT_FLAG_KEY AV_PKT_FLAG_KEY
#endif
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1257 1258

        pkt.flags |= PKT_FLAG_KEY;
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
        pkt.stream_index= video_st->index;
        pkt.data= (uint8_t *)picture;
        pkt.size= sizeof(AVPicture);

        ret = av_write_frame(oc, &pkt);
    } else {
        /* encode the image */
        out_size = avcodec_encode_video(c, outbuf, outbuf_size, picture);
        /* if zero size, it means the image was buffered */
        if (out_size > 0) {
            AVPacket pkt;
            av_init_packet(&pkt);

#if LIBAVFORMAT_BUILD > 4752
1273
            if(c->coded_frame->pts != (int64_t)AV_NOPTS_VALUE)
1274
                pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st->time_base);
1275
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1276
            pkt.pts = c->coded_frame->pts;
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
#endif
            if(c->coded_frame->key_frame)
                pkt.flags |= PKT_FLAG_KEY;
            pkt.stream_index= video_st->index;
            pkt.data= outbuf;
            pkt.size= out_size;

            /* write the compressed frame in the media file */
            ret = av_write_frame(oc, &pkt);
        } else {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1287
            ret = OPENCV_NO_FRAMES_WRITTEN_CODE;
1288 1289
        }
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1290
    return ret;
1291 1292 1293 1294 1295
}

/// write a frame with FFMPEG
bool CvVideoWriter_FFMPEG::writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin )
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1296
    bool ret = false;
1297

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1298 1299 1300 1301
    if( (width & -2) != frame_width || (height & -2) != frame_height || !data )
        return false;
    width = frame_width;
    height = frame_height;
1302

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1303
    // typecast from opaque data type to implemented struct
1304 1305 1306
#if LIBAVFORMAT_BUILD > 4628
    AVCodecContext *c = video_st->codec;
#else
1307
    AVCodecContext *c = &(video_st->codec);
1308 1309 1310 1311
#endif

#if LIBAVFORMAT_BUILD < 5231
    // It is not needed in the latest versions of the ffmpeg
1312
    if( c->codec_id == CV_CODEC(CODEC_ID_RAWVIDEO) && origin != 1 )
1313 1314 1315 1316 1317 1318 1319
    {
        if( !temp_image.data )
        {
            temp_image.step = (width*cn + 3) & -4;
            temp_image.width = width;
            temp_image.height = height;
            temp_image.cn = cn;
Alexander Shishkov's avatar
Alexander Shishkov committed
1320
            temp_image.data = (unsigned char*)malloc(temp_image.step*temp_image.height);
1321 1322 1323 1324 1325 1326
        }
        for( int y = 0; y < height; y++ )
            memcpy(temp_image.data + y*temp_image.step, data + (height-1-y)*step, width*cn);
        data = temp_image.data;
        step = temp_image.step;
    }
Alexander Shishkov's avatar
Alexander Shishkov committed
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
#else
    if( width*cn != step )
    {
        if( !temp_image.data )
        {
            temp_image.step = width*cn;
            temp_image.width = width;
            temp_image.height = height;
            temp_image.cn = cn;
            temp_image.data = (unsigned char*)malloc(temp_image.step*temp_image.height);
        }
        if (origin == 1)
            for( int y = 0; y < height; y++ )
                memcpy(temp_image.data + y*temp_image.step, data + (height-1-y)*step, temp_image.step);
        else
            for( int y = 0; y < height; y++ )
                memcpy(temp_image.data + y*temp_image.step, data + y*step, temp_image.step);
        data = temp_image.data;
        step = temp_image.step;
    }
1347 1348 1349 1350 1351 1352 1353 1354
#endif

    // check parameters
    if (input_pix_fmt == PIX_FMT_BGR24) {
        if (cn != 3) {
            return false;
        }
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1355
    else if (input_pix_fmt == PIX_FMT_GRAY8) {
1356 1357 1358 1359
        if (cn != 1) {
            return false;
        }
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1360
    else {
1361 1362 1363
        assert(false);
    }

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1364 1365 1366 1367
    if ( c->pix_fmt != input_pix_fmt ) {
        assert( input_picture );
        // let input_picture point to the raw data buffer of 'image'
        avpicture_fill((AVPicture *)input_picture, (uint8_t *) data,
1368
                       (PixelFormat)input_pix_fmt, width, height);
1369

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
        if( !img_convert_ctx )
        {
            img_convert_ctx = sws_getContext(width,
                                             height,
                                             (PixelFormat)input_pix_fmt,
                                             c->width,
                                             c->height,
                                             c->pix_fmt,
                                             SWS_BICUBIC,
                                             NULL, NULL, NULL);
            if( !img_convert_ctx )
                return false;
        }
1383 1384 1385 1386 1387 1388

        if ( sws_scale(img_convert_ctx, input_picture->data,
                       input_picture->linesize, 0,
                       height,
                       picture->data, picture->linesize) < 0 )
            return false;
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1389 1390 1391
    }
    else{
        avpicture_fill((AVPicture *)picture, (uint8_t *) data,
1392
                       (PixelFormat)input_pix_fmt, width, height);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1393
    }
1394

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1395
    ret = icv_av_write_frame_FFMPEG( oc, video_st, outbuf, outbuf_size, picture) >= 0;
1396

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1397
    return ret;
1398 1399 1400 1401 1402
}

/// close video output stream and free associated memory
void CvVideoWriter_FFMPEG::close()
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1403 1404 1405
    // nothing to do if already released
    if ( !picture )
        return;
1406

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1407 1408 1409 1410
    /* 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?
1411

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
    /* write the trailer, if any */
    if(ok && oc)
    {
        if( (oc->oformat->flags & AVFMT_RAWPICTURE) == 0 )
        {
            for(;;)
            {
                int ret = icv_av_write_frame_FFMPEG( oc, video_st, outbuf, outbuf_size, NULL);
                if( ret == OPENCV_NO_FRAMES_WRITTEN_CODE || ret < 0 )
                    break;
            }
        }
        av_write_trailer(oc);
    }
1426

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1427 1428 1429 1430 1431
    if( img_convert_ctx )
    {
        sws_freeContext(img_convert_ctx);
        img_convert_ctx = 0;
    }
1432

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1433
    // free pictures
1434
#if LIBAVFORMAT_BUILD > 4628
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1435
    if( video_st->codec->pix_fmt != input_pix_fmt)
1436
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1437
    if( video_st->codec.pix_fmt != input_pix_fmt)
1438
#endif
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1439 1440 1441 1442 1443 1444
    {
        if(picture->data[0])
            free(picture->data[0]);
        picture->data[0] = 0;
    }
    av_free(picture);
1445

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1446 1447
    if (input_picture)
        av_free(input_picture);
1448

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1449
    /* close codec */
1450
#if LIBAVFORMAT_BUILD > 4628
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1451
    avcodec_close(video_st->codec);
1452
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1453
    avcodec_close(&(video_st->codec));
1454 1455
#endif

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1456
    av_free(outbuf);
1457

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1458 1459 1460
    if (!(fmt->flags & AVFMT_NOFILE))
    {
        /* close the output file */
1461

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1462
#if LIBAVCODEC_VERSION_INT < ((52<<16)+(123<<8)+0)
1463
#if LIBAVCODEC_VERSION_INT >= ((51<<16)+(49<<8)+0)
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1464
        url_fclose(oc->pb);
1465
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1466 1467 1468 1469
        url_fclose(&oc->pb);
#endif
#else
        avio_close(oc->pb);
1470 1471
#endif

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1472
    }
1473

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1474
    /* free the stream */
1475
    avformat_free_context(oc);
1476

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1477 1478 1479 1480
    if( temp_image.data )
    {
        free(temp_image.data);
        temp_image.data = 0;
1481
    }
1482

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1483 1484
    init();
}
1485

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1486 1487 1488 1489
/// Create a video writer object that uses FFMPEG
bool CvVideoWriter_FFMPEG::open( const char * filename, int fourcc,
                                 double fps, int width, int height, bool is_color )
{
1490
    CV_CODEC_ID codec_id = CV_CODEC(CODEC_ID_NONE);
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1491 1492
    int err, codec_pix_fmt;
    double bitrate_scale = 1;
1493

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1494
    close();
1495

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1496 1497 1498 1499 1500
    // check arguments
    if( !filename )
        return false;
    if(fps <= 0)
        return false;
1501

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1502 1503 1504 1505 1506 1507 1508
    // 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;
1509

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1510
    /* auto detect the output format from the name and fourcc code. */
1511

1512
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1513
    fmt = av_guess_format(NULL, filename, NULL);
1514
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1515
    fmt = guess_format(NULL, filename, NULL);
1516
#endif
1517

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1518 1519
    if (!fmt)
        return false;
1520

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1521 1522 1523 1524 1525 1526 1527
    /* determine optimal pixel format */
    if (is_color) {
        input_pix_fmt = PIX_FMT_BGR24;
    }
    else {
        input_pix_fmt = PIX_FMT_GRAY8;
    }
1528

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1529
    /* Lookup codec_id for given fourcc */
1530
#if LIBAVCODEC_VERSION_INT<((51<<16)+(49<<8)+0)
1531
    if( (codec_id = codec_get_bmp_id( fourcc )) == CV_CODEC(CODEC_ID_NONE) )
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1532
        return false;
1533
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1534
    const struct AVCodecTag * tags[] = { codec_bmp_tags, NULL};
1535
    if( (codec_id = av_codec_get_id(tags, fourcc)) == CV_CODEC(CODEC_ID_NONE) )
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1536
        return false;
1537 1538
#endif

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1539
    // alloc memory for context
1540
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1541
    oc = avformat_alloc_context();
1542
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1543
    oc = av_alloc_format_context();
1544
#endif
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1545
    assert (oc);
1546

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1547 1548 1549
    /* set file name */
    oc->oformat = fmt;
    snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
1550

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1551 1552
    /* set some options */
    oc->max_delay = (int)(0.7*AV_TIME_BASE);  /* This reduces buffer underrun warnings with MPEG */
1553

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1554 1555
    // set a few optimal pixel formats for lossless codecs of interest..
    switch (codec_id) {
1556
#if LIBAVCODEC_VERSION_INT>((50<<16)+(1<<8)+0)
1557
    case CV_CODEC(CODEC_ID_JPEGLS):
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1558 1559 1560
        // BGR24 or GRAY8 depending on is_color...
        codec_pix_fmt = input_pix_fmt;
        break;
1561
#endif
1562
    case CV_CODEC(CODEC_ID_HUFFYUV):
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1563 1564
        codec_pix_fmt = PIX_FMT_YUV422P;
        break;
1565 1566
    case CV_CODEC(CODEC_ID_MJPEG):
    case CV_CODEC(CODEC_ID_LJPEG):
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1567 1568 1569
        codec_pix_fmt = PIX_FMT_YUVJ420P;
        bitrate_scale = 3;
        break;
1570
    case CV_CODEC(CODEC_ID_RAWVIDEO):
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1571 1572 1573 1574 1575 1576 1577 1578 1579
        codec_pix_fmt = input_pix_fmt == PIX_FMT_GRAY8 ||
                        input_pix_fmt == PIX_FMT_GRAY16LE ||
                        input_pix_fmt == PIX_FMT_GRAY16BE ? input_pix_fmt : PIX_FMT_YUV420P;
        break;
    default:
        // good for lossy formats, MPEG, etc.
        codec_pix_fmt = PIX_FMT_YUV420P;
        break;
    }
1580

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1581
    double bitrate = MIN(bitrate_scale*fps*width*height, (double)INT_MAX/2);
1582

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1583 1584 1585 1586
    // TODO -- safe to ignore output audio stream?
    video_st = icv_add_video_stream_FFMPEG(oc, codec_id,
                                           width, height, (int)(bitrate + 0.5),
                                           fps, codec_pix_fmt);
1587

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1588 1589 1590 1591 1592 1593 1594
    /* set the output parameters (must be done even if no
   parameters). */
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
    if (av_set_parameters(oc, NULL) < 0) {
        return false;
    }
#endif
1595

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1596 1597 1598
#if 0
#if FF_API_DUMP_FORMAT
    dump_format(oc, 0, filename, 1);
1599
#else
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1600 1601
    av_dump_format(oc, 0, filename, 1);
#endif
1602 1603
#endif

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1604 1605 1606 1607
    /* now that all the parameters are set, we can open the audio and
     video codecs and allocate the necessary encode buffers */
    if (!video_st){
        return false;
1608
    }
1609

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1610 1611
    AVCodec *codec;
    AVCodecContext *c;
1612

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1613 1614 1615 1616 1617
#if LIBAVFORMAT_BUILD > 4628
    c = (video_st->codec);
#else
    c = &(video_st->codec);
#endif
1618

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
    c->codec_tag = fourcc;
    /* find the video encoder */
    codec = avcodec_find_encoder(c->codec_id);
    if (!codec) {
        fprintf(stderr, "Could not find encoder for codec id %d: %s", c->codec_id, icvFFMPEGErrStr(
        #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
                AVERROR_ENCODER_NOT_FOUND
        #else
                -1
        #endif
                ));
        return false;
1631
    }
1632

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1633 1634 1635 1636 1637
    int64_t lbit_rate = (int64_t)c->bit_rate;
    lbit_rate += (bitrate / 2);
    lbit_rate = std::min(lbit_rate, (int64_t)INT_MAX);
    c->bit_rate_tolerance = (int)lbit_rate;
    c->bit_rate = (int)lbit_rate;
1638

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
    /* open the codec */
    if ((err=
#if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
         avcodec_open2(c, codec, NULL)
#else
         avcodec_open(c, codec)
#endif
         ) < 0) {
        fprintf(stderr, "Could not open codec '%s': %s", codec->name, icvFFMPEGErrStr(err));
        return false;
1649
    }
1650

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1651
    outbuf = NULL;
1652

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1653 1654 1655 1656 1657
    if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
        /* allocate output buffer */
        /* assume we will never get codec output with more than 4 bytes per pixel... */
        outbuf_size = width*height*4;
        outbuf = (uint8_t *) av_malloc(outbuf_size);
1658
    }
1659

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1660 1661
    bool need_color_convert;
    need_color_convert = (c->pix_fmt != input_pix_fmt);
1662

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1663 1664 1665 1666
    /* allocate the encoded raw picture */
    picture = icv_alloc_picture_FFMPEG(c->pix_fmt, c->width, c->height, need_color_convert);
    if (!picture) {
        return false;
1667
    }
1668

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1669 1670 1671 1672 1673 1674 1675 1676
    /* if the output format is not our input format, then a temporary
   picture of the input format is needed too. It is then converted
   to the required output format */
    input_picture = NULL;
    if ( need_color_convert ) {
        input_picture = icv_alloc_picture_FFMPEG(input_pix_fmt, c->width, c->height, false);
        if (!input_picture) {
            return false;
1677
        }
1678 1679
    }

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
    /* open the output file, if needed */
    if (!(fmt->flags & AVFMT_NOFILE)) {
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0)
#else
            if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0)
#endif
            {
            return false;
        }
1690
    }
1691

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1692 1693 1694 1695 1696
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    /* write the stream header, if any */
    err=avformat_write_header(oc, NULL);
#else
    err=av_write_header( oc );
1697 1698
#endif

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1699
    if(err < 0)
1700
    {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1701 1702 1703
        close();
        remove(filename);
        return false;
1704
    }
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1705 1706 1707
    frame_width = width;
    frame_height = height;
    ok = true;
1708

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1709
    return true;
1710 1711 1712 1713
}



Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1714
CvCapture_FFMPEG* cvCreateFileCapture_FFMPEG( const char* filename )
1715
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1716 1717 1718 1719
    CvCapture_FFMPEG* capture = (CvCapture_FFMPEG*)malloc(sizeof(*capture));
    capture->init();
    if( capture->open( filename ))
        return capture;
1720

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1721 1722 1723
    capture->close();
    free(capture);
    return 0;
1724 1725
}

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1726 1727

void cvReleaseCapture_FFMPEG(CvCapture_FFMPEG** capture)
1728
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1729
    if( capture && *capture )
1730
    {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1731 1732 1733
        (*capture)->close();
        free(*capture);
        *capture = 0;
1734 1735 1736
    }
}

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1737
int cvSetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id, double value)
1738
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1739
    return capture->setProperty(prop_id, value);
1740 1741
}

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1742
double cvGetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id)
1743
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1744
    return capture->getProperty(prop_id);
1745 1746
}

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1747
int cvGrabFrame_FFMPEG(CvCapture_FFMPEG* capture)
1748
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1749
    return capture->grabFrame();
1750
}
1751

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1752
int cvRetrieveFrame_FFMPEG(CvCapture_FFMPEG* capture, unsigned char** data, int* step, int* width, int* height, int* cn)
1753
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1754
    return capture->retrieveFrame(0, data, step, width, height, cn);
1755 1756
}

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1757 1758
CvVideoWriter_FFMPEG* cvCreateVideoWriter_FFMPEG( const char* filename, int fourcc, double fps,
                                                  int width, int height, int isColor )
1759
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1760 1761 1762 1763 1764 1765 1766
    CvVideoWriter_FFMPEG* writer = (CvVideoWriter_FFMPEG*)malloc(sizeof(*writer));
    writer->init();
    if( writer->open( filename, fourcc, fps, width, height, isColor != 0 ))
        return writer;
    writer->close();
    free(writer);
    return 0;
1767 1768
}

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1769 1770 1771
void cvReleaseVideoWriter_FFMPEG( CvVideoWriter_FFMPEG** writer )
{
    if( writer && *writer )
1772
    {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1773 1774 1775
        (*writer)->close();
        free(*writer);
        *writer = 0;
1776 1777 1778 1779
    }
}


Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1780 1781 1782
int cvWriteFrame_FFMPEG( CvVideoWriter_FFMPEG* writer,
                         const unsigned char* data, int step,
                         int width, int height, int cn, int origin)
1783
{
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
1784
    return writer->writeFrame(data, step, width, height, cn, origin);
1785 1786
}

1787 1788 1789 1790 1791 1792 1793 1794 1795 1796


/*
 * For CUDA encoder
 */

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

1798 1799 1800
    void write(unsigned char* data, int size, int keyFrame);

    // add a video output stream to the container
1801
    static AVStream* addVideoStream(AVFormatContext *oc, CV_CODEC_ID codec_id, int w, int h, int bitrate, double fps, PixelFormat pixel_format);
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847

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

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

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

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

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

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

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

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

1848
AVStream* OutputMediaStream_FFMPEG::addVideoStream(AVFormatContext *oc, CV_CODEC_ID codec_id, int w, int h, int bitrate, double fps, PixelFormat pixel_format)
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
{
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 10, 0)
        AVStream* st = avformat_new_stream(oc, 0);
    #else
        AVStream* st = av_new_stream(oc, 0);
    #endif
    if (!st)
        return 0;

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

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

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

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

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

    AVCodec* codec = avcodec_find_encoder(c->codec_id);

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

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

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

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

1910
                if (error.num < 0)
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
                    error.num *= -1;

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

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

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

1928
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG2VIDEO))
1929 1930
        c->max_b_frames = 2;

1931
    if (c->codec_id == CV_CODEC(CODEC_ID_MPEG1VIDEO) || c->codec_id == CV_CODEC(CODEC_ID_MSMPEG4V3))
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 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
    {
        // needed to avoid using macroblocks in which some coeffs overflow
        // this doesnt happen with normal video, it just happens here as the
        // motion of the chroma plane doesnt match the luma plane

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

        c->mb_decision = 2;
    }

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

    return st;
}

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

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

1968
    CV_CODEC_ID codec_id = CV_CODEC(CODEC_ID_H264);
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037

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

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

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

    // set a few optimal pixel formats for lossless codecs of interest..
    PixelFormat codec_pix_fmt = PIX_FMT_YUV420P;
    int bitrate_scale = 64;

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

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

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

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

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

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

        if (err != 0)
            return false;
    }

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

    return true;
}

void OutputMediaStream_FFMPEG::write(unsigned char* data, int size, int keyFrame)
{
    // if zero size, it means the image was buffered
2038
    if (size > 0)
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
    {
        AVPacket pkt;
        av_init_packet(&pkt);

        if (keyFrame)
            pkt.flags |= PKT_FLAG_KEY;

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

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

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

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

    stream->close();
    free(stream);
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 2092 2093 2094 2095 2096 2097 2098
    return 0;
}

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

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

/*
 * For CUDA decoder
 */

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

    // Uncompressed YUV
    VideoCodec_YUV420 = (('I'<<24)|('Y'<<16)|('U'<<8)|('V')),   // Y,U,V (4:2:0)
    VideoCodec_YV12   = (('Y'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,V,U (4:2:0)
    VideoCodec_NV12   = (('N'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,UV  (4:2:0)
    VideoCodec_YUYV   = (('Y'<<24)|('U'<<16)|('Y'<<8)|('V')),   // YUYV/YUY2 (4:2:2)
Ilya Lavrenov's avatar
Ilya Lavrenov committed
2099
    VideoCodec_UYVY   = (('U'<<24)|('Y'<<16)|('V'<<8)|('Y'))    // UYVY (4:2:2)
2100 2101 2102 2103 2104 2105 2106
};

enum
{
    VideoChromaFormat_Monochrome = 0,
    VideoChromaFormat_YUV420,
    VideoChromaFormat_YUV422,
Ilya Lavrenov's avatar
Ilya Lavrenov committed
2107
    VideoChromaFormat_YUV444
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
};

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

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

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

    AVFormatContext* ctx_;
    int video_stream_id_;
    AVPacket pkt_;
};

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

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

    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 13, 0)
        avformat_network_init();
    #endif

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

2147
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 6, 0)
2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
        err = avformat_find_stream_info(ctx_, 0);
    #else
        err = av_find_stream_info(ctx_);
    #endif
    if (err < 0)
        return false;

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

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

            switch (enc->codec_id)
            {
2169
            case CV_CODEC(CODEC_ID_MPEG1VIDEO):
2170 2171 2172
                *codec = ::VideoCodec_MPEG1;
                break;

2173
            case CV_CODEC(CODEC_ID_MPEG2VIDEO):
2174 2175 2176
                *codec = ::VideoCodec_MPEG2;
                break;

2177
            case CV_CODEC(CODEC_ID_MPEG4):
2178 2179 2180
                *codec = ::VideoCodec_MPEG4;
                break;

2181
            case CV_CODEC(CODEC_ID_VC1):
2182 2183 2184
                *codec = ::VideoCodec_VC1;
                break;

2185
            case CV_CODEC(CODEC_ID_H264):
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257
                *codec = ::VideoCodec_H264;
                break;

            default:
                return false;
            };

            switch (enc->pix_fmt)
            {
            case PIX_FMT_YUV420P:
                *chroma_format = ::VideoChromaFormat_YUV420;
                break;

            case PIX_FMT_YUV422P:
                *chroma_format = ::VideoChromaFormat_YUV422;
                break;

            case PIX_FMT_YUV444P:
                *chroma_format = ::VideoChromaFormat_YUV444;
                break;

            default:
                return false;
            }

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

            break;
        }
    }

    if (video_stream_id_ < 0)
        return false;

    av_init_packet(&pkt_);

    return true;
}

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

    // free last packet if exist
    if (pkt_.data)
        av_free_packet(&pkt_);
}

bool InputMediaStream_FFMPEG::read(unsigned char** data, int* size, int* endOfFile)
{
    // free last packet if exist
    if (pkt_.data)
        av_free_packet(&pkt_);

    // get the next frame
    for (;;)
    {
        int ret = av_read_frame(ctx_, &pkt_);

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

        if (ret < 0)
        {
2258
            if (ret == (int)AVERROR_EOF)
2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
                *endOfFile = true;
            return false;
        }

        if (pkt_.stream_index != video_stream_id_)
        {
            av_free_packet(&pkt_);
            continue;
        }

        break;
    }

    *data = pkt_.data;
    *size = pkt_.size;
    *endOfFile = false;

    return true;
}

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

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

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

    return 0;
}

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

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