vtkFFMPEGVideoSource.cxx 24.4 KB
Newer Older
Ken Martin's avatar
Ken Martin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkFFMPEGVideoSource.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkFFMPEGVideoSource.h"

17
#include "vtkConditionVariable.h"
Ken Martin's avatar
Ken Martin committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "vtkCriticalSection.h"
#include "vtkMultiThreader.h"
#include "vtkMutexLock.h"
#include "vtkObjectFactory.h"
#include "vtkTimerLog.h"
#include "vtkUnsignedCharArray.h"
#include "vtksys/SystemTools.hxx"

extern "C" {
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
}

#include <cctype>

/////////////////////////////////////////////////////////////////////////
// building ffmpeg on windows
//
// vs2017 shell
//
// inside it run msys_command.cmd
//
40
41
42
// if building libvpx make sure to add -enable-libvpx to the ffmpeg configure line
// and do the following
//
Ken Martin's avatar
Ken Martin committed
43
44
45
46
47
48
49
50
// export INCLUDE="C:\ffmpeg\include"\;$INCLUDE
// export LIB="C:\ffmpeg\lib;C:\ffmpeg\lib\x64"\;$LIB
//
// ./configure --target=x86_64-win64-vs15 --enable-vp8 --enable-vp9 --prefix=/c/ffmpeg
// make
// make install
// rename to vpx.lib
//
51
52
53
// Then to build ffmpeg as follows
//
// ./configure --enable-asm --enable-x86asm --arch=amd64  --disable-avdevice --enable-swscale --disable-doc --disable-ffplay --disable-ffprobe --disable-ffmpeg --enable-shared --disable-static --disable-bzlib --disable-libopenjpeg --disable-iconv --disable-zlib --prefix=/c/ffmpeg --toolchain=msvc
Ken Martin's avatar
Ken Martin committed
54
55
56
57
58
59
60
61
// make
// make install
//
// add libs to vtk build, I just add them to the FFMPEG_LIBAVCODEC_LIBRARIES variable
//
// Ws2_32.lib
// Bcrypt.lib
// Secur32.dll
62
//
Ken Martin's avatar
Ken Martin committed
63
64
65
66
67
68
/////////////////////////////////////////////////////////////////////////

class vtkFFMPEGVideoSourceInternal
{
public:
  vtkFFMPEGVideoSourceInternal() {}
69
70
71
72
73
74
75
  void ReleaseSystemResources()
  {
    if (this->Frame)
    {
      av_frame_free(&this->Frame);
      this->Frame = nullptr;
    }
76
77
78
79
80
    if (this->AudioFrame)
    {
      av_frame_free(&this->AudioFrame);
      this->AudioFrame = nullptr;
    }
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
    if (this->VideoDecodeContext)
    {
      avcodec_close(this->VideoDecodeContext);
      this->VideoDecodeContext = nullptr;
    }
    if (this->AudioDecodeContext)
    {
      avcodec_close(this->AudioDecodeContext);
      this->AudioDecodeContext = nullptr;
    }
    if (this->FormatContext)
    {
      avformat_close_input(&this->FormatContext);
      this->FormatContext = nullptr;
    }
    if (this->RGBContext)
    {
      sws_freeContext(this->RGBContext);
      this->RGBContext = nullptr;
    }
  }

Ken Martin's avatar
Ken Martin committed
103
104
105
106
107
108
109
110
  AVFormatContext *FormatContext = nullptr;
  AVCodecContext *VideoDecodeContext = nullptr;
  AVCodecContext *AudioDecodeContext = nullptr;
  AVStream *VideoStream = nullptr;
  AVStream *AudioStream = nullptr;
  int VideoStreamIndex = -1;
  int AudioStreamIndex = -1;
  AVFrame *Frame = nullptr;
111
  AVFrame *AudioFrame = nullptr;
Ken Martin's avatar
Ken Martin committed
112
  AVPacket Packet;
113
  struct SwsContext* RGBContext = nullptr;
Ken Martin's avatar
Ken Martin committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
};

vtkStandardNewMacro(vtkFFMPEGVideoSource);

//----------------------------------------------------------------------------
vtkFFMPEGVideoSource::vtkFFMPEGVideoSource()
{
  this->Internal = new vtkFFMPEGVideoSourceInternal;
  this->Initialized = 0;
  this->FileName = nullptr;

  this->FrameRate = 30;
  this->OutputFormat = VTK_RGB;
  this->NumberOfScalarComponents = 3;
  this->FrameBufferBitsPerPixel = 24;
  this->FlipFrames = 0;
  this->FrameBufferRowAlignment = 4;
  this->EndOfFile = true;
132
133
134
  this->AudioCallback = nullptr;
  this->AudioCallbackClientData = nullptr;
  this->DecodingThreads = 4;
Ken Martin's avatar
Ken Martin committed
135
136
137
  this->FeedThreadId = -1;
  this->DrainThreadId = -1;
  this->DrainAudioThreadId = -1;
Ken Martin's avatar
Ken Martin committed
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
}

//----------------------------------------------------------------------------
vtkFFMPEGVideoSource::~vtkFFMPEGVideoSource()
{
  this->vtkFFMPEGVideoSource::ReleaseSystemResources();
  delete [] this->FileName;
  delete this->Internal;
}

//----------------------------------------------------------------------------
void vtkFFMPEGVideoSource::Initialize()
{
  if (this->Initialized)
  {
    return;
  }

  // Preliminary update of frame buffer, just in case we don't get
  // though the initialization but need the framebuffer for Updates
  this->UpdateFrameBuffer();

160
161
162
163
#ifdef NDEBUG
  av_log_set_level(AV_LOG_ERROR);
#endif

Ken Martin's avatar
Ken Martin committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
  /* open input file, and allocate format context */
  if (avformat_open_input(&this->Internal->FormatContext, this->FileName, nullptr, nullptr) < 0)
  {
    vtkErrorMacro("Could not open source file " << this->FileName);
    return;
  }

  // local var to keep the code shorter
  AVFormatContext *fcontext = this->Internal->FormatContext;

  /* retrieve stream information */
  if (avformat_find_stream_info(fcontext, nullptr) < 0)
  {
    vtkErrorMacro("Could not find stream information");
    return;
  }

  this->Internal->VideoStreamIndex =
    av_find_best_stream(fcontext, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
  if (this->Internal->VideoStreamIndex < 0)
  {
    vtkErrorMacro("Could not find video stream in input file ");
    return;
  }

  this->Internal->VideoStream =
    fcontext->streams[this->Internal->VideoStreamIndex];

  AVCodec *dec =
    avcodec_find_decoder(this->Internal->VideoStream->codecpar->codec_id);
  if (!dec)
  {
    vtkErrorMacro("Failed to find codec for video");
    return;
  }
  this->Internal->VideoDecodeContext = avcodec_alloc_context3(dec);
200
201
202
203

  this->Internal->VideoDecodeContext->thread_count = this->DecodingThreads;
  // this->Internal->VideoDecodeContext->thread_type = FF_THREAD_FRAME;

Ken Martin's avatar
Ken Martin committed
204
205
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
234
235
236
237
238
  avcodec_parameters_to_context(
    this->Internal->VideoDecodeContext,
    this->Internal->VideoStream->codecpar);
  avcodec_open2(this->Internal->VideoDecodeContext, dec, nullptr);

  AVDictionary *opts = nullptr;
  /* Init the decoders, with or without reference counting */
  av_dict_set(&opts, "refcounted_frames", "1", 0);
  if (avcodec_open2(this->Internal->VideoDecodeContext, dec, &opts) < 0)
  {
    vtkErrorMacro("Failed to open codec for video");
    return;
  }

  this->SetFrameRate(static_cast<double>(this->Internal->VideoStream->r_frame_rate.num)/
    this->Internal->VideoStream->r_frame_rate.den);

  this->SetFrameSize(
    this->Internal->VideoDecodeContext->width,
    this->Internal->VideoDecodeContext->height,
    1);

  // create a something to RGB converter
  this->Internal->RGBContext = sws_getContext(
     this->Internal->VideoDecodeContext->width,
     this->Internal->VideoDecodeContext->height,
     this->Internal->VideoDecodeContext->pix_fmt,
     this->Internal->VideoDecodeContext->width,
     this->Internal->VideoDecodeContext->height,
     AV_PIX_FMT_RGB24, SWS_FAST_BILINEAR, NULL, NULL, NULL);
  if (!this->Internal->RGBContext)
  {
    vtkErrorMacro("Failed to create RGB context");
  }

239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
  // now handle audio streams, these are optional
  this->Internal->AudioStreamIndex =
    av_find_best_stream(fcontext, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0);
  // do we have an audio stream?
  if (this->Internal->AudioStreamIndex >= 0)
  {
    this->Internal->AudioStream =
      fcontext->streams[this->Internal->AudioStreamIndex];

    AVCodec *adec =
      avcodec_find_decoder(this->Internal->AudioStream->codecpar->codec_id);
    if (!adec)
    {
      vtkErrorMacro("Failed to find codec for audio");
      return;
    }

    this->Internal->AudioDecodeContext = avcodec_alloc_context3(adec);
    avcodec_parameters_to_context(
      this->Internal->AudioDecodeContext,
      this->Internal->AudioStream->codecpar);
    avcodec_open2(this->Internal->AudioDecodeContext, adec, nullptr);

    AVDictionary *aopts = nullptr;
    /* Init the decoders, with or without reference counting */
    av_dict_set(&aopts, "refcounted_frames", "1", 0);
    if (avcodec_open2(this->Internal->AudioDecodeContext, adec, &aopts) < 0)
    {
      vtkErrorMacro("Failed to open codec for audio");
      return;
    }

    this->Internal->AudioFrame = av_frame_alloc();
    if (!this->Internal->AudioFrame)
    {
      vtkErrorMacro("Could not allocate audio frame");
      return;
    }
  }

  this->EndOfFile = false;
Ken Martin's avatar
Ken Martin committed
280
281
282
283
284
285
286
287
288
289

  this->Internal->Frame = av_frame_alloc();
  if (!this->Internal->Frame)
  {
    vtkErrorMacro("Could not allocate frame");
    return;
  }

  /* initialize packet, set data to NULL, let the demuxer fill it */
  av_init_packet(&this->Internal->Packet);
290
  this->Internal->Packet.data = nullptr;
Ken Martin's avatar
Ken Martin committed
291
292
293
294
295
296
297
298
299
300
  this->Internal->Packet.size = 0;

  // update framebuffer again to reflect any changes which
  // might have occurred
  this->UpdateFrameBuffer();

  this->Initialized = 1;
}

//----------------------------------------------------------------------------
301
302
// Feed frames to the decoder
void *vtkFFMPEGVideoSource::FeedThread(vtkMultiThreader::ThreadInfo *data)
Ken Martin's avatar
Ken Martin committed
303
{
304
305
306
  vtkFFMPEGVideoSource *self = static_cast<vtkFFMPEGVideoSource *>(data->UserData);
  return self->Feed(data);
}
Ken Martin's avatar
Ken Martin committed
307

308
309
310
311
312
313
314
315
316
317
318
319
//
// based off of https://blogs.gentoo.org/lu_zero/2016/03/29/new-avcodec-api/
//
void *vtkFFMPEGVideoSource::Feed(vtkMultiThreader::ThreadInfo *data)
{
  bool done = false;

  unsigned short count = 0;
  bool retryPacket = false;
  int fret = AVERROR_EOF;

  while (!done)
Ken Martin's avatar
Ken Martin committed
320
  {
321
322
323
324
325
326
327
    // read in the packet
    if (!retryPacket)
    {
      av_packet_unref(&this->Internal->Packet);
      fret = av_read_frame(this->Internal->FormatContext, &this->Internal->Packet);
    }
    retryPacket = false;
328
    // feed video
329
330
    if (fret >= 0 &&
        this->Internal->Packet.stream_index == this->Internal->VideoStreamIndex)
Ken Martin's avatar
Ken Martin committed
331
    {
332
333
      // lock the decoder
      this->FeedMutex->Lock();
Ken Martin's avatar
Ken Martin committed
334

335
336
337
338
      int sret = avcodec_send_packet(
        this->Internal->VideoDecodeContext,
        &this->Internal->Packet);
      if (sret == 0) // good decode
Ken Martin's avatar
Ken Martin committed
339
      {
340
341
342
343
344
345
346
347
348
349
350
351
352
353
        this->FeedCondition->Signal();
      }
      else if (sret == AVERROR(EAGAIN))
      {
        // Signal the draining loop
        this->FeedCondition->Signal();
        // Wait here
        this->FeedCondition->Wait(this->FeedMutex);
        retryPacket = true;
      }
      else if (sret < 0) // error
      {
        this->FeedMutex->Unlock();
        return nullptr;
Ken Martin's avatar
Ken Martin committed
354
355
      }

356
      this->FeedMutex->Unlock();
Ken Martin's avatar
Ken Martin committed
357
358
    }

359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
    // feed audio
    if (fret >= 0 &&
        this->Internal->Packet.stream_index == this->Internal->AudioStreamIndex)
    {
      // lock the decoder
      this->FeedAudioMutex->Lock();

      int sret = avcodec_send_packet(
        this->Internal->AudioDecodeContext,
        &this->Internal->Packet);
      if (sret == 0) // good decode
      {
        this->FeedAudioCondition->Signal();
      }
      else if (sret == AVERROR(EAGAIN))
      {
        // Signal the draining loop
        this->FeedAudioCondition->Signal();
        // Wait here
        this->FeedAudioCondition->Wait(this->FeedAudioMutex);
        retryPacket = true;
      }
      else if (sret < 0) // error
      {
        this->FeedAudioMutex->Unlock();
        return nullptr;
      }

      this->FeedAudioMutex->Unlock();
    }

390
391
392
393
394
    // are we out of data?
    if (fret == AVERROR_EOF)
    {
      done = true;
    }
Ken Martin's avatar
Ken Martin committed
395

396
397
398
399
400
401
402
403
404
    // check to see if we are being told to quit every so often
    if (count == 10)
    {
      data->ActiveFlagLock->Lock();
      done = done || (*(data->ActiveFlag) == 0);
      data->ActiveFlagLock->Unlock();
      count = 0;
    }
    count++;
Ken Martin's avatar
Ken Martin committed
405
406
  }

407
408
409
410
411
  // flush remaning data
  this->FeedMutex->Lock();
  avcodec_send_packet(this->Internal->VideoDecodeContext, nullptr);
  this->FeedCondition->Signal();
  this->FeedMutex->Unlock();
Ken Martin's avatar
Ken Martin committed
412

413
414
415
416
417
418
419
420
421
  if (this->Internal->AudioDecodeContext)
  {
    this->FeedAudioMutex->Lock();
    avcodec_send_packet(this->Internal->AudioDecodeContext, nullptr);
    this->FeedAudioCondition->Signal();
    this->FeedAudioMutex->Unlock();
  }

  this->EndOfFile = true;
422
  return nullptr;
Ken Martin's avatar
Ken Martin committed
423
424
425
426
427
428
}

//----------------------------------------------------------------------------
// Sleep until the specified absolute time has arrived.
// You must pass a handle to the current thread.
// If '0' is returned, then the thread was aborted before or during the wait.
429
static void vtkThreadSleep(double time)
Ken Martin's avatar
Ken Martin committed
430
{
431
432
  static size_t count = 0;

Ken Martin's avatar
Ken Martin committed
433
434
435
  // loop either until the time has arrived or until the thread is ended
  for (int i = 0;; i++)
  {
436
    count++;
Ken Martin's avatar
Ken Martin committed
437
438
    double remaining = time - vtkTimerLog::GetUniversalTime();

439
440
441
442
443
444
445
446
447
448
    // check to see if we are being told to quit
    // data->ActiveFlagLock->Lock();
    // int activeFlag = *(data->ActiveFlag);
    // data->ActiveFlagLock->Unlock();

    // if (activeFlag == 0)
    // {
    //   break;
    // }

Ken Martin's avatar
Ken Martin committed
449
450
451
    // check to see if we have reached the specified time
    if (remaining <= 0.0)
    {
452
      if (i == 0 && count % 100 == 0)
Ken Martin's avatar
Ken Martin committed
453
      {
454
        cerr << "dropped frames, now beind by " << remaining << " seconds\n";
Ken Martin's avatar
Ken Martin committed
455
      }
456
      break;
Ken Martin's avatar
Ken Martin committed
457
    }
458
459

    // do not sleep for more than 0.1 seconds
Ken Martin's avatar
Ken Martin committed
460
461
462
463
464
    if (remaining > 0.1)
    {
      remaining = 0.1;
    }

465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
    vtksys::SystemTools::Delay(static_cast<unsigned int>(remaining * 1000.0));
  }
}

void *vtkFFMPEGVideoSource::DrainThread(vtkMultiThreader::ThreadInfo *data)
{
  vtkFFMPEGVideoSource *self = static_cast<vtkFFMPEGVideoSource *>(data->UserData);
  return self->Drain(data);
}

void *vtkFFMPEGVideoSource::Drain(vtkMultiThreader::ThreadInfo *data)
{
  bool done = false;
  unsigned short count = 0;

  double startTime = vtkTimerLog::GetUniversalTime();
  double rate = this->GetFrameRate();
  int frame = 0;

  while (!done)
  {
    this->FeedMutex->Lock();
Ken Martin's avatar
Ken Martin committed
487

488
489
490
    int ret = avcodec_receive_frame(this->Internal->VideoDecodeContext,
              this->Internal->Frame);
    if (ret == 0)
Ken Martin's avatar
Ken Martin committed
491
    {
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
      this->FeedCondition->Signal();
    }
    else if (ret == AVERROR(EAGAIN))
    {
      // Signal the feeding loop
      this->FeedCondition->Signal();
      // Wait here
      this->FeedCondition->Wait(this->FeedMutex);
    }
    else if (ret == AVERROR_EOF)
    {
      return nullptr;
    }
    else if (ret < 0) // error code
    {
      this->FeedMutex->Unlock();
508
      cerr << "video drain thread exiting on error!\n";
509
      return nullptr;
Ken Martin's avatar
Ken Martin committed
510
511
    }

512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
    this->FeedMutex->Unlock();

    if (ret == 0)
    {
      vtkThreadSleep(startTime + frame/rate);
      this->InternalGrab();
      frame++;
    }

    // check to see if we are being told to quit every so often
    if (count == 10)
    {
      data->ActiveFlagLock->Lock();
      done = done || (*(data->ActiveFlag) == 0);
      data->ActiveFlagLock->Unlock();
      count = 0;
    }
    count++;
  }

  return nullptr;
}

535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
void *vtkFFMPEGVideoSource::DrainAudioThread(vtkMultiThreader::ThreadInfo *data)
{
  vtkFFMPEGVideoSource *self = static_cast<vtkFFMPEGVideoSource *>(data->UserData);
  return self->DrainAudio(data);
}

void *vtkFFMPEGVideoSource::DrainAudio(vtkMultiThreader::ThreadInfo *data)
{
  bool done = false;
  unsigned short count = 0;

  int frame = 0;

  while (!done)
  {
    this->FeedAudioMutex->Lock();

    int ret = avcodec_receive_frame(this->Internal->AudioDecodeContext,
              this->Internal->AudioFrame);
    if (ret == 0)
    {
      this->FeedAudioCondition->Signal();
    }
    else if (ret == AVERROR(EAGAIN))
    {
      // Signal the feeding loop
      this->FeedAudioCondition->Signal();
      // Wait here
      this->FeedAudioCondition->Wait(this->FeedAudioMutex);
    }
    else if (ret == AVERROR_EOF)
    {
      return nullptr;
    }
    else if (ret < 0) // error code
    {
      this->FeedAudioMutex->Unlock();
      cerr << "audio drain thread exiting on error!\n";
      return nullptr;
    }

    this->FeedAudioMutex->Unlock();

    if (ret == 0)
    {
      // do something with the data here
      // vtkThreadSleep(startTime + frame/rate);

      int sampleFormat = VTK_UNSIGNED_CHAR;
      bool packed = true;
      switch (this->Internal->AudioDecodeContext->sample_fmt)
      {
        default:
        case AV_SAMPLE_FMT_U8:
          sampleFormat = VTK_UNSIGNED_CHAR;
          break;
        case AV_SAMPLE_FMT_U8P:
          sampleFormat = VTK_UNSIGNED_CHAR;
          packed = false;
          break;
        case AV_SAMPLE_FMT_S16:
          sampleFormat = VTK_SHORT;
          break;
        case AV_SAMPLE_FMT_S16P:
          sampleFormat = VTK_SHORT;
          packed = false;
          break;
        case AV_SAMPLE_FMT_S32:
          sampleFormat = VTK_LONG;
          break;
        case AV_SAMPLE_FMT_S32P:
          sampleFormat = VTK_LONG;
          packed = false;
          break;
        case AV_SAMPLE_FMT_FLT:
          sampleFormat = VTK_FLOAT;
          break;
        case AV_SAMPLE_FMT_FLTP:
          sampleFormat = VTK_FLOAT;
          packed = false;
          break;
        case AV_SAMPLE_FMT_DBL:
          sampleFormat = VTK_DOUBLE;
          break;
        case AV_SAMPLE_FMT_DBLP:
          sampleFormat = VTK_DOUBLE;
          packed = false;
          break;
      }

      if (this->AudioCallback)
      {
627
        vtkFFMPEGVideoSourceAudioCallbackData cbd;
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
        cbd.NumberOfSamples = this->Internal->AudioFrame->nb_samples;
        cbd.BytesPerSample =
          av_get_bytes_per_sample(this->Internal->AudioDecodeContext->sample_fmt);
        cbd.NumberOfChannels = this->Internal->AudioDecodeContext->channels;
        cbd.SampleRate = this->Internal->AudioDecodeContext->sample_rate;
        cbd.DataType = sampleFormat;
        cbd.Data = this->Internal->AudioFrame->extended_data;
        cbd.Caller = this;
        cbd.Packed = packed;
        cbd.ClientData = this->AudioCallbackClientData;
        this->AudioCallback(cbd);
      }
      frame++;
    }

    // check to see if we are being told to quit every so often
    if (count == 10)
    {
      data->ActiveFlagLock->Lock();
      done = done || (*(data->ActiveFlag) == 0);
      data->ActiveFlagLock->Unlock();
      count = 0;
    }
    count++;
  }

  return nullptr;
}
656
657
658
659
660

void vtkFFMPEGVideoSource::ReadFrame()
{
  // first try to grab a frame from data we already have
  bool gotFrame = false;
661
662
  while (!gotFrame &&
    (!this->EndOfFile || this->Internal->Packet.size > 0))
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
  {
    int ret = AVERROR(EAGAIN);
    if (this->Internal->Packet.size > 0)
    {
      ret = avcodec_receive_frame(this->Internal->VideoDecodeContext,
              this->Internal->Frame);
      if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
      {
        vtkErrorMacro("codec did not receive video frame");
        return;
      }
      if (ret == AVERROR_EOF)
      {
        this->EndOfFile = true;
        return;
      }
      if (ret == 0)
      {
        gotFrame = true;
      }
    }

    // if we are out of data then we must send more
686
    if (ret == AVERROR(EAGAIN) && !this->EndOfFile)
687
688
689
690
691
692
693
694
695
696
697
698
699
700
    {
      // if the packet is empty read more data from the file
      av_packet_unref(&this->Internal->Packet);
      int fret = av_read_frame(this->Internal->FormatContext, &this->Internal->Packet);
      if (fret >= 0 &&
          this->Internal->Packet.stream_index == this->Internal->VideoStreamIndex)
      {
        int sret = avcodec_send_packet(this->Internal->VideoDecodeContext, &this->Internal->Packet);
        if (sret < 0 && sret != AVERROR(EAGAIN) && sret != AVERROR_EOF)
        {
          vtkErrorMacro("codec did not send packet");
          return;
        }
      }
701
702
703
704
705
      if (fret == AVERROR_EOF)
      {
        this->EndOfFile = true;
        return;
      }
706
    }
Ken Martin's avatar
Ken Martin committed
707
  }
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
}

void vtkFFMPEGVideoSource::InternalGrab()
{
  // get a thread lock on the frame buffer
  this->FrameBufferMutex->Lock();

  if (this->AutoAdvance)
  {
    this->AdvanceFrameBuffer(1);
    if (this->FrameIndex + 1 < this->FrameBufferSize)
    {
      this->FrameIndex++;
    }
  }

  int index = this->FrameBufferIndex;

  this->FrameCount++;

  unsigned char *ptr = (unsigned char *)
    ((reinterpret_cast<vtkUnsignedCharArray*>(this->FrameBuffer[index])) \
      ->GetPointer(0));

  // the DIB has rows which are multiples of 4 bytes
  int outBytesPerRow = ((this->FrameBufferExtent[1]-
                         this->FrameBufferExtent[0]+1)
                        * this->FrameBufferBitsPerPixel + 7)/8;
  outBytesPerRow += outBytesPerRow % this->FrameBufferRowAlignment;
  outBytesPerRow += outBytesPerRow % 4;
  int rows = this->FrameBufferExtent[3]-this->FrameBufferExtent[2]+1;
Ken Martin's avatar
Ken Martin committed
739

740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
  // update frame time
  this->FrameBufferTimeStamps[index] =
    this->StartTimeStamp + this->FrameCount / this->FrameRate;

  uint8_t * dst[4];
  int dstStride[4];
  // we flip y axis here
  dstStride[0] = -outBytesPerRow;
  dst[0] = ptr + outBytesPerRow*(rows-1);
  sws_scale(this->Internal->RGBContext,
    this->Internal->Frame->data,
    this->Internal->Frame->linesize,
    0,
    this->Internal->Frame->height,
    dst, dstStride);

  this->FrameBufferMutex->Unlock();

  this->Modified();
Ken Martin's avatar
Ken Martin committed
759
760
761
}

//----------------------------------------------------------------------------
762
void vtkFFMPEGVideoSource::ReleaseSystemResources()
Ken Martin's avatar
Ken Martin committed
763
{
764
765
766
767
768
769
770
  if (this->Initialized)
  {
    this->Internal->ReleaseSystemResources();
    this->Initialized = 0;
    this->Modified();
  }
}
Ken Martin's avatar
Ken Martin committed
771

772
773
774
775
776
777
778
//----------------------------------------------------------------------------
void vtkFFMPEGVideoSource::Grab()
{
  if (this->Recording)
  {
    return;
  }
Ken Martin's avatar
Ken Martin committed
779

780
781
782
  // ensure that the frame buffer is properly initialized
  this->Initialize();
  if (!this->Initialized)
Ken Martin's avatar
Ken Martin committed
783
  {
784
    return;
Ken Martin's avatar
Ken Martin committed
785
786
  }

787
788
789
790
791
792
793
794
  this->ReadFrame();
  this->InternalGrab();
}

//----------------------------------------------------------------------------
void vtkFFMPEGVideoSource::Play()
{
  this->vtkVideoSource::Play();
Ken Martin's avatar
Ken Martin committed
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
}

//----------------------------------------------------------------------------
void vtkFFMPEGVideoSource::Record()
{
  if (this->Playing)
  {
    this->Stop();
  }

  if (!this->Recording)
  {
    this->Initialize();

    this->EndOfFile = false;
    this->Recording = 1;
    this->FrameCount = 0;
    this->Modified();
813
814
815
816
    this->FeedThreadId =
      this->PlayerThreader->SpawnThread((vtkThreadFunctionType)\
                                &vtkFFMPEGVideoSource::FeedThread,this);
    this->DrainThreadId =
Ken Martin's avatar
Ken Martin committed
817
      this->PlayerThreader->SpawnThread((vtkThreadFunctionType)\
818
                                &vtkFFMPEGVideoSource::DrainThread,this);
819
820
821
822
823
824
825
826
827
828
    if (this->Internal->AudioDecodeContext)
    {
      this->DrainAudioThreadId =
        this->PlayerThreader->SpawnThread((vtkThreadFunctionType)\
                                  &vtkFFMPEGVideoSource::DrainAudioThread,this);
    }
    else
    {
      this->DrainAudioThreadId = 0;
    }
Ken Martin's avatar
Ken Martin committed
829
830
831
832
833
834
  }
}

//----------------------------------------------------------------------------
void vtkFFMPEGVideoSource::Stop()
{
835
  if (this->Playing || this->Recording)
Ken Martin's avatar
Ken Martin committed
836
  {
837
838
    this->PlayerThreader->TerminateThread(this->FeedThreadId);
    this->PlayerThreader->TerminateThread(this->DrainThreadId);
839
840
841
842
    if (this->DrainAudioThreadId)
    {
      this->PlayerThreader->TerminateThread(this->DrainAudioThreadId);
    }
843
    this->Playing = 0;
Ken Martin's avatar
Ken Martin committed
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
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
923
924
925
926
927
928
929
930
931
932
933
934
    this->Recording = 0;
    this->Modified();
  }
}

//----------------------------------------------------------------------------
// try for the specified frame size
void vtkFFMPEGVideoSource::SetFrameSize(int x, int y, int z)
{
  if (x == this->FrameSize[0] &&
      y == this->FrameSize[1] &&
      z == this->FrameSize[2])
  {
    return;
  }

  if (x < 1 || y < 1 || z != 1)
  {
    vtkErrorMacro(<< "SetFrameSize: Illegal frame size");
    return;
  }

  this->FrameSize[0] = x;
  this->FrameSize[1] = y;
  this->FrameSize[2] = z;
  this->Modified();

  if (this->Initialized)
  {
    this->FrameBufferMutex->Lock();
    this->UpdateFrameBuffer();
    this->FrameBufferMutex->Unlock();
  }
}

//----------------------------------------------------------------------------
void vtkFFMPEGVideoSource::SetFrameRate(float rate)
{
  if (rate == this->FrameRate)
  {
    return;
  }

  this->FrameRate = rate;
  this->Modified();
}

//----------------------------------------------------------------------------
void vtkFFMPEGVideoSource::SetOutputFormat(int format)
{
  if (format == this->OutputFormat)
  {
    return;
  }

  this->OutputFormat = format;

  // convert color format to number of scalar components
  int numComponents;

  switch (this->OutputFormat)
  {
    case VTK_RGBA:
      numComponents = 4;
      break;
    case VTK_RGB:
      numComponents = 3;
      break;
    case VTK_LUMINANCE:
      numComponents = 1;
      break;
    default:
      numComponents = 0;
      vtkErrorMacro(<< "SetOutputFormat: Unrecognized color format.");
      break;
  }
  this->NumberOfScalarComponents = numComponents;

  if (this->FrameBufferBitsPerPixel != numComponents*8)
  {
    this->FrameBufferMutex->Lock();
    this->FrameBufferBitsPerPixel = numComponents*8;
    if (this->Initialized)
    {
      this->UpdateFrameBuffer();
    }
    this->FrameBufferMutex->Unlock();
  }

  this->Modified();
}