Spelling Cleanup
[blender.git] / source / gameengine / VideoTexture / VideoFFmpeg.cpp
1 /*
2 -----------------------------------------------------------------------------
3 This source file is part of VideoTexture library
4
5 Copyright (c) 2007 The Zdeno Ash Miklas
6
7 This program is free software; you can redistribute it and/or modify it under
8 the terms of the GNU Lesser General Public License as published by the Free Software
9 Foundation; either version 2 of the License, or (at your option) any later
10 version.
11
12 This program is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License along with
17 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
18 Place - Suite 330, Boston, MA 02111-1307, USA, or go to
19 http://www.gnu.org/copyleft/lesser.txt.
20 -----------------------------------------------------------------------------
21 */
22
23 /** \file gameengine/VideoTexture/VideoFFmpeg.cpp
24  *  \ingroup bgevideotex
25  */
26
27
28 #ifdef WITH_FFMPEG
29
30 // INT64_C fix for some linux machines (C99ism)
31 #ifndef __STDC_CONSTANT_MACROS
32 #define __STDC_CONSTANT_MACROS
33 #endif
34 #include <stdint.h>
35
36
37 #include "MEM_guardedalloc.h"
38 #include "PIL_time.h"
39
40 #include <string>
41
42 #include "Exception.h"
43 #include "VideoFFmpeg.h"
44
45
46 // default framerate
47 const double defFrameRate = 25.0;
48 // time scale constant
49 const long timeScale = 1000;
50
51 // macro for exception handling and logging
52 #define CATCH_EXCP catch (Exception & exp) \
53 { exp.report(); m_status = SourceError; }
54
55 extern "C" void do_init_ffmpeg();
56
57 // class RenderVideo
58
59 // constructor
60 VideoFFmpeg::VideoFFmpeg (HRESULT * hRslt) : VideoBase(), 
61 m_codec(NULL), m_formatCtx(NULL), m_codecCtx(NULL), 
62 m_frame(NULL), m_frameDeinterlaced(NULL), m_frameRGB(NULL), m_imgConvertCtx(NULL),
63 m_deinterlace(false), m_preseek(0),     m_videoStream(-1), m_baseFrameRate(25.0),
64 m_lastFrame(-1),  m_eof(false), m_externTime(false), m_curPosition(-1), m_startTime(0), 
65 m_captWidth(0), m_captHeight(0), m_captRate(0.f), m_isImage(false),
66 m_isThreaded(false), m_isStreaming(false), m_stopThread(false), m_cacheStarted(false)
67 {
68         // set video format
69         m_format = RGB24;
70         // force flip because ffmpeg always return the image in the wrong orientation for texture
71         setFlip(true);
72         // construction is OK
73         *hRslt = S_OK;
74         m_thread.first = m_thread.last = NULL;
75         pthread_mutex_init(&m_cacheMutex, NULL);
76         m_frameCacheFree.first = m_frameCacheFree.last = NULL;
77         m_frameCacheBase.first = m_frameCacheBase.last = NULL;
78         m_packetCacheFree.first = m_packetCacheFree.last = NULL;
79         m_packetCacheBase.first = m_packetCacheBase.last = NULL;
80 }
81
82 // destructor
83 VideoFFmpeg::~VideoFFmpeg () 
84 {
85 }
86
87
88 // release components
89 bool VideoFFmpeg::release()
90 {
91         // release
92         stopCache();
93         if (m_codecCtx)
94         {
95                 avcodec_close(m_codecCtx);
96                 m_codecCtx = NULL;
97         }
98         if (m_formatCtx)
99         {
100                 av_close_input_file(m_formatCtx);
101                 m_formatCtx = NULL;
102         }
103         if (m_frame)
104         {
105                 av_free(m_frame);
106                 m_frame = NULL;
107         }
108         if (m_frameDeinterlaced)
109         {
110                 MEM_freeN(m_frameDeinterlaced->data[0]);
111                 av_free(m_frameDeinterlaced);
112                 m_frameDeinterlaced = NULL;
113         }
114         if (m_frameRGB)
115         {
116                 MEM_freeN(m_frameRGB->data[0]);
117                 av_free(m_frameRGB);
118                 m_frameRGB = NULL;
119         }
120         if (m_imgConvertCtx)
121         {
122                 sws_freeContext(m_imgConvertCtx);
123                 m_imgConvertCtx = NULL;
124         }
125         m_codec = NULL;
126         m_status = SourceStopped;
127         m_lastFrame = -1;
128         return true;
129 }
130
131 AVFrame *VideoFFmpeg::allocFrameRGB()
132 {
133         AVFrame *frame;
134         frame = avcodec_alloc_frame();
135         if (m_format == RGBA32)
136         {
137                 avpicture_fill((AVPicture*)frame, 
138                         (uint8_t*)MEM_callocN(avpicture_get_size(
139                                 PIX_FMT_RGBA,
140                                 m_codecCtx->width, m_codecCtx->height),
141                                 "ffmpeg rgba"),
142                         PIX_FMT_RGBA, m_codecCtx->width, m_codecCtx->height);
143         } else 
144         {
145                 avpicture_fill((AVPicture*)frame, 
146                         (uint8_t*)MEM_callocN(avpicture_get_size(
147                                 PIX_FMT_RGB24,
148                                 m_codecCtx->width, m_codecCtx->height),
149                                 "ffmpeg rgb"),
150                         PIX_FMT_RGB24, m_codecCtx->width, m_codecCtx->height);
151         }
152         return frame;
153 }
154
155 // set initial parameters
156 void VideoFFmpeg::initParams (short width, short height, float rate, bool image)
157 {
158         m_captWidth = width;
159         m_captHeight = height;
160         m_captRate = rate;
161         m_isImage = image;
162 }
163
164
165 int VideoFFmpeg::openStream(const char *filename, AVInputFormat *inputFormat, AVFormatParameters *formatParams)
166 {
167         AVFormatContext *formatCtx;
168         int                             i, videoStream;
169         AVCodec                 *codec;
170         AVCodecContext  *codecCtx;
171
172         if(av_open_input_file(&formatCtx, filename, inputFormat, 0, formatParams)!=0)
173                 return -1;
174
175         if(av_find_stream_info(formatCtx)<0) 
176         {
177                 av_close_input_file(formatCtx);
178                 return -1;
179         }
180
181         /* Find the first video stream */
182         videoStream=-1;
183         for(i=0; i<formatCtx->nb_streams; i++)
184         {
185                 if(formatCtx->streams[i] &&
186                         get_codec_from_stream(formatCtx->streams[i]) && 
187                         (get_codec_from_stream(formatCtx->streams[i])->codec_type==AVMEDIA_TYPE_VIDEO))
188                 {
189                         videoStream=i;
190                         break;
191                 }
192         }
193
194         if(videoStream==-1) 
195         {
196                 av_close_input_file(formatCtx);
197                 return -1;
198         }
199
200         codecCtx = get_codec_from_stream(formatCtx->streams[videoStream]);
201
202         /* Find the decoder for the video stream */
203         codec=avcodec_find_decoder(codecCtx->codec_id);
204         if(codec==NULL) 
205         {
206                 av_close_input_file(formatCtx);
207                 return -1;
208         }
209         codecCtx->workaround_bugs = 1;
210         if(avcodec_open(codecCtx, codec)<0) 
211         {
212                 av_close_input_file(formatCtx);
213                 return -1;
214         }
215
216 #ifdef FFMPEG_OLD_FRAME_RATE
217         if(codecCtx->frame_rate>1000 && codecCtx->frame_rate_base==1)
218                 codecCtx->frame_rate_base=1000;
219         m_baseFrameRate = (double)codecCtx->frame_rate / (double)codecCtx->frame_rate_base;
220 #else
221         m_baseFrameRate = av_q2d(formatCtx->streams[videoStream]->r_frame_rate);
222 #endif
223         if (m_baseFrameRate <= 0.0) 
224                 m_baseFrameRate = defFrameRate;
225
226         m_codec = codec;
227         m_codecCtx = codecCtx;
228         m_formatCtx = formatCtx;
229         m_videoStream = videoStream;
230         m_frame = avcodec_alloc_frame();
231         m_frameDeinterlaced = avcodec_alloc_frame();
232
233         // allocate buffer if deinterlacing is required
234         avpicture_fill((AVPicture*)m_frameDeinterlaced, 
235                 (uint8_t*)MEM_callocN(avpicture_get_size(
236                 m_codecCtx->pix_fmt,
237                 m_codecCtx->width, m_codecCtx->height), 
238                 "ffmpeg deinterlace"), 
239                 m_codecCtx->pix_fmt, m_codecCtx->width, m_codecCtx->height);
240
241         // check if the pixel format supports Alpha
242         if (m_codecCtx->pix_fmt == PIX_FMT_RGB32 ||
243                 m_codecCtx->pix_fmt == PIX_FMT_BGR32 ||
244                 m_codecCtx->pix_fmt == PIX_FMT_RGB32_1 ||
245                 m_codecCtx->pix_fmt == PIX_FMT_BGR32_1) 
246         {
247                 // allocate buffer to store final decoded frame
248                 m_format = RGBA32;
249                 // allocate sws context
250                 m_imgConvertCtx = sws_getContext(
251                         m_codecCtx->width,
252                         m_codecCtx->height,
253                         m_codecCtx->pix_fmt,
254                         m_codecCtx->width,
255                         m_codecCtx->height,
256                         PIX_FMT_RGBA,
257                         SWS_FAST_BILINEAR,
258                         NULL, NULL, NULL);
259         } else
260         {
261                 // allocate buffer to store final decoded frame
262                 m_format = RGB24;
263                 // allocate sws context
264                 m_imgConvertCtx = sws_getContext(
265                         m_codecCtx->width,
266                         m_codecCtx->height,
267                         m_codecCtx->pix_fmt,
268                         m_codecCtx->width,
269                         m_codecCtx->height,
270                         PIX_FMT_RGB24,
271                         SWS_FAST_BILINEAR,
272                         NULL, NULL, NULL);
273         }
274         m_frameRGB = allocFrameRGB();
275
276         if (!m_imgConvertCtx) {
277                 avcodec_close(m_codecCtx);
278                 m_codecCtx = NULL;
279                 av_close_input_file(m_formatCtx);
280                 m_formatCtx = NULL;
281                 av_free(m_frame);
282                 m_frame = NULL;
283                 MEM_freeN(m_frameDeinterlaced->data[0]);
284                 av_free(m_frameDeinterlaced);
285                 m_frameDeinterlaced = NULL;
286                 MEM_freeN(m_frameRGB->data[0]);
287                 av_free(m_frameRGB);
288                 m_frameRGB = NULL;
289                 return -1;
290         }
291         return 0;
292 }
293
294 /*
295  * This thread is used to load video frame asynchronously.
296  * It provides a frame caching service. 
297  * The main thread is responsible for positionning the frame pointer in the
298  * file correctly before calling startCache() which starts this thread.
299  * The cache is organized in two layers: 1) a cache of 20-30 undecoded packets to keep
300  * memory and CPU low 2) a cache of 5 decoded frames. 
301  * If the main thread does not find the frame in the cache (because the video has restarted
302  * or because the GE is lagging), it stops the cache with StopCache() (this is a synchronous
303  * function: it sends a signal to stop the cache thread and wait for confirmation), then
304  * change the position in the stream and restarts the cache thread.
305  */
306 void *VideoFFmpeg::cacheThread(void *data)
307 {
308         VideoFFmpeg* video = (VideoFFmpeg*)data;
309         // holds the frame that is being decoded
310         CacheFrame *currentFrame = NULL;
311         CachePacket *cachePacket;
312         bool endOfFile = false;
313         int frameFinished = 0;
314         double timeBase = av_q2d(video->m_formatCtx->streams[video->m_videoStream]->time_base);
315         int64_t startTs = video->m_formatCtx->streams[video->m_videoStream]->start_time;
316
317         if (startTs == AV_NOPTS_VALUE)
318                 startTs = 0;
319
320         while (!video->m_stopThread)
321         {
322                 // packet cache is used solely by this thread, no need to lock
323                 // In case the stream/file contains other stream than the one we are looking for,
324                 // allow a bit of cycling to get rid quickly of those frames
325                 frameFinished = 0;
326                 while (    !endOfFile 
327                                 && (cachePacket = (CachePacket *)video->m_packetCacheFree.first) != NULL 
328                                 && frameFinished < 25)
329                 {
330                         // free packet => packet cache is not full yet, just read more
331                         if (av_read_frame(video->m_formatCtx, &cachePacket->packet)>=0) 
332                         {
333                                 if (cachePacket->packet.stream_index == video->m_videoStream)
334                                 {
335                                         // make sure fresh memory is allocated for the packet and move it to queue
336                                         av_dup_packet(&cachePacket->packet);
337                                         BLI_remlink(&video->m_packetCacheFree, cachePacket);
338                                         BLI_addtail(&video->m_packetCacheBase, cachePacket);
339                                         break;
340                                 } else {
341                                         // this is not a good packet for us, just leave it on free queue
342                                         // Note: here we could handle sound packet
343                                         av_free_packet(&cachePacket->packet);
344                                         frameFinished++;
345                                 }
346                                 
347                         } else {
348                                 if (video->m_isFile)
349                                         // this mark the end of the file
350                                         endOfFile = true;
351                                 // if we cannot read a packet, no need to continue
352                                 break;
353                         }
354                 }
355                 // frame cache is also used by main thread, lock
356                 if (currentFrame == NULL) 
357                 {
358                         // no current frame being decoded, take free one
359                         pthread_mutex_lock(&video->m_cacheMutex);
360                         if ((currentFrame = (CacheFrame *)video->m_frameCacheFree.first) != NULL)
361                                 BLI_remlink(&video->m_frameCacheFree, currentFrame);
362                         pthread_mutex_unlock(&video->m_cacheMutex);
363                 }
364                 if (currentFrame != NULL)
365                 {
366                         // this frame is out of free and busy queue, we can manipulate it without locking
367                         frameFinished = 0;
368                         while (!frameFinished && (cachePacket = (CachePacket *)video->m_packetCacheBase.first) != NULL)
369                         {
370                                 BLI_remlink(&video->m_packetCacheBase, cachePacket);
371                                 // use m_frame because when caching, it is not used in main thread
372                                 // we can't use currentFrame directly because we need to convert to RGB first
373                                 avcodec_decode_video2(video->m_codecCtx, 
374                                         video->m_frame, &frameFinished, 
375                                         &cachePacket->packet);
376                                 if(frameFinished) 
377                                 {
378                                         AVFrame * input = video->m_frame;
379
380                                         /* This means the data wasnt read properly, this check stops crashing */
381                                         if (   input->data[0]!=0 || input->data[1]!=0 
382                                                 || input->data[2]!=0 || input->data[3]!=0)
383                                         {
384                                                 if (video->m_deinterlace) 
385                                                 {
386                                                         if (avpicture_deinterlace(
387                                                                 (AVPicture*) video->m_frameDeinterlaced,
388                                                                 (const AVPicture*) video->m_frame,
389                                                                 video->m_codecCtx->pix_fmt,
390                                                                 video->m_codecCtx->width,
391                                                                 video->m_codecCtx->height) >= 0)
392                                                         {
393                                                                 input = video->m_frameDeinterlaced;
394                                                         }
395                                                 }
396                                                 // convert to RGB24
397                                                 sws_scale(video->m_imgConvertCtx,
398                                                         input->data,
399                                                         input->linesize,
400                                                         0,
401                                                         video->m_codecCtx->height,
402                                                         currentFrame->frame->data,
403                                                         currentFrame->frame->linesize);
404                                                 // move frame to queue, this frame is necessarily the next one
405                                                 video->m_curPosition = (long)((cachePacket->packet.dts-startTs) * (video->m_baseFrameRate*timeBase) + 0.5);
406                                                 currentFrame->framePosition = video->m_curPosition;
407                                                 pthread_mutex_lock(&video->m_cacheMutex);
408                                                 BLI_addtail(&video->m_frameCacheBase, currentFrame);
409                                                 pthread_mutex_unlock(&video->m_cacheMutex);
410                                                 currentFrame = NULL;
411                                         }
412                                 }
413                                 av_free_packet(&cachePacket->packet);
414                                 BLI_addtail(&video->m_packetCacheFree, cachePacket);
415                         } 
416                         if (currentFrame && endOfFile) 
417                         {
418                                 // no more packet and end of file => put a special frame that indicates that
419                                 currentFrame->framePosition = -1;
420                                 pthread_mutex_lock(&video->m_cacheMutex);
421                                 BLI_addtail(&video->m_frameCacheBase, currentFrame);
422                                 pthread_mutex_unlock(&video->m_cacheMutex);
423                                 currentFrame = NULL;
424                                 // no need to stay any longer in this thread
425                                 break;
426                         }
427                 }
428                 // small sleep to avoid unnecessary looping
429                 PIL_sleep_ms(10);
430         }
431         // before quitting, put back the current frame to queue to allow freeing
432         if (currentFrame)
433         {
434                 pthread_mutex_lock(&video->m_cacheMutex);
435                 BLI_addtail(&video->m_frameCacheFree, currentFrame);
436                 pthread_mutex_unlock(&video->m_cacheMutex);
437         }
438         return 0;
439 }
440
441 // start thread to cache video frame from file/capture/stream
442 // this function should be called only when the position in the stream is set for the
443 // first frame to cache
444 bool VideoFFmpeg::startCache()
445 {
446         if (!m_cacheStarted && m_isThreaded)
447         {
448                 m_stopThread = false;
449                 for (int i=0; i<CACHE_FRAME_SIZE; i++)
450                 {
451                         CacheFrame *frame = new CacheFrame();
452                         frame->frame = allocFrameRGB();
453                         BLI_addtail(&m_frameCacheFree, frame);
454                 }
455                 for (int i=0; i<CACHE_PACKET_SIZE; i++) 
456                 {
457                         CachePacket *packet = new CachePacket();
458                         BLI_addtail(&m_packetCacheFree, packet);
459                 }
460                 BLI_init_threads(&m_thread, cacheThread, 1);
461                 BLI_insert_thread(&m_thread, this);
462                 m_cacheStarted = true;
463         }
464         return m_cacheStarted;
465 }
466
467 void VideoFFmpeg::stopCache()
468 {
469         if (m_cacheStarted)
470         {
471                 m_stopThread = true;
472                 BLI_end_threads(&m_thread);
473                 // now delete the cache
474                 CacheFrame *frame;
475                 CachePacket *packet;
476                 while ((frame = (CacheFrame *)m_frameCacheBase.first) != NULL)
477                 {
478                         BLI_remlink(&m_frameCacheBase, frame);
479                         MEM_freeN(frame->frame->data[0]);
480                         av_free(frame->frame);
481                         delete frame;
482                 }
483                 while ((frame = (CacheFrame *)m_frameCacheFree.first) != NULL)
484                 {
485                         BLI_remlink(&m_frameCacheFree, frame);
486                         MEM_freeN(frame->frame->data[0]);
487                         av_free(frame->frame);
488                         delete frame;
489                 }
490                 while((packet = (CachePacket *)m_packetCacheBase.first) != NULL)
491                 {
492                         BLI_remlink(&m_packetCacheBase, packet);
493                         av_free_packet(&packet->packet);
494                         delete packet;
495                 }
496                 while((packet = (CachePacket *)m_packetCacheFree.first) != NULL)
497                 {
498                         BLI_remlink(&m_packetCacheFree, packet);
499                         delete packet;
500                 }
501                 m_cacheStarted = false;
502         }
503 }
504
505 void VideoFFmpeg::releaseFrame(AVFrame* frame)
506 {
507         if (frame == m_frameRGB)
508         {
509                 // this is not a frame from the cache, ignore
510                 return;
511         }
512         // this frame MUST be the first one of the queue
513         pthread_mutex_lock(&m_cacheMutex);
514         CacheFrame *cacheFrame = (CacheFrame *)m_frameCacheBase.first;
515         assert (cacheFrame != NULL && cacheFrame->frame == frame);
516         BLI_remlink(&m_frameCacheBase, cacheFrame);
517         BLI_addtail(&m_frameCacheFree, cacheFrame);
518         pthread_mutex_unlock(&m_cacheMutex);
519 }
520
521 // open video file
522 void VideoFFmpeg::openFile (char * filename)
523 {
524         do_init_ffmpeg();
525
526         if (openStream(filename, NULL, NULL) != 0)
527                 return;
528
529         if (m_codecCtx->gop_size)
530                 m_preseek = (m_codecCtx->gop_size < 25) ? m_codecCtx->gop_size+1 : 25;
531         else if (m_codecCtx->has_b_frames)              
532                 m_preseek = 25; // should determine gopsize
533         else
534                 m_preseek = 0;
535
536         // get video time range
537         m_range[0] = 0.0;
538         m_range[1] = (double)m_formatCtx->duration / AV_TIME_BASE;
539
540         // open base class
541         VideoBase::openFile(filename);
542
543         if (
544                 // ffmpeg reports that http source are actually non stream
545                 // but it is really not desirable to seek on http file, so force streaming.
546                 // It would be good to find this information from the context but there are no simple indication
547                 !strncmp(filename, "http://", 7) ||
548 #ifdef FFMPEG_PB_IS_POINTER
549                 (m_formatCtx->pb && m_formatCtx->pb->is_streamed)
550 #else
551                 m_formatCtx->pb.is_streamed
552 #endif
553                 )
554         {
555                 // the file is in fact a streaming source, treat as cam to prevent seeking
556                 m_isFile = false;
557                 // but it's not handled exactly like a camera.
558                 m_isStreaming = true;
559                 // for streaming it is important to do non blocking read
560                 m_formatCtx->flags |= AVFMT_FLAG_NONBLOCK;
561         }
562
563         if (m_isImage) 
564         {
565                 // the file is to be treated as an image, i.e. load the first frame only
566                 m_isFile = false;
567                 // in case of reload, the filename is taken from m_imageName, no need to change it
568                 if (m_imageName.Ptr() != filename)
569                         m_imageName = filename;
570                 m_preseek = 0;
571                 m_avail = false;
572                 play();
573         }
574         // check if we should do multi-threading?
575         if (!m_isImage && BLI_system_thread_count() > 1)
576         {
577                 // never thread image: there are no frame to read ahead
578                 // no need to thread if the system has a single core
579                 m_isThreaded =  true;
580         }
581 }
582
583
584 // open video capture device
585 void VideoFFmpeg::openCam (char * file, short camIdx)
586 {
587         // open camera source
588         AVInputFormat           *inputFormat;
589         AVFormatParameters      formatParams;
590         AVRational                      frameRate;
591         char                            *p, filename[28], rateStr[20];
592
593         do_init_ffmpeg();
594
595         memset(&formatParams, 0, sizeof(formatParams));
596 #ifdef WIN32
597         // video capture on windows only through Video For Windows driver
598         inputFormat = av_find_input_format("vfwcap");
599         if (!inputFormat)
600                 // Video For Windows not supported??
601                 return;
602         sprintf(filename, "%d", camIdx);
603 #else
604         // In Linux we support two types of devices: VideoForLinux and DV1394. 
605         // the user specify it with the filename:
606         // [<device_type>][:<standard>]
607         // <device_type> : 'v4l' for VideoForLinux, 'dv1394' for DV1394. By default 'v4l'
608         // <standard>    : 'pal', 'secam' or 'ntsc'. By default 'ntsc'
609         // The driver name is constructed automatically from the device type:
610         // v4l   : /dev/video<camIdx>
611         // dv1394: /dev/dv1394/<camIdx>
612         // If you have different driver name, you can specify the driver name explicitly
613         // instead of device type. Examples of valid filename:
614         //    /dev/v4l/video0:pal
615         //    /dev/ieee1394/1:ntsc
616         //    dv1394:secam
617         //    v4l:pal
618         if (file && strstr(file, "1394") != NULL) 
619         {
620                 // the user specifies a driver, check if it is v4l or d41394
621                 inputFormat = av_find_input_format("dv1394");
622                 sprintf(filename, "/dev/dv1394/%d", camIdx);
623         } else 
624         {
625                 inputFormat = av_find_input_format("video4linux");
626                 sprintf(filename, "/dev/video%d", camIdx);
627         }
628         if (!inputFormat)
629                 // these format should be supported, check ffmpeg compilation
630                 return;
631         if (file && strncmp(file, "/dev", 4) == 0) 
632         {
633                 // user does not specify a driver
634                 strncpy(filename, file, sizeof(filename));
635                 filename[sizeof(filename)-1] = 0;
636                 if ((p = strchr(filename, ':')) != 0)
637                         *p = 0;
638         }
639         if (file && (p = strchr(file, ':')) != NULL)
640                 formatParams.standard = p+1;
641 #endif
642         //frame rate
643         if (m_captRate <= 0.f)
644                 m_captRate = defFrameRate;
645         sprintf(rateStr, "%f", m_captRate);
646         av_parse_video_rate(&frameRate, rateStr);
647         // populate format parameters
648         // need to specify the time base = inverse of rate
649         formatParams.time_base.num = frameRate.den;
650         formatParams.time_base.den = frameRate.num;
651         formatParams.width = m_captWidth;
652         formatParams.height = m_captHeight;
653
654         if (openStream(filename, inputFormat, &formatParams) != 0)
655                 return;
656
657         // for video capture it is important to do non blocking read
658         m_formatCtx->flags |= AVFMT_FLAG_NONBLOCK;
659         // open base class
660         VideoBase::openCam(file, camIdx);
661         // check if we should do multi-threading?
662         if (BLI_system_thread_count() > 1)
663         {
664                 // no need to thread if the system has a single core
665                 m_isThreaded =  true;
666         }
667 }
668
669 // play video
670 bool VideoFFmpeg::play (void)
671 {
672         try
673         {
674                 // if object is able to play
675                 if (VideoBase::play())
676                 {
677                         // set video position
678                         setPositions();
679                         // return success
680                         return true;
681                 }
682         }
683         CATCH_EXCP;
684         return false;
685 }
686
687
688 // pause video
689 bool VideoFFmpeg::pause (void)
690 {
691         try
692         {
693                 if (VideoBase::pause())
694                 {
695                         return true;
696                 }
697         }
698         CATCH_EXCP;
699         return false;
700 }
701
702 // stop video
703 bool VideoFFmpeg::stop (void)
704 {
705         try
706         {
707                 VideoBase::stop();
708                 // force restart when play
709                 m_lastFrame = -1;
710                 return true;
711         }
712         CATCH_EXCP;
713         return false;
714 }
715
716
717 // set video range
718 void VideoFFmpeg::setRange (double start, double stop)
719 {
720         try
721         {
722                 // set range
723                 if (m_isFile)
724                 {
725                         VideoBase::setRange(start, stop);
726                         // set range for video
727                         setPositions();
728                 }
729         }
730         CATCH_EXCP;
731 }
732
733 // set framerate
734 void VideoFFmpeg::setFrameRate (float rate)
735 {
736         VideoBase::setFrameRate(rate);
737 }
738
739
740 // image calculation
741 // load frame from video
742 void VideoFFmpeg::calcImage (unsigned int texId, double ts)
743 {
744         if (m_status == SourcePlaying)
745         {
746                 // get actual time
747                 double startTime = PIL_check_seconds_timer();
748                 double actTime;
749                 // timestamp passed from audio actuators can sometimes be slightly negative
750                 if (m_isFile && ts >= -0.5)
751                 {
752                         // allow setting timestamp only when not streaming
753                         actTime = ts;
754                         if (actTime * actFrameRate() < m_lastFrame) 
755                         {
756                                 // user is asking to rewind, force a cache clear to make sure we will do a seek
757                                 // note that this does not decrement m_repeat if ts didn't reach m_range[1]
758                                 stopCache();
759                         }
760                 }
761                 else
762                 {
763                         if (m_lastFrame == -1 && !m_isFile)
764                                 m_startTime = startTime;
765                         actTime = startTime - m_startTime;
766                 }
767                 // if video has ended
768                 if (m_isFile && actTime * m_frameRate >= m_range[1])
769                 {
770                         // in any case, this resets the cache
771                         stopCache();
772                         // if repeats are set, decrease them
773                         if (m_repeat > 0) 
774                                 --m_repeat;
775                         // if video has to be replayed
776                         if (m_repeat != 0)
777                         {
778                                 // reset its position
779                                 actTime -= (m_range[1] - m_range[0]) / m_frameRate;
780                                 m_startTime += (m_range[1] - m_range[0]) / m_frameRate;
781                         }
782                         // if video has to be stopped, stop it
783                         else 
784                         {
785                                 m_status = SourceStopped;
786                                 return;
787                         }
788                 }
789                 // actual frame
790                 long actFrame = (m_isImage) ? m_lastFrame+1 : long(actTime * actFrameRate());
791                 // if actual frame differs from last frame
792                 if (actFrame != m_lastFrame)
793                 {
794                         AVFrame* frame;
795                         // get image
796                         if((frame = grabFrame(actFrame)) != NULL)
797                         {
798                                 if (!m_isFile && !m_cacheStarted) 
799                                 {
800                                         // streaming without cache: detect synchronization problem
801                                         double execTime = PIL_check_seconds_timer() - startTime;
802                                         if (execTime > 0.005) 
803                                         {
804                                                 // exec time is too long, it means that the function was blocking
805                                                 // resynchronize the stream from this time
806                                                 m_startTime += execTime;
807                                         }
808                                 }
809                                 // save actual frame
810                                 m_lastFrame = actFrame;
811                                 // init image, if needed
812                                 init(short(m_codecCtx->width), short(m_codecCtx->height));
813                                 // process image
814                                 process((BYTE*)(frame->data[0]));
815                                 // finished with the frame, release it so that cache can reuse it
816                                 releaseFrame(frame);
817                                 // in case it is an image, automatically stop reading it
818                                 if (m_isImage)
819                                 {
820                                         m_status = SourceStopped;
821                                         // close the file as we don't need it anymore
822                                         release();
823                                 }
824                         } else if (m_isStreaming)
825                         {
826                                 // we didn't get a frame and we are streaming, this may be due to
827                                 // a delay in the network or because we are getting the frame too fast.
828                                 // In the later case, shift time by a small amount to compensate for a drift
829                                 m_startTime += 0.001;
830                         }
831                 }
832         }
833 }
834
835
836 // set actual position
837 void VideoFFmpeg::setPositions (void)
838 {
839         // set video start time
840         m_startTime = PIL_check_seconds_timer();
841         // if file is played and actual position is before end position
842         if (!m_eof && m_lastFrame >= 0 && (!m_isFile || m_lastFrame < m_range[1] * actFrameRate()))
843                 // continue from actual position
844                 m_startTime -= double(m_lastFrame) / actFrameRate();
845         else {
846                 m_startTime -= m_range[0];
847                 // start from begining, stop cache just in case
848                 stopCache();
849         }
850 }
851
852 // position pointer in file, position in second
853 AVFrame *VideoFFmpeg::grabFrame(long position)
854 {
855         AVPacket packet;
856         int frameFinished;
857         int posFound = 1;
858         bool frameLoaded = false;
859         int64_t targetTs = 0;
860         CacheFrame *frame;
861         int64_t dts = 0;
862
863         if (m_cacheStarted)
864         {
865                 // when cache is active, we must not read the file directly
866                 do {
867                         pthread_mutex_lock(&m_cacheMutex);
868                         frame = (CacheFrame *)m_frameCacheBase.first;
869                         pthread_mutex_unlock(&m_cacheMutex);
870                         // no need to remove the frame from the queue: the cache thread does not touch the head, only the tail
871                         if (frame == NULL)
872                         {
873                                 // no frame in cache, in case of file it is an abnormal situation
874                                 if (m_isFile)
875                                 {
876                                         // go back to no threaded reading
877                                         stopCache();
878                                         break;
879                                 }
880                                 return NULL;
881                         }
882                         if (frame->framePosition == -1) 
883                         {
884                                 // this frame mark the end of the file (only used for file)
885                                 // leave in cache to make sure we don't miss it
886                                 m_eof = true;
887                                 return NULL;
888                         }
889                         // for streaming, always return the next frame, 
890                         // that's what grabFrame does in non cache mode anyway.
891                         if (m_isStreaming || frame->framePosition == position)
892                         {
893                                 return frame->frame;
894                         }
895                         // for cam, skip old frames to keep image realtime.
896                         // There should be no risk of clock drift since it all happens on the same CPU
897                         if (frame->framePosition > position) 
898                         {
899                                 // this can happen after rewind if the seek didn't find the first frame
900                                 // the frame in the buffer is ahead of time, just leave it there
901                                 return NULL;
902                         }
903                         // this frame is not useful, release it
904                         pthread_mutex_lock(&m_cacheMutex);
905                         BLI_remlink(&m_frameCacheBase, frame);
906                         BLI_addtail(&m_frameCacheFree, frame);
907                         pthread_mutex_unlock(&m_cacheMutex);
908                 } while (true);
909         }
910         double timeBase = av_q2d(m_formatCtx->streams[m_videoStream]->time_base);
911         int64_t startTs = m_formatCtx->streams[m_videoStream]->start_time;
912         if (startTs == AV_NOPTS_VALUE)
913                 startTs = 0;
914
915         // come here when there is no cache or cache has been stopped
916         // locate the frame, by seeking if necessary (seeking is only possible for files)
917         if (m_isFile)
918         {
919                 // first check if the position that we are looking for is in the preseek range
920                 // if so, just read the frame until we get there
921                 if (position > m_curPosition + 1 
922                         && m_preseek 
923                         && position - (m_curPosition + 1) < m_preseek) 
924                 {
925                         while(av_read_frame(m_formatCtx, &packet)>=0) 
926                         {
927                                 if (packet.stream_index == m_videoStream) 
928                                 {
929                                         avcodec_decode_video2(
930                                                 m_codecCtx, 
931                                                 m_frame, &frameFinished, 
932                                                 &packet);
933                                         if (frameFinished)
934                                         {
935                                                 m_curPosition = (long)((packet.dts-startTs) * (m_baseFrameRate*timeBase) + 0.5);
936                                         }
937                                 }
938                                 av_free_packet(&packet);
939                                 if (position == m_curPosition+1)
940                                         break;
941                         }
942                 }
943                 // if the position is not in preseek, do a direct jump
944                 if (position != m_curPosition + 1) 
945                 { 
946                         int64_t pos = (int64_t)((position - m_preseek) / (m_baseFrameRate*timeBase));
947
948                         if (pos < 0)
949                                 pos = 0;
950
951                         pos += startTs;
952
953                         if (position <= m_curPosition || !m_eof)
954                         {
955 #if 0
956                                 // Tried to make this work but couldn't: seeking on byte is ignored by the
957                                 // format plugin and it will generally continue to read from last timestamp.
958                                 // Too bad because frame seek is not always able to get the first frame
959                                 // of the file.
960                                 if (position <= m_preseek)
961                                 {
962                                         // we can safely go the begining of the file
963                                         if (av_seek_frame(m_formatCtx, m_videoStream, 0, AVSEEK_FLAG_BYTE) >= 0)
964                                         {
965                                                 // binary seek does not reset the timestamp, must do it now
966                                                 av_update_cur_dts(m_formatCtx, m_formatCtx->streams[m_videoStream], startTs);
967                                                 m_curPosition = 0;
968                                         }
969                                 }
970                                 else
971 #endif
972                                 {
973                                         // current position is now lost, guess a value. 
974                                         if (av_seek_frame(m_formatCtx, m_videoStream, pos, AVSEEK_FLAG_BACKWARD) >= 0)
975                                         {
976                                                 // current position is now lost, guess a value. 
977                                                 // It's not important because it will be set at this end of this function
978                                                 m_curPosition = position - m_preseek - 1;
979                                         }
980                                 }
981                         }
982                         // this is the timestamp of the frame we're looking for
983                         targetTs = (int64_t)(position / (m_baseFrameRate * timeBase)) + startTs;
984
985                         posFound = 0;
986                         avcodec_flush_buffers(m_codecCtx);
987                 }
988         } else if (m_isThreaded)
989         {
990                 // cache is not started but threading is possible
991                 // better not read the stream => make take some time, better start caching
992                 if (startCache())
993                         return NULL;
994                 // Abnormal!!! could not start cache, fall back on direct read
995                 m_isThreaded = false;
996         }
997
998         // find the correct frame, in case of streaming and no cache, it means just
999         // return the next frame. This is not quite correct, may need more work
1000         while(av_read_frame(m_formatCtx, &packet)>=0) 
1001         {
1002                 if(packet.stream_index == m_videoStream) 
1003                 {
1004                         avcodec_decode_video2(m_codecCtx, 
1005                                 m_frame, &frameFinished, 
1006                                 &packet);
1007                         // remember dts to compute exact frame number
1008                         dts = packet.dts;
1009                         if (frameFinished && !posFound) 
1010                         {
1011                                 if (dts >= targetTs)
1012                                 {
1013                                         posFound = 1;
1014                                 }
1015                         } 
1016
1017                         if (frameFinished && posFound == 1) 
1018                         {
1019                                 AVFrame * input = m_frame;
1020
1021                                 /* This means the data wasnt read properly, 
1022                                 this check stops crashing */
1023                                 if (   input->data[0]==0 && input->data[1]==0 
1024                                         && input->data[2]==0 && input->data[3]==0)
1025                                 {
1026                                         av_free_packet(&packet);
1027                                         break;
1028                                 }
1029
1030                                 if (m_deinterlace) 
1031                                 {
1032                                         if (avpicture_deinterlace(
1033                                                 (AVPicture*) m_frameDeinterlaced,
1034                                                 (const AVPicture*) m_frame,
1035                                                 m_codecCtx->pix_fmt,
1036                                                 m_codecCtx->width,
1037                                                 m_codecCtx->height) >= 0)
1038                                         {
1039                                                 input = m_frameDeinterlaced;
1040                                         }
1041                                 }
1042                                 // convert to RGB24
1043                                 sws_scale(m_imgConvertCtx,
1044                                         input->data,
1045                                         input->linesize,
1046                                         0,
1047                                         m_codecCtx->height,
1048                                         m_frameRGB->data,
1049                                         m_frameRGB->linesize);
1050                                 av_free_packet(&packet);
1051                                 frameLoaded = true;
1052                                 break;
1053                         }
1054                 }
1055                 av_free_packet(&packet);
1056         }
1057         m_eof = m_isFile && !frameLoaded;
1058         if (frameLoaded)
1059         {
1060                 m_curPosition = (long)((dts-startTs) * (m_baseFrameRate*timeBase) + 0.5);
1061                 if (m_isThreaded)
1062                 {
1063                         // normal case for file: first locate, then start cache
1064                         if (!startCache())
1065                         {
1066                                 // Abnormal!! could not start cache, return to non-cache mode
1067                                 m_isThreaded = false;
1068                         }
1069                 }
1070                 return m_frameRGB;
1071         }
1072         return NULL;
1073 }
1074
1075
1076 // python methods
1077
1078
1079 // cast Image pointer to VideoFFmpeg
1080 inline VideoFFmpeg * getVideoFFmpeg (PyImage * self)
1081 { return static_cast<VideoFFmpeg*>(self->m_image); }
1082
1083
1084 // object initialization
1085 static int VideoFFmpeg_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
1086 {
1087         PyImage * self = reinterpret_cast<PyImage*>(pySelf);
1088         // parameters - video source
1089         // file name or format type for capture (only for Linux: video4linux or dv1394)
1090         char * file = NULL;
1091         // capture device number
1092         short capt = -1;
1093         // capture width, only if capt is >= 0
1094         short width = 0;
1095         // capture height, only if capt is >= 0
1096         short height = 0;
1097         // capture rate, only if capt is >= 0
1098         float rate = 25.f;
1099
1100         static const char *kwlist[] = {"file", "capture", "rate", "width", "height", NULL};
1101
1102         // get parameters
1103         if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|hfhh",
1104                 const_cast<char**>(kwlist), &file, &capt, &rate, &width, &height))
1105                 return -1; 
1106
1107         try
1108         {
1109                 // create video object
1110                 Video_init<VideoFFmpeg>(self);
1111
1112                 // set thread usage
1113                 getVideoFFmpeg(self)->initParams(width, height, rate);
1114
1115                 // open video source
1116                 Video_open(getVideo(self), file, capt);
1117         }
1118         catch (Exception & exp)
1119         {
1120                 exp.report();
1121                 return -1;
1122         }
1123         // initialization succeded
1124         return 0;
1125 }
1126
1127 PyObject * VideoFFmpeg_getPreseek (PyImage *self, void * closure)
1128 {
1129         return Py_BuildValue("h", getFFmpeg(self)->getPreseek());
1130 }
1131
1132 // set range
1133 int VideoFFmpeg_setPreseek (PyImage * self, PyObject * value, void * closure)
1134 {
1135         // check validity of parameter
1136         if (value == NULL || !PyLong_Check(value))
1137         {
1138                 PyErr_SetString(PyExc_TypeError, "The value must be an integer");
1139                 return -1;
1140         }
1141         // set preseek
1142         getFFmpeg(self)->setPreseek(PyLong_AsSsize_t(value));
1143         // success
1144         return 0;
1145 }
1146
1147 // get deinterlace
1148 PyObject * VideoFFmpeg_getDeinterlace (PyImage * self, void * closure)
1149 {
1150         if (getFFmpeg(self)->getDeinterlace())
1151                 Py_RETURN_TRUE;
1152         else
1153                 Py_RETURN_FALSE;
1154 }
1155
1156 // set flip
1157 int VideoFFmpeg_setDeinterlace (PyImage * self, PyObject * value, void * closure)
1158 {
1159         // check parameter, report failure
1160         if (value == NULL || !PyBool_Check(value))
1161         {
1162                 PyErr_SetString(PyExc_TypeError, "The value must be a bool");
1163                 return -1;
1164         }
1165         // set deinterlace
1166         getFFmpeg(self)->setDeinterlace(value == Py_True);
1167         // success
1168         return 0;
1169 }
1170
1171 // methods structure
1172 static PyMethodDef videoMethods[] =
1173 { // methods from VideoBase class
1174         {"play", (PyCFunction)Video_play, METH_NOARGS, "Play (restart) video"},
1175         {"pause", (PyCFunction)Video_pause, METH_NOARGS, "pause video"},
1176         {"stop", (PyCFunction)Video_stop, METH_NOARGS, "stop video (play will replay it from start)"},
1177         {"refresh", (PyCFunction)Video_refresh, METH_NOARGS, "Refresh video - get its status"},
1178         {NULL}
1179 };
1180 // attributes structure
1181 static PyGetSetDef videoGetSets[] =
1182 { // methods from VideoBase class
1183         {(char*)"status", (getter)Video_getStatus, NULL, (char*)"video status", NULL},
1184         {(char*)"range", (getter)Video_getRange, (setter)Video_setRange, (char*)"replay range", NULL},
1185         {(char*)"repeat", (getter)Video_getRepeat, (setter)Video_setRepeat, (char*)"repeat count, -1 for infinite repeat", NULL},
1186         {(char*)"framerate", (getter)Video_getFrameRate, (setter)Video_setFrameRate, (char*)"frame rate", NULL},
1187         // attributes from ImageBase class
1188         {(char*)"valid", (getter)Image_valid, NULL, (char*)"bool to tell if an image is available", NULL},
1189         {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
1190         {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
1191         {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
1192         {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
1193         {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
1194         {(char*)"preseek", (getter)VideoFFmpeg_getPreseek, (setter)VideoFFmpeg_setPreseek, (char*)"nb of frames of preseek", NULL},
1195         {(char*)"deinterlace", (getter)VideoFFmpeg_getDeinterlace, (setter)VideoFFmpeg_setDeinterlace, (char*)"deinterlace image", NULL},
1196         {NULL}
1197 };
1198
1199 // python type declaration
1200 PyTypeObject VideoFFmpegType =
1201
1202         PyVarObject_HEAD_INIT(NULL, 0)
1203         "VideoTexture.VideoFFmpeg",   /*tp_name*/
1204         sizeof(PyImage),          /*tp_basicsize*/
1205         0,                         /*tp_itemsize*/
1206         (destructor)Image_dealloc, /*tp_dealloc*/
1207         0,                         /*tp_print*/
1208         0,                         /*tp_getattr*/
1209         0,                         /*tp_setattr*/
1210         0,                         /*tp_compare*/
1211         0,                         /*tp_repr*/
1212         0,                         /*tp_as_number*/
1213         0,                         /*tp_as_sequence*/
1214         0,                         /*tp_as_mapping*/
1215         0,                         /*tp_hash */
1216         0,                         /*tp_call*/
1217         0,                         /*tp_str*/
1218         0,                         /*tp_getattro*/
1219         0,                         /*tp_setattro*/
1220         &imageBufferProcs,         /*tp_as_buffer*/
1221         Py_TPFLAGS_DEFAULT,        /*tp_flags*/
1222         "FFmpeg video source",       /* tp_doc */
1223         0,                             /* tp_traverse */
1224         0,                             /* tp_clear */
1225         0,                             /* tp_richcompare */
1226         0,                             /* tp_weaklistoffset */
1227         0,                             /* tp_iter */
1228         0,                             /* tp_iternext */
1229         videoMethods,    /* tp_methods */
1230         0,                   /* tp_members */
1231         videoGetSets,          /* tp_getset */
1232         0,                         /* tp_base */
1233         0,                         /* tp_dict */
1234         0,                         /* tp_descr_get */
1235         0,                         /* tp_descr_set */
1236         0,                         /* tp_dictoffset */
1237         (initproc)VideoFFmpeg_init,     /* tp_init */
1238         0,                         /* tp_alloc */
1239         Image_allocNew,           /* tp_new */
1240 };
1241
1242 // object initialization
1243 static int ImageFFmpeg_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
1244 {
1245         PyImage * self = reinterpret_cast<PyImage*>(pySelf);
1246         // parameters - video source
1247         // file name or format type for capture (only for Linux: video4linux or dv1394)
1248         char * file = NULL;
1249
1250         // get parameters
1251         if (!PyArg_ParseTuple(args, "s:ImageFFmpeg", &file))
1252                 return -1; 
1253
1254         try
1255         {
1256                 // create video object
1257                 Video_init<VideoFFmpeg>(self);
1258
1259                 getVideoFFmpeg(self)->initParams(0, 0, 1.0, true);
1260
1261                 // open video source
1262                 Video_open(getVideo(self), file, -1);
1263         }
1264         catch (Exception & exp)
1265         {
1266                 exp.report();
1267                 return -1;
1268         }
1269         // initialization succeded
1270         return 0;
1271 }
1272
1273 PyObject * Image_reload (PyImage * self, PyObject *args)
1274 {
1275         char * newname = NULL;
1276         if (!PyArg_ParseTuple(args, "|s:reload", &newname))
1277                 return NULL;
1278         if (self->m_image != NULL)
1279         {
1280                 VideoFFmpeg* video = getFFmpeg(self);
1281                 // check type of object
1282                 if (!newname)
1283                         newname = video->getImageName();
1284                 if (!newname) {
1285                         // if not set, retport error
1286                         PyErr_SetString(PyExc_RuntimeError, "No image file name given");
1287                         return NULL;
1288                 }
1289                 // make sure the previous file is cleared
1290                 video->release();
1291                 // open the new file
1292                 video->openFile(newname);
1293         }
1294         Py_RETURN_NONE;
1295 }
1296
1297 // methods structure
1298 static PyMethodDef imageMethods[] =
1299 { // methods from VideoBase class
1300         {"refresh", (PyCFunction)Video_refresh, METH_NOARGS, "Refresh image, i.e. load it"},
1301         {"reload", (PyCFunction)Image_reload, METH_VARARGS, "Reload image, i.e. reopen it"},
1302         {NULL}
1303 };
1304 // attributes structure
1305 static PyGetSetDef imageGetSets[] =
1306 { // methods from VideoBase class
1307         {(char*)"status", (getter)Video_getStatus, NULL, (char*)"video status", NULL},
1308         // attributes from ImageBase class
1309         {(char*)"valid", (getter)Image_valid, NULL, (char*)"bool to tell if an image is available", NULL},
1310         {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
1311         {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
1312         {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
1313         {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
1314         {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
1315         {NULL}
1316 };
1317
1318 // python type declaration
1319 PyTypeObject ImageFFmpegType =
1320
1321         PyVarObject_HEAD_INIT(NULL, 0)
1322         "VideoTexture.ImageFFmpeg",   /*tp_name*/
1323         sizeof(PyImage),          /*tp_basicsize*/
1324         0,                         /*tp_itemsize*/
1325         (destructor)Image_dealloc, /*tp_dealloc*/
1326         0,                         /*tp_print*/
1327         0,                         /*tp_getattr*/
1328         0,                         /*tp_setattr*/
1329         0,                         /*tp_compare*/
1330         0,                         /*tp_repr*/
1331         0,                         /*tp_as_number*/
1332         0,                         /*tp_as_sequence*/
1333         0,                         /*tp_as_mapping*/
1334         0,                         /*tp_hash */
1335         0,                         /*tp_call*/
1336         0,                         /*tp_str*/
1337         0,                         /*tp_getattro*/
1338         0,                         /*tp_setattro*/
1339         &imageBufferProcs,         /*tp_as_buffer*/
1340         Py_TPFLAGS_DEFAULT,        /*tp_flags*/
1341         "FFmpeg image source",       /* tp_doc */
1342         0,                             /* tp_traverse */
1343         0,                             /* tp_clear */
1344         0,                             /* tp_richcompare */
1345         0,                             /* tp_weaklistoffset */
1346         0,                             /* tp_iter */
1347         0,                             /* tp_iternext */
1348         imageMethods,    /* tp_methods */
1349         0,                   /* tp_members */
1350         imageGetSets,          /* tp_getset */
1351         0,                         /* tp_base */
1352         0,                         /* tp_dict */
1353         0,                         /* tp_descr_get */
1354         0,                         /* tp_descr_set */
1355         0,                         /* tp_dictoffset */
1356         (initproc)ImageFFmpeg_init,     /* tp_init */
1357         0,                         /* tp_alloc */
1358         Image_allocNew,           /* tp_new */
1359 };
1360
1361 #endif  //WITH_FFMPEG
1362
1363