f07a18cb89ce5dc37eaf16b9a02ee60fe89e1738
[blender.git] / source / blender / imbuf / intern / anim_movie.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/imbuf/intern/anim_movie.c
29  *  \ingroup imbuf
30  */
31
32
33 #ifdef _WIN32
34 #define INC_OLE2
35 #include <windows.h>
36 #include <windowsx.h>
37 #include <mmsystem.h>
38 #include <memory.h>
39 #include <commdlg.h>
40
41 #ifndef FREE_WINDOWS
42 #include <vfw.h>
43 #endif
44
45 #undef AVIIF_KEYFRAME /* redefined in AVI_avi.h */
46 #undef AVIIF_LIST /* redefined in AVI_avi.h */
47
48 #define FIXCC(fcc) \
49         { \
50                 if (fcc == 0)       { fcc = mmioFOURCC('N', 'o', 'n', 'e'); } \
51                 if (fcc == BI_RLE8) { fcc = mmioFOURCC('R', 'l', 'e', '8'); } \
52         } (void)0
53
54 #endif
55
56 #include <sys/types.h>
57 #include <ctype.h>
58 #include <stdlib.h>
59 #include <stdio.h>
60 #include <math.h>
61 #ifndef _WIN32
62 #include <dirent.h>
63 #else
64 #include <io.h>
65 #endif
66
67 #include "BLI_string.h"
68 #include "BLI_path_util.h"
69 #include "BLI_utildefines.h"
70 #include "BLI_math_base.h"
71
72 #include "MEM_guardedalloc.h"
73
74 #include "DNA_userdef_types.h"
75
76 #include "BKE_global.h"
77 #include "BKE_depsgraph.h"
78
79 #include "imbuf.h"
80
81 #include "AVI_avi.h"
82
83 #ifdef WITH_QUICKTIME
84 #if defined(_WIN32) || defined(__APPLE__)
85 #include "quicktime_import.h"
86 #endif /* _WIN32 || __APPLE__ */
87 #endif /* WITH_QUICKTIME */
88
89 #include "IMB_imbuf_types.h"
90 #include "IMB_imbuf.h"
91
92 #include "IMB_allocimbuf.h"
93 #include "IMB_anim.h"
94 #include "IMB_indexer.h"
95
96 #ifdef WITH_FFMPEG
97 #include <libavformat/avformat.h>
98 #include <libavcodec/avcodec.h>
99 #include <libavutil/rational.h>
100 #include <libswscale/swscale.h>
101
102 #include "ffmpeg_compat.h"
103
104 #endif //WITH_FFMPEG
105
106 #ifdef WITH_REDCODE
107 #ifdef _WIN32 /* on windows we use the ones in extern instead */
108 #include "libredcode/format.h"
109 #include "libredcode/codec.h"
110 #else
111 #include "libredcode/format.h"
112 #include "libredcode/codec.h"
113 #endif
114 #endif
115
116 int ismovie(const char *UNUSED(filepath))
117 {
118         return 0;
119 }
120
121 /* never called, just keep the linker happy */
122 static int startmovie(struct anim *UNUSED(anim))
123 {
124         return 1;
125 }
126 static ImBuf *movie_fetchibuf(struct anim *UNUSED(anim), int UNUSED(position))
127 {
128         return NULL;
129 }
130 static void free_anim_movie(struct anim *UNUSED(anim))
131 {
132         /* pass */
133 }
134
135
136 #if defined(_WIN32)
137 # define PATHSEPERATOR '\\'
138 #else
139 # define PATHSEPERATOR '/'
140 #endif
141
142 static int an_stringdec(const char *string, char *head, char *tail, unsigned short *numlen)
143 {
144         unsigned short len, nume, nums = 0;
145         short i, found = FALSE;
146
147         len = strlen(string);
148         nume = len;
149
150         for (i = len - 1; i >= 0; i--) {
151                 if (string[i] == PATHSEPERATOR) break;
152                 if (isdigit(string[i])) {
153                         if (found) {
154                                 nums = i;
155                         }
156                         else {
157                                 nume = i;
158                                 nums = i;
159                                 found = TRUE;
160                         }
161                 }
162                 else {
163                         if (found) break;
164                 }
165         }
166         if (found) {
167                 strcpy(tail, &string[nume + 1]);
168                 strcpy(head, string);
169                 head[nums] = '\0';
170                 *numlen = nume - nums + 1;
171                 return ((int)atoi(&(string[nums])));
172         }
173         tail[0] = '\0';
174         strcpy(head, string);
175         *numlen = 0;
176         return TRUE;
177 }
178
179
180 static void an_stringenc(char *string, const char *head, const char *tail, unsigned short numlen, int pic)
181 {
182         BLI_stringenc(string, head, tail, numlen, pic);
183 }
184
185 static void free_anim_avi(struct anim *anim)
186 {
187 #if defined(_WIN32) && !defined(FREE_WINDOWS)
188         int i;
189 #endif
190
191         if (anim == NULL) return;
192         if (anim->avi == NULL) return;
193
194         AVI_close(anim->avi);
195         MEM_freeN(anim->avi);
196         anim->avi = NULL;
197
198 #if defined(_WIN32) && !defined(FREE_WINDOWS)
199
200         if (anim->pgf) {
201                 AVIStreamGetFrameClose(anim->pgf);
202                 anim->pgf = NULL;
203         }
204
205         for (i = 0; i < anim->avistreams; i++) {
206                 AVIStreamRelease(anim->pavi[i]);
207         }
208         anim->avistreams = 0;
209
210         if (anim->pfileopen) {
211                 AVIFileRelease(anim->pfile);
212                 anim->pfileopen = 0;
213                 AVIFileExit();
214         }
215 #endif
216
217         anim->duration = 0;
218 }
219
220 #ifdef WITH_FFMPEG
221 static void free_anim_ffmpeg(struct anim *anim);
222 #endif
223 #ifdef WITH_REDCODE
224 static void free_anim_redcode(struct anim *anim);
225 #endif
226
227 void IMB_free_anim(struct anim *anim)
228 {
229         if (anim == NULL) {
230                 printf("free anim, anim == NULL\n");
231                 return;
232         }
233
234         free_anim_movie(anim);
235         free_anim_avi(anim);
236
237 #ifdef WITH_QUICKTIME
238         free_anim_quicktime(anim);
239 #endif
240 #ifdef WITH_FFMPEG
241         free_anim_ffmpeg(anim);
242 #endif
243 #ifdef WITH_REDCODE
244         free_anim_redcode(anim);
245 #endif
246         IMB_free_indices(anim);
247
248         MEM_freeN(anim);
249 }
250
251 void IMB_close_anim(struct anim *anim)
252 {
253         if (anim == NULL) return;
254
255         IMB_free_anim(anim);
256 }
257
258 void IMB_close_anim_proxies(struct anim *anim)
259 {
260         if (anim == NULL)
261                 return;
262
263         IMB_free_indices(anim);
264 }
265
266 struct anim *IMB_open_anim(const char *name, int ib_flags, int streamindex)
267 {
268         struct anim *anim;
269
270         anim = (struct anim *)MEM_callocN(sizeof(struct anim), "anim struct");
271         if (anim != NULL) {
272                 BLI_strncpy(anim->name, name, sizeof(anim->name));
273                 anim->ib_flags = ib_flags;
274                 anim->streamindex = streamindex;
275         }
276         return(anim);
277 }
278
279
280 static int startavi(struct anim *anim)
281 {
282
283         AviError avierror;
284 #if defined(_WIN32) && !defined(FREE_WINDOWS)
285         HRESULT hr;
286         int i, firstvideo = -1;
287         int streamcount;
288         BYTE abFormat[1024];
289         LONG l;
290         LPBITMAPINFOHEADER lpbi;
291         AVISTREAMINFO avis;
292
293         streamcount = anim->streamindex;
294 #endif
295
296         anim->avi = MEM_callocN(sizeof(AviMovie), "animavi");
297
298         if (anim->avi == NULL) {
299                 printf("Can't open avi: %s\n", anim->name);
300                 return -1;
301         }
302
303         avierror = AVI_open_movie(anim->name, anim->avi);
304
305 #if defined(_WIN32) && !defined(FREE_WINDOWS)
306         if (avierror == AVI_ERROR_COMPRESSION) {
307                 AVIFileInit();
308                 hr = AVIFileOpen(&anim->pfile, anim->name, OF_READ, 0L);
309                 if (hr == 0) {
310                         anim->pfileopen = 1;
311                         for (i = 0; i < MAXNUMSTREAMS; i++) {
312                                 if (AVIFileGetStream(anim->pfile, &anim->pavi[i], 0L, i) != AVIERR_OK) {
313                                         break;
314                                 }
315                                 
316                                 AVIStreamInfo(anim->pavi[i], &avis, sizeof(avis));
317                                 if ((avis.fccType == streamtypeVIDEO) && (firstvideo == -1)) {
318                                         if (streamcount > 0) {
319                                                 streamcount--;
320                                                 continue;
321                                         }
322                                         anim->pgf = AVIStreamGetFrameOpen(anim->pavi[i], NULL);
323                                         if (anim->pgf) {
324                                                 firstvideo = i;
325
326                                                 /* get stream length */
327                                                 anim->avi->header->TotalFrames = AVIStreamLength(anim->pavi[i]);
328
329                                                 /* get information about images inside the stream */
330                                                 l = sizeof(abFormat);
331                                                 AVIStreamReadFormat(anim->pavi[i], 0, &abFormat, &l);
332                                                 lpbi = (LPBITMAPINFOHEADER)abFormat;
333                                                 anim->avi->header->Height = lpbi->biHeight;
334                                                 anim->avi->header->Width = lpbi->biWidth;
335                                         }
336                                         else {
337                                                 FIXCC(avis.fccHandler);
338                                                 FIXCC(avis.fccType);
339                                                 printf("Can't find AVI decoder for type : %4.4hs/%4.4hs\n",
340                                                        (LPSTR)&avis.fccType,
341                                                        (LPSTR)&avis.fccHandler);
342                                         }
343                                 }
344                         }
345
346                         /* register number of opened avistreams */
347                         anim->avistreams = i;
348
349                         /*
350                          * Couldn't get any video streams out of this file
351                          */
352                         if ((anim->avistreams == 0) || (firstvideo == -1)) {
353                                 avierror = AVI_ERROR_FORMAT;
354                         }
355                         else {
356                                 avierror = AVI_ERROR_NONE;
357                                 anim->firstvideo = firstvideo;
358                         }
359                 }
360                 else {
361                         AVIFileExit();
362                 }
363         }
364 #endif
365
366         if (avierror != AVI_ERROR_NONE) {
367                 AVI_print_error(avierror);
368                 printf("Error loading avi: %s\n", anim->name);
369                 free_anim_avi(anim);
370                 return -1;
371         }
372         
373         anim->duration = anim->avi->header->TotalFrames;
374         anim->params = NULL;
375
376         anim->x = anim->avi->header->Width;
377         anim->y = anim->avi->header->Height;
378         anim->interlacing = 0;
379         anim->orientation = 0;
380         anim->framesize = anim->x * anim->y * 4;
381
382         anim->curposition = 0;
383         anim->preseek = 0;
384
385         /*  printf("x:%d y:%d size:%d interl:%d dur:%d\n", anim->x, anim->y, anim->framesize, anim->interlacing, anim->duration);*/
386
387         return 0;
388 }
389
390 static ImBuf *avi_fetchibuf(struct anim *anim, int position)
391 {
392         ImBuf *ibuf = NULL;
393         int *tmp;
394         int y;
395         
396         if (anim == NULL) {
397                 return NULL;
398         }
399
400 #if defined(_WIN32) && !defined(FREE_WINDOWS)
401         if (anim->avistreams) {
402                 LPBITMAPINFOHEADER lpbi;
403
404                 if (anim->pgf) {
405                         lpbi = AVIStreamGetFrame(anim->pgf, position + AVIStreamStart(anim->pavi[anim->firstvideo]));
406                         if (lpbi) {
407                                 ibuf = IMB_ibImageFromMemory((unsigned char *) lpbi, 100, IB_rect, "<avi_fetchibuf>");
408 //Oh brother...
409                         }
410                 }
411         }
412         else {
413 #else
414         if (1) {
415 #endif
416                 ibuf = IMB_allocImBuf(anim->x, anim->y, 24, IB_rect);
417
418                 tmp = AVI_read_frame(anim->avi, AVI_FORMAT_RGB32, position,
419                                      AVI_get_stream(anim->avi, AVIST_VIDEO, 0));
420                 
421                 if (tmp == NULL) {
422                         printf("Error reading frame from AVI: '%s'\n", anim->name);
423                         IMB_freeImBuf(ibuf);
424                         return NULL;
425                 }
426
427                 for (y = 0; y < anim->y; y++) {
428                         memcpy(&(ibuf->rect)[((anim->y - y) - 1) * anim->x],  &tmp[y * anim->x],
429                                anim->x * 4);
430                 }
431                 
432                 MEM_freeN(tmp);
433         }
434         
435         ibuf->profile = IB_PROFILE_SRGB;
436         
437         return ibuf;
438 }
439
440 #ifdef WITH_FFMPEG
441
442 extern void do_init_ffmpeg(void);
443
444 static int startffmpeg(struct anim *anim)
445 {
446         int i, videoStream;
447
448         AVCodec *pCodec;
449         AVFormatContext *pFormatCtx = NULL;
450         AVCodecContext *pCodecCtx;
451         int frs_num;
452         double frs_den;
453         int streamcount;
454
455 #ifdef FFMPEG_SWSCALE_COLOR_SPACE_SUPPORT
456         /* The following for color space determination */
457         int srcRange, dstRange, brightness, contrast, saturation;
458         int *table;
459         const int *inv_table;
460 #endif
461
462         if (anim == 0) return(-1);
463
464         streamcount = anim->streamindex;
465
466         do_init_ffmpeg();
467
468         if (avformat_open_input(&pFormatCtx, anim->name, NULL, NULL) != 0) {
469                 return -1;
470         }
471
472         if (av_find_stream_info(pFormatCtx) < 0) {
473                 av_close_input_file(pFormatCtx);
474                 return -1;
475         }
476
477         av_dump_format(pFormatCtx, 0, anim->name, 0);
478
479
480         /* Find the video stream */
481         videoStream = -1;
482
483         for (i = 0; i < pFormatCtx->nb_streams; i++)
484                 if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
485                         if (streamcount > 0) {
486                                 streamcount--;
487                                 continue;
488                         }
489                         videoStream = i;
490                         break;
491                 }
492
493         if (videoStream == -1) {
494                 av_close_input_file(pFormatCtx);
495                 return -1;
496         }
497
498         pCodecCtx = pFormatCtx->streams[videoStream]->codec;
499
500         /* Find the decoder for the video stream */
501         pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
502         if (pCodec == NULL) {
503                 av_close_input_file(pFormatCtx);
504                 return -1;
505         }
506
507         pCodecCtx->workaround_bugs = 1;
508
509         if (avcodec_open(pCodecCtx, pCodec) < 0) {
510                 av_close_input_file(pFormatCtx);
511                 return -1;
512         }
513
514         anim->duration = ceil(pFormatCtx->duration *
515                               av_q2d(pFormatCtx->streams[videoStream]->r_frame_rate) /
516                               AV_TIME_BASE);
517
518         frs_num = pFormatCtx->streams[videoStream]->r_frame_rate.num;
519         frs_den = pFormatCtx->streams[videoStream]->r_frame_rate.den;
520
521         frs_den *= AV_TIME_BASE;
522
523         while (frs_num % 10 == 0 && frs_den >= 2.0 && frs_num > 10) {
524                 frs_num /= 10;
525                 frs_den /= 10;
526         }
527
528         anim->frs_sec = frs_num;
529         anim->frs_sec_base = frs_den;
530
531         anim->params = 0;
532
533         anim->x = pCodecCtx->width;
534         anim->y = pCodecCtx->height;
535         anim->interlacing = 0;
536         anim->orientation = 0;
537         anim->framesize = anim->x * anim->y * 4;
538
539         anim->curposition = -1;
540         anim->last_frame = 0;
541         anim->last_pts = -1;
542         anim->next_pts = -1;
543         anim->next_packet.stream_index = -1;
544
545         anim->pFormatCtx = pFormatCtx;
546         anim->pCodecCtx = pCodecCtx;
547         anim->pCodec = pCodec;
548         anim->videoStream = videoStream;
549
550         anim->pFrame = avcodec_alloc_frame();
551         anim->pFrameComplete = FALSE;
552         anim->pFrameDeinterlaced = avcodec_alloc_frame();
553         anim->pFrameRGB = avcodec_alloc_frame();
554
555         if (avpicture_get_size(PIX_FMT_RGBA, anim->x, anim->y) !=
556             anim->x * anim->y * 4)
557         {
558                 fprintf(stderr,
559                         "ffmpeg has changed alloc scheme ... ARGHHH!\n");
560                 avcodec_close(anim->pCodecCtx);
561                 av_close_input_file(anim->pFormatCtx);
562                 av_free(anim->pFrameRGB);
563                 av_free(anim->pFrameDeinterlaced);
564                 av_free(anim->pFrame);
565                 anim->pCodecCtx = NULL;
566                 return -1;
567         }
568
569         if (anim->ib_flags & IB_animdeinterlace) {
570                 avpicture_fill((AVPicture *) anim->pFrameDeinterlaced,
571                                MEM_callocN(avpicture_get_size(
572                                                anim->pCodecCtx->pix_fmt,
573                                                anim->x, anim->y),
574                                            "ffmpeg deinterlace"),
575                                anim->pCodecCtx->pix_fmt, anim->x, anim->y);
576         }
577
578         if (pCodecCtx->has_b_frames) {
579                 anim->preseek = 25; /* FIXME: detect gopsize ... */
580         }
581         else {
582                 anim->preseek = 0;
583         }
584         
585         anim->img_convert_ctx = sws_getContext(
586                 anim->pCodecCtx->width,
587                 anim->pCodecCtx->height,
588                 anim->pCodecCtx->pix_fmt,
589                 anim->pCodecCtx->width,
590                 anim->pCodecCtx->height,
591                 PIX_FMT_RGBA,
592                 SWS_FAST_BILINEAR | SWS_PRINT_INFO,
593                 NULL, NULL, NULL);
594                 
595         if (!anim->img_convert_ctx) {
596                 fprintf(stderr,
597                         "Can't transform color space??? Bailing out...\n");
598                 avcodec_close(anim->pCodecCtx);
599                 av_close_input_file(anim->pFormatCtx);
600                 av_free(anim->pFrameRGB);
601                 av_free(anim->pFrameDeinterlaced);
602                 av_free(anim->pFrame);
603                 anim->pCodecCtx = NULL;
604                 return -1;
605         }
606
607 #ifdef FFMPEG_SWSCALE_COLOR_SPACE_SUPPORT
608         /* Try do detect if input has 0-255 YCbCR range (JFIF Jpeg MotionJpeg) */
609         if (!sws_getColorspaceDetails(anim->img_convert_ctx, (int **)&inv_table, &srcRange,
610                                       &table, &dstRange, &brightness, &contrast, &saturation))
611         {
612                 srcRange = srcRange || anim->pCodecCtx->color_range == AVCOL_RANGE_JPEG;
613                 inv_table = sws_getCoefficients(anim->pCodecCtx->colorspace);
614
615                 if (sws_setColorspaceDetails(anim->img_convert_ctx, (int *)inv_table, srcRange,
616                                              table, dstRange, brightness, contrast, saturation))
617                 {
618                         printf("Warning: Could not set libswscale colorspace details.\n");
619                 }
620         }
621         else {
622                 printf("Warning: Could not set libswscale colorspace details.\n");
623         }
624 #endif
625                 
626         return (0);
627 }
628
629 /* postprocess the image in anim->pFrame and do color conversion
630  * and deinterlacing stuff.
631  *
632  * Output is anim->last_frame
633  */
634
635 static void ffmpeg_postprocess(struct anim *anim)
636 {
637         AVFrame *input = anim->pFrame;
638         ImBuf *ibuf = anim->last_frame;
639         int filter_y = 0;
640
641         ibuf->profile = IB_PROFILE_SRGB;
642
643         if (!anim->pFrameComplete) {
644                 return;
645         }
646
647         /* This means the data wasnt read properly, 
648          * this check stops crashing */
649         if (input->data[0] == 0 && input->data[1] == 0 &&
650             input->data[2] == 0 && input->data[3] == 0)
651         {
652                 fprintf(stderr, "ffmpeg_fetchibuf: "
653                         "data not read properly...\n");
654                 return;
655         }
656
657         av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
658                "  POSTPROC: anim->pFrame planes: %p %p %p %p\n",
659                input->data[0], input->data[1], input->data[2],
660                input->data[3]);
661
662
663         if (anim->ib_flags & IB_animdeinterlace) {
664                 if (avpicture_deinterlace(
665                         (AVPicture *)
666                         anim->pFrameDeinterlaced,
667                         (const AVPicture *)
668                         anim->pFrame,
669                         anim->pCodecCtx->pix_fmt,
670                         anim->pCodecCtx->width,
671                         anim->pCodecCtx->height) < 0)
672                 {
673                         filter_y = TRUE;
674                 }
675                 else {
676                         input = anim->pFrameDeinterlaced;
677                 }
678         }
679         
680         avpicture_fill((AVPicture *) anim->pFrameRGB,
681                        (unsigned char *) ibuf->rect,
682                        PIX_FMT_RGBA, anim->x, anim->y);
683
684         if (ENDIAN_ORDER == B_ENDIAN) {
685                 int *dstStride   = anim->pFrameRGB->linesize;
686                 uint8_t **dst     = anim->pFrameRGB->data;
687                 int dstStride2[4] = { dstStride[0], 0, 0, 0 };
688                 uint8_t *dst2[4]  = { dst[0], 0, 0, 0 };
689                 int x, y, h, w;
690                 unsigned char *bottom;
691                 unsigned char *top;
692                 
693                 sws_scale(anim->img_convert_ctx,
694                           (const uint8_t *const *)input->data,
695                           input->linesize,
696                           0,
697                           anim->pCodecCtx->height,
698                           dst2,
699                           dstStride2);
700                 
701                 bottom = (unsigned char *) ibuf->rect;
702                 top = bottom + ibuf->x * (ibuf->y - 1) * 4;
703                 
704                 h = (ibuf->y + 1) / 2;
705                 w = ibuf->x;
706                 
707                 for (y = 0; y < h; y++) {
708                         unsigned char tmp[4];
709                         unsigned int *tmp_l =
710                             (unsigned int *) tmp;
711                         
712                         for (x = 0; x < w; x++) {
713                                 tmp[0] = bottom[0];
714                                 tmp[1] = bottom[1];
715                                 tmp[2] = bottom[2];
716                                 tmp[3] = bottom[3];
717                                 
718                                 bottom[0] = top[0];
719                                 bottom[1] = top[1];
720                                 bottom[2] = top[2];
721                                 bottom[3] = top[3];
722                                 
723                                 *(unsigned int *) top = *tmp_l;
724                                 
725                                 bottom += 4;
726                                 top += 4;
727                         }
728                         top -= 8 * w;
729                 }
730         }
731         else {
732                 int *dstStride   = anim->pFrameRGB->linesize;
733                 uint8_t **dst     = anim->pFrameRGB->data;
734                 int dstStride2[4] = { -dstStride[0], 0, 0, 0 };
735                 uint8_t *dst2[4]  = { dst[0] + (anim->y - 1) * dstStride[0],
736                                           0, 0, 0 };
737                 
738                 sws_scale(anim->img_convert_ctx,
739                           (const uint8_t *const *)input->data,
740                           input->linesize,
741                           0,
742                           anim->pCodecCtx->height,
743                           dst2,
744                           dstStride2);
745         }
746
747         if (filter_y) {
748                 IMB_filtery(ibuf);
749         }
750 }
751
752 /* decode one video frame also considering the packet read into next_packet */
753
754 static int ffmpeg_decode_video_frame(struct anim *anim)
755 {
756         int rval = 0;
757
758         av_log(anim->pFormatCtx, AV_LOG_DEBUG, "  DECODE VIDEO FRAME\n");
759
760         if (anim->next_packet.stream_index == anim->videoStream) {
761                 av_free_packet(&anim->next_packet);
762                 anim->next_packet.stream_index = -1;
763         }
764         
765         while ((rval = av_read_frame(anim->pFormatCtx, &anim->next_packet)) >= 0) {
766                 av_log(anim->pFormatCtx, 
767                        AV_LOG_DEBUG, 
768                        "%sREAD: strID=%d (VID: %d) dts=%lld pts=%lld "
769                        "%s\n",
770                        (anim->next_packet.stream_index == anim->videoStream)
771                        ? "->" : "  ",
772                        anim->next_packet.stream_index, 
773                        anim->videoStream,
774                        (anim->next_packet.dts == AV_NOPTS_VALUE) ? -1 :
775                        (long long int)anim->next_packet.dts,
776                        (anim->next_packet.pts == AV_NOPTS_VALUE) ? -1 :
777                        (long long int)anim->next_packet.pts,
778                        (anim->next_packet.flags & AV_PKT_FLAG_KEY) ? 
779                        " KEY" : "");
780                 if (anim->next_packet.stream_index == anim->videoStream) {
781                         anim->pFrameComplete = 0;
782
783                         avcodec_decode_video2(
784                             anim->pCodecCtx,
785                             anim->pFrame, &anim->pFrameComplete,
786                             &anim->next_packet);
787
788                         if (anim->pFrameComplete) {
789                                 anim->next_pts = av_get_pts_from_frame(
790                                         anim->pFormatCtx, anim->pFrame);
791
792                                 av_log(anim->pFormatCtx,
793                                        AV_LOG_DEBUG,
794                                        "  FRAME DONE: next_pts=%lld "
795                                        "pkt_pts=%lld, guessed_pts=%lld\n",
796                                        (anim->pFrame->pts == AV_NOPTS_VALUE) ?
797                                        -1 : (long long int)anim->pFrame->pts,
798                                        (anim->pFrame->pkt_pts == AV_NOPTS_VALUE) ?
799                                        -1 : (long long int)anim->pFrame->pkt_pts,
800                                        (long long int)anim->next_pts);
801                                 break;
802                         }
803                 }
804                 av_free_packet(&anim->next_packet);
805                 anim->next_packet.stream_index = -1;
806         }
807         
808         if (rval < 0) {
809                 anim->next_packet.stream_index = -1;
810
811                 av_log(anim->pFormatCtx,
812                        AV_LOG_ERROR, "  DECODE READ FAILED: av_read_frame() "
813                        "returned error: %d\n",  rval);
814         }
815
816         return (rval >= 0);
817 }
818
819 static void ffmpeg_decode_video_frame_scan(
820         struct anim *anim, int64_t pts_to_search)
821 {
822         /* there seem to exist *very* silly GOP lengths out in the wild... */
823         int count = 1000;
824
825         av_log(anim->pFormatCtx,
826                AV_LOG_DEBUG, 
827                "SCAN start: considering pts=%lld in search of %lld\n", 
828                (long long int)anim->next_pts, (long long int)pts_to_search);
829
830         while (count > 0 && anim->next_pts < pts_to_search) {
831                 av_log(anim->pFormatCtx,
832                        AV_LOG_DEBUG, 
833                        "  WHILE: pts=%lld in search of %lld\n", 
834                        (long long int)anim->next_pts, (long long int)pts_to_search);
835                 if (!ffmpeg_decode_video_frame(anim)) {
836                         break;
837                 }
838                 count--;
839         }
840         if (count == 0) {
841                 av_log(anim->pFormatCtx,
842                        AV_LOG_ERROR, 
843                        "SCAN failed: completely lost in stream, "
844                        "bailing out at PTS=%lld, searching for PTS=%lld\n", 
845                        (long long int)anim->next_pts, (long long int)pts_to_search);
846         }
847         if (anim->next_pts == pts_to_search) {
848                 av_log(anim->pFormatCtx,
849                        AV_LOG_DEBUG, "SCAN HAPPY: we found our PTS!\n");
850         }
851         else {
852                 av_log(anim->pFormatCtx,
853                        AV_LOG_ERROR, "SCAN UNHAPPY: PTS not matched!\n");
854         }
855 }
856
857 static int match_format(const char *name, AVFormatContext *pFormatCtx)
858 {
859         const char *p;
860         int len, namelen;
861
862         const char *names = pFormatCtx->iformat->name;
863
864         if (!name || !names)
865                 return 0;
866
867         namelen = strlen(name);
868         while ((p = strchr(names, ','))) {
869                 len = MAX2(p - names, namelen);
870                 if (!BLI_strncasecmp(name, names, len))
871                         return 1;
872                 names = p + 1;
873         }
874         return !BLI_strcasecmp(name, names);
875 }
876
877 static int ffmpeg_seek_by_byte(AVFormatContext *pFormatCtx)
878 {
879         static const char *byte_seek_list[] = { "mpegts", 0 };
880         const char **p;
881
882         if (pFormatCtx->iformat->flags & AVFMT_TS_DISCONT) {
883                 return TRUE;
884         }
885
886         p = byte_seek_list;
887
888         while (*p) {
889                 if (match_format(*p++, pFormatCtx)) {
890                         return TRUE;
891                 }
892         }
893
894         return FALSE;
895 }
896
897 static ImBuf *ffmpeg_fetchibuf(struct anim *anim, int position,
898                                IMB_Timecode_Type tc) {
899         int64_t pts_to_search = 0;
900         double frame_rate;
901         double pts_time_base;
902         long long st_time; 
903         struct anim_index *tc_index = 0;
904         AVStream *v_st;
905         int new_frame_index = 0; /* To quite gcc barking... */
906         int old_frame_index = 0; /* To quite gcc barking... */
907
908         if (anim == 0) return (0);
909
910         av_log(anim->pFormatCtx, AV_LOG_DEBUG, "FETCH: pos=%d\n", position);
911
912         if (tc != IMB_TC_NONE) {
913                 tc_index = IMB_anim_open_index(anim, tc);
914         }
915
916         v_st = anim->pFormatCtx->streams[anim->videoStream];
917
918         frame_rate = av_q2d(v_st->r_frame_rate);
919
920         st_time = anim->pFormatCtx->start_time;
921         pts_time_base = av_q2d(v_st->time_base);
922
923         if (tc_index) {
924                 new_frame_index = IMB_indexer_get_frame_index(
925                         tc_index, position);
926                 old_frame_index = IMB_indexer_get_frame_index(
927                         tc_index, anim->curposition);
928                 pts_to_search = IMB_indexer_get_pts(
929                         tc_index, new_frame_index);
930         }
931         else {
932                 pts_to_search = (long long) 
933                                 floor(((double) position) /
934                                       pts_time_base / frame_rate + 0.5);
935
936                 if (st_time != AV_NOPTS_VALUE) {
937                         pts_to_search += st_time / pts_time_base / AV_TIME_BASE;
938                 }
939         }
940
941         av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
942                "FETCH: looking for PTS=%lld "
943                "(pts_timebase=%g, frame_rate=%g, st_time=%lld)\n", 
944                (long long int)pts_to_search, pts_time_base, frame_rate, st_time);
945
946         if (anim->last_frame && 
947             anim->last_pts <= pts_to_search && anim->next_pts > pts_to_search)
948         {
949                 av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
950                        "FETCH: frame repeat: last: %lld next: %lld\n",
951                        (long long int)anim->last_pts, 
952                        (long long int)anim->next_pts);
953                 IMB_refImBuf(anim->last_frame);
954                 anim->curposition = position;
955                 return anim->last_frame;
956         }
957          
958         if (position > anim->curposition + 1 &&
959             anim->preseek &&
960             !tc_index &&
961             position - (anim->curposition + 1) < anim->preseek)
962         {
963                 av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
964                        "FETCH: within preseek interval (no index)\n");
965
966                 ffmpeg_decode_video_frame_scan(anim, pts_to_search);
967         }
968         else if (tc_index &&
969                  IMB_indexer_can_scan(tc_index, old_frame_index,
970                                       new_frame_index))
971         {
972                 av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
973                        "FETCH: within preseek interval "
974                        "(index tells us)\n");
975
976                 ffmpeg_decode_video_frame_scan(anim, pts_to_search);
977         }
978         else if (position != anim->curposition + 1) {
979                 long long pos;
980                 int ret;
981
982                 if (tc_index) {
983                         unsigned long long dts;
984
985                         pos = IMB_indexer_get_seek_pos(
986                             tc_index, new_frame_index);
987                         dts = IMB_indexer_get_seek_pos_dts(
988                             tc_index, new_frame_index);
989
990                         av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
991                                "TC INDEX seek pos = %lld\n", pos);
992                         av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
993                                "TC INDEX seek dts = %lld\n", dts);
994
995                         if (ffmpeg_seek_by_byte(anim->pFormatCtx)) {
996                                 av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
997                                        "... using BYTE pos\n");
998
999                                 ret = av_seek_frame(anim->pFormatCtx, 
1000                                                     -1,
1001                                                     pos, AVSEEK_FLAG_BYTE);
1002                                 av_update_cur_dts(anim->pFormatCtx, v_st, dts);
1003                         }
1004                         else {
1005                                 av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
1006                                        "... using DTS pos\n");
1007                                 ret = av_seek_frame(anim->pFormatCtx, 
1008                                                     anim->videoStream,
1009                                                     dts, AVSEEK_FLAG_BACKWARD);
1010                         }
1011                 }
1012                 else {
1013                         pos = (long long) (position - anim->preseek) *
1014                               AV_TIME_BASE / frame_rate;
1015
1016                         av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
1017                                "NO INDEX seek pos = %lld, st_time = %lld\n", 
1018                                pos, (st_time != AV_NOPTS_VALUE) ? st_time : 0);
1019
1020                         if (pos < 0) {
1021                                 pos = 0;
1022                         }
1023                 
1024                         if (st_time != AV_NOPTS_VALUE) {
1025                                 pos += st_time;
1026                         }
1027
1028                         av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
1029                                "NO INDEX final seek pos = %lld\n", pos);
1030
1031                         ret = av_seek_frame(anim->pFormatCtx, -1, 
1032                                             pos, AVSEEK_FLAG_BACKWARD);
1033                 }
1034
1035                 if (ret < 0) {
1036                         av_log(anim->pFormatCtx, AV_LOG_ERROR,
1037                                "FETCH: "
1038                                "error while seeking to DTS = %lld "
1039                                "(frameno = %d, PTS = %lld): errcode = %d\n",
1040                                pos, position, (long long int)pts_to_search, ret);
1041                 }
1042
1043                 avcodec_flush_buffers(anim->pCodecCtx);
1044
1045                 anim->next_pts = -1;
1046
1047                 if (anim->next_packet.stream_index == anim->videoStream) {
1048                         av_free_packet(&anim->next_packet);
1049                         anim->next_packet.stream_index = -1;
1050                 }
1051
1052                 /* memset(anim->pFrame, ...) ?? */
1053
1054                 if (ret >= 0) {
1055                         ffmpeg_decode_video_frame_scan(anim, pts_to_search);
1056                 }
1057         }
1058         else if (position == 0 && anim->curposition == -1) {
1059                 /* first frame without seeking special case... */
1060                 ffmpeg_decode_video_frame(anim);
1061         }
1062         else {
1063                 av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
1064                        "FETCH: no seek necessary, just continue...\n");
1065         }
1066
1067         IMB_freeImBuf(anim->last_frame);
1068         anim->last_frame = IMB_allocImBuf(anim->x, anim->y, 32, IB_rect);
1069
1070         ffmpeg_postprocess(anim);
1071
1072         anim->last_pts = anim->next_pts;
1073         
1074         ffmpeg_decode_video_frame(anim);
1075         
1076         anim->curposition = position;
1077         
1078         IMB_refImBuf(anim->last_frame);
1079
1080         return anim->last_frame;
1081 }
1082
1083 static void free_anim_ffmpeg(struct anim *anim)
1084 {
1085         if (anim == NULL) return;
1086
1087         if (anim->pCodecCtx) {
1088                 avcodec_close(anim->pCodecCtx);
1089                 av_close_input_file(anim->pFormatCtx);
1090                 av_free(anim->pFrameRGB);
1091                 av_free(anim->pFrame);
1092
1093                 if (anim->ib_flags & IB_animdeinterlace) {
1094                         MEM_freeN(anim->pFrameDeinterlaced->data[0]);
1095                 }
1096                 av_free(anim->pFrameDeinterlaced);
1097                 sws_freeContext(anim->img_convert_ctx);
1098                 IMB_freeImBuf(anim->last_frame);
1099                 if (anim->next_packet.stream_index != -1) {
1100                         av_free_packet(&anim->next_packet);
1101                 }
1102         }
1103         anim->duration = 0;
1104 }
1105
1106 #endif
1107
1108 #ifdef WITH_REDCODE
1109
1110 static int startredcode(struct anim *anim)
1111 {
1112         anim->redcodeCtx = redcode_open(anim->name);
1113         if (!anim->redcodeCtx) {
1114                 return -1;
1115         }
1116         anim->duration = redcode_get_length(anim->redcodeCtx);
1117         
1118         return 0;
1119 }
1120
1121 static ImBuf *redcode_fetchibuf(struct anim *anim, int position)
1122 {
1123         struct ImBuf *ibuf;
1124         struct redcode_frame *frame;
1125         struct redcode_frame_raw *raw_frame;
1126
1127         if (!anim->redcodeCtx) {
1128                 return NULL;
1129         }
1130
1131         frame = redcode_read_video_frame(anim->redcodeCtx, position);
1132         
1133         if (!frame) {
1134                 return NULL;
1135         }
1136
1137         raw_frame = redcode_decode_video_raw(frame, 1);
1138
1139         redcode_free_frame(frame);
1140
1141         if (!raw_frame) {
1142                 return NULL;
1143         }
1144         
1145         ibuf = IMB_allocImBuf(raw_frame->width * 2,
1146                               raw_frame->height * 2, 32, IB_rectfloat);
1147
1148         redcode_decode_video_float(raw_frame, ibuf->rect_float, 1);
1149
1150         return ibuf;
1151 }
1152
1153 static void free_anim_redcode(struct anim *anim)
1154 {
1155         if (anim->redcodeCtx) {
1156                 redcode_close(anim->redcodeCtx);
1157                 anim->redcodeCtx = 0;
1158         }
1159         anim->duration = 0;
1160 }
1161
1162 #endif
1163
1164 /* Try next picture to read */
1165 /* No picture, try to open next animation */
1166 /* Succeed, remove first image from animation */
1167
1168 static ImBuf *anim_getnew(struct anim *anim)
1169 {
1170         struct ImBuf *ibuf = NULL;
1171
1172         if (anim == NULL) return(NULL);
1173
1174         free_anim_movie(anim);
1175         free_anim_avi(anim);
1176 #ifdef WITH_QUICKTIME
1177         free_anim_quicktime(anim);
1178 #endif
1179 #ifdef WITH_FFMPEG
1180         free_anim_ffmpeg(anim);
1181 #endif
1182 #ifdef WITH_REDCODE
1183         free_anim_redcode(anim);
1184 #endif
1185
1186
1187         if (anim->curtype != 0) return (NULL);
1188         anim->curtype = imb_get_anim_type(anim->name);  
1189
1190         switch (anim->curtype) {
1191                 case ANIM_SEQUENCE:
1192                         ibuf = IMB_loadiffname(anim->name, anim->ib_flags);
1193                         if (ibuf) {
1194                                 BLI_strncpy(anim->first, anim->name, sizeof(anim->first));
1195                                 anim->duration = 1;
1196                         }
1197                         break;
1198                 case ANIM_MOVIE:
1199                         if (startmovie(anim)) return (NULL);
1200                         ibuf = IMB_allocImBuf(anim->x, anim->y, 24, 0); /* fake */
1201                         break;
1202                 case ANIM_AVI:
1203                         if (startavi(anim)) {
1204                                 printf("couldnt start avi\n");
1205                                 return (NULL);
1206                         }
1207                         ibuf = IMB_allocImBuf(anim->x, anim->y, 24, 0);
1208                         break;
1209 #ifdef WITH_QUICKTIME
1210                 case ANIM_QTIME:
1211                         if (startquicktime(anim)) return (0);
1212                         ibuf = IMB_allocImBuf(anim->x, anim->y, 24, 0);
1213                         break;
1214 #endif
1215 #ifdef WITH_FFMPEG
1216                 case ANIM_FFMPEG:
1217                         if (startffmpeg(anim)) return (0);
1218                         ibuf = IMB_allocImBuf(anim->x, anim->y, 24, 0);
1219                         break;
1220 #endif
1221 #ifdef WITH_REDCODE
1222                 case ANIM_REDCODE:
1223                         if (startredcode(anim)) return (0);
1224                         ibuf = IMB_allocImBuf(8, 8, 32, 0);
1225                         break;
1226 #endif
1227         }
1228         return(ibuf);
1229 }
1230
1231 struct ImBuf *IMB_anim_previewframe(struct anim *anim)
1232 {
1233         struct ImBuf *ibuf = NULL;
1234         int position = 0;
1235         
1236         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1237         if (ibuf) {
1238                 IMB_freeImBuf(ibuf);
1239                 position = anim->duration / 2;
1240                 ibuf = IMB_anim_absolute(anim, position, IMB_TC_NONE,
1241                                          IMB_PROXY_NONE);
1242         }
1243         return ibuf;
1244 }
1245
1246 struct ImBuf *IMB_anim_absolute(struct anim *anim, int position,
1247                                 IMB_Timecode_Type tc,
1248                                 IMB_Proxy_Size preview_size) {
1249         struct ImBuf *ibuf = NULL;
1250         char head[256], tail[256];
1251         unsigned short digits;
1252         int pic;
1253         int filter_y;
1254         if (anim == NULL) return(NULL);
1255
1256         filter_y = (anim->ib_flags & IB_animdeinterlace);
1257
1258         if (anim->curtype == 0) {
1259                 ibuf = anim_getnew(anim);
1260                 if (ibuf == NULL) {
1261                         return(NULL);
1262                 }
1263
1264                 IMB_freeImBuf(ibuf); /* ???? */
1265                 ibuf = NULL;
1266         }
1267
1268         if (position < 0) return(NULL);
1269         if (position >= anim->duration) return(NULL);
1270
1271         if (preview_size != IMB_PROXY_NONE) {
1272                 struct anim *proxy = IMB_anim_open_proxy(anim, preview_size);
1273
1274                 if (proxy) {
1275                         position = IMB_anim_index_get_frame_index(
1276                             anim, tc, position);
1277                         return IMB_anim_absolute(
1278                                    proxy, position,
1279                                    IMB_TC_NONE, IMB_PROXY_NONE);
1280                 }
1281         }
1282
1283         switch (anim->curtype) {
1284                 case ANIM_SEQUENCE:
1285                         pic = an_stringdec(anim->first, head, tail, &digits);
1286                         pic += position;
1287                         an_stringenc(anim->name, head, tail, digits, pic);
1288                         ibuf = IMB_loadiffname(anim->name, IB_rect);
1289                         if (ibuf) {
1290                                 anim->curposition = position;
1291                         }
1292                         break;
1293                 case ANIM_MOVIE:
1294                         ibuf = movie_fetchibuf(anim, position);
1295                         if (ibuf) {
1296                                 anim->curposition = position;
1297                                 IMB_convert_rgba_to_abgr(ibuf);
1298                                 ibuf->profile = IB_PROFILE_SRGB;
1299                         }
1300                         break;
1301                 case ANIM_AVI:
1302                         ibuf = avi_fetchibuf(anim, position);
1303                         if (ibuf)
1304                                 anim->curposition = position;
1305                         break;
1306 #ifdef WITH_QUICKTIME
1307                 case ANIM_QTIME:
1308                         ibuf = qtime_fetchibuf(anim, position);
1309                         if (ibuf)
1310                                 anim->curposition = position;
1311                         break;
1312 #endif
1313 #ifdef WITH_FFMPEG
1314                 case ANIM_FFMPEG:
1315                         ibuf = ffmpeg_fetchibuf(anim, position, tc);
1316                         if (ibuf)
1317                                 anim->curposition = position;
1318                         filter_y = 0; /* done internally */
1319                         break;
1320 #endif
1321 #ifdef WITH_REDCODE
1322                 case ANIM_REDCODE:
1323                         ibuf = redcode_fetchibuf(anim, position);
1324                         if (ibuf) anim->curposition = position;
1325                         break;
1326 #endif
1327         }
1328
1329         if (ibuf) {
1330                 if (filter_y) IMB_filtery(ibuf);
1331                 BLI_snprintf(ibuf->name, sizeof(ibuf->name), "%s.%04d", anim->name, anim->curposition + 1);
1332                 
1333         }
1334         return(ibuf);
1335 }
1336
1337 /***/
1338
1339 int IMB_anim_get_duration(struct anim *anim, IMB_Timecode_Type tc)
1340 {
1341         struct anim_index *idx;
1342         if (tc == IMB_TC_NONE) {
1343                 return anim->duration;
1344         }
1345         
1346         idx = IMB_anim_open_index(anim, tc);
1347         if (!idx) {
1348                 return anim->duration;
1349         }
1350
1351         return IMB_indexer_get_duration(idx);
1352 }
1353
1354 int IMB_anim_get_fps(struct anim *anim,
1355                      short *frs_sec, float *frs_sec_base)
1356 {
1357         if (anim->frs_sec) {
1358                 *frs_sec = anim->frs_sec;
1359                 *frs_sec_base = anim->frs_sec_base;
1360                 return TRUE;
1361         }
1362         return FALSE;
1363 }
1364
1365 void IMB_anim_set_preseek(struct anim *anim, int preseek)
1366 {
1367         anim->preseek = preseek;
1368 }
1369
1370 int IMB_anim_get_preseek(struct anim *anim)
1371 {
1372         return anim->preseek;
1373 }