adf1a2fd9a8584ead2a78965369b3669c20e6575
[blender.git] / source / blender / blenkernel / intern / movieclip.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) 2011 Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation,
22  *                 Sergey Sharybin
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/blenkernel/intern/movieclip.c
28  *  \ingroup bke
29  */
30
31
32 #include <stdio.h>
33 #include <string.h>
34 #include <fcntl.h>
35
36 #ifndef WIN32
37 #include <unistd.h>
38 #else
39 #include <io.h>
40 #endif
41
42 #include <time.h>
43
44 #ifdef _WIN32
45 #define open _open
46 #define close _close
47 #endif
48
49 #include "MEM_guardedalloc.h"
50
51 #include "DNA_constraint_types.h"
52 #include "DNA_screen_types.h"
53 #include "DNA_space_types.h"
54 #include "DNA_movieclip_types.h"
55 #include "DNA_object_types.h"
56 #include "DNA_scene_types.h"
57 #include "DNA_view3d_types.h"
58
59 #include "BLI_utildefines.h"
60
61 #include "BLI_blenlib.h"
62 #include "BLI_ghash.h"
63 #include "BLI_math.h"
64 #include "BLI_mempool.h"
65 #include "BLI_threads.h"
66
67 #include "BKE_animsys.h"
68 #include "BKE_constraint.h"
69 #include "BKE_library.h"
70 #include "BKE_global.h"
71 #include "BKE_main.h"
72 #include "BKE_utildefines.h"
73 #include "BKE_movieclip.h"
74 #include "BKE_image.h"  /* openanim */
75 #include "BKE_tracking.h"
76
77 #include "IMB_imbuf_types.h"
78 #include "IMB_imbuf.h"
79 #include "IMB_moviecache.h"
80
81 /*********************** movieclip buffer loaders *************************/
82
83 static int sequence_guess_offset(const char *full_name, int head_len, unsigned short numlen)
84 {
85         char num[FILE_MAX] = {0};
86
87         BLI_strncpy(num, full_name + head_len, numlen + 1);
88
89         return atoi(num);
90 }
91
92 static int rendersize_to_proxy(MovieClipUser *user, int flag)
93 {
94         if ((flag & MCLIP_USE_PROXY) == 0)
95                 return IMB_PROXY_NONE;
96
97         switch (user->render_size) {
98                 case MCLIP_PROXY_RENDER_SIZE_25:
99                         return IMB_PROXY_25;
100
101                 case MCLIP_PROXY_RENDER_SIZE_50:
102                         return IMB_PROXY_50;
103
104                 case MCLIP_PROXY_RENDER_SIZE_75:
105                         return IMB_PROXY_75;
106
107                 case MCLIP_PROXY_RENDER_SIZE_100:
108                         return IMB_PROXY_100;
109
110                 case MCLIP_PROXY_RENDER_SIZE_FULL:
111                         return IMB_PROXY_NONE;
112         }
113
114         return IMB_PROXY_NONE;
115 }
116
117 static int rendersize_to_number(int render_size)
118 {
119         switch (render_size) {
120                 case MCLIP_PROXY_RENDER_SIZE_25:
121                         return 25;
122
123                 case MCLIP_PROXY_RENDER_SIZE_50:
124                         return 50;
125
126                 case MCLIP_PROXY_RENDER_SIZE_75:
127                         return 75;
128
129                 case MCLIP_PROXY_RENDER_SIZE_100:
130                         return 100;
131
132                 case MCLIP_PROXY_RENDER_SIZE_FULL:
133                         return 100;
134         }
135
136         return 100;
137 }
138
139 static int get_timecode(MovieClip *clip, int flag)
140 {
141         if ((flag & MCLIP_USE_PROXY) == 0)
142                 return IMB_TC_NONE;
143
144         return clip->proxy.tc;
145 }
146
147 static void get_sequence_fname(MovieClip *clip, int framenr, char *name)
148 {
149         unsigned short numlen;
150         char head[FILE_MAX], tail[FILE_MAX];
151         int offset;
152
153         BLI_strncpy(name, clip->name, sizeof(clip->name));
154         BLI_stringdec(name, head, tail, &numlen);
155
156         /* movieclips always points to first image from sequence,
157          * autoguess offset for now. could be something smarter in the future
158          */
159         offset = sequence_guess_offset(clip->name, strlen(head), numlen);
160
161         if (numlen)
162                 BLI_stringenc(name, head, tail, numlen, offset + framenr - clip->start_frame + clip->frame_offset);
163         else
164                 BLI_strncpy(name, clip->name, sizeof(clip->name));
165
166         BLI_path_abs(name, ID_BLEND_PATH(G.main, &clip->id));
167 }
168
169 /* supposed to work with sequences only */
170 static void get_proxy_fname(MovieClip *clip, int proxy_render_size, int undistorted, int framenr, char *name)
171 {
172         int size = rendersize_to_number(proxy_render_size);
173         char dir[FILE_MAX], clipdir[FILE_MAX], clipfile[FILE_MAX];
174         int proxynr = framenr - clip->start_frame + 1 + clip->frame_offset;
175
176         BLI_split_dirfile(clip->name, clipdir, clipfile, FILE_MAX, FILE_MAX);
177
178         if (clip->flag & MCLIP_USE_PROXY_CUSTOM_DIR) {
179                 BLI_strncpy(dir, clip->proxy.dir, sizeof(dir));
180         }
181         else {
182                 BLI_snprintf(dir, FILE_MAX, "%s/BL_proxy", clipdir);
183         }
184
185         if (undistorted)
186                 BLI_snprintf(name, FILE_MAX, "%s/%s/proxy_%d_undistorted/%08d", dir, clipfile, size, proxynr);
187         else
188                 BLI_snprintf(name, FILE_MAX, "%s/%s/proxy_%d/%08d", dir, clipfile, size, proxynr);
189
190         BLI_path_abs(name, G.main->name);
191         BLI_path_frame(name, 1, 0);
192
193         strcat(name, ".jpg");
194 }
195
196 static ImBuf *movieclip_load_sequence_file(MovieClip *clip, MovieClipUser *user, int framenr, int flag)
197 {
198         struct ImBuf *ibuf;
199         char name[FILE_MAX];
200         int loadflag, use_proxy = FALSE;
201
202         use_proxy = (flag & MCLIP_USE_PROXY) && user->render_size != MCLIP_PROXY_RENDER_SIZE_FULL;
203         if (use_proxy) {
204                 int undistort = user->render_flag & MCLIP_PROXY_RENDER_UNDISTORT;
205                 get_proxy_fname(clip, user->render_size, undistort, framenr, name);
206         }
207         else
208                 get_sequence_fname(clip, framenr, name);
209
210         loadflag = IB_rect | IB_multilayer;
211
212         /* read ibuf */
213         ibuf = IMB_loadiffname(name, loadflag);
214
215         return ibuf;
216 }
217
218 static void movieclip_open_anim_file(MovieClip *clip)
219 {
220         char str[FILE_MAX];
221
222         if (!clip->anim) {
223                 BLI_strncpy(str, clip->name, FILE_MAX);
224                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &clip->id));
225
226                 /* FIXME: make several stream accessible in image editor, too */
227                 clip->anim = openanim(str, IB_rect, 0);
228
229                 if (clip->anim) {
230                         if (clip->flag & MCLIP_USE_PROXY_CUSTOM_DIR) {
231                                 char dir[FILE_MAX];
232                                 BLI_strncpy(dir, clip->proxy.dir, sizeof(dir));
233                                 BLI_path_abs(dir, G.main->name);
234                                 IMB_anim_set_index_dir(clip->anim, dir);
235                         }
236                 }
237         }
238 }
239
240 static ImBuf *movieclip_load_movie_file(MovieClip *clip, MovieClipUser *user, int framenr, int flag)
241 {
242         ImBuf *ibuf = NULL;
243         int tc = get_timecode(clip, flag);
244         int proxy = rendersize_to_proxy(user, flag);
245
246         movieclip_open_anim_file(clip);
247
248         if (clip->anim) {
249                 int dur;
250                 int fra;
251
252                 dur = IMB_anim_get_duration(clip->anim, tc);
253                 fra = framenr - clip->start_frame + clip->frame_offset;
254
255                 if (fra < 0)
256                         fra = 0;
257
258                 if (fra > (dur - 1))
259                         fra = dur - 1;
260
261                 ibuf = IMB_anim_absolute(clip->anim, fra, tc, proxy);
262         }
263
264         return ibuf;
265 }
266
267 static void movieclip_calc_length(MovieClip *clip)
268 {
269         if (clip->source == MCLIP_SRC_MOVIE) {
270                 movieclip_open_anim_file(clip);
271
272                 if (clip->anim) {
273                         clip->len = IMB_anim_get_duration(clip->anim, clip->proxy.tc);
274                 }
275         }
276         else if (clip->source == MCLIP_SRC_SEQUENCE) {
277                 int framenr = 1;
278                 unsigned short numlen;
279                 char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
280
281                 BLI_stringdec(clip->name, head, tail, &numlen);
282
283                 if (numlen == 0) {
284                         /* there's no number group in file name, assume it's single framed sequence */
285                         clip->len = framenr + 1;
286                 }
287                 else {
288                         for (;; ) {
289                                 get_sequence_fname(clip, framenr, name);
290
291                                 if (!BLI_exists(name)) {
292                                         clip->len = framenr + 1;
293                                         break;
294                                 }
295
296                                 framenr++;
297                         }
298                 }
299         }
300 }
301
302 /*********************** image buffer cache *************************/
303
304 typedef struct MovieClipCache {
305         /* regular movie cache */
306         struct MovieCache *moviecache;
307
308         /* cached postprocessed shot */
309         struct {
310                 ImBuf *ibuf;
311                 int framenr;
312                 int flag;
313
314                 /* cache for undistorted shot */
315                 float principal[2];
316                 float k1, k2, k3;
317                 short undistortion_used;
318
319                 int proxy;
320                 short render_flag;
321         } postprocessed;
322
323         /* cache for stable shot */
324         struct {
325                 ImBuf *ibuf;
326                 int framenr;
327                 int postprocess_flag;
328
329                 float loc[2], scale, angle, aspect;
330                 int proxy, filter;
331                 short render_flag;
332         } stabilized;
333 } MovieClipCache;
334
335 typedef struct MovieClipImBufCacheKey {
336         int framenr;
337         int proxy;
338         short render_flag;
339 } MovieClipImBufCacheKey;
340
341 static void moviecache_keydata(void *userkey, int *framenr, int *proxy, int *render_flags)
342 {
343         MovieClipImBufCacheKey *key = (MovieClipImBufCacheKey *)userkey;
344
345         *framenr = key->framenr;
346         *proxy = key->proxy;
347         *render_flags = key->render_flag;
348 }
349
350 static unsigned int moviecache_hashhash(const void *keyv)
351 {
352         MovieClipImBufCacheKey *key = (MovieClipImBufCacheKey *)keyv;
353         int rval = key->framenr;
354
355         return rval;
356 }
357
358 static int moviecache_hashcmp(const void *av, const void *bv)
359 {
360         const MovieClipImBufCacheKey *a = (MovieClipImBufCacheKey *)av;
361         const MovieClipImBufCacheKey *b = (MovieClipImBufCacheKey *)bv;
362
363         if (a->framenr < b->framenr)
364                 return -1;
365         else if (a->framenr > b->framenr)
366                 return 1;
367
368         if (a->proxy < b->proxy)
369                 return -1;
370         else if (a->proxy > b->proxy)
371                 return 1;
372
373         if (a->render_flag < b->render_flag)
374                 return -1;
375         else if (a->render_flag > b->render_flag)
376                 return 1;
377
378         return 0;
379 }
380
381 static ImBuf *get_imbuf_cache(MovieClip *clip, MovieClipUser *user, int flag)
382 {
383         if (clip->cache) {
384                 MovieClipImBufCacheKey key;
385
386                 key.framenr = user->framenr;
387
388                 if (flag & MCLIP_USE_PROXY) {
389                         key.proxy = rendersize_to_proxy(user, flag);
390                         key.render_flag = user->render_flag;
391                 }
392                 else {
393                         key.proxy = IMB_PROXY_NONE;
394                         key.render_flag = 0;
395                 }
396
397                 return IMB_moviecache_get(clip->cache->moviecache, &key);
398         }
399
400         return NULL;
401 }
402
403 static void put_imbuf_cache(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf, int flag)
404 {
405         MovieClipImBufCacheKey key;
406
407         if (!clip->cache) {
408                 clip->cache = MEM_callocN(sizeof(MovieClipCache), "movieClipCache");
409
410                 clip->cache->moviecache = IMB_moviecache_create(sizeof(MovieClipImBufCacheKey), moviecache_hashhash,
411                                                                 moviecache_hashcmp, moviecache_keydata);
412         }
413
414         key.framenr = user->framenr;
415
416         if (flag & MCLIP_USE_PROXY) {
417                 key.proxy = rendersize_to_proxy(user, flag);
418                 key.render_flag = user->render_flag;
419         }
420         else {
421                 key.proxy = IMB_PROXY_NONE;
422                 key.render_flag = 0;
423         }
424
425         IMB_moviecache_put(clip->cache->moviecache, &key, ibuf);
426 }
427
428 /*********************** common functions *************************/
429
430 /* only image block itself */
431 static MovieClip *movieclip_alloc(const char *name)
432 {
433         MovieClip *clip;
434
435         clip = BKE_libblock_alloc(&G.main->movieclip, ID_MC, name);
436
437         clip->aspx = clip->aspy = 1.0f;
438
439         BKE_tracking_init_settings(&clip->tracking);
440
441         clip->proxy.build_size_flag = IMB_PROXY_25;
442         clip->proxy.build_tc_flag = IMB_TC_RECORD_RUN |
443                                     IMB_TC_FREE_RUN |
444                                     IMB_TC_INTERPOLATED_REC_DATE_FREE_RUN |
445                                     IMB_TC_RECORD_RUN_NO_GAPS;
446         clip->proxy.quality = 90;
447
448         clip->start_frame = 1;
449         clip->frame_offset = 0;
450
451         return clip;
452 }
453
454 /* checks if image was already loaded, then returns same image
455  * otherwise creates new.
456  * does not load ibuf itself
457  * pass on optional frame for #name images */
458 MovieClip *BKE_movieclip_file_add(const char *name)
459 {
460         MovieClip *clip;
461         MovieClipUser user = {0};
462         int file, len, width, height;
463         const char *libname;
464         char str[FILE_MAX], strtest[FILE_MAX];
465
466         BLI_strncpy(str, name, sizeof(str));
467         BLI_path_abs(str, G.main->name);
468
469         /* exists? */
470         file = BLI_open(str, O_BINARY | O_RDONLY, 0);
471         if (file == -1)
472                 return NULL;
473         close(file);
474
475         /* ** first search an identical clip ** */
476         for (clip = G.main->movieclip.first; clip; clip = clip->id.next) {
477                 BLI_strncpy(strtest, clip->name, sizeof(clip->name));
478                 BLI_path_abs(strtest, G.main->name);
479
480                 if (strcmp(strtest, str) == 0) {
481                         BLI_strncpy(clip->name, name, sizeof(clip->name));  /* for stringcode */
482                         clip->id.us++;  /* officially should not, it doesn't link here! */
483
484                         return clip;
485                 }
486         }
487
488         /* ** add new movieclip ** */
489
490         /* create a short library name */
491         len = strlen(name);
492
493         while (len > 0 && name[len - 1] != '/' && name[len - 1] != '\\')
494                 len--;
495         libname = name + len;
496
497         clip = movieclip_alloc(libname);
498         BLI_strncpy(clip->name, name, sizeof(clip->name));
499
500         if (BLI_testextensie_array(name, imb_ext_movie))
501                 clip->source = MCLIP_SRC_MOVIE;
502         else
503                 clip->source = MCLIP_SRC_SEQUENCE;
504
505         user.framenr = 1;
506         BKE_movieclip_get_size(clip, &user, &width, &height);
507         if (width && height) {
508                 clip->tracking.camera.principal[0] = ((float)width) / 2.0f;
509                 clip->tracking.camera.principal[1] = ((float)height) / 2.0f;
510
511                 clip->tracking.camera.focal = 24.0f * width / clip->tracking.camera.sensor_width;
512         }
513
514         movieclip_calc_length(clip);
515
516         return clip;
517 }
518
519 static void real_ibuf_size(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf, int *width, int *height)
520 {
521         *width = ibuf->x;
522         *height = ibuf->y;
523
524         if (clip->flag & MCLIP_USE_PROXY) {
525                 switch (user->render_size) {
526                         case MCLIP_PROXY_RENDER_SIZE_25:
527                                 (*width) *= 4;
528                                 (*height) *= 4;
529                                 break;
530
531                         case MCLIP_PROXY_RENDER_SIZE_50:
532                                 (*width) *= 2.0f;
533                                 (*height) *= 2.0f;
534                                 break;
535
536                         case MCLIP_PROXY_RENDER_SIZE_75:
537                                 *width = ((float)*width) * 4.0f / 3.0f;
538                                 *height = ((float)*height) * 4.0f / 3.0f;
539                                 break;
540                 }
541         }
542 }
543
544 static ImBuf *get_undistorted_ibuf(MovieClip *clip, struct MovieDistortion *distortion, ImBuf *ibuf)
545 {
546         ImBuf *undistibuf;
547
548         if (distortion)
549                 undistibuf = BKE_tracking_distortion_exec(distortion, &clip->tracking, ibuf, ibuf->x, ibuf->y, 0.0f, 1);
550         else
551                 undistibuf = BKE_tracking_undistort(&clip->tracking, ibuf, ibuf->x, ibuf->y, 0.0f);
552
553         if (undistibuf->userflags & IB_RECT_INVALID) {
554                 ibuf->userflags &= ~IB_RECT_INVALID;
555                 IMB_rect_from_float(undistibuf);
556         }
557
558         IMB_scaleImBuf(undistibuf, ibuf->x, ibuf->y);
559
560         return undistibuf;
561 }
562
563 static int need_undistortion_postprocess(MovieClipUser *user, int flag)
564 {
565         int result = 0;
566
567         /* only full undistorted render can be used as on-fly undistorting image */
568         if (flag & MCLIP_USE_PROXY) {
569                 result |= (user->render_size == MCLIP_PROXY_RENDER_SIZE_FULL) &&
570                           (user->render_flag & MCLIP_PROXY_RENDER_UNDISTORT) != 0;
571         }
572
573         return result;
574 }
575
576 static int need_postprocessed_frame(MovieClipUser *user, int flag, int postprocess_flag)
577 {
578         int result = postprocess_flag;
579
580         result |= need_undistortion_postprocess(user, flag);
581
582         return result;
583 }
584
585 static int check_undistortion_cache_flags(MovieClip *clip)
586 {
587         MovieClipCache *cache = clip->cache;
588         MovieTrackingCamera *camera = &clip->tracking.camera;
589
590         /* check for distortion model changes */
591         if (!equals_v2v2(camera->principal, cache->postprocessed.principal))
592                 return FALSE;
593
594         if (!equals_v3v3(&camera->k1, &cache->postprocessed.k1))
595                 return FALSE;
596
597         return TRUE;
598 }
599
600 static ImBuf *get_postprocessed_cached_frame(MovieClip *clip, MovieClipUser *user, int flag, int postprocess_flag)
601 {
602         MovieClipCache *cache = clip->cache;
603         int framenr = user->framenr;
604         short proxy = IMB_PROXY_NONE;
605         int render_flag = 0;
606
607         if (flag & MCLIP_USE_PROXY) {
608                 proxy = rendersize_to_proxy(user, flag);
609                 render_flag = user->render_flag;
610         }
611
612         /* no cache or no cached postprocessed image */
613         if (!clip->cache || !clip->cache->postprocessed.ibuf)
614                 return NULL;
615
616         /* postprocessing happened for other frame */
617         if (cache->postprocessed.framenr != framenr)
618                 return NULL;
619
620         /* cached ibuf used different proxy settings */
621         if (cache->postprocessed.render_flag != render_flag || cache->postprocessed.proxy != proxy)
622                 return NULL;
623
624         if (cache->postprocessed.flag != postprocess_flag)
625                 return NULL;
626
627         if (need_undistortion_postprocess(user, flag)) {
628                 if (!check_undistortion_cache_flags(clip))
629                         return NULL;
630         }
631         else if (cache->postprocessed.undistortion_used)
632                 return NULL;
633
634         IMB_refImBuf(cache->postprocessed.ibuf);
635
636         return cache->postprocessed.ibuf;
637 }
638
639 static ImBuf *put_postprocessed_frame_to_cache(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf,
640                                                int flag, int postprocess_flag)
641 {
642         MovieClipCache *cache = clip->cache;
643         MovieTrackingCamera *camera = &clip->tracking.camera;
644         ImBuf *postproc_ibuf = NULL;
645
646         if (cache->postprocessed.ibuf)
647                 IMB_freeImBuf(cache->postprocessed.ibuf);
648
649         cache->postprocessed.framenr = user->framenr;
650         cache->postprocessed.flag = postprocess_flag;
651
652         if (flag & MCLIP_USE_PROXY) {
653                 cache->postprocessed.proxy = rendersize_to_proxy(user, flag);
654                 cache->postprocessed.render_flag = user->render_flag;
655         }
656         else {
657                 cache->postprocessed.proxy = IMB_PROXY_NONE;
658                 cache->postprocessed.render_flag = 0;
659         }
660
661         if (need_undistortion_postprocess(user, flag)) {
662                 copy_v2_v2(cache->postprocessed.principal, camera->principal);
663                 copy_v3_v3(&cache->postprocessed.k1, &camera->k1);
664                 cache->postprocessed.undistortion_used = TRUE;
665                 postproc_ibuf = get_undistorted_ibuf(clip, NULL, ibuf);
666         }
667         else {
668                 cache->postprocessed.undistortion_used = FALSE;
669         }
670
671         if (postprocess_flag) {
672                 int disable_red   = postprocess_flag & MOVIECLIP_DISABLE_RED,
673                     disable_green = postprocess_flag & MOVIECLIP_DISABLE_GREEN,
674                     disable_blue  = postprocess_flag & MOVIECLIP_DISABLE_BLUE,
675                     grayscale     = postprocess_flag & MOVIECLIP_PREVIEW_GRAYSCALE;
676
677                 if (!postproc_ibuf)
678                         postproc_ibuf = IMB_dupImBuf(ibuf);
679
680                 if (disable_red || disable_green || disable_blue || grayscale)
681                         BKE_tracking_disable_imbuf_channels(postproc_ibuf, disable_red, disable_green, disable_blue, 1);
682         }
683
684         IMB_refImBuf(postproc_ibuf);
685
686         cache->postprocessed.ibuf = postproc_ibuf;
687
688         if (cache->stabilized.ibuf) {
689                 /* force stable buffer be re-calculated */
690                 IMB_freeImBuf(cache->stabilized.ibuf);
691                 cache->stabilized.ibuf = NULL;
692         }
693
694         return postproc_ibuf;
695 }
696
697 static ImBuf *movieclip_get_postprocessed_ibuf(MovieClip *clip, MovieClipUser *user, int flag,
698                                                int postprocess_flag, int cache_flag)
699 {
700         ImBuf *ibuf = NULL;
701         int framenr = user->framenr, need_postprocess = FALSE;
702
703         /* cache isn't threadsafe itself and also loading of movies
704          * can't happen from concurent threads that's why we use lock here */
705         BLI_lock_thread(LOCK_MOVIECLIP);
706
707         /* try to obtain cached postprocessed frame first */
708         if (need_postprocessed_frame(user, flag, postprocess_flag)) {
709                 ibuf = get_postprocessed_cached_frame(clip, user, flag, postprocess_flag);
710
711                 if (!ibuf)
712                         need_postprocess = TRUE;
713         }
714
715         if (!ibuf)
716                 ibuf = get_imbuf_cache(clip, user, flag);
717
718         if (!ibuf) {
719                 int use_sequence = FALSE;
720
721                 /* undistorted proxies for movies should be read as image sequence */
722                 use_sequence = (user->render_flag & MCLIP_PROXY_RENDER_UNDISTORT) &&
723                                (user->render_size != MCLIP_PROXY_RENDER_SIZE_FULL);
724
725                 if (clip->source == MCLIP_SRC_SEQUENCE || use_sequence) {
726                         ibuf = movieclip_load_sequence_file(clip, user, framenr, flag);
727                 }
728                 else {
729                         ibuf = movieclip_load_movie_file(clip, user, framenr, flag);
730                 }
731
732                 if (ibuf && (cache_flag & MOVIECLIP_CACHE_SKIP) == 0)
733                         put_imbuf_cache(clip, user, ibuf, flag);
734         }
735
736         if (ibuf) {
737                 clip->lastframe = framenr;
738                 real_ibuf_size(clip, user, ibuf, &clip->lastsize[0], &clip->lastsize[1]);
739
740                 /* postprocess frame and put to cache */
741                 if (need_postprocess) {
742                         ImBuf *tmpibuf = ibuf;
743                         ibuf = put_postprocessed_frame_to_cache(clip, user, tmpibuf, flag, postprocess_flag);
744                         IMB_freeImBuf(tmpibuf);
745                 }
746         }
747
748         BLI_unlock_thread(LOCK_MOVIECLIP);
749
750         return ibuf;
751 }
752
753 ImBuf *BKE_movieclip_get_ibuf(MovieClip *clip, MovieClipUser *user)
754 {
755         return BKE_movieclip_get_ibuf_flag(clip, user, clip->flag, 0);
756 }
757
758 ImBuf *BKE_movieclip_get_ibuf_flag(MovieClip *clip, MovieClipUser *user, int flag, int cache_flag)
759 {
760         return movieclip_get_postprocessed_ibuf(clip, user, flag, 0, cache_flag);
761 }
762
763 ImBuf *BKE_movieclip_get_postprocessed_ibuf(MovieClip *clip, MovieClipUser *user, int postprocess_flag)
764 {
765         return movieclip_get_postprocessed_ibuf(clip, user, clip->flag, postprocess_flag, 0);
766 }
767
768 static ImBuf *get_stable_cached_frame(MovieClip *clip, MovieClipUser *user, int framenr, int postprocess_flag)
769 {
770         MovieClipCache *cache = clip->cache;
771         MovieTracking *tracking = &clip->tracking;
772         ImBuf *stableibuf;
773         float tloc[2], tscale, tangle;
774         short proxy = IMB_PROXY_NONE;
775         int render_flag = 0;
776
777         if (clip->flag & MCLIP_USE_PROXY) {
778                 proxy = rendersize_to_proxy(user, clip->flag);
779                 render_flag = user->render_flag;
780         }
781
782         /* there's no cached frame or it was calculated for another frame */
783         if (!cache->stabilized.ibuf || cache->stabilized.framenr != framenr)
784                 return NULL;
785
786         /* cached ibuf used different proxy settings */
787         if (cache->stabilized.render_flag != render_flag || cache->stabilized.proxy != proxy)
788                 return NULL;
789
790         if (cache->stabilized.postprocess_flag != postprocess_flag)
791                 return NULL;
792
793         /* stabilization also depends on pixel aspect ratio */
794         if (cache->stabilized.aspect != tracking->camera.pixel_aspect)
795                 return NULL;
796
797         if (cache->stabilized.filter != tracking->stabilization.filter)
798                 return NULL;
799
800         stableibuf = cache->stabilized.ibuf;
801
802         BKE_tracking_stabilization_data(&clip->tracking, framenr, stableibuf->x, stableibuf->y, tloc, &tscale, &tangle);
803
804         /* check for stabilization parameters */
805         if (tscale != cache->stabilized.scale ||
806             tangle != cache->stabilized.angle ||
807             !equals_v2v2(tloc, cache->stabilized.loc))
808         {
809                 return NULL;
810         }
811
812         IMB_refImBuf(stableibuf);
813
814         return stableibuf;
815 }
816
817 static ImBuf *put_stabilized_frame_to_cache(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf,
818                                             int framenr, int postprocess_flag)
819 {
820         MovieClipCache *cache = clip->cache;
821         MovieTracking *tracking = &clip->tracking;
822         ImBuf *stableibuf;
823         float tloc[2], tscale, tangle;
824
825         if (cache->stabilized.ibuf)
826                 IMB_freeImBuf(cache->stabilized.ibuf);
827
828         stableibuf = BKE_tracking_stabilize(&clip->tracking, framenr, ibuf, tloc, &tscale, &tangle);
829
830         cache->stabilized.ibuf = stableibuf;
831
832         copy_v2_v2(cache->stabilized.loc, tloc);
833
834         cache->stabilized.scale = tscale;
835         cache->stabilized.angle = tangle;
836         cache->stabilized.framenr = framenr;
837         cache->stabilized.aspect = tracking->camera.pixel_aspect;
838         cache->stabilized.filter = tracking->stabilization.filter;
839
840         if (clip->flag & MCLIP_USE_PROXY) {
841                 cache->stabilized.proxy = rendersize_to_proxy(user, clip->flag);
842                 cache->stabilized.render_flag = user->render_flag;
843         }
844         else {
845                 cache->stabilized.proxy = IMB_PROXY_NONE;
846                 cache->stabilized.render_flag = 0;
847         }
848
849         cache->stabilized.postprocess_flag = postprocess_flag;
850
851         IMB_refImBuf(stableibuf);
852
853         return stableibuf;
854 }
855
856 ImBuf *BKE_movieclip_get_stable_ibuf(MovieClip *clip, MovieClipUser *user, float loc[2], float *scale, float *angle,
857                                      int postprocess_flag)
858 {
859         ImBuf *ibuf, *stableibuf = NULL;
860         int framenr = user->framenr;
861
862         ibuf = BKE_movieclip_get_postprocessed_ibuf(clip, user, postprocess_flag);
863
864         if (!ibuf)
865                 return NULL;
866
867         if (clip->tracking.stabilization.flag & TRACKING_2D_STABILIZATION) {
868                 MovieClipCache *cache = clip->cache;
869
870                 stableibuf = get_stable_cached_frame(clip, user, framenr, postprocess_flag);
871
872                 if (!stableibuf)
873                         stableibuf = put_stabilized_frame_to_cache(clip, user, ibuf, framenr, postprocess_flag);
874
875                 if (loc)
876                         copy_v2_v2(loc, cache->stabilized.loc);
877
878                 if (scale)
879                         *scale = cache->stabilized.scale;
880
881                 if (angle)
882                         *angle = cache->stabilized.angle;
883         }
884         else {
885                 if (loc)
886                         zero_v2(loc);
887
888                 if (scale)
889                         *scale = 1.0f;
890
891                 if (angle)
892                         *angle = 0.0f;
893
894                 stableibuf = ibuf;
895         }
896
897         if (stableibuf != ibuf) {
898                 IMB_freeImBuf(ibuf);
899                 ibuf = stableibuf;
900         }
901
902         return ibuf;
903
904 }
905
906 int BKE_movieclip_has_frame(MovieClip *clip, MovieClipUser *user)
907 {
908         ImBuf *ibuf = BKE_movieclip_get_ibuf(clip, user);
909
910         if (ibuf) {
911                 IMB_freeImBuf(ibuf);
912                 return TRUE;
913         }
914
915         return FALSE;
916 }
917
918 void BKE_movieclip_get_size(MovieClip *clip, MovieClipUser *user, int *width, int *height)
919 {
920 #if 0
921         /* originally was needed to support image sequences with different image dimensions,
922          * which might be useful for such things as reconstruction of unordered image sequence,
923          * or painting/rotoscoping of non-equal-sized images, but this ended up in unneeded
924          * cache lookups and even unwanted non-proxied files loading when doing mask parenting,
925          * so let's disable this for now and assume image sequence consists of images with
926          * equal sizes (sergey)
927          */
928         if (user->framenr == clip->lastframe) {
929 #endif
930         if (clip->lastsize[0] != 0 && clip->lastsize[1] != 0) {
931                 *width = clip->lastsize[0];
932                 *height = clip->lastsize[1];
933         }
934         else {
935                 ImBuf *ibuf = BKE_movieclip_get_ibuf(clip, user);
936
937                 if (ibuf && ibuf->x && ibuf->y) {
938                         real_ibuf_size(clip, user, ibuf, width, height);
939                 }
940                 else {
941                         *width = clip->lastsize[0];
942                         *height = clip->lastsize[1];
943                 }
944
945                 if (ibuf)
946                         IMB_freeImBuf(ibuf);
947         }
948 }
949
950 int BKE_movieclip_get_duration(MovieClip *clip)
951 {
952         if (!clip->len) {
953                 movieclip_calc_length(clip);
954         }
955
956         return clip->len;
957 }
958
959 void BKE_movieclip_aspect(MovieClip *clip, float *aspx, float *aspy)
960 {
961         *aspx = *aspy = 1.0;
962
963         /* x is always 1 */
964         *aspy = clip->aspy / clip->aspx / clip->tracking.camera.pixel_aspect;
965 }
966
967 /* get segments of cached frames. useful for debugging cache policies */
968 void BKE_movieclip_get_cache_segments(MovieClip *clip, MovieClipUser *user, int *totseg_r, int **points_r)
969 {
970         *totseg_r = 0;
971         *points_r = NULL;
972
973         if (clip->cache) {
974                 int proxy = rendersize_to_proxy(user, clip->flag);
975
976                 IMB_moviecache_get_cache_segments(clip->cache->moviecache, proxy, user->render_flag, totseg_r, points_r);
977         }
978 }
979
980 void BKE_movieclip_user_set_frame(MovieClipUser *iuser, int framenr)
981 {
982         /* TODO: clamp framenr here? */
983
984         iuser->framenr = framenr;
985 }
986
987 static void free_buffers(MovieClip *clip)
988 {
989         if (clip->cache) {
990                 IMB_moviecache_free(clip->cache->moviecache);
991
992                 if (clip->cache->postprocessed.ibuf)
993                         IMB_freeImBuf(clip->cache->postprocessed.ibuf);
994
995                 if (clip->cache->stabilized.ibuf)
996                         IMB_freeImBuf(clip->cache->stabilized.ibuf);
997
998                 MEM_freeN(clip->cache);
999                 clip->cache = NULL;
1000         }
1001
1002         if (clip->anim) {
1003                 IMB_free_anim(clip->anim);
1004                 clip->anim = NULL;
1005         }
1006
1007         BKE_free_animdata((ID *) clip);
1008 }
1009
1010 void BKE_movieclip_reload(MovieClip *clip)
1011 {
1012         /* clear cache */
1013         free_buffers(clip);
1014
1015         clip->tracking.stabilization.ok = FALSE;
1016
1017         /* update clip source */
1018         if (BLI_testextensie_array(clip->name, imb_ext_movie))
1019                 clip->source = MCLIP_SRC_MOVIE;
1020         else
1021                 clip->source = MCLIP_SRC_SEQUENCE;
1022
1023         movieclip_calc_length(clip);
1024 }
1025
1026 void BKE_movieclip_update_scopes(MovieClip *clip, MovieClipUser *user, MovieClipScopes *scopes)
1027 {
1028         if (scopes->ok)
1029                 return;
1030
1031         if (scopes->track_preview) {
1032                 IMB_freeImBuf(scopes->track_preview);
1033                 scopes->track_preview = NULL;
1034         }
1035
1036         if (scopes->track_search) {
1037                 IMB_freeImBuf(scopes->track_search);
1038                 scopes->track_search = NULL;
1039         }
1040
1041         scopes->marker = NULL;
1042         scopes->track = NULL;
1043         scopes->track_locked = TRUE;
1044
1045         if (clip) {
1046                 MovieTrackingTrack *act_track = BKE_tracking_active_track(&clip->tracking);
1047
1048                 if (act_track) {
1049                         MovieTrackingTrack *track = act_track;
1050                         int framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, user->framenr);
1051                         MovieTrackingMarker *marker = BKE_tracking_get_marker(track, framenr);
1052
1053                         if (marker->flag & MARKER_DISABLED) {
1054                                 scopes->track_disabled = TRUE;
1055                         }
1056                         else {
1057                                 ImBuf *ibuf = BKE_movieclip_get_ibuf(clip, user);
1058
1059                                 scopes->track_disabled = FALSE;
1060                                 scopes->marker = marker;
1061                                 scopes->track = track;
1062
1063                                 if (ibuf && (ibuf->rect || ibuf->rect_float)) {
1064                                         ImBuf *search_ibuf;
1065                                         MovieTrackingMarker undist_marker = *marker;
1066
1067                                         if (user->render_flag & MCLIP_PROXY_RENDER_UNDISTORT) {
1068                                                 int width, height;
1069                                                 float aspy = 1.0f / clip->tracking.camera.pixel_aspect;
1070
1071                                                 BKE_movieclip_get_size(clip, user, &width, &height);
1072
1073                                                 undist_marker.pos[0] *= width;
1074                                                 undist_marker.pos[1] *= height * aspy;
1075
1076                                                 BKE_tracking_invert_intrinsics(&clip->tracking, undist_marker.pos, undist_marker.pos);
1077
1078                                                 undist_marker.pos[0] /= width;
1079                                                 undist_marker.pos[1] /= height * aspy;
1080                                         }
1081
1082                                         search_ibuf = BKE_tracking_get_search_imbuf(ibuf, track, &undist_marker, TRUE, TRUE);
1083
1084                                         if (!search_ibuf->rect_float) {
1085                                                 /* sampling happens in float buffer */
1086                                                 IMB_float_from_rect(search_ibuf);
1087                                         }
1088
1089                                         scopes->undist_marker = undist_marker;
1090                                         scopes->track_search = search_ibuf;
1091
1092                                         scopes->frame_width = ibuf->x;
1093                                         scopes->frame_height = ibuf->y;
1094
1095                                         scopes->use_track_mask = track->flag & TRACK_PREVIEW_ALPHA;
1096                                 }
1097
1098                                 IMB_freeImBuf(ibuf);
1099                         }
1100
1101                         if ((track->flag & TRACK_LOCKED) == 0) {
1102                                 float pat_min[2], pat_max[2];
1103
1104                                 scopes->track_locked = FALSE;
1105
1106                                 /* XXX: would work fine with non-transformed patterns, but would likely fail
1107                                  *      with transformed patterns, but that would be easier to debug when
1108                                  *      we'll have real pattern sampling (at least to test) */
1109                                 BKE_tracking_marker_pattern_minmax(marker, pat_min, pat_max);
1110
1111                                 scopes->slide_scale[0] = pat_max[0] - pat_min[0];
1112                                 scopes->slide_scale[1] = pat_max[1] - pat_min[1];
1113                         }
1114                 }
1115         }
1116
1117         scopes->framenr = user->framenr;
1118         scopes->ok = TRUE;
1119 }
1120
1121 static void movieclip_build_proxy_ibuf(MovieClip *clip, ImBuf *ibuf, int cfra, int proxy_render_size, int undistorted)
1122 {
1123         char name[FILE_MAX];
1124         int quality, rectx, recty;
1125         int size = rendersize_to_number(proxy_render_size);
1126         ImBuf *scaleibuf;
1127
1128         get_proxy_fname(clip, proxy_render_size, undistorted, cfra, name);
1129
1130         rectx = ibuf->x * size / 100.0f;
1131         recty = ibuf->y * size / 100.0f;
1132
1133         scaleibuf = IMB_dupImBuf(ibuf);
1134
1135         IMB_scaleImBuf(scaleibuf, (short)rectx, (short)recty);
1136
1137         quality = clip->proxy.quality;
1138         scaleibuf->ftype = JPG | quality;
1139
1140         /* unsupported feature only confuses other s/w */
1141         if (scaleibuf->planes == 32)
1142                 scaleibuf->planes = 24;
1143
1144         BLI_lock_thread(LOCK_MOVIECLIP);
1145
1146         BLI_make_existing_file(name);
1147         if (IMB_saveiff(scaleibuf, name, IB_rect) == 0)
1148                 perror(name);
1149
1150         BLI_unlock_thread(LOCK_MOVIECLIP);
1151
1152         IMB_freeImBuf(scaleibuf);
1153 }
1154
1155 void BKE_movieclip_build_proxy_frame(MovieClip *clip, int clip_flag, struct MovieDistortion *distortion,
1156                                      int cfra, int *build_sizes, int build_count, int undistorted)
1157 {
1158         ImBuf *ibuf;
1159         MovieClipUser user;
1160
1161         user.framenr = cfra;
1162         user.render_flag = 0;
1163         user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL;
1164
1165         ibuf = BKE_movieclip_get_ibuf_flag(clip, &user, clip_flag, MOVIECLIP_CACHE_SKIP);
1166
1167         if (ibuf) {
1168                 ImBuf *tmpibuf = ibuf;
1169                 int i;
1170
1171                 if (undistorted)
1172                         tmpibuf = get_undistorted_ibuf(clip, distortion, ibuf);
1173
1174                 for (i = 0; i < build_count; i++)
1175                         movieclip_build_proxy_ibuf(clip, tmpibuf, cfra, build_sizes[i], undistorted);
1176
1177                 IMB_freeImBuf(ibuf);
1178
1179                 if (tmpibuf != ibuf)
1180                         IMB_freeImBuf(tmpibuf);
1181         }
1182 }
1183
1184 void BKE_movieclip_free(MovieClip *clip)
1185 {
1186         free_buffers(clip);
1187
1188         BKE_tracking_free(&clip->tracking);
1189 }
1190
1191 void BKE_movieclip_unlink(Main *bmain, MovieClip *clip)
1192 {
1193         bScreen *scr;
1194         ScrArea *area;
1195         SpaceLink *sl;
1196         Scene *sce;
1197         Object *ob;
1198
1199         for (scr = bmain->screen.first; scr; scr = scr->id.next) {
1200                 for (area = scr->areabase.first; area; area = area->next) {
1201                         for (sl = area->spacedata.first; sl; sl = sl->next) {
1202                                 if (sl->spacetype == SPACE_CLIP) {
1203                                         SpaceClip *sc = (SpaceClip *) sl;
1204
1205                                         if (sc->clip == clip)
1206                                                 sc->clip = NULL;
1207                                 }
1208                                 else if (sl->spacetype == SPACE_VIEW3D) {
1209                                         View3D *v3d = (View3D *) sl;
1210                                         BGpic *bgpic;
1211
1212                                         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
1213                                                 if (bgpic->clip == clip)
1214                                                         bgpic->clip = NULL;
1215                                         }
1216                                 }
1217                         }
1218                 }
1219         }
1220
1221         for (sce = bmain->scene.first; sce; sce = sce->id.next) {
1222                 if (sce->clip == clip)
1223                         sce->clip = NULL;
1224         }
1225
1226         for (ob = bmain->object.first; ob; ob = ob->id.next) {
1227                 bConstraint *con;
1228
1229                 for (con = ob->constraints.first; con; con = con->next) {
1230                         bConstraintTypeInfo *cti = constraint_get_typeinfo(con);
1231
1232                         if (cti->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
1233                                 bFollowTrackConstraint *data = (bFollowTrackConstraint *) con->data;
1234
1235                                 if (data->clip == clip)
1236                                         data->clip = NULL;
1237                         }
1238                         else if (cti->type == CONSTRAINT_TYPE_CAMERASOLVER) {
1239                                 bCameraSolverConstraint *data = (bCameraSolverConstraint *) con->data;
1240
1241                                 if (data->clip == clip)
1242                                         data->clip = NULL;
1243                         }
1244                         else if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
1245                                 bObjectSolverConstraint *data = (bObjectSolverConstraint *) con->data;
1246
1247                                 if (data->clip == clip)
1248                                         data->clip = NULL;
1249                         }
1250                 }
1251         }
1252
1253         clip->id.us = 0;
1254 }
1255
1256 int BKE_movieclip_remap_scene_to_clip_frame(MovieClip *clip, int framenr)
1257 {
1258         return framenr - clip->start_frame + 1;
1259 }
1260
1261 int BKE_movieclip_remap_clip_to_scene_frame(MovieClip *clip, int framenr)
1262 {
1263         return framenr + clip->start_frame - 1;
1264 }