Camera tracking: animation datablock for MovieClip
[blender-staging.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, int 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         offset= sequence_guess_offset(clip->name, strlen(head), numlen);
159
160         if (numlen) BLI_stringenc(name, head, tail, numlen, offset+framenr-1);
161         else        BLI_strncpy(name, clip->name, sizeof(clip->name));
162
163         BLI_path_abs(name, ID_BLEND_PATH(G.main, &clip->id));
164 }
165
166 /* supposed to work with sequences only */
167 static void get_proxy_fname(MovieClip *clip, int proxy_render_size, int undistorted, int framenr, char *name)
168 {
169         int size= rendersize_to_number(proxy_render_size);
170         char dir[FILE_MAX], clipdir[FILE_MAX], clipfile[FILE_MAX];
171
172         BLI_split_dirfile(clip->name, clipdir, clipfile, FILE_MAX, FILE_MAX);
173
174         if(clip->flag&MCLIP_USE_PROXY_CUSTOM_DIR) {
175                 BLI_strncpy(dir, clip->proxy.dir, sizeof(dir));
176         } else {
177                 BLI_snprintf(dir, FILE_MAX, "%s/BL_proxy", clipdir);
178         }
179
180         if(undistorted)
181                 BLI_snprintf(name, FILE_MAX, "%s/%s/proxy_%d_undistorted/%08d", dir, clipfile, size, framenr);
182         else
183                 BLI_snprintf(name, FILE_MAX, "%s/%s/proxy_%d/%08d", dir, clipfile, size, framenr);
184
185         BLI_path_abs(name, G.main->name);
186         BLI_path_frame(name, 1, 0);
187
188         strcat(name, ".jpg");
189 }
190
191 static ImBuf *movieclip_load_sequence_file(MovieClip *clip, MovieClipUser *user, int framenr, int flag)
192 {
193         struct ImBuf *ibuf;
194         char name[FILE_MAX];
195         int loadflag, use_proxy= 0;
196
197         use_proxy= (flag&MCLIP_USE_PROXY) && user->render_size != MCLIP_PROXY_RENDER_SIZE_FULL;
198         if(use_proxy) {
199                 int undistort= user->render_flag&MCLIP_PROXY_RENDER_UNDISTORT;
200                 get_proxy_fname(clip, user->render_size, undistort, framenr, name);
201         } else
202                 get_sequence_fname(clip, framenr, name);
203
204         loadflag= IB_rect|IB_multilayer;
205
206         /* read ibuf */
207         ibuf= IMB_loadiffname(name, loadflag);
208
209         return ibuf;
210 }
211
212 static ImBuf *movieclip_load_movie_file(MovieClip *clip, MovieClipUser *user, int framenr, int flag)
213 {
214         ImBuf *ibuf= NULL;
215         int tc= get_timecode(clip, flag);
216         int proxy= rendersize_to_proxy(user, flag);
217         char str[FILE_MAX];
218
219         if(!clip->anim) {
220                 BLI_strncpy(str, clip->name, FILE_MAX);
221                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &clip->id));
222
223                 /* FIXME: make several stream accessible in image editor, too */
224                 clip->anim= openanim(str, IB_rect, 0);
225
226                 if(clip->anim) {
227                         if(clip->flag&MCLIP_USE_PROXY_CUSTOM_DIR) {
228                                 char dir[FILE_MAX];
229                                 BLI_strncpy(dir, clip->proxy.dir, sizeof(dir));
230                                 BLI_path_abs(dir, G.main->name);
231                                 IMB_anim_set_index_dir(clip->anim, dir);
232                         }
233                 }
234         }
235
236         if(clip->anim) {
237                 int dur;
238                 int fra;
239
240                 dur= IMB_anim_get_duration(clip->anim, tc);
241                 fra= framenr-1;
242
243                 if(fra<0)
244                         fra= 0;
245
246                 if(fra>(dur-1))
247                         fra= dur-1;
248
249                 ibuf= IMB_anim_absolute(clip->anim, fra, tc, proxy);
250         }
251
252         return ibuf;
253 }
254
255 /*********************** image buffer cache *************************/
256
257 typedef struct MovieClipCache {
258         /* regular movie cache */
259         struct MovieCache *moviecache;
260
261         /* cached postprocessed shot */
262         struct {
263                 ImBuf *ibuf;
264                 int framenr;
265                 int flag;
266
267                 /* cache for undistorted shot */
268                 float principal[2];
269                 float k1, k2, k3;
270                 short undistoriton_used;
271
272                 int proxy;
273                 short render_flag;
274         } postprocessed;
275
276         /* cache for stable shot */
277         struct {
278                 ImBuf *ibuf;
279                 int framenr;
280
281                 float loc[2], scale, angle;
282                 int proxy;
283                 short render_flag;
284         } stabilized;
285 } MovieClipCache;
286
287 typedef struct MovieClipImBufCacheKey {
288         int framenr;
289         int proxy;
290         short render_flag;
291 } MovieClipImBufCacheKey;
292
293 static void moviecache_keydata(void *userkey, int *framenr, int *proxy, int *render_flags)
294 {
295         MovieClipImBufCacheKey *key= (MovieClipImBufCacheKey*)userkey;
296
297         *framenr= key->framenr;
298         *proxy= key->proxy;
299         *render_flags= key->render_flag;
300 }
301
302 static unsigned int moviecache_hashhash(const void *keyv)
303 {
304         MovieClipImBufCacheKey *key= (MovieClipImBufCacheKey*)keyv;
305         int rval= key->framenr;
306
307         return rval;
308 }
309
310 static int moviecache_hashcmp(const void *av, const void *bv)
311 {
312         const MovieClipImBufCacheKey *a= (MovieClipImBufCacheKey*)av;
313         const MovieClipImBufCacheKey *b= (MovieClipImBufCacheKey*)bv;
314
315         if(a->framenr<b->framenr) return -1;
316         else if(a->framenr>b->framenr) return 1;
317
318         if(a->proxy<b->proxy) return -1;
319         else if(a->proxy>b->proxy) return 1;
320
321         if(a->render_flag<b->render_flag) return -1;
322         else if(a->render_flag>b->render_flag) return 1;
323
324         return 0;
325 }
326
327 static ImBuf *get_imbuf_cache(MovieClip *clip, MovieClipUser *user, int flag)
328 {
329         if(clip->cache) {
330                 MovieClipImBufCacheKey key;
331
332                 key.framenr= user->framenr;
333
334                 if(flag&MCLIP_USE_PROXY) {
335                         key.proxy= rendersize_to_proxy(user, flag);
336                         key.render_flag= user->render_flag;
337                 }
338                 else {
339                         key.proxy= IMB_PROXY_NONE;
340                         key.render_flag= 0;
341                 }
342
343                 return IMB_moviecache_get(clip->cache->moviecache, &key);
344         }
345
346         return NULL;
347 }
348
349 static void put_imbuf_cache(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf, int flag)
350 {
351         MovieClipImBufCacheKey key;
352
353         if(!clip->cache) {
354                 clip->cache= MEM_callocN(sizeof(MovieClipCache), "movieClipCache");
355
356                 clip->cache->moviecache= IMB_moviecache_create(sizeof(MovieClipImBufCacheKey), moviecache_hashhash,
357                                 moviecache_hashcmp, moviecache_keydata);
358         }
359
360         key.framenr= user->framenr;
361
362         if(flag&MCLIP_USE_PROXY) {
363                 key.proxy= rendersize_to_proxy(user, flag);
364                 key.render_flag= user->render_flag;
365         }
366         else {
367                 key.proxy= IMB_PROXY_NONE;
368                 key.render_flag= 0;
369         }
370
371         IMB_moviecache_put(clip->cache->moviecache, &key, ibuf);
372 }
373
374 /*********************** common functions *************************/
375
376 /* only image block itself */
377 static MovieClip *movieclip_alloc(const char *name)
378 {
379         MovieClip *clip;
380
381         clip= alloc_libblock(&G.main->movieclip, ID_MC, name);
382
383         clip->aspx= clip->aspy= 1.0f;
384
385         BKE_tracking_init_settings(&clip->tracking);
386
387         clip->proxy.build_size_flag= IMB_PROXY_25;
388         clip->proxy.build_tc_flag= IMB_TC_RECORD_RUN |
389                                    IMB_TC_FREE_RUN |
390                                    IMB_TC_INTERPOLATED_REC_DATE_FREE_RUN |
391                                    IMB_TC_RECORD_RUN_NO_GAPS;
392         clip->proxy.quality= 90;
393
394         return clip;
395 }
396
397 /* checks if image was already loaded, then returns same image
398    otherwise creates new.
399    does not load ibuf itself
400    pass on optional frame for #name images */
401 MovieClip *BKE_add_movieclip_file(const char *name)
402 {
403         MovieClip *clip;
404         MovieClipUser user;
405         int file, len, width, height;
406         const char *libname;
407         char str[FILE_MAX], strtest[FILE_MAX];
408
409         BLI_strncpy(str, name, sizeof(str));
410         BLI_path_abs(str, G.main->name);
411
412         /* exists? */
413         file= open(str, O_BINARY|O_RDONLY);
414         if(file== -1) return NULL;
415         close(file);
416
417         /* ** first search an identical clip ** */
418         for(clip= G.main->movieclip.first; clip; clip= clip->id.next) {
419                 BLI_strncpy(strtest, clip->name, sizeof(clip->name));
420                 BLI_path_abs(strtest, G.main->name);
421
422                 if(strcmp(strtest, str)==0) {
423                         BLI_strncpy(clip->name, name, sizeof(clip->name));  /* for stringcode */
424                         clip->id.us++;  /* officially should not, it doesn't link here! */
425
426                         return clip;
427                 }
428         }
429
430         /* ** add new movieclip ** */
431
432         /* create a short library name */
433         len= strlen(name);
434
435         while (len > 0 && name[len - 1] != '/' && name[len - 1] != '\\') len--;
436         libname= name+len;
437
438         clip= movieclip_alloc(libname);
439         BLI_strncpy(clip->name, name, sizeof(clip->name));
440
441         if(BLI_testextensie_array(name, imb_ext_movie)) clip->source= MCLIP_SRC_MOVIE;
442         else clip->source= MCLIP_SRC_SEQUENCE;
443
444         user.framenr= 1;
445         BKE_movieclip_get_size(clip, &user, &width, &height);
446         if(width && height) {
447                 clip->tracking.camera.principal[0]= ((float)width)/2;
448                 clip->tracking.camera.principal[1]= ((float)height)/2;
449
450                 clip->tracking.camera.focal= 24.0f*width/clip->tracking.camera.sensor_width;
451         }
452
453         return clip;
454 }
455
456 static void real_ibuf_size(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf, int *width, int *height)
457 {
458         *width= ibuf->x;
459         *height= ibuf->y;
460
461         if(clip->flag&MCLIP_USE_PROXY) {
462                 switch(user->render_size) {
463                         case MCLIP_PROXY_RENDER_SIZE_25:
464                                 (*width)*= 4;
465                                 (*height)*= 4;
466                                 break;
467
468                         case MCLIP_PROXY_RENDER_SIZE_50:
469                                 (*width)*= 2.0f;
470                                 (*height)*= 2.0f;
471                                 break;
472
473                         case MCLIP_PROXY_RENDER_SIZE_75:
474                                 *width= ((float)*width)*4.0f/3.0f;
475                                 *height= ((float)*height)*4.0f/3.0f;
476                                 break;
477                 }
478         }
479 }
480
481 static ImBuf *get_undistorted_ibuf(MovieClip *clip, struct MovieDistortion *distortion, ImBuf *ibuf)
482 {
483         ImBuf *undistibuf;
484
485         /* XXX: because of #27997 do not use float buffers to undistort,
486                 otherwise, undistorted proxy can be darker than it should */
487         imb_freerectfloatImBuf(ibuf);
488
489         if(distortion)
490                 undistibuf= BKE_tracking_distortion_exec(distortion, &clip->tracking, ibuf, ibuf->x, ibuf->y, 0.0f, 1);
491         else
492                 undistibuf= BKE_tracking_undistort(&clip->tracking, ibuf, ibuf->x, ibuf->y, 0.0f);
493
494         if(undistibuf->userflags&IB_RECT_INVALID) {
495                 ibuf->userflags&= ~IB_RECT_INVALID;
496                 IMB_rect_from_float(undistibuf);
497         }
498
499         IMB_scaleImBuf(undistibuf, ibuf->x, ibuf->y);
500
501         return undistibuf;
502 }
503
504 static int need_undistortion_postprocess(MovieClipUser *user, int flag)
505 {
506         int result = 0;
507
508         /* only full undistorted render can be used as on-fly undistorting image */
509         if(flag & MCLIP_USE_PROXY) {
510                 result |= (user->render_size == MCLIP_PROXY_RENDER_SIZE_FULL) &&
511                           (user->render_flag & MCLIP_PROXY_RENDER_UNDISTORT) != 0;
512         }
513
514         return result;
515 }
516
517 static int need_postprocessed_frame(MovieClipUser *user, int flag, int postprocess_flag)
518 {
519         int result = postprocess_flag;
520
521         result |= need_undistortion_postprocess(user, flag);
522
523         return result;
524 }
525
526 static int check_undistortion_cache_flags(MovieClip *clip)
527 {
528         MovieClipCache *cache= clip->cache;
529         MovieTrackingCamera *camera= &clip->tracking.camera;
530
531         /* check for distortion model changes */
532         if(!equals_v2v2(camera->principal, cache->postprocessed.principal))
533                 return 0;
534
535         if(!equals_v3v3(&camera->k1, &cache->postprocessed.k1))
536                 return 0;
537
538         return 1;
539 }
540
541 static ImBuf *get_postprocessed_cached_frame(MovieClip *clip, MovieClipUser *user, int flag, int postprocess_flag)
542 {
543         MovieClipCache *cache= clip->cache;
544         int framenr= user->framenr;
545         short proxy= IMB_PROXY_NONE;
546         int render_flag= 0;
547
548         if(flag&MCLIP_USE_PROXY) {
549                 proxy= rendersize_to_proxy(user, flag);
550                 render_flag= user->render_flag;
551         }
552
553         /* no cache or no cached postprocessed image */
554         if(!clip->cache || !clip->cache->postprocessed.ibuf)
555                 return NULL;
556
557         /* postprocessing happened for other frame */
558         if(cache->postprocessed.framenr != framenr)
559                 return NULL;
560
561         /* cached ibuf used different proxy settings */
562         if(cache->postprocessed.render_flag != render_flag || cache->postprocessed.proxy != proxy)
563                 return NULL;
564
565         if(cache->postprocessed.flag != postprocess_flag)
566                 return NULL;
567
568         if(need_undistortion_postprocess(user, flag)) {
569                 if(!check_undistortion_cache_flags(clip))
570                         return NULL;
571         }
572         else if(cache->postprocessed.undistoriton_used)
573                 return NULL;
574
575         IMB_refImBuf(cache->postprocessed.ibuf);
576
577         return cache->postprocessed.ibuf;
578 }
579
580 static ImBuf *put_postprocessed_frame_to_cache(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf, int flag, int postprocess_flag)
581 {
582         MovieClipCache *cache= clip->cache;
583         MovieTrackingCamera *camera= &clip->tracking.camera;
584         ImBuf *postproc_ibuf = NULL;
585
586         if(cache->postprocessed.ibuf)
587                 IMB_freeImBuf(cache->postprocessed.ibuf);
588
589         cache->postprocessed.framenr= user->framenr;
590         cache->postprocessed.flag = postprocess_flag;
591
592         if(flag&MCLIP_USE_PROXY) {
593                 cache->postprocessed.proxy= rendersize_to_proxy(user, flag);
594                 cache->postprocessed.render_flag= user->render_flag;
595         }
596         else {
597                 cache->postprocessed.proxy = IMB_PROXY_NONE;
598                 cache->postprocessed.render_flag = 0;
599         }
600
601         if(need_undistortion_postprocess(user, flag)) {
602                 copy_v2_v2(cache->postprocessed.principal, camera->principal);
603                 copy_v3_v3(&cache->postprocessed.k1, &camera->k1);
604                 cache->postprocessed.undistoriton_used = 1;
605                 postproc_ibuf= get_undistorted_ibuf(clip, NULL, ibuf);
606         }
607         else cache->postprocessed.undistoriton_used = 0;
608
609         if(postprocess_flag) {
610                 int disable_red   = postprocess_flag & MOVIECLIP_DISABLE_RED,
611                     disable_green = postprocess_flag & MOVIECLIP_DISABLE_GREEN,
612                         disable_blue  = postprocess_flag & MOVIECLIP_DISABLE_BLUE,
613                         grayscale     = postprocess_flag & MOVIECLIP_PREVIEW_GRAYSCALE;
614
615                 if(!postproc_ibuf)
616                         postproc_ibuf = IMB_dupImBuf(ibuf);
617
618                 if(disable_red || disable_green || disable_blue || grayscale)
619                         BKE_tracking_disable_imbuf_channels(postproc_ibuf, disable_red, disable_green, disable_blue, 1);
620         }
621
622         IMB_refImBuf(postproc_ibuf);
623
624         cache->postprocessed.ibuf= postproc_ibuf;
625
626         if(cache->stabilized.ibuf) {
627                 /* force stable buffer be re-calculated */
628                 IMB_freeImBuf(cache->stabilized.ibuf);
629                 cache->stabilized.ibuf= NULL;
630         }
631
632         return postproc_ibuf;
633 }
634
635 static ImBuf *movieclip_get_postprocessed_ibuf(MovieClip *clip, MovieClipUser *user, int flag,
636                                                int postprocess_flag, int cache_flag)
637 {
638         ImBuf *ibuf= NULL;
639         int framenr= user->framenr, need_postprocess= 0;
640
641         /* cache isn't threadsafe itself and also loading of movies
642            can't happen from concurent threads that's why we use lock here */
643         BLI_lock_thread(LOCK_MOVIECLIP);
644
645         /* try to obtain cached postprocessed frame first */
646         if(need_postprocessed_frame(user, flag, postprocess_flag)) {
647                 ibuf= get_postprocessed_cached_frame(clip, user, flag, postprocess_flag);
648
649                 if(!ibuf)
650                         need_postprocess= 1;
651         }
652
653         if(!ibuf)
654                 ibuf= get_imbuf_cache(clip, user, flag);
655
656         if(!ibuf) {
657                 int use_sequence= 0;
658
659                 /* undistorted proxies for movies should be read as image sequence */
660                 use_sequence= (user->render_flag&MCLIP_PROXY_RENDER_UNDISTORT) &&
661                         (user->render_size!=MCLIP_PROXY_RENDER_SIZE_FULL);
662
663                 if(clip->source==MCLIP_SRC_SEQUENCE || use_sequence)
664                         ibuf= movieclip_load_sequence_file(clip, user, framenr, flag);
665                 else {
666                         ibuf= movieclip_load_movie_file(clip, user, framenr, flag);
667                 }
668
669                 if(ibuf && (cache_flag & MOVIECLIP_CACHE_SKIP) == 0)
670                         put_imbuf_cache(clip, user, ibuf, flag);
671         }
672
673         if(ibuf) {
674                 clip->lastframe= framenr;
675                 real_ibuf_size(clip, user, ibuf, &clip->lastsize[0], &clip->lastsize[1]);
676
677                 /* postprocess frame and put to cache */
678                 if(need_postprocess) {
679                         ImBuf *tmpibuf= ibuf;
680                         ibuf= put_postprocessed_frame_to_cache(clip, user, tmpibuf, flag, postprocess_flag);
681                         IMB_freeImBuf(tmpibuf);
682                 }
683         }
684
685         BLI_unlock_thread(LOCK_MOVIECLIP);
686
687         return ibuf;
688 }
689
690 ImBuf *BKE_movieclip_get_ibuf(MovieClip *clip, MovieClipUser *user)
691 {
692         return BKE_movieclip_get_ibuf_flag(clip, user, clip->flag, 0);
693 }
694
695 ImBuf *BKE_movieclip_get_ibuf_flag(MovieClip *clip, MovieClipUser *user, int flag, int cache_flag)
696 {
697         return movieclip_get_postprocessed_ibuf(clip, user, flag, 0, cache_flag);
698 }
699
700 ImBuf *BKE_movieclip_get_postprocessed_ibuf(MovieClip *clip, MovieClipUser *user, int postprocess_flag)
701 {
702         return movieclip_get_postprocessed_ibuf(clip, user, clip->flag, postprocess_flag, 0);
703 }
704
705 static ImBuf *get_stable_cached_frame(MovieClip *clip, MovieClipUser *user, int framenr)
706 {
707         MovieClipCache *cache = clip->cache;
708         ImBuf *stableibuf;
709         float tloc[2], tscale, tangle;
710         short proxy = IMB_PROXY_NONE;
711         int render_flag = 0;
712
713         if(clip->flag&MCLIP_USE_PROXY) {
714                 proxy = rendersize_to_proxy(user, clip->flag);
715                 render_flag = user->render_flag;
716         }
717
718         /* there's no cached frame or it was calculated for another frame */
719         if(!cache->stabilized.ibuf || cache->stabilized.framenr != framenr)
720                 return NULL;
721
722         /* cached ibuf used different proxy settings */
723         if(cache->stabilized.render_flag!=render_flag || cache->stabilized.proxy!=proxy)
724                 return NULL;
725
726         stableibuf = cache->stabilized.ibuf;
727
728         BKE_tracking_stabilization_data(&clip->tracking, framenr, stableibuf->x, stableibuf->y, tloc, &tscale, &tangle);
729
730         /* check for stabilization parameters */
731         if(tscale != cache->stabilized.scale ||
732            tangle != cache->stabilized.angle ||
733            !equals_v2v2(tloc, cache->stabilized.loc))
734         {
735                 return NULL;
736         }
737
738         IMB_refImBuf(stableibuf);
739
740         return stableibuf;
741 }
742
743 static ImBuf *put_stabilized_frame_to_cache(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf, int framenr)
744 {
745         MovieClipCache *cache = clip->cache;
746         ImBuf *stableibuf;
747         float tloc[2], tscale, tangle;
748
749         if(cache->stabilized.ibuf)
750                 IMB_freeImBuf(cache->stabilized.ibuf);
751
752         stableibuf = BKE_tracking_stabilize(&clip->tracking, framenr, ibuf, tloc, &tscale, &tangle);
753
754         cache->stabilized.ibuf= stableibuf;
755
756         copy_v2_v2(cache->stabilized.loc, tloc);
757
758         cache->stabilized.scale = tscale;
759         cache->stabilized.angle = tangle;
760         cache->stabilized.framenr = framenr;
761
762         if(clip->flag&MCLIP_USE_PROXY) {
763                 cache->stabilized.proxy= rendersize_to_proxy(user, clip->flag);
764                 cache->stabilized.render_flag= user->render_flag;
765         }
766         else {
767                 cache->stabilized.proxy = IMB_PROXY_NONE;
768                 cache->stabilized.render_flag = 0;
769         }
770
771         IMB_refImBuf(stableibuf);
772
773         return stableibuf;
774 }
775
776 ImBuf *BKE_movieclip_get_stable_ibuf(MovieClip *clip, MovieClipUser *user, float loc[2], float *scale, float *angle, int postprocess_flag)
777 {
778         ImBuf *ibuf, *stableibuf= NULL;
779         int framenr= user->framenr;
780
781         ibuf= BKE_movieclip_get_postprocessed_ibuf(clip, user, postprocess_flag);
782
783         if(!ibuf)
784                 return NULL;
785
786         if(clip->tracking.stabilization.flag&TRACKING_2D_STABILIZATION) {
787                 MovieClipCache *cache= clip->cache;
788
789                 stableibuf= get_stable_cached_frame(clip, user, framenr);
790
791                 if(!stableibuf)
792                         stableibuf= put_stabilized_frame_to_cache(clip, user, ibuf, framenr);
793
794                 if(loc)         copy_v2_v2(loc, cache->stabilized.loc);
795                 if(scale)       *scale= cache->stabilized.scale;
796                 if(angle)       *angle= cache->stabilized.angle;
797         } else {
798                 if(loc)         zero_v2(loc);
799                 if(scale)       *scale= 1.0f;
800                 if(angle)       *angle= 0.0f;
801
802                 stableibuf= ibuf;
803         }
804
805         if(stableibuf!=ibuf) {
806                 IMB_freeImBuf(ibuf);
807                 ibuf= stableibuf;
808         }
809
810         return ibuf;
811
812 }
813
814 int BKE_movieclip_has_frame(MovieClip *clip, MovieClipUser *user)
815 {
816         ImBuf *ibuf= BKE_movieclip_get_ibuf(clip, user);
817
818         if(ibuf) {
819                 IMB_freeImBuf(ibuf);
820                 return 1;
821         }
822
823         return 0;
824 }
825
826 void BKE_movieclip_get_size(MovieClip *clip, MovieClipUser *user, int *width, int *height)
827 {
828         if(user->framenr==clip->lastframe) {
829                 *width= clip->lastsize[0];
830                 *height= clip->lastsize[1];
831         } else {
832                 ImBuf *ibuf= BKE_movieclip_get_ibuf(clip, user);
833
834                 if(ibuf && ibuf->x && ibuf->y) {
835                         real_ibuf_size(clip, user, ibuf, width, height);
836                 } else {
837                         *width= 0;
838                         *height= 0;
839                 }
840
841                 if(ibuf)
842                         IMB_freeImBuf(ibuf);
843         }
844 }
845
846 void BKE_movieclip_aspect(MovieClip *clip, float *aspx, float *aspy)
847 {
848         *aspx= *aspy= 1.0;
849
850         /* x is always 1 */
851         *aspy = clip->aspy/clip->aspx/clip->tracking.camera.pixel_aspect;
852 }
853
854 /* get segments of cached frames. useful for debugging cache policies */
855 void BKE_movieclip_get_cache_segments(MovieClip *clip, MovieClipUser *user, int *totseg_r, int **points_r)
856 {
857         *totseg_r= 0;
858         *points_r= NULL;
859
860         if(clip->cache) {
861                 int proxy= rendersize_to_proxy(user, clip->flag);
862
863                 IMB_moviecache_get_cache_segments(clip->cache->moviecache, proxy, user->render_flag, totseg_r, points_r);
864         }
865 }
866
867 void BKE_movieclip_user_set_frame(MovieClipUser *iuser, int framenr)
868 {
869         /* TODO: clamp framenr here? */
870
871         iuser->framenr= framenr;
872 }
873
874 static void free_buffers(MovieClip *clip)
875 {
876         if(clip->cache) {
877                 IMB_moviecache_free(clip->cache->moviecache);
878
879                 if(clip->cache->postprocessed.ibuf)
880                         IMB_freeImBuf(clip->cache->postprocessed.ibuf);
881
882                 if(clip->cache->stabilized.ibuf)
883                         IMB_freeImBuf(clip->cache->stabilized.ibuf);
884
885                 MEM_freeN(clip->cache);
886                 clip->cache= NULL;
887         }
888
889         if(clip->anim) {
890                 IMB_free_anim(clip->anim);
891                 clip->anim= FALSE;
892         }
893
894         BKE_free_animdata((ID *) clip);
895 }
896
897 void BKE_movieclip_reload(MovieClip *clip)
898 {
899         /* clear cache */
900         free_buffers(clip);
901
902         clip->tracking.stabilization.ok= 0;
903
904         /* update clip source */
905         if(BLI_testextensie_array(clip->name, imb_ext_movie)) clip->source= MCLIP_SRC_MOVIE;
906         else clip->source= MCLIP_SRC_SEQUENCE;
907 }
908
909 void BKE_movieclip_update_scopes(MovieClip *clip, MovieClipUser *user, MovieClipScopes *scopes)
910 {
911         if(scopes->ok)
912                 return;
913
914         if(scopes->track_preview) {
915                 IMB_freeImBuf(scopes->track_preview);
916                 scopes->track_preview= NULL;
917         }
918
919         scopes->marker= NULL;
920         scopes->track= NULL;
921
922         if(clip) {
923                 MovieTrackingTrack *act_track= BKE_tracking_active_track(&clip->tracking);
924
925                 if(act_track) {
926                         MovieTrackingTrack *track= act_track;
927                         MovieTrackingMarker *marker= BKE_tracking_get_marker(track, user->framenr);
928
929                         if(marker->flag&MARKER_DISABLED) {
930                                 scopes->track_disabled= 1;
931                         } else {
932                                 ImBuf *ibuf= BKE_movieclip_get_ibuf(clip, user);
933
934                                 scopes->track_disabled= 0;
935
936                                 if(ibuf && ibuf->rect) {
937                                         ImBuf *tmpibuf;
938                                         MovieTrackingMarker undist_marker= *marker;
939
940                                         if(user->render_flag&MCLIP_PROXY_RENDER_UNDISTORT) {
941                                                 int width, height;
942                                                 float aspy= 1.0f/clip->tracking.camera.pixel_aspect;;
943
944                                                 BKE_movieclip_get_size(clip, user, &width, &height);
945
946                                                 undist_marker.pos[0]*= width;
947                                                 undist_marker.pos[1]*= height*aspy;
948
949                                                 BKE_tracking_invert_intrinsics(&clip->tracking, undist_marker.pos, undist_marker.pos);
950
951                                                 undist_marker.pos[0]/= width;
952                                                 undist_marker.pos[1]/= height*aspy;
953                                         }
954
955                                         /* NOTE: margin should be kept in sync with value from ui_draw_but_TRACKPREVIEW */
956                                         tmpibuf= BKE_tracking_get_pattern_imbuf(ibuf, track, &undist_marker, 3 /* margin */,
957                                                         1 /* anchor */, scopes->track_pos, NULL);
958
959                                         if(tmpibuf->rect_float)
960                                                 IMB_rect_from_float(tmpibuf);
961
962                                         if(tmpibuf->rect)
963                                                 scopes->track_preview= tmpibuf;
964                                         else
965                                                 IMB_freeImBuf(tmpibuf);
966                                 }
967
968                                 IMB_freeImBuf(ibuf);
969                         }
970
971                         if((track->flag&TRACK_LOCKED)==0) {
972                                 scopes->marker= marker;
973                                 scopes->track= track;
974                                 scopes->slide_scale[0]= track->pat_max[0]-track->pat_min[0];
975                                 scopes->slide_scale[1]= track->pat_max[1]-track->pat_min[1];
976                         }
977                 }
978         }
979
980         scopes->framenr= user->framenr;
981         scopes->ok= 1;
982 }
983
984 static void movieclip_build_proxy_ibuf(MovieClip *clip, ImBuf *ibuf, int cfra, int proxy_render_size, int undistorted)
985 {
986         char name[FILE_MAX];
987         int quality, rectx, recty;
988         int size= rendersize_to_number(proxy_render_size);
989         ImBuf *scaleibuf;
990
991         get_proxy_fname(clip, proxy_render_size, undistorted, cfra, name);
992
993         rectx= ibuf->x*size/100.0f;
994         recty= ibuf->y*size/100.0f;
995
996         scaleibuf= IMB_dupImBuf(ibuf);
997
998         IMB_scaleImBuf(scaleibuf, (short)rectx, (short)recty);
999
1000         quality= clip->proxy.quality;
1001         scaleibuf->ftype= JPG | quality;
1002
1003         /* unsupported feature only confuses other s/w */
1004         if(scaleibuf->planes==32)
1005                 scaleibuf->planes= 24;
1006
1007         BLI_lock_thread(LOCK_MOVIECLIP);
1008
1009         BLI_make_existing_file(name);
1010         if(IMB_saveiff(scaleibuf, name, IB_rect)==0)
1011                 perror(name);
1012
1013         BLI_unlock_thread(LOCK_MOVIECLIP);
1014
1015         IMB_freeImBuf(scaleibuf);
1016 }
1017
1018 void BKE_movieclip_build_proxy_frame(MovieClip *clip, int clip_flag, struct MovieDistortion *distortion,
1019                         int cfra, int *build_sizes, int build_count, int undistorted)
1020 {
1021         ImBuf *ibuf;
1022         MovieClipUser user;
1023
1024         user.framenr= cfra;
1025         user.render_flag= 0;
1026         user.render_size= MCLIP_PROXY_RENDER_SIZE_FULL;
1027
1028         ibuf= BKE_movieclip_get_ibuf_flag(clip, &user, clip_flag, MOVIECLIP_CACHE_SKIP);
1029
1030         if(ibuf) {
1031                 ImBuf *tmpibuf= ibuf;
1032                 int i;
1033
1034                 if(undistorted)
1035                         tmpibuf= get_undistorted_ibuf(clip, distortion, ibuf);
1036
1037                 for(i= 0; i<build_count; i++)
1038                         movieclip_build_proxy_ibuf(clip, tmpibuf, cfra, build_sizes[i], undistorted);
1039
1040                 IMB_freeImBuf(ibuf);
1041
1042                 if(tmpibuf!=ibuf)
1043                         IMB_freeImBuf(tmpibuf);
1044         }
1045 }
1046
1047 void free_movieclip(MovieClip *clip)
1048 {
1049         free_buffers(clip);
1050
1051         BKE_tracking_free(&clip->tracking);
1052 }
1053
1054 void unlink_movieclip(Main *bmain, MovieClip *clip)
1055 {
1056         bScreen *scr;
1057         ScrArea *area;
1058         SpaceLink *sl;
1059         Scene *sce;
1060         Object *ob;
1061
1062         for(scr= bmain->screen.first; scr; scr= scr->id.next) {
1063                 for(area= scr->areabase.first; area; area= area->next) {
1064                         for(sl= area->spacedata.first; sl; sl= sl->next) {
1065                                 if(sl->spacetype==SPACE_CLIP) {
1066                                         SpaceClip *sc= (SpaceClip *) sl;
1067
1068                                         if(sc->clip==clip)
1069                                                 sc->clip= NULL;
1070                                 }
1071                                 else if(sl->spacetype==SPACE_VIEW3D) {
1072                                         View3D *v3d= (View3D *) sl;
1073                                         BGpic *bgpic;
1074
1075                                         for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next) {
1076                                                 if(bgpic->clip==clip)
1077                                                         bgpic->clip= NULL;
1078                                         }
1079                                 }
1080                         }
1081                 }
1082         }
1083
1084         for(sce= bmain->scene.first; sce; sce= sce->id.next) {
1085                 if(sce->clip==clip)
1086                         sce->clip= NULL;
1087         }
1088
1089         for(ob= bmain->object.first; ob; ob= ob->id.next) {
1090                 bConstraint *con;
1091
1092                 for(con= ob->constraints.first; con; con= con->next) {
1093                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1094
1095                         if(cti->type==CONSTRAINT_TYPE_FOLLOWTRACK) {
1096                                 bFollowTrackConstraint *data= (bFollowTrackConstraint *) con->data;
1097
1098                                 if(data->clip==clip)
1099                                         data->clip= NULL;
1100                         }
1101                         else if(cti->type==CONSTRAINT_TYPE_CAMERASOLVER) {
1102                                 bCameraSolverConstraint *data= (bCameraSolverConstraint *) con->data;
1103
1104                                 if(data->clip==clip)
1105                                         data->clip= NULL;
1106                         }
1107                 }
1108         }
1109
1110         clip->id.us= 0;
1111 }