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