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