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