Some FFmpeg changes
[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 static int startffmpeg(struct anim *anim)
443 {
444         int i, videoStream;
445
446         AVCodec *pCodec;
447         AVFormatContext *pFormatCtx = NULL;
448         AVCodecContext *pCodecCtx;
449         int frs_num;
450         double frs_den;
451         int streamcount;
452
453 #ifdef FFMPEG_SWSCALE_COLOR_SPACE_SUPPORT
454         /* The following for color space determination */
455         int srcRange, dstRange, brightness, contrast, saturation;
456         int *table;
457         const int *inv_table;
458 #endif
459
460         if (anim == 0) return(-1);
461
462         streamcount = anim->streamindex;
463
464         if (avformat_open_input(&pFormatCtx, anim->name, NULL, NULL) != 0) {
465                 return -1;
466         }
467
468         if (av_find_stream_info(pFormatCtx) < 0) {
469                 av_close_input_file(pFormatCtx);
470                 return -1;
471         }
472
473         av_dump_format(pFormatCtx, 0, anim->name, 0);
474
475
476         /* Find the video stream */
477         videoStream = -1;
478
479         for (i = 0; i < pFormatCtx->nb_streams; i++)
480                 if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
481                         if (streamcount > 0) {
482                                 streamcount--;
483                                 continue;
484                         }
485                         videoStream = i;
486                         break;
487                 }
488
489         if (videoStream == -1) {
490                 av_close_input_file(pFormatCtx);
491                 return -1;
492         }
493
494         pCodecCtx = pFormatCtx->streams[videoStream]->codec;
495
496         /* Find the decoder for the video stream */
497         pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
498         if (pCodec == NULL) {
499                 av_close_input_file(pFormatCtx);
500                 return -1;
501         }
502
503         pCodecCtx->workaround_bugs = 1;
504
505         if (avcodec_open(pCodecCtx, pCodec) < 0) {
506                 av_close_input_file(pFormatCtx);
507                 return -1;
508         }
509
510         anim->duration = ceil(pFormatCtx->duration *
511                               av_q2d(pFormatCtx->streams[videoStream]->r_frame_rate) /
512                               AV_TIME_BASE);
513
514         frs_num = pFormatCtx->streams[videoStream]->r_frame_rate.num;
515         frs_den = pFormatCtx->streams[videoStream]->r_frame_rate.den;
516
517         frs_den *= AV_TIME_BASE;
518
519         while (frs_num % 10 == 0 && frs_den >= 2.0 && frs_num > 10) {
520                 frs_num /= 10;
521                 frs_den /= 10;
522         }
523
524         anim->frs_sec = frs_num;
525         anim->frs_sec_base = frs_den;
526
527         anim->params = 0;
528
529         anim->x = pCodecCtx->width;
530         anim->y = pCodecCtx->height;
531         anim->interlacing = 0;
532         anim->orientation = 0;
533         anim->framesize = anim->x * anim->y * 4;
534
535         anim->curposition = -1;
536         anim->last_frame = 0;
537         anim->last_pts = -1;
538         anim->next_pts = -1;
539         anim->next_packet.stream_index = -1;
540
541         anim->pFormatCtx = pFormatCtx;
542         anim->pCodecCtx = pCodecCtx;
543         anim->pCodec = pCodec;
544         anim->videoStream = videoStream;
545
546         anim->pFrame = avcodec_alloc_frame();
547         anim->pFrameComplete = FALSE;
548         anim->pFrameDeinterlaced = avcodec_alloc_frame();
549         anim->pFrameRGB = avcodec_alloc_frame();
550
551         if (avpicture_get_size(PIX_FMT_RGBA, anim->x, anim->y) !=
552             anim->x * anim->y * 4)
553         {
554                 fprintf(stderr,
555                         "ffmpeg has changed alloc scheme ... ARGHHH!\n");
556                 avcodec_close(anim->pCodecCtx);
557                 av_close_input_file(anim->pFormatCtx);
558                 av_free(anim->pFrameRGB);
559                 av_free(anim->pFrameDeinterlaced);
560                 av_free(anim->pFrame);
561                 anim->pCodecCtx = NULL;
562                 return -1;
563         }
564
565         if (anim->ib_flags & IB_animdeinterlace) {
566                 avpicture_fill((AVPicture *) anim->pFrameDeinterlaced,
567                                MEM_callocN(avpicture_get_size(
568                                                anim->pCodecCtx->pix_fmt,
569                                                anim->x, anim->y),
570                                            "ffmpeg deinterlace"),
571                                anim->pCodecCtx->pix_fmt, anim->x, anim->y);
572         }
573
574         if (pCodecCtx->has_b_frames) {
575                 anim->preseek = 25; /* FIXME: detect gopsize ... */
576         }
577         else {
578                 anim->preseek = 0;
579         }
580         
581         anim->img_convert_ctx = sws_getContext(
582                 anim->pCodecCtx->width,
583                 anim->pCodecCtx->height,
584                 anim->pCodecCtx->pix_fmt,
585                 anim->pCodecCtx->width,
586                 anim->pCodecCtx->height,
587                 PIX_FMT_RGBA,
588                 SWS_FAST_BILINEAR | SWS_PRINT_INFO,
589                 NULL, NULL, NULL);
590                 
591         if (!anim->img_convert_ctx) {
592                 fprintf(stderr,
593                         "Can't transform color space??? Bailing out...\n");
594                 avcodec_close(anim->pCodecCtx);
595                 av_close_input_file(anim->pFormatCtx);
596                 av_free(anim->pFrameRGB);
597                 av_free(anim->pFrameDeinterlaced);
598                 av_free(anim->pFrame);
599                 anim->pCodecCtx = NULL;
600                 return -1;
601         }
602
603 #ifdef FFMPEG_SWSCALE_COLOR_SPACE_SUPPORT
604         /* Try do detect if input has 0-255 YCbCR range (JFIF Jpeg MotionJpeg) */
605         if (!sws_getColorspaceDetails(anim->img_convert_ctx, (int **)&inv_table, &srcRange,
606                                       &table, &dstRange, &brightness, &contrast, &saturation))
607         {
608                 srcRange = srcRange || anim->pCodecCtx->color_range == AVCOL_RANGE_JPEG;
609                 inv_table = sws_getCoefficients(anim->pCodecCtx->colorspace);
610
611                 if (sws_setColorspaceDetails(anim->img_convert_ctx, (int *)inv_table, srcRange,
612                                              table, dstRange, brightness, contrast, saturation))
613                 {
614                         printf("Warning: Could not set libswscale colorspace details.\n");
615                 }
616         }
617         else {
618                 printf("Warning: Could not set libswscale colorspace details.\n");
619         }
620 #endif
621                 
622         return (0);
623 }
624
625 /* postprocess the image in anim->pFrame and do color conversion
626  * and deinterlacing stuff.
627  *
628  * Output is anim->last_frame
629  */
630
631 static void ffmpeg_postprocess(struct anim *anim)
632 {
633         AVFrame *input = anim->pFrame;
634         ImBuf *ibuf = anim->last_frame;
635         int filter_y = 0;
636
637         ibuf->profile = IB_PROFILE_SRGB;
638
639         if (!anim->pFrameComplete) {
640                 return;
641         }
642
643         /* This means the data wasnt read properly, 
644          * this check stops crashing */
645         if (input->data[0] == 0 && input->data[1] == 0 &&
646             input->data[2] == 0 && input->data[3] == 0)
647         {
648                 fprintf(stderr, "ffmpeg_fetchibuf: "
649                         "data not read properly...\n");
650                 return;
651         }
652
653         av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
654                "  POSTPROC: anim->pFrame planes: %p %p %p %p\n",
655                input->data[0], input->data[1], input->data[2],
656                input->data[3]);
657
658
659         if (anim->ib_flags & IB_animdeinterlace) {
660                 if (avpicture_deinterlace(
661                         (AVPicture *)
662                         anim->pFrameDeinterlaced,
663                         (const AVPicture *)
664                         anim->pFrame,
665                         anim->pCodecCtx->pix_fmt,
666                         anim->pCodecCtx->width,
667                         anim->pCodecCtx->height) < 0)
668                 {
669                         filter_y = TRUE;
670                 }
671                 else {
672                         input = anim->pFrameDeinterlaced;
673                 }
674         }
675         
676         avpicture_fill((AVPicture *) anim->pFrameRGB,
677                        (unsigned char *) ibuf->rect,
678                        PIX_FMT_RGBA, anim->x, anim->y);
679
680         if (ENDIAN_ORDER == B_ENDIAN) {
681                 int *dstStride   = anim->pFrameRGB->linesize;
682                 uint8_t **dst     = anim->pFrameRGB->data;
683                 int dstStride2[4] = { dstStride[0], 0, 0, 0 };
684                 uint8_t *dst2[4]  = { dst[0], 0, 0, 0 };
685                 int x, y, h, w;
686                 unsigned char *bottom;
687                 unsigned char *top;
688                 
689                 sws_scale(anim->img_convert_ctx,
690                           (const uint8_t *const *)input->data,
691                           input->linesize,
692                           0,
693                           anim->pCodecCtx->height,
694                           dst2,
695                           dstStride2);
696                 
697                 bottom = (unsigned char *) ibuf->rect;
698                 top = bottom + ibuf->x * (ibuf->y - 1) * 4;
699                 
700                 h = (ibuf->y + 1) / 2;
701                 w = ibuf->x;
702                 
703                 for (y = 0; y < h; y++) {
704                         unsigned char tmp[4];
705                         unsigned int *tmp_l =
706                             (unsigned int *) tmp;
707                         
708                         for (x = 0; x < w; x++) {
709                                 tmp[0] = bottom[0];
710                                 tmp[1] = bottom[1];
711                                 tmp[2] = bottom[2];
712                                 tmp[3] = bottom[3];
713                                 
714                                 bottom[0] = top[0];
715                                 bottom[1] = top[1];
716                                 bottom[2] = top[2];
717                                 bottom[3] = top[3];
718                                 
719                                 *(unsigned int *) top = *tmp_l;
720                                 
721                                 bottom += 4;
722                                 top += 4;
723                         }
724                         top -= 8 * w;
725                 }
726         }
727         else {
728                 int *dstStride   = anim->pFrameRGB->linesize;
729                 uint8_t **dst     = anim->pFrameRGB->data;
730                 int dstStride2[4] = { -dstStride[0], 0, 0, 0 };
731                 uint8_t *dst2[4]  = { dst[0] + (anim->y - 1) * dstStride[0],
732                                           0, 0, 0 };
733                 
734                 sws_scale(anim->img_convert_ctx,
735                           (const uint8_t *const *)input->data,
736                           input->linesize,
737                           0,
738                           anim->pCodecCtx->height,
739                           dst2,
740                           dstStride2);
741         }
742
743         if (filter_y) {
744                 IMB_filtery(ibuf);
745         }
746 }
747
748 /* decode one video frame also considering the packet read into next_packet */
749
750 static int ffmpeg_decode_video_frame(struct anim *anim)
751 {
752         int rval = 0;
753
754         av_log(anim->pFormatCtx, AV_LOG_DEBUG, "  DECODE VIDEO FRAME\n");
755
756         if (anim->next_packet.stream_index == anim->videoStream) {
757                 av_free_packet(&anim->next_packet);
758                 anim->next_packet.stream_index = -1;
759         }
760         
761         while ((rval = av_read_frame(anim->pFormatCtx, &anim->next_packet)) >= 0) {
762                 av_log(anim->pFormatCtx, 
763                        AV_LOG_DEBUG, 
764                        "%sREAD: strID=%d (VID: %d) dts=%lld pts=%lld "
765                        "%s\n",
766                        (anim->next_packet.stream_index == anim->videoStream)
767                        ? "->" : "  ",
768                        anim->next_packet.stream_index, 
769                        anim->videoStream,
770                        (anim->next_packet.dts == AV_NOPTS_VALUE) ? -1 :
771                        (long long int)anim->next_packet.dts,
772                        (anim->next_packet.pts == AV_NOPTS_VALUE) ? -1 :
773                        (long long int)anim->next_packet.pts,
774                        (anim->next_packet.flags & AV_PKT_FLAG_KEY) ? 
775                        " KEY" : "");
776                 if (anim->next_packet.stream_index == anim->videoStream) {
777                         anim->pFrameComplete = 0;
778
779                         avcodec_decode_video2(
780                             anim->pCodecCtx,
781                             anim->pFrame, &anim->pFrameComplete,
782                             &anim->next_packet);
783
784                         if (anim->pFrameComplete) {
785                                 anim->next_pts = av_get_pts_from_frame(
786                                         anim->pFormatCtx, anim->pFrame);
787
788                                 av_log(anim->pFormatCtx,
789                                        AV_LOG_DEBUG,
790                                        "  FRAME DONE: next_pts=%lld "
791                                        "pkt_pts=%lld, guessed_pts=%lld\n",
792                                        (anim->pFrame->pts == AV_NOPTS_VALUE) ?
793                                        -1 : (long long int)anim->pFrame->pts,
794                                        (anim->pFrame->pkt_pts == AV_NOPTS_VALUE) ?
795                                        -1 : (long long int)anim->pFrame->pkt_pts,
796                                        (long long int)anim->next_pts);
797                                 break;
798                         }
799                 }
800                 av_free_packet(&anim->next_packet);
801                 anim->next_packet.stream_index = -1;
802         }
803         
804         if (rval < 0) {
805                 anim->next_packet.stream_index = -1;
806
807                 av_log(anim->pFormatCtx,
808                        AV_LOG_ERROR, "  DECODE READ FAILED: av_read_frame() "
809                        "returned error: %d\n",  rval);
810         }
811
812         return (rval >= 0);
813 }
814
815 static void ffmpeg_decode_video_frame_scan(
816         struct anim *anim, int64_t pts_to_search)
817 {
818         /* there seem to exist *very* silly GOP lengths out in the wild... */
819         int count = 1000;
820
821         av_log(anim->pFormatCtx,
822                AV_LOG_DEBUG, 
823                "SCAN start: considering pts=%lld in search of %lld\n", 
824                (long long int)anim->next_pts, (long long int)pts_to_search);
825
826         while (count > 0 && anim->next_pts < pts_to_search) {
827                 av_log(anim->pFormatCtx,
828                        AV_LOG_DEBUG, 
829                        "  WHILE: pts=%lld in search of %lld\n", 
830                        (long long int)anim->next_pts, (long long int)pts_to_search);
831                 if (!ffmpeg_decode_video_frame(anim)) {
832                         break;
833                 }
834                 count--;
835         }
836         if (count == 0) {
837                 av_log(anim->pFormatCtx,
838                        AV_LOG_ERROR, 
839                        "SCAN failed: completely lost in stream, "
840                        "bailing out at PTS=%lld, searching for PTS=%lld\n", 
841                        (long long int)anim->next_pts, (long long int)pts_to_search);
842         }
843         if (anim->next_pts == pts_to_search) {
844                 av_log(anim->pFormatCtx,
845                        AV_LOG_DEBUG, "SCAN HAPPY: we found our PTS!\n");
846         }
847         else {
848                 av_log(anim->pFormatCtx,
849                        AV_LOG_ERROR, "SCAN UNHAPPY: PTS not matched!\n");
850         }
851 }
852
853 static int match_format(const char *name, AVFormatContext *pFormatCtx)
854 {
855         const char *p;
856         int len, namelen;
857
858         const char *names = pFormatCtx->iformat->name;
859
860         if (!name || !names)
861                 return 0;
862
863         namelen = strlen(name);
864         while ((p = strchr(names, ','))) {
865                 len = MAX2(p - names, namelen);
866                 if (!BLI_strncasecmp(name, names, len))
867                         return 1;
868                 names = p + 1;
869         }
870         return !BLI_strcasecmp(name, names);
871 }
872
873 static int ffmpeg_seek_by_byte(AVFormatContext *pFormatCtx)
874 {
875         static const char *byte_seek_list[] = { "mpegts", 0 };
876         const char **p;
877
878         if (pFormatCtx->iformat->flags & AVFMT_TS_DISCONT) {
879                 return TRUE;
880         }
881
882         p = byte_seek_list;
883
884         while (*p) {
885                 if (match_format(*p++, pFormatCtx)) {
886                         return TRUE;
887                 }
888         }
889
890         return FALSE;
891 }
892
893 static ImBuf *ffmpeg_fetchibuf(struct anim *anim, int position,
894                                IMB_Timecode_Type tc) {
895         int64_t pts_to_search = 0;
896         double frame_rate;
897         double pts_time_base;
898         long long st_time; 
899         struct anim_index *tc_index = 0;
900         AVStream *v_st;
901         int new_frame_index = 0; /* To quite gcc barking... */
902         int old_frame_index = 0; /* To quite gcc barking... */
903
904         if (anim == 0) return (0);
905
906         av_log(anim->pFormatCtx, AV_LOG_DEBUG, "FETCH: pos=%d\n", position);
907
908         if (tc != IMB_TC_NONE) {
909                 tc_index = IMB_anim_open_index(anim, tc);
910         }
911
912         v_st = anim->pFormatCtx->streams[anim->videoStream];
913
914         frame_rate = av_q2d(v_st->r_frame_rate);
915
916         st_time = anim->pFormatCtx->start_time;
917         pts_time_base = av_q2d(v_st->time_base);
918
919         if (tc_index) {
920                 new_frame_index = IMB_indexer_get_frame_index(
921                         tc_index, position);
922                 old_frame_index = IMB_indexer_get_frame_index(
923                         tc_index, anim->curposition);
924                 pts_to_search = IMB_indexer_get_pts(
925                         tc_index, new_frame_index);
926         }
927         else {
928                 pts_to_search = (long long) 
929                                 floor(((double) position) /
930                                       pts_time_base / frame_rate + 0.5);
931
932                 if (st_time != AV_NOPTS_VALUE) {
933                         pts_to_search += st_time / pts_time_base / AV_TIME_BASE;
934                 }
935         }
936
937         av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
938                "FETCH: looking for PTS=%lld "
939                "(pts_timebase=%g, frame_rate=%g, st_time=%lld)\n", 
940                (long long int)pts_to_search, pts_time_base, frame_rate, st_time);
941
942         if (anim->last_frame && 
943             anim->last_pts <= pts_to_search && anim->next_pts > pts_to_search)
944         {
945                 av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
946                        "FETCH: frame repeat: last: %lld next: %lld\n",
947                        (long long int)anim->last_pts, 
948                        (long long int)anim->next_pts);
949                 IMB_refImBuf(anim->last_frame);
950                 anim->curposition = position;
951                 return anim->last_frame;
952         }
953          
954         if (position > anim->curposition + 1 &&
955             anim->preseek &&
956             !tc_index &&
957             position - (anim->curposition + 1) < anim->preseek)
958         {
959                 av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
960                        "FETCH: within preseek interval (no index)\n");
961
962                 ffmpeg_decode_video_frame_scan(anim, pts_to_search);
963         }
964         else if (tc_index &&
965                  IMB_indexer_can_scan(tc_index, old_frame_index,
966                                       new_frame_index))
967         {
968                 av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
969                        "FETCH: within preseek interval "
970                        "(index tells us)\n");
971
972                 ffmpeg_decode_video_frame_scan(anim, pts_to_search);
973         }
974         else if (position != anim->curposition + 1) {
975                 long long pos;
976                 int ret;
977
978                 if (tc_index) {
979                         unsigned long long dts;
980
981                         pos = IMB_indexer_get_seek_pos(
982                             tc_index, new_frame_index);
983                         dts = IMB_indexer_get_seek_pos_dts(
984                             tc_index, new_frame_index);
985
986                         av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
987                                "TC INDEX seek pos = %lld\n", pos);
988                         av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
989                                "TC INDEX seek dts = %lld\n", dts);
990
991                         if (ffmpeg_seek_by_byte(anim->pFormatCtx)) {
992                                 av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
993                                        "... using BYTE pos\n");
994
995                                 ret = av_seek_frame(anim->pFormatCtx, 
996                                                     -1,
997                                                     pos, AVSEEK_FLAG_BYTE);
998                                 av_update_cur_dts(anim->pFormatCtx, v_st, dts);
999                         }
1000                         else {
1001                                 av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
1002                                        "... using DTS pos\n");
1003                                 ret = av_seek_frame(anim->pFormatCtx, 
1004                                                     anim->videoStream,
1005                                                     dts, AVSEEK_FLAG_BACKWARD);
1006                         }
1007                 }
1008                 else {
1009                         pos = (long long) (position - anim->preseek) *
1010                               AV_TIME_BASE / frame_rate;
1011
1012                         av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
1013                                "NO INDEX seek pos = %lld, st_time = %lld\n", 
1014                                pos, (st_time != AV_NOPTS_VALUE) ? st_time : 0);
1015
1016                         if (pos < 0) {
1017                                 pos = 0;
1018                         }
1019                 
1020                         if (st_time != AV_NOPTS_VALUE) {
1021                                 pos += st_time;
1022                         }
1023
1024                         av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
1025                                "NO INDEX final seek pos = %lld\n", pos);
1026
1027                         ret = av_seek_frame(anim->pFormatCtx, -1, 
1028                                             pos, AVSEEK_FLAG_BACKWARD);
1029                 }
1030
1031                 if (ret < 0) {
1032                         av_log(anim->pFormatCtx, AV_LOG_ERROR,
1033                                "FETCH: "
1034                                "error while seeking to DTS = %lld "
1035                                "(frameno = %d, PTS = %lld): errcode = %d\n",
1036                                pos, position, (long long int)pts_to_search, ret);
1037                 }
1038
1039                 avcodec_flush_buffers(anim->pCodecCtx);
1040
1041                 anim->next_pts = -1;
1042
1043                 if (anim->next_packet.stream_index == anim->videoStream) {
1044                         av_free_packet(&anim->next_packet);
1045                         anim->next_packet.stream_index = -1;
1046                 }
1047
1048                 /* memset(anim->pFrame, ...) ?? */
1049
1050                 if (ret >= 0) {
1051                         ffmpeg_decode_video_frame_scan(anim, pts_to_search);
1052                 }
1053         }
1054         else if (position == 0 && anim->curposition == -1) {
1055                 /* first frame without seeking special case... */
1056                 ffmpeg_decode_video_frame(anim);
1057         }
1058         else {
1059                 av_log(anim->pFormatCtx, AV_LOG_DEBUG, 
1060                        "FETCH: no seek necessary, just continue...\n");
1061         }
1062
1063         IMB_freeImBuf(anim->last_frame);
1064         anim->last_frame = IMB_allocImBuf(anim->x, anim->y, 32, IB_rect);
1065
1066         ffmpeg_postprocess(anim);
1067
1068         anim->last_pts = anim->next_pts;
1069         
1070         ffmpeg_decode_video_frame(anim);
1071         
1072         anim->curposition = position;
1073         
1074         IMB_refImBuf(anim->last_frame);
1075
1076         return anim->last_frame;
1077 }
1078
1079 static void free_anim_ffmpeg(struct anim *anim)
1080 {
1081         if (anim == NULL) return;
1082
1083         if (anim->pCodecCtx) {
1084                 avcodec_close(anim->pCodecCtx);
1085                 av_close_input_file(anim->pFormatCtx);
1086                 av_free(anim->pFrameRGB);
1087                 av_free(anim->pFrame);
1088
1089                 if (anim->ib_flags & IB_animdeinterlace) {
1090                         MEM_freeN(anim->pFrameDeinterlaced->data[0]);
1091                 }
1092                 av_free(anim->pFrameDeinterlaced);
1093                 sws_freeContext(anim->img_convert_ctx);
1094                 IMB_freeImBuf(anim->last_frame);
1095                 if (anim->next_packet.stream_index != -1) {
1096                         av_free_packet(&anim->next_packet);
1097                 }
1098         }
1099         anim->duration = 0;
1100 }
1101
1102 #endif
1103
1104 #ifdef WITH_REDCODE
1105
1106 static int startredcode(struct anim *anim)
1107 {
1108         anim->redcodeCtx = redcode_open(anim->name);
1109         if (!anim->redcodeCtx) {
1110                 return -1;
1111         }
1112         anim->duration = redcode_get_length(anim->redcodeCtx);
1113         
1114         return 0;
1115 }
1116
1117 static ImBuf *redcode_fetchibuf(struct anim *anim, int position)
1118 {
1119         struct ImBuf *ibuf;
1120         struct redcode_frame *frame;
1121         struct redcode_frame_raw *raw_frame;
1122
1123         if (!anim->redcodeCtx) {
1124                 return NULL;
1125         }
1126
1127         frame = redcode_read_video_frame(anim->redcodeCtx, position);
1128         
1129         if (!frame) {
1130                 return NULL;
1131         }
1132
1133         raw_frame = redcode_decode_video_raw(frame, 1);
1134
1135         redcode_free_frame(frame);
1136
1137         if (!raw_frame) {
1138                 return NULL;
1139         }
1140         
1141         ibuf = IMB_allocImBuf(raw_frame->width * 2,
1142                               raw_frame->height * 2, 32, IB_rectfloat);
1143
1144         redcode_decode_video_float(raw_frame, ibuf->rect_float, 1);
1145
1146         return ibuf;
1147 }
1148
1149 static void free_anim_redcode(struct anim *anim)
1150 {
1151         if (anim->redcodeCtx) {
1152                 redcode_close(anim->redcodeCtx);
1153                 anim->redcodeCtx = 0;
1154         }
1155         anim->duration = 0;
1156 }
1157
1158 #endif
1159
1160 /* Try next picture to read */
1161 /* No picture, try to open next animation */
1162 /* Succeed, remove first image from animation */
1163
1164 static ImBuf *anim_getnew(struct anim *anim)
1165 {
1166         struct ImBuf *ibuf = NULL;
1167
1168         if (anim == NULL) return(NULL);
1169
1170         free_anim_movie(anim);
1171         free_anim_avi(anim);
1172 #ifdef WITH_QUICKTIME
1173         free_anim_quicktime(anim);
1174 #endif
1175 #ifdef WITH_FFMPEG
1176         free_anim_ffmpeg(anim);
1177 #endif
1178 #ifdef WITH_REDCODE
1179         free_anim_redcode(anim);
1180 #endif
1181
1182
1183         if (anim->curtype != 0) return (NULL);
1184         anim->curtype = imb_get_anim_type(anim->name);  
1185
1186         switch (anim->curtype) {
1187                 case ANIM_SEQUENCE:
1188                         ibuf = IMB_loadiffname(anim->name, anim->ib_flags);
1189                         if (ibuf) {
1190                                 BLI_strncpy(anim->first, anim->name, sizeof(anim->first));
1191                                 anim->duration = 1;
1192                         }
1193                         break;
1194                 case ANIM_MOVIE:
1195                         if (startmovie(anim)) return (NULL);
1196                         ibuf = IMB_allocImBuf(anim->x, anim->y, 24, 0); /* fake */
1197                         break;
1198                 case ANIM_AVI:
1199                         if (startavi(anim)) {
1200                                 printf("couldnt start avi\n");
1201                                 return (NULL);
1202                         }
1203                         ibuf = IMB_allocImBuf(anim->x, anim->y, 24, 0);
1204                         break;
1205 #ifdef WITH_QUICKTIME
1206                 case ANIM_QTIME:
1207                         if (startquicktime(anim)) return (0);
1208                         ibuf = IMB_allocImBuf(anim->x, anim->y, 24, 0);
1209                         break;
1210 #endif
1211 #ifdef WITH_FFMPEG
1212                 case ANIM_FFMPEG:
1213                         if (startffmpeg(anim)) return (0);
1214                         ibuf = IMB_allocImBuf(anim->x, anim->y, 24, 0);
1215                         break;
1216 #endif
1217 #ifdef WITH_REDCODE
1218                 case ANIM_REDCODE:
1219                         if (startredcode(anim)) return (0);
1220                         ibuf = IMB_allocImBuf(8, 8, 32, 0);
1221                         break;
1222 #endif
1223         }
1224         return(ibuf);
1225 }
1226
1227 struct ImBuf *IMB_anim_previewframe(struct anim *anim)
1228 {
1229         struct ImBuf *ibuf = NULL;
1230         int position = 0;
1231         
1232         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1233         if (ibuf) {
1234                 IMB_freeImBuf(ibuf);
1235                 position = anim->duration / 2;
1236                 ibuf = IMB_anim_absolute(anim, position, IMB_TC_NONE,
1237                                          IMB_PROXY_NONE);
1238         }
1239         return ibuf;
1240 }
1241
1242 struct ImBuf *IMB_anim_absolute(struct anim *anim, int position,
1243                                 IMB_Timecode_Type tc,
1244                                 IMB_Proxy_Size preview_size) {
1245         struct ImBuf *ibuf = NULL;
1246         char head[256], tail[256];
1247         unsigned short digits;
1248         int pic;
1249         int filter_y;
1250         if (anim == NULL) return(NULL);
1251
1252         filter_y = (anim->ib_flags & IB_animdeinterlace);
1253
1254         if (anim->curtype == 0) {
1255                 ibuf = anim_getnew(anim);
1256                 if (ibuf == NULL) {
1257                         return(NULL);
1258                 }
1259
1260                 IMB_freeImBuf(ibuf); /* ???? */
1261                 ibuf = NULL;
1262         }
1263
1264         if (position < 0) return(NULL);
1265         if (position >= anim->duration) return(NULL);
1266
1267         if (preview_size != IMB_PROXY_NONE) {
1268                 struct anim *proxy = IMB_anim_open_proxy(anim, preview_size);
1269
1270                 if (proxy) {
1271                         position = IMB_anim_index_get_frame_index(
1272                             anim, tc, position);
1273                         return IMB_anim_absolute(
1274                                    proxy, position,
1275                                    IMB_TC_NONE, IMB_PROXY_NONE);
1276                 }
1277         }
1278
1279         switch (anim->curtype) {
1280                 case ANIM_SEQUENCE:
1281                         pic = an_stringdec(anim->first, head, tail, &digits);
1282                         pic += position;
1283                         an_stringenc(anim->name, head, tail, digits, pic);
1284                         ibuf = IMB_loadiffname(anim->name, IB_rect);
1285                         if (ibuf) {
1286                                 anim->curposition = position;
1287                         }
1288                         break;
1289                 case ANIM_MOVIE:
1290                         ibuf = movie_fetchibuf(anim, position);
1291                         if (ibuf) {
1292                                 anim->curposition = position;
1293                                 IMB_convert_rgba_to_abgr(ibuf);
1294                                 ibuf->profile = IB_PROFILE_SRGB;
1295                         }
1296                         break;
1297                 case ANIM_AVI:
1298                         ibuf = avi_fetchibuf(anim, position);
1299                         if (ibuf)
1300                                 anim->curposition = position;
1301                         break;
1302 #ifdef WITH_QUICKTIME
1303                 case ANIM_QTIME:
1304                         ibuf = qtime_fetchibuf(anim, position);
1305                         if (ibuf)
1306                                 anim->curposition = position;
1307                         break;
1308 #endif
1309 #ifdef WITH_FFMPEG
1310                 case ANIM_FFMPEG:
1311                         ibuf = ffmpeg_fetchibuf(anim, position, tc);
1312                         if (ibuf)
1313                                 anim->curposition = position;
1314                         filter_y = 0; /* done internally */
1315                         break;
1316 #endif
1317 #ifdef WITH_REDCODE
1318                 case ANIM_REDCODE:
1319                         ibuf = redcode_fetchibuf(anim, position);
1320                         if (ibuf) anim->curposition = position;
1321                         break;
1322 #endif
1323         }
1324
1325         if (ibuf) {
1326                 if (filter_y) IMB_filtery(ibuf);
1327                 BLI_snprintf(ibuf->name, sizeof(ibuf->name), "%s.%04d", anim->name, anim->curposition + 1);
1328                 
1329         }
1330         return(ibuf);
1331 }
1332
1333 /***/
1334
1335 int IMB_anim_get_duration(struct anim *anim, IMB_Timecode_Type tc)
1336 {
1337         struct anim_index *idx;
1338         if (tc == IMB_TC_NONE) {
1339                 return anim->duration;
1340         }
1341         
1342         idx = IMB_anim_open_index(anim, tc);
1343         if (!idx) {
1344                 return anim->duration;
1345         }
1346
1347         return IMB_indexer_get_duration(idx);
1348 }
1349
1350 int IMB_anim_get_fps(struct anim *anim,
1351                      short *frs_sec, float *frs_sec_base)
1352 {
1353         if (anim->frs_sec) {
1354                 *frs_sec = anim->frs_sec;
1355                 *frs_sec_base = anim->frs_sec_base;
1356                 return TRUE;
1357         }
1358         return FALSE;
1359 }
1360
1361 void IMB_anim_set_preseek(struct anim *anim, int preseek)
1362 {
1363         anim->preseek = preseek;
1364 }
1365
1366 int IMB_anim_get_preseek(struct anim *anim)
1367 {
1368         return anim->preseek;
1369 }