f9c584fba392b6d2a4fc2fdd01868ec24ebeb456
[blender.git] / source / blender / imbuf / intern / anim.c
1 /**
2  * anim.c
3  *
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #ifdef _WIN32
33 #define INC_OLE2
34 #include <windows.h>
35 #include <windowsx.h>
36 #include <mmsystem.h>
37 #include <memory.h>
38 #include <commdlg.h>
39
40 #ifndef FREE_WINDOWS
41 #include <vfw.h>
42 #endif
43
44 #undef AVIIF_KEYFRAME // redefined in AVI_avi.h
45 #undef AVIIF_LIST // redefined in AVI_avi.h
46
47 #define FIXCC(fcc)  if (fcc == 0)       fcc = mmioFOURCC('N', 'o', 'n', 'e'); \
48                 if (fcc == BI_RLE8) fcc = mmioFOURCC('R', 'l', 'e', '8');
49 #endif
50
51 #include <sys/types.h>
52 #include <ctype.h>
53 #include <stdlib.h>
54 #include <stdio.h>
55 #ifndef _WIN32
56 #include <dirent.h>
57 #else
58 #include <io.h>
59 #endif
60
61 #include "BLI_blenlib.h" /* BLI_remlink BLI_filesize BLI_addtail
62                             BLI_countlist BLI_stringdec */
63 #include "DNA_userdef_types.h"
64 #include "BKE_global.h"
65
66 #include "imbuf.h"
67 #include "imbuf_patch.h"
68
69 #include "AVI_avi.h"
70
71 #ifdef WITH_QUICKTIME
72 #if defined(_WIN32) || defined(__APPLE__)
73 #include "quicktime_import.h"
74 #endif /* _WIN32 || __APPLE__ */
75 #endif /* WITH_QUICKTIME */
76
77 #include "IMB_imbuf_types.h"
78 #include "IMB_imbuf.h"
79
80 #include "IMB_allocimbuf.h"
81 #include "IMB_bitplanes.h"
82 #include "IMB_anim.h"
83 #include "IMB_anim5.h"
84
85 #ifdef WITH_FFMPEG
86 #include <ffmpeg/avformat.h>
87 #include <ffmpeg/avcodec.h>
88 #include <ffmpeg/rational.h>
89 #include <ffmpeg/swscale.h>
90
91 #if LIBAVFORMAT_VERSION_INT < (49 << 16)
92 #define FFMPEG_OLD_FRAME_RATE 1
93 #else
94 #define FFMPEG_CODEC_IS_POINTER 1
95 #endif
96
97 #endif
98
99 #ifdef WITH_REDCODE
100 #include <redcode/format.h>
101 #include <redcode/codec.h>
102 #endif
103
104 /****/
105
106 #ifdef __sgi
107
108 #include <dmedia/moviefile.h>
109
110 static void movie_printerror(char * str) {
111         const char * errstr = mvGetErrorStr(mvGetErrno());
112
113         if (str) {
114                 if (errstr) printf("%s: %s\n", str, errstr);
115                 else printf("%s: returned error\n", str);
116         } else printf("%s\n", errstr);
117 }
118
119 static int startmovie(struct anim * anim) {
120         if (anim == 0) return(-1);
121
122         if ( mvOpenFile (anim->name, O_BINARY|O_RDONLY, &anim->movie ) != DM_SUCCESS ) {
123                 printf("Can't open movie: %s\n", anim->name);
124                 return(-1);
125         }
126         if ( mvFindTrackByMedium (anim->movie, DM_IMAGE, &anim->track) != DM_SUCCESS ) {
127                 printf("No image track in movie: %s\n", anim->name);
128                 mvClose(anim->movie);
129                 return(-1);
130         }
131
132         anim->duration = mvGetTrackLength (anim->track);
133         anim->params = mvGetParams( anim->track );
134
135         anim->x = dmParamsGetInt( anim->params, DM_IMAGE_WIDTH);
136         anim->y = dmParamsGetInt( anim->params, DM_IMAGE_HEIGHT);
137         anim->interlacing = dmParamsGetEnum (anim->params, DM_IMAGE_INTERLACING);
138         anim->orientation = dmParamsGetEnum (anim->params, DM_IMAGE_ORIENTATION);
139         anim->framesize = dmImageFrameSize(anim->params);
140
141         anim->curposition = 0;
142         anim->preseek = 0;
143
144         /*printf("x:%d y:%d size:%d interl:%d dur:%d\n", anim->x, anim->y, anim->framesize, anim->interlacing, anim->duration);*/
145         return (0);
146 }
147
148 static ImBuf * movie_fetchibuf(struct anim * anim, int position) {
149         ImBuf * ibuf;
150 /*      extern rectcpy(); */
151         int size;
152         unsigned int *rect1, *rect2;
153
154         if (anim == 0) return (0);
155
156         ibuf = IMB_allocImBuf(anim->x, anim->y, 24, IB_rect, 0);
157
158         if ( mvReadFrames(anim->track, position, 1, ibuf->x * ibuf->y * 
159                 sizeof(int), ibuf->rect ) != DM_SUCCESS ) {
160                 movie_printerror("mvReadFrames");
161                 IMB_freeImBuf(ibuf);
162                 return(0);
163         }
164
165 /*
166         if (anim->interlacing == DM_IMAGE_INTERLACED_EVEN) {
167                 rect1 = ibuf->rect + (ibuf->x * ibuf->y) - 1;
168                 rect2 = rect1 - ibuf->x;
169     
170                 for (size = ibuf->x * (ibuf->y - 1); size > 0; size--){
171                         *rect1-- = *rect2--;
172                 }
173         }
174 */
175
176         if (anim->interlacing == DM_IMAGE_INTERLACED_EVEN)
177         {
178                 rect1 = ibuf->rect;
179                 rect2 = rect1 + ibuf->x;
180
181                 for (size = ibuf->x * (ibuf->y - 1); size > 0; size--){
182                         *rect1++ = *rect2++;
183                 }
184         }
185         /*if (anim->orientation == DM_TOP_TO_BOTTOM) IMB_flipy(ibuf);*/
186
187
188         return(ibuf);
189 }
190
191 static void free_anim_movie(struct anim * anim) {
192         if (anim == NULL) return;
193
194         if (anim->movie) {
195                 mvClose(anim->movie);
196                 anim->movie = NULL;
197         }
198         anim->duration = 0;
199 }
200
201 int ismovie(char *name) {
202         return (mvIsMovieFile(name) == DM_TRUE);
203 }
204
205 #else
206
207 int ismovie(char *name) {
208         return 0;
209 }
210
211         /* never called, just keep the linker happy */
212 static int startmovie(struct anim * anim) { return 1; }
213 static ImBuf * movie_fetchibuf(struct anim * anim, int position) { return NULL; }
214 static void free_anim_movie(struct anim * anim) { ; }
215
216 #endif
217
218 static int an_stringdec(char *string, char* kop, char *staart,unsigned short *numlen) {
219         unsigned short len,nume,nums=0;
220         short i,found=FALSE;
221
222         len=strlen(string);
223         nume = len;
224
225         for(i=len-1;i>=0;i--){
226                 if (string[i]=='/') break;
227                 if (isdigit(string[i])) {
228                         if (found){
229                                 nums=i;
230                         } else{
231                                 nume=i;
232                                 nums=i;
233                                 found=TRUE;
234                         }
235                 } else{
236                         if (found) break;
237                 }
238         }
239         if (found){
240                 strcpy(staart,&string[nume+1]);
241                 strcpy(kop,string);
242                 kop[nums]=0;
243                 *numlen=nume-nums+1;
244                 return ((int)atoi(&(string[nums])));
245         }
246         staart[0]=0;
247         strcpy(kop,string);
248         *numlen=0;
249         return (1);
250 }
251
252
253 static void an_stringenc(char *string, char *kop, char *staart, 
254 unsigned short numlen, int pic) {
255         char numstr[10];
256         unsigned short len,i;
257
258         len=sprintf(numstr,"%d",pic);
259
260         strcpy(string,kop);
261         for(i=len;i<numlen;i++){
262                 strcat(string,"0");
263         }
264         strcat(string,numstr);
265         strcat(string,staart);
266 }
267
268
269 static void free_anim_avi (struct anim *anim) {
270 #if defined(_WIN32) && !defined(FREE_WINDOWS)
271         int i;
272 #endif
273
274         if (anim == NULL) return;
275         if (anim->avi == NULL) return;
276
277         AVI_close (anim->avi);
278         MEM_freeN (anim->avi);
279         anim->avi = NULL;
280
281 #if defined(_WIN32) && !defined(FREE_WINDOWS)
282
283         if (anim->pgf) {
284                 AVIStreamGetFrameClose(anim->pgf);
285                 anim->pgf = NULL;
286         }
287
288         for (i = 0; i < anim->avistreams; i++){
289                 AVIStreamRelease(anim->pavi[i]);
290         }
291         anim->avistreams = 0;
292
293         if (anim->pfileopen) {
294                 AVIFileRelease(anim->pfile);
295                 anim->pfileopen = 0;
296                 AVIFileExit();
297         }
298 #endif
299
300         anim->duration = 0;
301 }
302
303 void IMB_free_anim_ibuf(struct anim * anim) {
304         if (anim == NULL) return;
305
306         if (anim->ibuf1) IMB_freeImBuf(anim->ibuf1);
307         if (anim->ibuf2) IMB_freeImBuf(anim->ibuf2);
308
309         anim->ibuf1 = anim->ibuf2 = NULL;
310 }
311
312 #ifdef WITH_FFMPEG
313 static void free_anim_ffmpeg(struct anim * anim);
314 #endif
315
316 void IMB_free_anim(struct anim * anim) {
317         if (anim == NULL) {
318                 printf("free anim, anim == NULL\n");
319                 return;
320         }
321
322         IMB_free_anim_ibuf(anim);
323         free_anim_anim5(anim);
324         free_anim_movie(anim);
325         free_anim_avi(anim);
326
327 #ifdef WITH_QUICKTIME
328         free_anim_quicktime(anim);
329 #endif
330 #ifdef WITH_FFMPEG
331         free_anim_ffmpeg(anim);
332 #endif
333
334         free(anim);
335 }
336
337 void IMB_close_anim(struct anim * anim) {
338         if (anim == 0) return;
339
340         IMB_free_anim(anim);
341 }
342
343
344 struct anim * IMB_open_anim( const char * name, int ib_flags) {
345         struct anim * anim;
346
347         anim = (struct anim*)MEM_callocN(sizeof(struct anim), "anim struct");
348         if (anim != NULL) {
349                 strcpy(anim->name, name);  /* fixme: possible buffer overflow here? */
350                 anim->ib_flags = ib_flags;
351         }
352         return(anim);
353 }
354
355
356 static int startavi (struct anim *anim) {
357
358         AviError avierror;
359 #if defined(_WIN32) && !defined(FREE_WINDOWS)
360         HRESULT hr;
361         int i, firstvideo = -1;
362         BYTE abFormat[1024];
363         LONG l;
364         LPBITMAPINFOHEADER lpbi;
365         AVISTREAMINFO avis;
366 #endif
367
368         anim->avi = MEM_callocN (sizeof(AviMovie),"animavi");
369
370         if (anim->avi == NULL) {
371                 printf("Can't open avi: %s\n", anim->name);
372                 return -1;
373         }
374
375         avierror = AVI_open_movie (anim->name, anim->avi);
376
377 #if defined(_WIN32) && !defined(FREE_WINDOWS)
378         if (avierror == AVI_ERROR_COMPRESSION) {
379                 AVIFileInit();
380                 hr = AVIFileOpen(&anim->pfile, anim->name, OF_READ, 0L);
381                 if (hr == 0) {
382                         anim->pfileopen = 1;
383                         for (i = 0; i < MAXNUMSTREAMS; i++) {
384                                 if (AVIFileGetStream(anim->pfile, &anim->pavi[i], 0L, i) != AVIERR_OK) {
385                                         break;
386                                 }
387                                 
388                                 AVIStreamInfo(anim->pavi[i], &avis, sizeof(avis));
389                                 if ((avis.fccType == streamtypeVIDEO) && (firstvideo == -1)) {
390                                         anim->pgf = AVIStreamGetFrameOpen(anim->pavi[i], NULL);
391                                         if (anim->pgf) {
392                                                 firstvideo = i;
393
394                                                 // get stream length
395                                                 anim->avi->header->TotalFrames = AVIStreamLength(anim->pavi[i]);
396                                                 
397                                                 // get information about images inside the stream
398                                                 l = sizeof(abFormat);
399                                                 AVIStreamReadFormat(anim->pavi[i], 0, &abFormat, &l);
400                                                 lpbi = (LPBITMAPINFOHEADER)abFormat;
401                                                 anim->avi->header->Height = lpbi->biHeight;
402                                                 anim->avi->header->Width = lpbi->biWidth;
403                                         } else {
404                                                 FIXCC(avis.fccHandler);
405                                                 FIXCC(avis.fccType);
406                                                 printf("Can't find AVI decoder for type : %4.4hs/%4.4hs\n",
407                                                         (LPSTR)&avis.fccType,
408                                                         (LPSTR)&avis.fccHandler);
409                                         }
410                                 }
411                         }
412
413                         // register number of opened avistreams
414                         anim->avistreams = i;
415
416                         //
417                         // Couldn't get any video streams out of this file
418                         //
419                         if ((anim->avistreams == 0) || (firstvideo == -1)) {
420                                 avierror = AVI_ERROR_FORMAT;
421                         } else {
422                                 avierror = AVI_ERROR_NONE;
423                                 anim->firstvideo = firstvideo;
424                         }
425                 } else {
426                         AVIFileExit();
427                 }
428         }
429 #endif
430
431         if (avierror != AVI_ERROR_NONE) {
432                 AVI_print_error(avierror);
433                 printf ("Error loading avi: %s\n", anim->name);         
434                 free_anim_avi(anim);
435                 return -1;
436         }
437         
438         anim->duration = anim->avi->header->TotalFrames;
439         anim->params = 0;
440
441         anim->x = anim->avi->header->Width;
442         anim->y = anim->avi->header->Height;
443         anim->interlacing = 0;
444         anim->orientation = 0;
445         anim->framesize = anim->x * anim->y * 4;
446
447         anim->curposition = 0;
448         anim->preseek = 0;
449
450         /*  printf("x:%d y:%d size:%d interl:%d dur:%d\n", anim->x, anim->y, anim->framesize, anim->interlacing, anim->duration);*/
451
452         return 0;
453 }
454
455 static ImBuf * avi_fetchibuf (struct anim *anim, int position) {
456         ImBuf *ibuf = NULL;
457         int *tmp;
458         int y;
459         
460         if (anim == NULL) return (NULL);
461
462 #if defined(_WIN32) && !defined(FREE_WINDOWS)
463         if (anim->avistreams) {
464                 LPBITMAPINFOHEADER lpbi;
465
466                 if (anim->pgf) {
467                         lpbi = AVIStreamGetFrame(anim->pgf, position + AVIStreamStart(anim->pavi[anim->firstvideo]));
468                         if (lpbi) {
469                                 ibuf = IMB_ibImageFromMemory((int *) lpbi, 100, IB_rect);
470 //Oh brother...
471                         }
472                 }
473         } else {
474 #else
475         if (1) {
476 #endif
477                 ibuf = IMB_allocImBuf (anim->x, anim->y, 24, IB_rect, 0);
478
479                 tmp = AVI_read_frame (anim->avi, AVI_FORMAT_RGB32, position,
480                         AVI_get_stream(anim->avi, AVIST_VIDEO, 0));
481                 
482                 if (tmp == NULL) {
483                         printf ("Error reading frame from AVI");
484                         IMB_freeImBuf (ibuf);
485                         return NULL;
486                 }
487
488                 for (y=0; y < anim->y; y++) {
489                         memcpy (&(ibuf->rect)[((anim->y-y)-1)*anim->x],  &tmp[y*anim->x],  
490                                         anim->x * 4);
491                 }
492                 
493                 MEM_freeN (tmp);
494         }
495
496         return ibuf;
497 }
498
499 #ifdef WITH_FFMPEG
500
501 extern void do_init_ffmpeg();
502
503 #ifdef FFMPEG_CODEC_IS_POINTER
504 static AVCodecContext* get_codec_from_stream(AVStream* stream)
505 {
506         return stream->codec;
507 }
508 #else
509 static AVCodecContext* get_codec_from_stream(AVStream* stream)
510 {
511         return &stream->codec;
512 }
513 #endif
514
515 static int startffmpeg(struct anim * anim) {
516         int            i, videoStream;
517
518         AVCodec *pCodec;
519         AVFormatContext *pFormatCtx;
520         AVCodecContext *pCodecCtx;
521
522         if (anim == 0) return(-1);
523
524         do_init_ffmpeg();
525
526         if(av_open_input_file(&pFormatCtx, anim->name, NULL, 0, NULL)!=0) {
527                 return -1;
528         }
529
530         if(av_find_stream_info(pFormatCtx)<0) {
531                 av_close_input_file(pFormatCtx);
532                 return -1;
533         }
534
535         dump_format(pFormatCtx, 0, anim->name, 0);
536
537
538         /* Find the first video stream */
539         videoStream=-1;
540         for(i=0; i<pFormatCtx->nb_streams; i++)
541                 if(get_codec_from_stream(pFormatCtx->streams[i])->codec_type
542                    == CODEC_TYPE_VIDEO) {
543                         videoStream=i;
544                         break;
545                 }
546
547         if(videoStream==-1) {
548                 av_close_input_file(pFormatCtx);
549                 return -1;
550         }
551
552         pCodecCtx = get_codec_from_stream(pFormatCtx->streams[videoStream]);
553
554         /* Find the decoder for the video stream */
555         pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
556         if(pCodec==NULL) {
557                 av_close_input_file(pFormatCtx);
558                 return -1;
559         }
560
561         pCodecCtx->workaround_bugs = 1;
562
563         if(avcodec_open(pCodecCtx, pCodec)<0) {
564                 av_close_input_file(pFormatCtx);
565                 return -1;
566         }
567
568 #ifdef FFMPEG_OLD_FRAME_RATE
569         if(pCodecCtx->frame_rate>1000 && pCodecCtx->frame_rate_base==1)
570                 pCodecCtx->frame_rate_base=1000;
571
572
573         anim->duration = pFormatCtx->duration * pCodecCtx->frame_rate 
574                 / pCodecCtx->frame_rate_base / AV_TIME_BASE;
575 #else
576         anim->duration = pFormatCtx->duration 
577                 * av_q2d(pFormatCtx->streams[videoStream]->r_frame_rate) 
578                 / AV_TIME_BASE;
579
580 #endif
581         anim->params = 0;
582
583         anim->x = pCodecCtx->width;
584         anim->y = pCodecCtx->height;
585         anim->interlacing = 0;
586         anim->orientation = 0;
587         anim->framesize = anim->x * anim->y * 4;
588
589         anim->curposition = -1;
590
591         anim->pFormatCtx = pFormatCtx;
592         anim->pCodecCtx = pCodecCtx;
593         anim->pCodec = pCodec;
594         anim->videoStream = videoStream;
595
596         anim->pFrame = avcodec_alloc_frame();
597         anim->pFrameRGB = avcodec_alloc_frame();
598
599         if (avpicture_get_size(PIX_FMT_BGR32, anim->x, anim->y)
600             != anim->x * anim->y * 4) {
601                 fprintf (stderr,
602                          "ffmpeg has changed alloc scheme ... ARGHHH!\n");
603                 avcodec_close(anim->pCodecCtx);
604                 av_close_input_file(anim->pFormatCtx);
605                 av_free(anim->pFrameRGB);
606                 av_free(anim->pFrame);
607                 return -1;
608         }
609
610         if (pCodecCtx->has_b_frames) {
611                 anim->preseek = 25; /* FIXME: detect gopsize ... */
612         } else {
613                 anim->preseek = 0;
614         }
615         
616         anim->img_convert_ctx = sws_getContext(
617                 anim->pCodecCtx->width,
618                 anim->pCodecCtx->height,
619                 anim->pCodecCtx->pix_fmt,
620                 anim->pCodecCtx->width,
621                 anim->pCodecCtx->height,
622                 PIX_FMT_BGR32,
623                 SWS_FAST_BILINEAR | SWS_PRINT_INFO,
624                 NULL, NULL, NULL);
625                                 
626         return (0);
627 }
628
629 static ImBuf * ffmpeg_fetchibuf(struct anim * anim, int position) {
630         ImBuf * ibuf;
631         int frameFinished;
632         AVPacket packet;
633         int64_t pts_to_search = 0;
634         int pos_found = 1;
635
636         if (anim == 0) return (0);
637
638         ibuf = IMB_allocImBuf(anim->x, anim->y, 24, IB_rect, 0);
639
640         avpicture_fill((AVPicture *)anim->pFrameRGB, 
641                        (unsigned char*) ibuf->rect, 
642                        PIX_FMT_BGR32, anim->x, anim->y);
643
644         if (position != anim->curposition + 1) { 
645                 if (position > anim->curposition + 1 
646                     && anim->preseek 
647                     && position - (anim->curposition + 1) < anim->preseek) {
648                         while(av_read_frame(anim->pFormatCtx, &packet)>=0) {
649                                 if (packet.stream_index == anim->videoStream) {
650                                         avcodec_decode_video(
651                                                 anim->pCodecCtx, 
652                                                 anim->pFrame, &frameFinished, 
653                                                 packet.data, packet.size);
654
655                                         if (frameFinished) {
656                                                 anim->curposition++;
657                                         }
658                                 }
659                                 av_free_packet(&packet);
660                                 if (position == anim->curposition+1) {
661                                         break;
662                                 }
663                         }
664                 }
665         }
666
667         if (position != anim->curposition + 1) { 
668 #ifdef FFMPEG_OLD_FRAME_RATE
669                 double frame_rate = 
670                         (double) anim->pCodecCtx->frame_rate
671                         / (double) anim->pCodecCtx->frame_rate_base;
672 #else
673                 double frame_rate = 
674                         av_q2d(anim->pFormatCtx->streams[anim->videoStream]
675                                ->r_frame_rate);
676 #endif
677                 double time_base = 
678                         av_q2d(anim->pFormatCtx->streams[anim->videoStream]
679                                ->time_base);
680                 long long pos = (long long) (position - anim->preseek) 
681                         * AV_TIME_BASE / frame_rate;
682                 long long st_time = anim->pFormatCtx
683                         ->streams[anim->videoStream]->start_time;
684
685                 if (pos < 0) {
686                         pos = 0;
687                 }
688
689                 if (st_time != AV_NOPTS_VALUE) {
690                         pos += st_time * AV_TIME_BASE * time_base;
691                 }
692
693                 av_seek_frame(anim->pFormatCtx, -1, 
694                               pos, AVSEEK_FLAG_BACKWARD);
695
696                 pts_to_search = (long long) 
697                         (((double) position) / time_base / frame_rate);
698                 if (st_time != AV_NOPTS_VALUE) {
699                         pts_to_search += st_time;
700                 }
701
702                 pos_found = 0;
703                 avcodec_flush_buffers(anim->pCodecCtx);
704         }
705
706         while(av_read_frame(anim->pFormatCtx, &packet)>=0) {
707                 if(packet.stream_index == anim->videoStream) {
708                         avcodec_decode_video(anim->pCodecCtx, 
709                                              anim->pFrame, &frameFinished, 
710                                              packet.data, packet.size);
711
712                         if (frameFinished && !pos_found) {
713                                 if (packet.dts >= pts_to_search) {
714                                         pos_found = 1;
715                                 }
716                         } 
717
718                         if(frameFinished && pos_found == 1) {
719                                 if (G.order == B_ENDIAN) {
720                                         int * dstStride 
721                                                 = anim->pFrameRGB->linesize;
722                                         uint8_t** dst = anim->pFrameRGB->data;
723                                         int dstStride2[4]
724                                                 = { dstStride[0], 0, 0, 0 };
725                                         uint8_t* dst2[4]= {
726                                                 dst[0], 0, 0, 0 };
727                                         int x,y,h,w;
728                                         unsigned char* bottom;
729                                         unsigned char* top;
730
731                                         sws_scale(anim->img_convert_ctx,
732                                                   anim->pFrame->data,
733                                                   anim->pFrame->linesize,
734                                                   0,
735                                                   anim->pCodecCtx->height,
736                                                   dst2,
737                                                   dstStride2);
738                                 
739                                         /* workaround: sws_scale 
740                                            sets alpha = 0 and compensate
741                                            for altivec-bugs and flipy... */
742                                 
743                                         bottom = (unsigned char*) ibuf->rect;
744                                         top = bottom 
745                                                 + ibuf->x * (ibuf->y-1) * 4;
746
747                                         h = (ibuf->y + 1) / 2;
748                                         w = ibuf->x;
749
750                                         for (y = 0; y < h; y++) {
751                                                 unsigned char tmp[4];
752                                                 unsigned long * tmp_l =
753                                                         (unsigned long*) tmp;
754                                                 tmp[3] = 0xff;
755
756                                                 for (x = 0; x < w; x++) {
757                                                         tmp[0] = bottom[3];
758                                                         tmp[1] = bottom[2];
759                                                         tmp[2] = bottom[1];
760
761                                                         bottom[0] = top[3];
762                                                         bottom[1] = top[2];
763                                                         bottom[2] = top[1];
764                                                         bottom[3] = 0xff;
765                                                                 
766                                                         *(unsigned long*) top
767                                                                 = *tmp_l;
768
769                                                         bottom +=4;
770                                                         top += 4;
771                                                 }
772                                                 top -= 8 * w;
773                                         }
774
775                                         av_free_packet(&packet);
776                                         break;
777                                 } else {
778                                         int * dstStride 
779                                                 = anim->pFrameRGB->linesize;
780                                         uint8_t** dst = anim->pFrameRGB->data;
781                                         int dstStride2[4]
782                                                 = { -dstStride[0], 0, 0, 0 };
783                                         uint8_t* dst2[4]= {
784                                                 dst[0] 
785                                                 + (anim->y - 1)*dstStride[0],
786                                                 0, 0, 0 };
787                                         int i;
788                                         unsigned char* r;
789                                         
790                                         /* This means the data wasnt read properly, this check stops crashing */
791                                         if (anim->pFrame->data[0]!=0 || anim->pFrame->data[1]!=0 || anim->pFrame->data[2]!=0 || anim->pFrame->data[3]!=0) {
792                                                 
793                                                 sws_scale(anim->img_convert_ctx,
794                                                           anim->pFrame->data,
795                                                           anim->pFrame->linesize,
796                                                           0,
797                                                           anim->pCodecCtx->height,
798                                                           dst2,
799                                                           dstStride2);
800                                         
801                                                 /* workaround: sws_scale 
802                                                    sets alpha = 0... */
803                                         
804                                                 r = (unsigned char*) ibuf->rect;
805         
806                                                 for (i = 0; i < ibuf->x * ibuf->y;i++){
807                                                         r[3] = 0xff;
808                                                         r+=4;
809                                                 }
810                                         }
811                                         av_free_packet(&packet);
812                                         break;
813                                 }
814                         }
815                 }
816
817                 av_free_packet(&packet);
818         }
819
820         return(ibuf);
821 }
822
823 static void free_anim_ffmpeg(struct anim * anim) {
824         if (anim == NULL) return;
825
826         if (anim->pCodecCtx) {
827                 avcodec_close(anim->pCodecCtx);
828                 av_close_input_file(anim->pFormatCtx);
829                 av_free(anim->pFrameRGB);
830                 av_free(anim->pFrame);
831                 sws_freeContext(anim->img_convert_ctx);
832         }
833         anim->duration = 0;
834 }
835
836 #endif
837
838 #ifdef WITH_REDCODE
839
840 static int startredcode(struct anim * anim) {
841         anim->redcodeCtx = redcode_open(anim->name);
842         if (!anim->redcodeCtx) {
843                 return -1;
844         }
845         anim->duration = redcode_get_length(anim->redcodeCtx);
846         
847         return 0;
848 }
849
850 static ImBuf * redcode_fetchibuf(struct anim * anim, int position) {
851         struct ImBuf * ibuf;
852         struct redcode_frame * frame;
853         struct redcode_frame_raw * raw_frame;
854
855         if (!anim->redcodeCtx) {
856                 return NULL;
857         }
858
859         frame = redcode_read_video_frame(anim->redcodeCtx, position);
860         
861         if (!frame) {
862                 return NULL;
863         }
864
865         raw_frame = redcode_decode_video_raw(frame, 1);
866
867         redcode_free_frame(frame);
868
869         if (!raw_frame) {
870                 return NULL;
871         }
872         
873         ibuf = IMB_allocImBuf(raw_frame->width * 2, 
874                               raw_frame->height * 2, 32, IB_rectfloat, 0);
875
876         redcode_decode_video_float(raw_frame, ibuf->rect_float, 1);
877
878         return ibuf;
879 }
880
881 static void free_anim_redcode(struct anim * anim) {
882         if (anim->redcodeCtx) {
883                 redcode_close(anim->redcodeCtx);
884                 anim->redcodeCtx = 0;
885         }
886         anim->duration = 0;
887 }
888
889 #endif
890
891 /* probeer volgende plaatje te lezen */
892 /* Geen plaatje, probeer dan volgende animatie te openen */
893 /* gelukt, haal dan eerste plaatje van animatie */
894
895 static struct ImBuf * anim_getnew(struct anim * anim) {
896         struct ImBuf *ibuf = 0;
897
898         if (anim == NULL) return(0);
899
900         free_anim_anim5(anim);
901         free_anim_movie(anim);
902         free_anim_avi(anim);
903 #ifdef WITH_QUICKTIME
904         free_anim_quicktime(anim);
905 #endif
906 #ifdef WITH_FFMPEG
907         free_anim_ffmpeg(anim);
908 #endif
909 #ifdef WITH_REDCODE
910         free_anim_redcode(anim);
911 #endif
912
913
914         if (anim->curtype != 0) return (0);
915         anim->curtype = imb_get_anim_type(anim->name);  
916
917         switch (anim->curtype) {
918         case ANIM_ANIM5:
919                 if (startanim5(anim)) return (0);
920                 ibuf = anim5_fetchibuf(anim);
921                 break;
922         case ANIM_SEQUENCE:
923                 ibuf = IMB_loadiffname(anim->name, anim->ib_flags);
924                 if (ibuf) {
925                         strcpy(anim->first, anim->name);
926                         anim->duration = 1;
927                 }
928                 break;
929         case ANIM_MOVIE:
930                 if (startmovie(anim)) return (0);
931                 ibuf = IMB_allocImBuf (anim->x, anim->y, 24, 0, 0); /* fake */
932                 break;
933         case ANIM_AVI:
934                 if (startavi(anim)) {
935                         printf("couldnt start avi\n"); 
936                         return (0);
937                 }
938                 ibuf = IMB_allocImBuf (anim->x, anim->y, 24, 0, 0);
939                 break;
940 #ifdef WITH_QUICKTIME
941         case ANIM_QTIME:
942                 if (startquicktime(anim)) return (0);
943                 ibuf = IMB_allocImBuf (anim->x, anim->y, 24, 0, 0);
944                 break;
945 #endif
946 #ifdef WITH_FFMPEG
947         case ANIM_FFMPEG:
948                 if (startffmpeg(anim)) return (0);
949                 ibuf = IMB_allocImBuf (anim->x, anim->y, 24, 0, 0);
950                 break;
951 #endif
952 #ifdef WITH_REDCODE
953         case ANIM_REDCODE:
954                 if (startredcode(anim)) return (0);
955                 ibuf = IMB_allocImBuf (8, 8, 32, 0, 0);
956                 break;
957         }
958 #endif
959         return(ibuf);
960 }
961
962 struct ImBuf * IMB_anim_previewframe(struct anim * anim) {
963         struct ImBuf * ibuf = 0;
964         int position = 0;
965         
966         ibuf = IMB_anim_absolute(anim, 0);
967         if (ibuf) {
968                 IMB_freeImBuf(ibuf);
969                 position = anim->duration / 2;
970                 ibuf = IMB_anim_absolute(anim, position);
971         }
972         return ibuf;
973 }
974
975 struct ImBuf * IMB_anim_absolute(struct anim * anim, int position) {
976         struct ImBuf * ibuf = 0;
977         char head[256], tail[256];
978         unsigned short digits;
979         int pic;
980
981         if (anim == NULL) return(0);
982
983         if (anim->curtype == 0) {
984                 ibuf = anim_getnew(anim);
985                 if (ibuf == NULL) {
986                         return (0);
987                 }
988                 IMB_freeImBuf(ibuf); /* ???? */
989         }
990
991         if (position < 0) return(0);
992         if (position >= anim->duration) return(0);
993
994         switch(anim->curtype) {
995         case ANIM_ANIM5:
996                 if (anim->curposition > position) rewindanim5(anim);
997                 while (anim->curposition < position) {
998                         if (nextanim5(anim)) return (0);
999                 }
1000                 ibuf = anim5_fetchibuf(anim);
1001                 break;
1002         case ANIM_SEQUENCE:
1003                 pic = an_stringdec(anim->first, head, tail, &digits);
1004                 pic += position;
1005                 an_stringenc(anim->name, head, tail, digits, pic);
1006                 ibuf = IMB_loadiffname(anim->name, LI_rect);
1007                 if (ibuf) {
1008                         anim->curposition = position;
1009                         /* patch... by freeing the cmap you prevent a double apply cmap... */
1010                         /* probably the IB_CMAP option isn't working proper
1011                          * after the abgr->rgba reconstruction
1012                          */
1013                         IMB_freecmapImBuf(ibuf);
1014                 }
1015                 break;
1016         case ANIM_MOVIE:
1017                 ibuf = movie_fetchibuf(anim, position);
1018                 if (ibuf) {
1019                         anim->curposition = position;
1020                         IMB_convert_rgba_to_abgr(ibuf);
1021                 }
1022                 break;
1023         case ANIM_AVI:
1024                 ibuf = avi_fetchibuf(anim, position);
1025                 if (ibuf) anim->curposition = position;
1026                 break;
1027 #ifdef WITH_QUICKTIME
1028         case ANIM_QTIME:
1029                 ibuf = qtime_fetchibuf(anim, position);
1030                 if (ibuf) anim->curposition = position;
1031                 break;
1032 #endif
1033 #ifdef WITH_FFMPEG
1034         case ANIM_FFMPEG:
1035                 ibuf = ffmpeg_fetchibuf(anim, position);
1036                 if (ibuf) anim->curposition = position;
1037                 break;
1038 #endif
1039 #ifdef WITH_REDCODE
1040         case ANIM_REDCODE:
1041                 ibuf = redcode_fetchibuf(anim, position);
1042                 if (ibuf) anim->curposition = position;
1043                 break;
1044 #endif
1045         }
1046
1047         if (ibuf) {
1048                 if (anim->ib_flags & IB_ttob) IMB_flipy(ibuf);
1049                 sprintf(ibuf->name, "%s.%04d", anim->name, anim->curposition + 1);
1050                 
1051         }
1052         return(ibuf);
1053 }
1054
1055 struct ImBuf * IMB_anim_nextpic(struct anim * anim) {
1056         struct ImBuf * ibuf = 0;
1057
1058         if (anim == 0) return(0);
1059
1060         ibuf = IMB_anim_absolute(anim, anim->curposition + 1);
1061
1062         return(ibuf);
1063 }
1064
1065 /***/
1066
1067 int IMB_anim_get_duration(struct anim *anim) {
1068         return anim->duration;
1069 }
1070
1071 void IMB_anim_set_preseek(struct anim * anim, int preseek)
1072 {
1073         anim->preseek = preseek;
1074 }
1075
1076 int IMB_anim_get_preseek(struct anim * anim)
1077 {
1078         return anim->preseek;
1079 }