f4d3fb7522357bea058ad0c5cf82cd46e0e32352
[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 "VideoFFmpeg.h"
43 #include "Exception.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 positioning 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                            filename[28], rateStr[20];
592         char                *p;
593
594         do_init_ffmpeg();
595
596         memset(&formatParams, 0, sizeof(formatParams));
597 #ifdef WIN32
598         // video capture on windows only through Video For Windows driver
599         inputFormat = av_find_input_format("vfwcap");
600         if (!inputFormat)
601                 // Video For Windows not supported??
602                 return;
603         sprintf(filename, "%d", camIdx);
604 #else
605         // In Linux we support two types of devices: VideoForLinux and DV1394. 
606         // the user specify it with the filename:
607         // [<device_type>][:<standard>]
608         // <device_type> : 'v4l' for VideoForLinux, 'dv1394' for DV1394. By default 'v4l'
609         // <standard>    : 'pal', 'secam' or 'ntsc'. By default 'ntsc'
610         // The driver name is constructed automatically from the device type:
611         // v4l   : /dev/video<camIdx>
612         // dv1394: /dev/dv1394/<camIdx>
613         // If you have different driver name, you can specify the driver name explicitly
614         // instead of device type. Examples of valid filename:
615         //    /dev/v4l/video0:pal
616         //    /dev/ieee1394/1:ntsc
617         //    dv1394:secam
618         //    v4l:pal
619         if (file && strstr(file, "1394") != NULL) 
620         {
621                 // the user specifies a driver, check if it is v4l or d41394
622                 inputFormat = av_find_input_format("dv1394");
623                 sprintf(filename, "/dev/dv1394/%d", camIdx);
624         } else 
625         {
626                 inputFormat = av_find_input_format("video4linux");
627                 sprintf(filename, "/dev/video%d", camIdx);
628         }
629         if (!inputFormat)
630                 // these format should be supported, check ffmpeg compilation
631                 return;
632         if (file && strncmp(file, "/dev", 4) == 0) 
633         {
634                 // user does not specify a driver
635                 strncpy(filename, file, sizeof(filename));
636                 filename[sizeof(filename)-1] = 0;
637                 if ((p = strchr(filename, ':')) != 0)
638                         *p = 0;
639         }
640         if (file && (p = strchr(file, ':')) != NULL)
641                 formatParams.standard = p+1;
642 #endif
643         //frame rate
644         if (m_captRate <= 0.f)
645                 m_captRate = defFrameRate;
646         sprintf(rateStr, "%f", m_captRate);
647         av_parse_video_rate(&frameRate, rateStr);
648         // populate format parameters
649         // need to specify the time base = inverse of rate
650         formatParams.time_base.num = frameRate.den;
651         formatParams.time_base.den = frameRate.num;
652         formatParams.width = m_captWidth;
653         formatParams.height = m_captHeight;
654
655         if (openStream(filename, inputFormat, &formatParams) != 0)
656                 return;
657
658         // for video capture it is important to do non blocking read
659         m_formatCtx->flags |= AVFMT_FLAG_NONBLOCK;
660         // open base class
661         VideoBase::openCam(file, camIdx);
662         // check if we should do multi-threading?
663         if (BLI_system_thread_count() > 1)
664         {
665                 // no need to thread if the system has a single core
666                 m_isThreaded =  true;
667         }
668 }
669
670 // play video
671 bool VideoFFmpeg::play (void)
672 {
673         try
674         {
675                 // if object is able to play
676                 if (VideoBase::play())
677                 {
678                         // set video position
679                         setPositions();
680                         // return success
681                         return true;
682                 }
683         }
684         CATCH_EXCP;
685         return false;
686 }
687
688
689 // pause video
690 bool VideoFFmpeg::pause (void)
691 {
692         try
693         {
694                 if (VideoBase::pause())
695                 {
696                         return true;
697                 }
698         }
699         CATCH_EXCP;
700         return false;
701 }
702
703 // stop video
704 bool VideoFFmpeg::stop (void)
705 {
706         try
707         {
708                 VideoBase::stop();
709                 // force restart when play
710                 m_lastFrame = -1;
711                 return true;
712         }
713         CATCH_EXCP;
714         return false;
715 }
716
717
718 // set video range
719 void VideoFFmpeg::setRange (double start, double stop)
720 {
721         try
722         {
723                 // set range
724                 if (m_isFile)
725                 {
726                         VideoBase::setRange(start, stop);
727                         // set range for video
728                         setPositions();
729                 }
730         }
731         CATCH_EXCP;
732 }
733
734 // set framerate
735 void VideoFFmpeg::setFrameRate (float rate)
736 {
737         VideoBase::setFrameRate(rate);
738 }
739
740
741 // image calculation
742 // load frame from video
743 void VideoFFmpeg::calcImage (unsigned int texId, double ts)
744 {
745         if (m_status == SourcePlaying)
746         {
747                 // get actual time
748                 double startTime = PIL_check_seconds_timer();
749                 double actTime;
750                 // timestamp passed from audio actuators can sometimes be slightly negative
751                 if (m_isFile && ts >= -0.5)
752                 {
753                         // allow setting timestamp only when not streaming
754                         actTime = ts;
755                         if (actTime * actFrameRate() < m_lastFrame) 
756                         {
757                                 // user is asking to rewind, force a cache clear to make sure we will do a seek
758                                 // note that this does not decrement m_repeat if ts didn't reach m_range[1]
759                                 stopCache();
760                         }
761                 }
762                 else
763                 {
764                         if (m_lastFrame == -1 && !m_isFile)
765                                 m_startTime = startTime;
766                         actTime = startTime - m_startTime;
767                 }
768                 // if video has ended
769                 if (m_isFile && actTime * m_frameRate >= m_range[1])
770                 {
771                         // in any case, this resets the cache
772                         stopCache();
773                         // if repeats are set, decrease them
774                         if (m_repeat > 0) 
775                                 --m_repeat;
776                         // if video has to be replayed
777                         if (m_repeat != 0)
778                         {
779                                 // reset its position
780                                 actTime -= (m_range[1] - m_range[0]) / m_frameRate;
781                                 m_startTime += (m_range[1] - m_range[0]) / m_frameRate;
782                         }
783                         // if video has to be stopped, stop it
784                         else 
785                         {
786                                 m_status = SourceStopped;
787                                 return;
788                         }
789                 }
790                 // actual frame
791                 long actFrame = (m_isImage) ? m_lastFrame+1 : long(actTime * actFrameRate());
792                 // if actual frame differs from last frame
793                 if (actFrame != m_lastFrame)
794                 {
795                         AVFrame* frame;
796                         // get image
797                         if ((frame = grabFrame(actFrame)) != NULL)
798                         {
799                                 if (!m_isFile && !m_cacheStarted) 
800                                 {
801                                         // streaming without cache: detect synchronization problem
802                                         double execTime = PIL_check_seconds_timer() - startTime;
803                                         if (execTime > 0.005) 
804                                         {
805                                                 // exec time is too long, it means that the function was blocking
806                                                 // resynchronize the stream from this time
807                                                 m_startTime += execTime;
808                                         }
809                                 }
810                                 // save actual frame
811                                 m_lastFrame = actFrame;
812                                 // init image, if needed
813                                 init(short(m_codecCtx->width), short(m_codecCtx->height));
814                                 // process image
815                                 process((BYTE*)(frame->data[0]));
816                                 // finished with the frame, release it so that cache can reuse it
817                                 releaseFrame(frame);
818                                 // in case it is an image, automatically stop reading it
819                                 if (m_isImage)
820                                 {
821                                         m_status = SourceStopped;
822                                         // close the file as we don't need it anymore
823                                         release();
824                                 }
825                         } else if (m_isStreaming)
826                         {
827                                 // we didn't get a frame and we are streaming, this may be due to
828                                 // a delay in the network or because we are getting the frame too fast.
829                                 // In the later case, shift time by a small amount to compensate for a drift
830                                 m_startTime += 0.001;
831                         }
832                 }
833         }
834 }
835
836
837 // set actual position
838 void VideoFFmpeg::setPositions (void)
839 {
840         // set video start time
841         m_startTime = PIL_check_seconds_timer();
842         // if file is played and actual position is before end position
843         if (!m_eof && m_lastFrame >= 0 && (!m_isFile || m_lastFrame < m_range[1] * actFrameRate()))
844                 // continue from actual position
845                 m_startTime -= double(m_lastFrame) / actFrameRate();
846         else {
847                 m_startTime -= m_range[0];
848                 // start from beginning, stop cache just in case
849                 stopCache();
850         }
851 }
852
853 // position pointer in file, position in second
854 AVFrame *VideoFFmpeg::grabFrame(long position)
855 {
856         AVPacket packet;
857         int frameFinished;
858         int posFound = 1;
859         bool frameLoaded = false;
860         int64_t targetTs = 0;
861         CacheFrame *frame;
862         int64_t dts = 0;
863
864         if (m_cacheStarted)
865         {
866                 // when cache is active, we must not read the file directly
867                 do {
868                         pthread_mutex_lock(&m_cacheMutex);
869                         frame = (CacheFrame *)m_frameCacheBase.first;
870                         pthread_mutex_unlock(&m_cacheMutex);
871                         // no need to remove the frame from the queue: the cache thread does not touch the head, only the tail
872                         if (frame == NULL)
873                         {
874                                 // no frame in cache, in case of file it is an abnormal situation
875                                 if (m_isFile)
876                                 {
877                                         // go back to no threaded reading
878                                         stopCache();
879                                         break;
880                                 }
881                                 return NULL;
882                         }
883                         if (frame->framePosition == -1) 
884                         {
885                                 // this frame mark the end of the file (only used for file)
886                                 // leave in cache to make sure we don't miss it
887                                 m_eof = true;
888                                 return NULL;
889                         }
890                         // for streaming, always return the next frame, 
891                         // that's what grabFrame does in non cache mode anyway.
892                         if (m_isStreaming || frame->framePosition == position)
893                         {
894                                 return frame->frame;
895                         }
896                         // for cam, skip old frames to keep image realtime.
897                         // There should be no risk of clock drift since it all happens on the same CPU
898                         if (frame->framePosition > position) 
899                         {
900                                 // this can happen after rewind if the seek didn't find the first frame
901                                 // the frame in the buffer is ahead of time, just leave it there
902                                 return NULL;
903                         }
904                         // this frame is not useful, release it
905                         pthread_mutex_lock(&m_cacheMutex);
906                         BLI_remlink(&m_frameCacheBase, frame);
907                         BLI_addtail(&m_frameCacheFree, frame);
908                         pthread_mutex_unlock(&m_cacheMutex);
909                 } while (true);
910         }
911         double timeBase = av_q2d(m_formatCtx->streams[m_videoStream]->time_base);
912         int64_t startTs = m_formatCtx->streams[m_videoStream]->start_time;
913         if (startTs == AV_NOPTS_VALUE)
914                 startTs = 0;
915
916         // come here when there is no cache or cache has been stopped
917         // locate the frame, by seeking if necessary (seeking is only possible for files)
918         if (m_isFile)
919         {
920                 // first check if the position that we are looking for is in the preseek range
921                 // if so, just read the frame until we get there
922                 if (position > m_curPosition + 1 
923                         && m_preseek 
924                         && position - (m_curPosition + 1) < m_preseek) 
925                 {
926                         while(av_read_frame(m_formatCtx, &packet)>=0) 
927                         {
928                                 if (packet.stream_index == m_videoStream) 
929                                 {
930                                         avcodec_decode_video2(
931                                                 m_codecCtx, 
932                                                 m_frame, &frameFinished, 
933                                                 &packet);
934                                         if (frameFinished)
935                                         {
936                                                 m_curPosition = (long)((packet.dts-startTs) * (m_baseFrameRate*timeBase) + 0.5);
937                                         }
938                                 }
939                                 av_free_packet(&packet);
940                                 if (position == m_curPosition+1)
941                                         break;
942                         }
943                 }
944                 // if the position is not in preseek, do a direct jump
945                 if (position != m_curPosition + 1) 
946                 { 
947                         int64_t pos = (int64_t)((position - m_preseek) / (m_baseFrameRate*timeBase));
948
949                         if (pos < 0)
950                                 pos = 0;
951
952                         pos += startTs;
953
954                         if (position <= m_curPosition || !m_eof)
955                         {
956 #if 0
957                                 // Tried to make this work but couldn't: seeking on byte is ignored by the
958                                 // format plugin and it will generally continue to read from last timestamp.
959                                 // Too bad because frame seek is not always able to get the first frame
960                                 // of the file.
961                                 if (position <= m_preseek)
962                                 {
963                                         // we can safely go the beginning of the file
964                                         if (av_seek_frame(m_formatCtx, m_videoStream, 0, AVSEEK_FLAG_BYTE) >= 0)
965                                         {
966                                                 // binary seek does not reset the timestamp, must do it now
967                                                 av_update_cur_dts(m_formatCtx, m_formatCtx->streams[m_videoStream], startTs);
968                                                 m_curPosition = 0;
969                                         }
970                                 }
971                                 else
972 #endif
973                                 {
974                                         // current position is now lost, guess a value. 
975                                         if (av_seek_frame(m_formatCtx, m_videoStream, pos, AVSEEK_FLAG_BACKWARD) >= 0)
976                                         {
977                                                 // current position is now lost, guess a value. 
978                                                 // It's not important because it will be set at this end of this function
979                                                 m_curPosition = position - m_preseek - 1;
980                                         }
981                                 }
982                         }
983                         // this is the timestamp of the frame we're looking for
984                         targetTs = (int64_t)(position / (m_baseFrameRate * timeBase)) + startTs;
985
986                         posFound = 0;
987                         avcodec_flush_buffers(m_codecCtx);
988                 }
989         } else if (m_isThreaded)
990         {
991                 // cache is not started but threading is possible
992                 // better not read the stream => make take some time, better start caching
993                 if (startCache())
994                         return NULL;
995                 // Abnormal!!! could not start cache, fall back on direct read
996                 m_isThreaded = false;
997         }
998
999         // find the correct frame, in case of streaming and no cache, it means just
1000         // return the next frame. This is not quite correct, may need more work
1001         while(av_read_frame(m_formatCtx, &packet)>=0) 
1002         {
1003                 if (packet.stream_index == m_videoStream) 
1004                 {
1005                         avcodec_decode_video2(m_codecCtx, 
1006                                 m_frame, &frameFinished, 
1007                                 &packet);
1008                         // remember dts to compute exact frame number
1009                         dts = packet.dts;
1010                         if (frameFinished && !posFound) 
1011                         {
1012                                 if (dts >= targetTs)
1013                                 {
1014                                         posFound = 1;
1015                                 }
1016                         } 
1017
1018                         if (frameFinished && posFound == 1) 
1019                         {
1020                                 AVFrame * input = m_frame;
1021
1022                                 /* This means the data wasnt read properly, 
1023                                 this check stops crashing */
1024                                 if (   input->data[0]==0 && input->data[1]==0 
1025                                         && input->data[2]==0 && input->data[3]==0)
1026                                 {
1027                                         av_free_packet(&packet);
1028                                         break;
1029                                 }
1030
1031                                 if (m_deinterlace) 
1032                                 {
1033                                         if (avpicture_deinterlace(
1034                                                 (AVPicture*) m_frameDeinterlaced,
1035                                                 (const AVPicture*) m_frame,
1036                                                 m_codecCtx->pix_fmt,
1037                                                 m_codecCtx->width,
1038                                                 m_codecCtx->height) >= 0)
1039                                         {
1040                                                 input = m_frameDeinterlaced;
1041                                         }
1042                                 }
1043                                 // convert to RGB24
1044                                 sws_scale(m_imgConvertCtx,
1045                                         input->data,
1046                                         input->linesize,
1047                                         0,
1048                                         m_codecCtx->height,
1049                                         m_frameRGB->data,
1050                                         m_frameRGB->linesize);
1051                                 av_free_packet(&packet);
1052                                 frameLoaded = true;
1053                                 break;
1054                         }
1055                 }
1056                 av_free_packet(&packet);
1057         }
1058         m_eof = m_isFile && !frameLoaded;
1059         if (frameLoaded)
1060         {
1061                 m_curPosition = (long)((dts-startTs) * (m_baseFrameRate*timeBase) + 0.5);
1062                 if (m_isThreaded)
1063                 {
1064                         // normal case for file: first locate, then start cache
1065                         if (!startCache())
1066                         {
1067                                 // Abnormal!! could not start cache, return to non-cache mode
1068                                 m_isThreaded = false;
1069                         }
1070                 }
1071                 return m_frameRGB;
1072         }
1073         return NULL;
1074 }
1075
1076
1077 // python methods
1078
1079
1080 // cast Image pointer to VideoFFmpeg
1081 inline VideoFFmpeg * getVideoFFmpeg (PyImage * self)
1082 { return static_cast<VideoFFmpeg*>(self->m_image); }
1083
1084
1085 // object initialization
1086 static int VideoFFmpeg_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
1087 {
1088         PyImage * self = reinterpret_cast<PyImage*>(pySelf);
1089         // parameters - video source
1090         // file name or format type for capture (only for Linux: video4linux or dv1394)
1091         char * file = NULL;
1092         // capture device number
1093         short capt = -1;
1094         // capture width, only if capt is >= 0
1095         short width = 0;
1096         // capture height, only if capt is >= 0
1097         short height = 0;
1098         // capture rate, only if capt is >= 0
1099         float rate = 25.f;
1100
1101         static const char *kwlist[] = {"file", "capture", "rate", "width", "height", NULL};
1102
1103         // get parameters
1104         if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|hfhh",
1105                 const_cast<char**>(kwlist), &file, &capt, &rate, &width, &height))
1106                 return -1; 
1107
1108         try
1109         {
1110                 // create video object
1111                 Video_init<VideoFFmpeg>(self);
1112
1113                 // set thread usage
1114                 getVideoFFmpeg(self)->initParams(width, height, rate);
1115
1116                 // open video source
1117                 Video_open(getVideo(self), file, capt);
1118         }
1119         catch (Exception & exp)
1120         {
1121                 exp.report();
1122                 return -1;
1123         }
1124         // initialization succeded
1125         return 0;
1126 }
1127
1128 PyObject * VideoFFmpeg_getPreseek (PyImage *self, void * closure)
1129 {
1130         return Py_BuildValue("h", getFFmpeg(self)->getPreseek());
1131 }
1132
1133 // set range
1134 int VideoFFmpeg_setPreseek (PyImage * self, PyObject * value, void * closure)
1135 {
1136         // check validity of parameter
1137         if (value == NULL || !PyLong_Check(value))
1138         {
1139                 PyErr_SetString(PyExc_TypeError, "The value must be an integer");
1140                 return -1;
1141         }
1142         // set preseek
1143         getFFmpeg(self)->setPreseek(PyLong_AsSsize_t(value));
1144         // success
1145         return 0;
1146 }
1147
1148 // get deinterlace
1149 PyObject * VideoFFmpeg_getDeinterlace (PyImage * self, void * closure)
1150 {
1151         if (getFFmpeg(self)->getDeinterlace())
1152                 Py_RETURN_TRUE;
1153         else
1154                 Py_RETURN_FALSE;
1155 }
1156
1157 // set flip
1158 int VideoFFmpeg_setDeinterlace (PyImage * self, PyObject * value, void * closure)
1159 {
1160         // check parameter, report failure
1161         if (value == NULL || !PyBool_Check(value))
1162         {
1163                 PyErr_SetString(PyExc_TypeError, "The value must be a bool");
1164                 return -1;
1165         }
1166         // set deinterlace
1167         getFFmpeg(self)->setDeinterlace(value == Py_True);
1168         // success
1169         return 0;
1170 }
1171
1172 // methods structure
1173 static PyMethodDef videoMethods[] =
1174 { // methods from VideoBase class
1175         {"play", (PyCFunction)Video_play, METH_NOARGS, "Play (restart) video"},
1176         {"pause", (PyCFunction)Video_pause, METH_NOARGS, "pause video"},
1177         {"stop", (PyCFunction)Video_stop, METH_NOARGS, "stop video (play will replay it from start)"},
1178         {"refresh", (PyCFunction)Video_refresh, METH_NOARGS, "Refresh video - get its status"},
1179         {NULL}
1180 };
1181 // attributes structure
1182 static PyGetSetDef videoGetSets[] =
1183 { // methods from VideoBase class
1184         {(char*)"status", (getter)Video_getStatus, NULL, (char*)"video status", NULL},
1185         {(char*)"range", (getter)Video_getRange, (setter)Video_setRange, (char*)"replay range", NULL},
1186         {(char*)"repeat", (getter)Video_getRepeat, (setter)Video_setRepeat, (char*)"repeat count, -1 for infinite repeat", NULL},
1187         {(char*)"framerate", (getter)Video_getFrameRate, (setter)Video_setFrameRate, (char*)"frame rate", NULL},
1188         // attributes from ImageBase class
1189         {(char*)"valid", (getter)Image_valid, NULL, (char*)"bool to tell if an image is available", NULL},
1190         {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
1191         {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
1192         {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
1193         {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
1194         {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
1195         {(char*)"preseek", (getter)VideoFFmpeg_getPreseek, (setter)VideoFFmpeg_setPreseek, (char*)"nb of frames of preseek", NULL},
1196         {(char*)"deinterlace", (getter)VideoFFmpeg_getDeinterlace, (setter)VideoFFmpeg_setDeinterlace, (char*)"deinterlace image", NULL},
1197         {NULL}
1198 };
1199
1200 // python type declaration
1201 PyTypeObject VideoFFmpegType =
1202
1203         PyVarObject_HEAD_INIT(NULL, 0)
1204         "VideoTexture.VideoFFmpeg",   /*tp_name*/
1205         sizeof(PyImage),          /*tp_basicsize*/
1206         0,                         /*tp_itemsize*/
1207         (destructor)Image_dealloc, /*tp_dealloc*/
1208         0,                         /*tp_print*/
1209         0,                         /*tp_getattr*/
1210         0,                         /*tp_setattr*/
1211         0,                         /*tp_compare*/
1212         0,                         /*tp_repr*/
1213         0,                         /*tp_as_number*/
1214         0,                         /*tp_as_sequence*/
1215         0,                         /*tp_as_mapping*/
1216         0,                         /*tp_hash */
1217         0,                         /*tp_call*/
1218         0,                         /*tp_str*/
1219         0,                         /*tp_getattro*/
1220         0,                         /*tp_setattro*/
1221         &imageBufferProcs,         /*tp_as_buffer*/
1222         Py_TPFLAGS_DEFAULT,        /*tp_flags*/
1223         "FFmpeg video source",       /* tp_doc */
1224         0,                             /* tp_traverse */
1225         0,                             /* tp_clear */
1226         0,                             /* tp_richcompare */
1227         0,                             /* tp_weaklistoffset */
1228         0,                             /* tp_iter */
1229         0,                             /* tp_iternext */
1230         videoMethods,    /* tp_methods */
1231         0,                   /* tp_members */
1232         videoGetSets,          /* tp_getset */
1233         0,                         /* tp_base */
1234         0,                         /* tp_dict */
1235         0,                         /* tp_descr_get */
1236         0,                         /* tp_descr_set */
1237         0,                         /* tp_dictoffset */
1238         (initproc)VideoFFmpeg_init,     /* tp_init */
1239         0,                         /* tp_alloc */
1240         Image_allocNew,           /* tp_new */
1241 };
1242
1243 // object initialization
1244 static int ImageFFmpeg_init (PyObject * pySelf, PyObject * args, PyObject * kwds)
1245 {
1246         PyImage * self = reinterpret_cast<PyImage*>(pySelf);
1247         // parameters - video source
1248         // file name or format type for capture (only for Linux: video4linux or dv1394)
1249         char * file = NULL;
1250
1251         // get parameters
1252         if (!PyArg_ParseTuple(args, "s:ImageFFmpeg", &file))
1253                 return -1; 
1254
1255         try
1256         {
1257                 // create video object
1258                 Video_init<VideoFFmpeg>(self);
1259
1260                 getVideoFFmpeg(self)->initParams(0, 0, 1.0, true);
1261
1262                 // open video source
1263                 Video_open(getVideo(self), file, -1);
1264         }
1265         catch (Exception & exp)
1266         {
1267                 exp.report();
1268                 return -1;
1269         }
1270         // initialization succeded
1271         return 0;
1272 }
1273
1274 PyObject * Image_reload (PyImage * self, PyObject *args)
1275 {
1276         char * newname = NULL;
1277         if (!PyArg_ParseTuple(args, "|s:reload", &newname))
1278                 return NULL;
1279         if (self->m_image != NULL)
1280         {
1281                 VideoFFmpeg* video = getFFmpeg(self);
1282                 // check type of object
1283                 if (!newname)
1284                         newname = video->getImageName();
1285                 if (!newname) {
1286                         // if not set, retport error
1287                         PyErr_SetString(PyExc_RuntimeError, "No image file name given");
1288                         return NULL;
1289                 }
1290                 // make sure the previous file is cleared
1291                 video->release();
1292                 // open the new file
1293                 video->openFile(newname);
1294         }
1295         Py_RETURN_NONE;
1296 }
1297
1298 // methods structure
1299 static PyMethodDef imageMethods[] =
1300 { // methods from VideoBase class
1301         {"refresh", (PyCFunction)Video_refresh, METH_NOARGS, "Refresh image, i.e. load it"},
1302         {"reload", (PyCFunction)Image_reload, METH_VARARGS, "Reload image, i.e. reopen it"},
1303         {NULL}
1304 };
1305 // attributes structure
1306 static PyGetSetDef imageGetSets[] =
1307 { // methods from VideoBase class
1308         {(char*)"status", (getter)Video_getStatus, NULL, (char*)"video status", NULL},
1309         // attributes from ImageBase class
1310         {(char*)"valid", (getter)Image_valid, NULL, (char*)"bool to tell if an image is available", NULL},
1311         {(char*)"image", (getter)Image_getImage, NULL, (char*)"image data", NULL},
1312         {(char*)"size", (getter)Image_getSize, NULL, (char*)"image size", NULL},
1313         {(char*)"scale", (getter)Image_getScale, (setter)Image_setScale, (char*)"fast scale of image (near neighbor)", NULL},
1314         {(char*)"flip", (getter)Image_getFlip, (setter)Image_setFlip, (char*)"flip image vertically", NULL},
1315         {(char*)"filter", (getter)Image_getFilter, (setter)Image_setFilter, (char*)"pixel filter", NULL},
1316         {NULL}
1317 };
1318
1319 // python type declaration
1320 PyTypeObject ImageFFmpegType =
1321
1322         PyVarObject_HEAD_INIT(NULL, 0)
1323         "VideoTexture.ImageFFmpeg",   /*tp_name*/
1324         sizeof(PyImage),          /*tp_basicsize*/
1325         0,                         /*tp_itemsize*/
1326         (destructor)Image_dealloc, /*tp_dealloc*/
1327         0,                         /*tp_print*/
1328         0,                         /*tp_getattr*/
1329         0,                         /*tp_setattr*/
1330         0,                         /*tp_compare*/
1331         0,                         /*tp_repr*/
1332         0,                         /*tp_as_number*/
1333         0,                         /*tp_as_sequence*/
1334         0,                         /*tp_as_mapping*/
1335         0,                         /*tp_hash */
1336         0,                         /*tp_call*/
1337         0,                         /*tp_str*/
1338         0,                         /*tp_getattro*/
1339         0,                         /*tp_setattro*/
1340         &imageBufferProcs,         /*tp_as_buffer*/
1341         Py_TPFLAGS_DEFAULT,        /*tp_flags*/
1342         "FFmpeg image source",       /* tp_doc */
1343         0,                             /* tp_traverse */
1344         0,                             /* tp_clear */
1345         0,                             /* tp_richcompare */
1346         0,                             /* tp_weaklistoffset */
1347         0,                             /* tp_iter */
1348         0,                             /* tp_iternext */
1349         imageMethods,    /* tp_methods */
1350         0,                   /* tp_members */
1351         imageGetSets,          /* tp_getset */
1352         0,                         /* tp_base */
1353         0,                         /* tp_dict */
1354         0,                         /* tp_descr_get */
1355         0,                         /* tp_descr_set */
1356         0,                         /* tp_dictoffset */
1357         (initproc)ImageFFmpeg_init,     /* tp_init */
1358         0,                         /* tp_alloc */
1359         Image_allocNew,           /* tp_new */
1360 };
1361
1362 #endif  //WITH_FFMPEG
1363
1364