Fixed issues updating texture buffer used for clip editor frame display
[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 *reference_ibuf;
326
327                 ImBuf *ibuf;
328                 int framenr;
329                 int postprocess_flag;
330
331                 float loc[2], scale, angle, aspect;
332                 int proxy, filter;
333                 short render_flag;
334         } stabilized;
335 } MovieClipCache;
336
337 typedef struct MovieClipImBufCacheKey {
338         int framenr;
339         int proxy;
340         short render_flag;
341 } MovieClipImBufCacheKey;
342
343 static void moviecache_keydata(void *userkey, int *framenr, int *proxy, int *render_flags)
344 {
345         MovieClipImBufCacheKey *key = (MovieClipImBufCacheKey *)userkey;
346
347         *framenr = key->framenr;
348         *proxy = key->proxy;
349         *render_flags = key->render_flag;
350 }
351
352 static unsigned int moviecache_hashhash(const void *keyv)
353 {
354         MovieClipImBufCacheKey *key = (MovieClipImBufCacheKey *)keyv;
355         int rval = key->framenr;
356
357         return rval;
358 }
359
360 static int moviecache_hashcmp(const void *av, const void *bv)
361 {
362         const MovieClipImBufCacheKey *a = (MovieClipImBufCacheKey *)av;
363         const MovieClipImBufCacheKey *b = (MovieClipImBufCacheKey *)bv;
364
365         if (a->framenr < b->framenr)
366                 return -1;
367         else if (a->framenr > b->framenr)
368                 return 1;
369
370         if (a->proxy < b->proxy)
371                 return -1;
372         else if (a->proxy > b->proxy)
373                 return 1;
374
375         if (a->render_flag < b->render_flag)
376                 return -1;
377         else if (a->render_flag > b->render_flag)
378                 return 1;
379
380         return 0;
381 }
382
383 static ImBuf *get_imbuf_cache(MovieClip *clip, MovieClipUser *user, int flag)
384 {
385         if (clip->cache) {
386                 MovieClipImBufCacheKey key;
387
388                 key.framenr = user->framenr;
389
390                 if (flag & MCLIP_USE_PROXY) {
391                         key.proxy = rendersize_to_proxy(user, flag);
392                         key.render_flag = user->render_flag;
393                 }
394                 else {
395                         key.proxy = IMB_PROXY_NONE;
396                         key.render_flag = 0;
397                 }
398
399                 return IMB_moviecache_get(clip->cache->moviecache, &key);
400         }
401
402         return NULL;
403 }
404
405 static void put_imbuf_cache(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf, int flag)
406 {
407         MovieClipImBufCacheKey key;
408
409         if (!clip->cache) {
410                 clip->cache = MEM_callocN(sizeof(MovieClipCache), "movieClipCache");
411
412                 clip->cache->moviecache = IMB_moviecache_create(sizeof(MovieClipImBufCacheKey), moviecache_hashhash,
413                                                                 moviecache_hashcmp, moviecache_keydata);
414         }
415
416         key.framenr = user->framenr;
417
418         if (flag & MCLIP_USE_PROXY) {
419                 key.proxy = rendersize_to_proxy(user, flag);
420                 key.render_flag = user->render_flag;
421         }
422         else {
423                 key.proxy = IMB_PROXY_NONE;
424                 key.render_flag = 0;
425         }
426
427         IMB_moviecache_put(clip->cache->moviecache, &key, ibuf);
428 }
429
430 /*********************** common functions *************************/
431
432 /* only image block itself */
433 static MovieClip *movieclip_alloc(const char *name)
434 {
435         MovieClip *clip;
436
437         clip = BKE_libblock_alloc(&G.main->movieclip, ID_MC, name);
438
439         clip->aspx = clip->aspy = 1.0f;
440
441         BKE_tracking_settings_init(&clip->tracking);
442
443         clip->proxy.build_size_flag = IMB_PROXY_25;
444         clip->proxy.build_tc_flag = IMB_TC_RECORD_RUN |
445                                     IMB_TC_FREE_RUN |
446                                     IMB_TC_INTERPOLATED_REC_DATE_FREE_RUN |
447                                     IMB_TC_RECORD_RUN_NO_GAPS;
448         clip->proxy.quality = 90;
449
450         clip->start_frame = 1;
451         clip->frame_offset = 0;
452
453         return clip;
454 }
455
456 static void movieclip_load_get_szie(MovieClip *clip)
457 {
458         int width, height;
459         MovieClipUser user = {0};
460
461         user.framenr = 1;
462         BKE_movieclip_get_size(clip, &user, &width, &height);
463
464         if (width && height) {
465                 clip->tracking.camera.principal[0] = ((float)width) / 2.0f;
466                 clip->tracking.camera.principal[1] = ((float)height) / 2.0f;
467
468         }
469 }
470
471 /* checks if image was already loaded, then returns same image
472  * otherwise creates new.
473  * does not load ibuf itself
474  * pass on optional frame for #name images */
475 MovieClip *BKE_movieclip_file_add(const char *name)
476 {
477         MovieClip *clip;
478         int file, len;
479         const char *libname;
480         char str[FILE_MAX], strtest[FILE_MAX];
481
482         BLI_strncpy(str, name, sizeof(str));
483         BLI_path_abs(str, G.main->name);
484
485         /* exists? */
486         file = BLI_open(str, O_BINARY | O_RDONLY, 0);
487         if (file == -1)
488                 return NULL;
489         close(file);
490
491         /* ** first search an identical clip ** */
492         for (clip = G.main->movieclip.first; clip; clip = clip->id.next) {
493                 BLI_strncpy(strtest, clip->name, sizeof(clip->name));
494                 BLI_path_abs(strtest, G.main->name);
495
496                 if (strcmp(strtest, str) == 0) {
497                         BLI_strncpy(clip->name, name, sizeof(clip->name));  /* for stringcode */
498                         clip->id.us++;  /* officially should not, it doesn't link here! */
499
500                         return clip;
501                 }
502         }
503
504         /* ** add new movieclip ** */
505
506         /* create a short library name */
507         len = strlen(name);
508
509         while (len > 0 && name[len - 1] != '/' && name[len - 1] != '\\')
510                 len--;
511         libname = name + len;
512
513         clip = movieclip_alloc(libname);
514         BLI_strncpy(clip->name, name, sizeof(clip->name));
515
516         if (BLI_testextensie_array(name, imb_ext_movie))
517                 clip->source = MCLIP_SRC_MOVIE;
518         else
519                 clip->source = MCLIP_SRC_SEQUENCE;
520
521         movieclip_load_get_szie(clip);
522         if (clip->lastsize[0]) {
523                 int width = clip->lastsize[0];
524
525                 clip->tracking.camera.focal = 24.0f * width / clip->tracking.camera.sensor_width;
526         }
527
528         movieclip_calc_length(clip);
529
530         return clip;
531 }
532
533 static void real_ibuf_size(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf, int *width, int *height)
534 {
535         *width = ibuf->x;
536         *height = ibuf->y;
537
538         if (clip->flag & MCLIP_USE_PROXY) {
539                 switch (user->render_size) {
540                         case MCLIP_PROXY_RENDER_SIZE_25:
541                                 (*width) *= 4;
542                                 (*height) *= 4;
543                                 break;
544
545                         case MCLIP_PROXY_RENDER_SIZE_50:
546                                 (*width) *= 2.0f;
547                                 (*height) *= 2.0f;
548                                 break;
549
550                         case MCLIP_PROXY_RENDER_SIZE_75:
551                                 *width = ((float)*width) * 4.0f / 3.0f;
552                                 *height = ((float)*height) * 4.0f / 3.0f;
553                                 break;
554                 }
555         }
556 }
557
558 static ImBuf *get_undistorted_ibuf(MovieClip *clip, struct MovieDistortion *distortion, ImBuf *ibuf)
559 {
560         ImBuf *undistibuf;
561
562         if (distortion)
563                 undistibuf = BKE_tracking_distortion_exec(distortion, &clip->tracking, ibuf, ibuf->x, ibuf->y, 0.0f, 1);
564         else
565                 undistibuf = BKE_tracking_undistort_frame(&clip->tracking, ibuf, ibuf->x, ibuf->y, 0.0f);
566
567         if (undistibuf->userflags & IB_RECT_INVALID) {
568                 ibuf->userflags &= ~IB_RECT_INVALID;
569                 IMB_rect_from_float(undistibuf);
570         }
571
572         IMB_scaleImBuf(undistibuf, ibuf->x, ibuf->y);
573
574         return undistibuf;
575 }
576
577 static int need_undistortion_postprocess(MovieClipUser *user, int flag)
578 {
579         int result = 0;
580
581         /* only full undistorted render can be used as on-fly undistorting image */
582         if (flag & MCLIP_USE_PROXY) {
583                 result |= (user->render_size == MCLIP_PROXY_RENDER_SIZE_FULL) &&
584                           (user->render_flag & MCLIP_PROXY_RENDER_UNDISTORT) != 0;
585         }
586
587         return result;
588 }
589
590 static int need_postprocessed_frame(MovieClipUser *user, int flag, int postprocess_flag)
591 {
592         int result = postprocess_flag;
593
594         result |= need_undistortion_postprocess(user, flag);
595
596         return result;
597 }
598
599 static int check_undistortion_cache_flags(MovieClip *clip)
600 {
601         MovieClipCache *cache = clip->cache;
602         MovieTrackingCamera *camera = &clip->tracking.camera;
603
604         /* check for distortion model changes */
605         if (!equals_v2v2(camera->principal, cache->postprocessed.principal))
606                 return FALSE;
607
608         if (!equals_v3v3(&camera->k1, &cache->postprocessed.k1))
609                 return FALSE;
610
611         return TRUE;
612 }
613
614 static ImBuf *get_postprocessed_cached_frame(MovieClip *clip, MovieClipUser *user, int flag, int postprocess_flag)
615 {
616         MovieClipCache *cache = clip->cache;
617         int framenr = user->framenr;
618         short proxy = IMB_PROXY_NONE;
619         int render_flag = 0;
620
621         if (flag & MCLIP_USE_PROXY) {
622                 proxy = rendersize_to_proxy(user, flag);
623                 render_flag = user->render_flag;
624         }
625
626         /* no cache or no cached postprocessed image */
627         if (!clip->cache || !clip->cache->postprocessed.ibuf)
628                 return NULL;
629
630         /* postprocessing happened for other frame */
631         if (cache->postprocessed.framenr != framenr)
632                 return NULL;
633
634         /* cached ibuf used different proxy settings */
635         if (cache->postprocessed.render_flag != render_flag || cache->postprocessed.proxy != proxy)
636                 return NULL;
637
638         if (cache->postprocessed.flag != postprocess_flag)
639                 return NULL;
640
641         if (need_undistortion_postprocess(user, flag)) {
642                 if (!check_undistortion_cache_flags(clip))
643                         return NULL;
644         }
645         else if (cache->postprocessed.undistortion_used)
646                 return NULL;
647
648         IMB_refImBuf(cache->postprocessed.ibuf);
649
650         return cache->postprocessed.ibuf;
651 }
652
653 static ImBuf *put_postprocessed_frame_to_cache(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf,
654                                                int flag, int postprocess_flag)
655 {
656         MovieClipCache *cache = clip->cache;
657         MovieTrackingCamera *camera = &clip->tracking.camera;
658         ImBuf *postproc_ibuf = NULL;
659
660         cache->postprocessed.framenr = user->framenr;
661         cache->postprocessed.flag = postprocess_flag;
662
663         if (flag & MCLIP_USE_PROXY) {
664                 cache->postprocessed.proxy = rendersize_to_proxy(user, flag);
665                 cache->postprocessed.render_flag = user->render_flag;
666         }
667         else {
668                 cache->postprocessed.proxy = IMB_PROXY_NONE;
669                 cache->postprocessed.render_flag = 0;
670         }
671
672         if (need_undistortion_postprocess(user, flag)) {
673                 copy_v2_v2(cache->postprocessed.principal, camera->principal);
674                 copy_v3_v3(&cache->postprocessed.k1, &camera->k1);
675                 cache->postprocessed.undistortion_used = TRUE;
676                 postproc_ibuf = get_undistorted_ibuf(clip, NULL, ibuf);
677         }
678         else {
679                 cache->postprocessed.undistortion_used = FALSE;
680         }
681
682         if (postprocess_flag) {
683                 int disable_red   = postprocess_flag & MOVIECLIP_DISABLE_RED,
684                     disable_green = postprocess_flag & MOVIECLIP_DISABLE_GREEN,
685                     disable_blue  = postprocess_flag & MOVIECLIP_DISABLE_BLUE,
686                     grayscale     = postprocess_flag & MOVIECLIP_PREVIEW_GRAYSCALE;
687
688                 if (!postproc_ibuf)
689                         postproc_ibuf = IMB_dupImBuf(ibuf);
690
691                 if (disable_red || disable_green || disable_blue || grayscale)
692                         BKE_tracking_disable_channels(postproc_ibuf, disable_red, disable_green, disable_blue, 1);
693         }
694
695         IMB_refImBuf(postproc_ibuf);
696
697         if (cache->postprocessed.ibuf)
698                 IMB_freeImBuf(cache->postprocessed.ibuf);
699
700         cache->postprocessed.ibuf = postproc_ibuf;
701
702         return postproc_ibuf;
703 }
704
705 static ImBuf *movieclip_get_postprocessed_ibuf(MovieClip *clip, MovieClipUser *user, int flag,
706                                                int postprocess_flag, int cache_flag)
707 {
708         ImBuf *ibuf = NULL;
709         int framenr = user->framenr, need_postprocess = FALSE;
710
711         /* cache isn't threadsafe itself and also loading of movies
712          * can't happen from concurent threads that's why we use lock here */
713         BLI_lock_thread(LOCK_MOVIECLIP);
714
715         /* try to obtain cached postprocessed frame first */
716         if (need_postprocessed_frame(user, flag, postprocess_flag)) {
717                 ibuf = get_postprocessed_cached_frame(clip, user, flag, postprocess_flag);
718
719                 if (!ibuf)
720                         need_postprocess = TRUE;
721         }
722
723         if (!ibuf)
724                 ibuf = get_imbuf_cache(clip, user, flag);
725
726         if (!ibuf) {
727                 int use_sequence = FALSE;
728
729                 /* undistorted proxies for movies should be read as image sequence */
730                 use_sequence = (user->render_flag & MCLIP_PROXY_RENDER_UNDISTORT) &&
731                                (user->render_size != MCLIP_PROXY_RENDER_SIZE_FULL);
732
733                 if (clip->source == MCLIP_SRC_SEQUENCE || use_sequence) {
734                         ibuf = movieclip_load_sequence_file(clip, user, framenr, flag);
735                 }
736                 else {
737                         ibuf = movieclip_load_movie_file(clip, user, framenr, flag);
738                 }
739
740                 if (ibuf && (cache_flag & MOVIECLIP_CACHE_SKIP) == 0)
741                         put_imbuf_cache(clip, user, ibuf, flag);
742         }
743
744         if (ibuf) {
745                 clip->lastframe = framenr;
746                 real_ibuf_size(clip, user, ibuf, &clip->lastsize[0], &clip->lastsize[1]);
747
748                 /* postprocess frame and put to cache */
749                 if (need_postprocess) {
750                         ImBuf *tmpibuf = ibuf;
751                         ibuf = put_postprocessed_frame_to_cache(clip, user, tmpibuf, flag, postprocess_flag);
752                         IMB_freeImBuf(tmpibuf);
753                 }
754         }
755
756         BLI_unlock_thread(LOCK_MOVIECLIP);
757
758         return ibuf;
759 }
760
761 ImBuf *BKE_movieclip_get_ibuf(MovieClip *clip, MovieClipUser *user)
762 {
763         return BKE_movieclip_get_ibuf_flag(clip, user, clip->flag, 0);
764 }
765
766 ImBuf *BKE_movieclip_get_ibuf_flag(MovieClip *clip, MovieClipUser *user, int flag, int cache_flag)
767 {
768         return movieclip_get_postprocessed_ibuf(clip, user, flag, 0, cache_flag);
769 }
770
771 ImBuf *BKE_movieclip_get_postprocessed_ibuf(MovieClip *clip, MovieClipUser *user, int postprocess_flag)
772 {
773         return movieclip_get_postprocessed_ibuf(clip, user, clip->flag, postprocess_flag, 0);
774 }
775
776 static ImBuf *get_stable_cached_frame(MovieClip *clip, MovieClipUser *user, ImBuf *reference_ibuf,
777                                       int framenr, int postprocess_flag)
778 {
779         MovieClipCache *cache = clip->cache;
780         MovieTracking *tracking = &clip->tracking;
781         ImBuf *stableibuf;
782         float tloc[2], tscale, tangle;
783         short proxy = IMB_PROXY_NONE;
784         int render_flag = 0;
785         int clip_framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, framenr);
786
787         if (clip->flag & MCLIP_USE_PROXY) {
788                 proxy = rendersize_to_proxy(user, clip->flag);
789                 render_flag = user->render_flag;
790         }
791
792         /* there's no cached frame or it was calculated for another frame */
793         if (!cache->stabilized.ibuf || cache->stabilized.framenr != framenr)
794                 return NULL;
795
796         if (cache->stabilized.reference_ibuf != reference_ibuf)
797                 return NULL;
798
799         /* cached ibuf used different proxy settings */
800         if (cache->stabilized.render_flag != render_flag || cache->stabilized.proxy != proxy)
801                 return NULL;
802
803         if (cache->stabilized.postprocess_flag != postprocess_flag)
804                 return NULL;
805
806         /* stabilization also depends on pixel aspect ratio */
807         if (cache->stabilized.aspect != tracking->camera.pixel_aspect)
808                 return NULL;
809
810         if (cache->stabilized.filter != tracking->stabilization.filter)
811                 return NULL;
812
813         stableibuf = cache->stabilized.ibuf;
814
815         BKE_tracking_stabilization_data_get(&clip->tracking, clip_framenr, stableibuf->x, stableibuf->y, tloc, &tscale, &tangle);
816
817         /* check for stabilization parameters */
818         if (tscale != cache->stabilized.scale ||
819             tangle != cache->stabilized.angle ||
820             !equals_v2v2(tloc, cache->stabilized.loc))
821         {
822                 return NULL;
823         }
824
825         IMB_refImBuf(stableibuf);
826
827         return stableibuf;
828 }
829
830 static ImBuf *put_stabilized_frame_to_cache(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf,
831                                             int framenr, int postprocess_flag)
832 {
833         MovieClipCache *cache = clip->cache;
834         MovieTracking *tracking = &clip->tracking;
835         ImBuf *stableibuf;
836         float tloc[2], tscale, tangle;
837         int clip_framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, framenr);
838
839         stableibuf = BKE_tracking_stabilize_frame(&clip->tracking, clip_framenr, ibuf, tloc, &tscale, &tangle);
840
841         copy_v2_v2(cache->stabilized.loc, tloc);
842
843         cache->stabilized.scale = tscale;
844         cache->stabilized.angle = tangle;
845         cache->stabilized.framenr = framenr;
846         cache->stabilized.aspect = tracking->camera.pixel_aspect;
847         cache->stabilized.filter = tracking->stabilization.filter;
848
849         if (clip->flag & MCLIP_USE_PROXY) {
850                 cache->stabilized.proxy = rendersize_to_proxy(user, clip->flag);
851                 cache->stabilized.render_flag = user->render_flag;
852         }
853         else {
854                 cache->stabilized.proxy = IMB_PROXY_NONE;
855                 cache->stabilized.render_flag = 0;
856         }
857
858         cache->stabilized.postprocess_flag = postprocess_flag;
859
860         if (cache->stabilized.ibuf)
861                 IMB_freeImBuf(cache->stabilized.ibuf);
862
863         cache->stabilized.ibuf = stableibuf;
864
865         IMB_refImBuf(stableibuf);
866
867         return stableibuf;
868 }
869
870 ImBuf *BKE_movieclip_get_stable_ibuf(MovieClip *clip, MovieClipUser *user, float loc[2], float *scale, float *angle,
871                                      int postprocess_flag)
872 {
873         ImBuf *ibuf, *stableibuf = NULL;
874         int framenr = user->framenr;
875
876         ibuf = BKE_movieclip_get_postprocessed_ibuf(clip, user, postprocess_flag);
877
878         if (!ibuf)
879                 return NULL;
880
881         if (clip->tracking.stabilization.flag & TRACKING_2D_STABILIZATION) {
882                 MovieClipCache *cache = clip->cache;
883
884                 stableibuf = get_stable_cached_frame(clip, user, ibuf, framenr, postprocess_flag);
885
886                 if (!stableibuf)
887                         stableibuf = put_stabilized_frame_to_cache(clip, user, ibuf, framenr, postprocess_flag);
888
889                 if (loc)
890                         copy_v2_v2(loc, cache->stabilized.loc);
891
892                 if (scale)
893                         *scale = cache->stabilized.scale;
894
895                 if (angle)
896                         *angle = cache->stabilized.angle;
897         }
898         else {
899                 if (loc)
900                         zero_v2(loc);
901
902                 if (scale)
903                         *scale = 1.0f;
904
905                 if (angle)
906                         *angle = 0.0f;
907
908                 stableibuf = ibuf;
909         }
910
911         if (stableibuf != ibuf) {
912                 IMB_freeImBuf(ibuf);
913                 ibuf = stableibuf;
914         }
915
916         return ibuf;
917
918 }
919
920 int BKE_movieclip_has_frame(MovieClip *clip, MovieClipUser *user)
921 {
922         ImBuf *ibuf = BKE_movieclip_get_ibuf(clip, user);
923
924         if (ibuf) {
925                 IMB_freeImBuf(ibuf);
926                 return TRUE;
927         }
928
929         return FALSE;
930 }
931
932 void BKE_movieclip_get_size(MovieClip *clip, MovieClipUser *user, int *width, int *height)
933 {
934 #if 0
935         /* originally was needed to support image sequences with different image dimensions,
936          * which might be useful for such things as reconstruction of unordered image sequence,
937          * or painting/rotoscoping of non-equal-sized images, but this ended up in unneeded
938          * cache lookups and even unwanted non-proxied files loading when doing mask parenting,
939          * so let's disable this for now and assume image sequence consists of images with
940          * equal sizes (sergey)
941          */
942         if (user->framenr == clip->lastframe) {
943 #endif
944         if (clip->lastsize[0] != 0 && clip->lastsize[1] != 0) {
945                 *width = clip->lastsize[0];
946                 *height = clip->lastsize[1];
947         }
948         else {
949                 ImBuf *ibuf = BKE_movieclip_get_ibuf(clip, user);
950
951                 if (ibuf && ibuf->x && ibuf->y) {
952                         real_ibuf_size(clip, user, ibuf, width, height);
953                 }
954                 else {
955                         *width = clip->lastsize[0];
956                         *height = clip->lastsize[1];
957                 }
958
959                 if (ibuf)
960                         IMB_freeImBuf(ibuf);
961         }
962 }
963
964 int BKE_movieclip_get_duration(MovieClip *clip)
965 {
966         if (!clip->len) {
967                 movieclip_calc_length(clip);
968         }
969
970         return clip->len;
971 }
972
973 void BKE_movieclip_aspect(MovieClip *clip, float *aspx, float *aspy)
974 {
975         *aspx = *aspy = 1.0;
976
977         /* x is always 1 */
978         *aspy = clip->aspy / clip->aspx / clip->tracking.camera.pixel_aspect;
979 }
980
981 /* get segments of cached frames. useful for debugging cache policies */
982 void BKE_movieclip_get_cache_segments(MovieClip *clip, MovieClipUser *user, int *totseg_r, int **points_r)
983 {
984         *totseg_r = 0;
985         *points_r = NULL;
986
987         if (clip->cache) {
988                 int proxy = rendersize_to_proxy(user, clip->flag);
989
990                 IMB_moviecache_get_cache_segments(clip->cache->moviecache, proxy, user->render_flag, totseg_r, points_r);
991         }
992 }
993
994 void BKE_movieclip_user_set_frame(MovieClipUser *iuser, int framenr)
995 {
996         /* TODO: clamp framenr here? */
997
998         iuser->framenr = framenr;
999 }
1000
1001 static void free_buffers(MovieClip *clip)
1002 {
1003         if (clip->cache) {
1004                 IMB_moviecache_free(clip->cache->moviecache);
1005
1006                 if (clip->cache->postprocessed.ibuf)
1007                         IMB_freeImBuf(clip->cache->postprocessed.ibuf);
1008
1009                 if (clip->cache->stabilized.ibuf)
1010                         IMB_freeImBuf(clip->cache->stabilized.ibuf);
1011
1012                 MEM_freeN(clip->cache);
1013                 clip->cache = NULL;
1014         }
1015
1016         if (clip->anim) {
1017                 IMB_free_anim(clip->anim);
1018                 clip->anim = NULL;
1019         }
1020
1021         BKE_free_animdata((ID *) clip);
1022 }
1023
1024 void BKE_movieclip_reload(MovieClip *clip)
1025 {
1026         /* clear cache */
1027         free_buffers(clip);
1028
1029         clip->tracking.stabilization.ok = FALSE;
1030
1031         /* update clip source */
1032         if (BLI_testextensie_array(clip->name, imb_ext_movie))
1033                 clip->source = MCLIP_SRC_MOVIE;
1034         else
1035                 clip->source = MCLIP_SRC_SEQUENCE;
1036
1037         clip->lastsize[0] = clip->lastsize[1] = 0;
1038         movieclip_load_get_szie(clip);
1039
1040         movieclip_calc_length(clip);
1041 }
1042
1043 void BKE_movieclip_update_scopes(MovieClip *clip, MovieClipUser *user, MovieClipScopes *scopes)
1044 {
1045         if (scopes->ok)
1046                 return;
1047
1048         if (scopes->track_preview) {
1049                 IMB_freeImBuf(scopes->track_preview);
1050                 scopes->track_preview = NULL;
1051         }
1052
1053         if (scopes->track_search) {
1054                 IMB_freeImBuf(scopes->track_search);
1055                 scopes->track_search = NULL;
1056         }
1057
1058         scopes->marker = NULL;
1059         scopes->track = NULL;
1060         scopes->track_locked = TRUE;
1061
1062         if (clip) {
1063                 MovieTrackingTrack *act_track = BKE_tracking_track_get_active(&clip->tracking);
1064
1065                 if (act_track) {
1066                         MovieTrackingTrack *track = act_track;
1067                         int framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, user->framenr);
1068                         MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
1069
1070                         scopes->marker = marker;
1071                         scopes->track = track;
1072
1073                         if (marker->flag & MARKER_DISABLED) {
1074                                 scopes->track_disabled = TRUE;
1075                         }
1076                         else {
1077                                 ImBuf *ibuf = BKE_movieclip_get_ibuf(clip, user);
1078
1079                                 scopes->track_disabled = FALSE;
1080
1081                                 if (ibuf && (ibuf->rect || ibuf->rect_float)) {
1082                                         ImBuf *search_ibuf;
1083                                         MovieTrackingMarker undist_marker = *marker;
1084
1085                                         if (user->render_flag & MCLIP_PROXY_RENDER_UNDISTORT) {
1086                                                 int width, height;
1087                                                 float aspy = 1.0f / clip->tracking.camera.pixel_aspect;
1088
1089                                                 BKE_movieclip_get_size(clip, user, &width, &height);
1090
1091                                                 undist_marker.pos[0] *= width;
1092                                                 undist_marker.pos[1] *= height * aspy;
1093
1094                                                 BKE_tracking_undistort_v2(&clip->tracking, undist_marker.pos, undist_marker.pos);
1095
1096                                                 undist_marker.pos[0] /= width;
1097                                                 undist_marker.pos[1] /= height * aspy;
1098                                         }
1099
1100                                         search_ibuf = BKE_tracking_get_search_imbuf(ibuf, track, &undist_marker, TRUE, TRUE);
1101
1102                                         if (!search_ibuf->rect_float) {
1103                                                 /* sampling happens in float buffer */
1104                                                 IMB_float_from_rect(search_ibuf);
1105                                         }
1106
1107                                         scopes->undist_marker = undist_marker;
1108                                         scopes->track_search = search_ibuf;
1109
1110                                         scopes->frame_width = ibuf->x;
1111                                         scopes->frame_height = ibuf->y;
1112
1113                                         scopes->use_track_mask = track->flag & TRACK_PREVIEW_ALPHA;
1114                                 }
1115
1116                                 IMB_freeImBuf(ibuf);
1117                         }
1118
1119                         if ((track->flag & TRACK_LOCKED) == 0) {
1120                                 float pat_min[2], pat_max[2];
1121
1122                                 scopes->track_locked = FALSE;
1123
1124                                 /* XXX: would work fine with non-transformed patterns, but would likely fail
1125                                  *      with transformed patterns, but that would be easier to debug when
1126                                  *      we'll have real pattern sampling (at least to test) */
1127                                 BKE_tracking_marker_pattern_minmax(marker, pat_min, pat_max);
1128
1129                                 scopes->slide_scale[0] = pat_max[0] - pat_min[0];
1130                                 scopes->slide_scale[1] = pat_max[1] - pat_min[1];
1131                         }
1132                 }
1133         }
1134
1135         scopes->framenr = user->framenr;
1136         scopes->ok = TRUE;
1137 }
1138
1139 static void movieclip_build_proxy_ibuf(MovieClip *clip, ImBuf *ibuf, int cfra, int proxy_render_size, int undistorted)
1140 {
1141         char name[FILE_MAX];
1142         int quality, rectx, recty;
1143         int size = rendersize_to_number(proxy_render_size);
1144         ImBuf *scaleibuf;
1145
1146         get_proxy_fname(clip, proxy_render_size, undistorted, cfra, name);
1147
1148         rectx = ibuf->x * size / 100.0f;
1149         recty = ibuf->y * size / 100.0f;
1150
1151         scaleibuf = IMB_dupImBuf(ibuf);
1152
1153         IMB_scaleImBuf(scaleibuf, (short)rectx, (short)recty);
1154
1155         quality = clip->proxy.quality;
1156         scaleibuf->ftype = JPG | quality;
1157
1158         /* unsupported feature only confuses other s/w */
1159         if (scaleibuf->planes == 32)
1160                 scaleibuf->planes = 24;
1161
1162         BLI_lock_thread(LOCK_MOVIECLIP);
1163
1164         BLI_make_existing_file(name);
1165         if (IMB_saveiff(scaleibuf, name, IB_rect) == 0)
1166                 perror(name);
1167
1168         BLI_unlock_thread(LOCK_MOVIECLIP);
1169
1170         IMB_freeImBuf(scaleibuf);
1171 }
1172
1173 void BKE_movieclip_build_proxy_frame(MovieClip *clip, int clip_flag, struct MovieDistortion *distortion,
1174                                      int cfra, int *build_sizes, int build_count, int undistorted)
1175 {
1176         ImBuf *ibuf;
1177         MovieClipUser user;
1178
1179         user.framenr = cfra;
1180         user.render_flag = 0;
1181         user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL;
1182
1183         ibuf = BKE_movieclip_get_ibuf_flag(clip, &user, clip_flag, MOVIECLIP_CACHE_SKIP);
1184
1185         if (ibuf) {
1186                 ImBuf *tmpibuf = ibuf;
1187                 int i;
1188
1189                 if (undistorted)
1190                         tmpibuf = get_undistorted_ibuf(clip, distortion, ibuf);
1191
1192                 for (i = 0; i < build_count; i++)
1193                         movieclip_build_proxy_ibuf(clip, tmpibuf, cfra, build_sizes[i], undistorted);
1194
1195                 IMB_freeImBuf(ibuf);
1196
1197                 if (tmpibuf != ibuf)
1198                         IMB_freeImBuf(tmpibuf);
1199         }
1200 }
1201
1202 void BKE_movieclip_free(MovieClip *clip)
1203 {
1204         free_buffers(clip);
1205
1206         BKE_tracking_free(&clip->tracking);
1207 }
1208
1209 void BKE_movieclip_unlink(Main *bmain, MovieClip *clip)
1210 {
1211         bScreen *scr;
1212         ScrArea *area;
1213         SpaceLink *sl;
1214         Scene *sce;
1215         Object *ob;
1216
1217         for (scr = bmain->screen.first; scr; scr = scr->id.next) {
1218                 for (area = scr->areabase.first; area; area = area->next) {
1219                         for (sl = area->spacedata.first; sl; sl = sl->next) {
1220                                 if (sl->spacetype == SPACE_CLIP) {
1221                                         SpaceClip *sc = (SpaceClip *) sl;
1222
1223                                         if (sc->clip == clip)
1224                                                 sc->clip = NULL;
1225                                 }
1226                                 else if (sl->spacetype == SPACE_VIEW3D) {
1227                                         View3D *v3d = (View3D *) sl;
1228                                         BGpic *bgpic;
1229
1230                                         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
1231                                                 if (bgpic->clip == clip)
1232                                                         bgpic->clip = NULL;
1233                                         }
1234                                 }
1235                         }
1236                 }
1237         }
1238
1239         for (sce = bmain->scene.first; sce; sce = sce->id.next) {
1240                 if (sce->clip == clip)
1241                         sce->clip = NULL;
1242         }
1243
1244         for (ob = bmain->object.first; ob; ob = ob->id.next) {
1245                 bConstraint *con;
1246
1247                 for (con = ob->constraints.first; con; con = con->next) {
1248                         bConstraintTypeInfo *cti = constraint_get_typeinfo(con);
1249
1250                         if (cti->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
1251                                 bFollowTrackConstraint *data = (bFollowTrackConstraint *) con->data;
1252
1253                                 if (data->clip == clip)
1254                                         data->clip = NULL;
1255                         }
1256                         else if (cti->type == CONSTRAINT_TYPE_CAMERASOLVER) {
1257                                 bCameraSolverConstraint *data = (bCameraSolverConstraint *) con->data;
1258
1259                                 if (data->clip == clip)
1260                                         data->clip = NULL;
1261                         }
1262                         else if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
1263                                 bObjectSolverConstraint *data = (bObjectSolverConstraint *) con->data;
1264
1265                                 if (data->clip == clip)
1266                                         data->clip = NULL;
1267                         }
1268                 }
1269         }
1270
1271         clip->id.us = 0;
1272 }
1273
1274 float BKE_movieclip_remap_scene_to_clip_frame(MovieClip *clip, float framenr)
1275 {
1276         return framenr - (float) clip->start_frame + 1.0f;
1277 }
1278
1279 float BKE_movieclip_remap_clip_to_scene_frame(MovieClip *clip, float framenr)
1280 {
1281         return framenr + (float) clip->start_frame - 1.0f;
1282 }