Update build files to use new OpenAL libraries
[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         BKE_tracking_init_settings(&clip->tracking);
373
374         clip->proxy.build_size_flag= IMB_PROXY_25;
375         clip->proxy.build_tc_flag= IMB_TC_RECORD_RUN |
376                                    IMB_TC_FREE_RUN |
377                                    IMB_TC_INTERPOLATED_REC_DATE_FREE_RUN |
378                                    IMB_TC_RECORD_RUN_NO_GAPS;
379         clip->proxy.quality= 90;
380
381         return clip;
382 }
383
384 /* checks if image was already loaded, then returns same image
385    otherwise creates new.
386    does not load ibuf itself
387    pass on optional frame for #name images */
388 MovieClip *BKE_add_movieclip_file(const char *name)
389 {
390         MovieClip *clip;
391         MovieClipUser user;
392         int file, len, width, height;
393         const char *libname;
394         char str[FILE_MAX], strtest[FILE_MAX];
395
396         BLI_strncpy(str, name, sizeof(str));
397         BLI_path_abs(str, G.main->name);
398
399         /* exists? */
400         file= open(str, O_BINARY|O_RDONLY);
401         if(file== -1) return NULL;
402         close(file);
403
404         /* ** first search an identical clip ** */
405         for(clip= G.main->movieclip.first; clip; clip= clip->id.next) {
406                 BLI_strncpy(strtest, clip->name, sizeof(clip->name));
407                 BLI_path_abs(strtest, G.main->name);
408
409                 if(strcmp(strtest, str)==0) {
410                         BLI_strncpy(clip->name, name, sizeof(clip->name));  /* for stringcode */
411                         clip->id.us++;  /* officially should not, it doesn't link here! */
412
413                         return clip;
414                 }
415         }
416
417         /* ** add new movieclip ** */
418
419         /* create a short library name */
420         len= strlen(name);
421
422         while (len > 0 && name[len - 1] != '/' && name[len - 1] != '\\') len--;
423         libname= name+len;
424
425         clip= movieclip_alloc(libname);
426         BLI_strncpy(clip->name, name, sizeof(clip->name));
427
428         if(BLI_testextensie_array(name, imb_ext_movie)) clip->source= MCLIP_SRC_MOVIE;
429         else clip->source= MCLIP_SRC_SEQUENCE;
430
431         user.framenr= 1;
432         BKE_movieclip_get_size(clip, &user, &width, &height);
433         if(width && height) {
434                 clip->tracking.camera.principal[0]= ((float)width)/2;
435                 clip->tracking.camera.principal[1]= ((float)height)/2;
436
437                 clip->tracking.camera.focal= 24.0f*width/clip->tracking.camera.sensor_width;
438         }
439
440         return clip;
441 }
442
443 static void real_ibuf_size(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf, int *width, int *height)
444 {
445         *width= ibuf->x;
446         *height= ibuf->y;
447
448         if(clip->flag&MCLIP_USE_PROXY) {
449                 switch(user->render_size) {
450                         case MCLIP_PROXY_RENDER_SIZE_25:
451                                 (*width)*= 4;
452                                 (*height)*= 4;
453                                 break;
454
455                         case MCLIP_PROXY_RENDER_SIZE_50:
456                                 (*width)*= 2.0f;
457                                 (*height)*= 2.0f;
458                                 break;
459
460                         case MCLIP_PROXY_RENDER_SIZE_75:
461                                 *width= ((float)*width)*4.0f/3.0f;
462                                 *height= ((float)*height)*4.0f/3.0f;
463                                 break;
464                 }
465         }
466 }
467
468 static int need_undistorted_cache(MovieClipUser *user, int flag)
469 {
470         /* only full undistorted render can be used as on-fly undistorting image */
471         if(flag&MCLIP_USE_PROXY) {
472                 if(user->render_size != MCLIP_PROXY_RENDER_SIZE_FULL || (user->render_flag&MCLIP_PROXY_RENDER_UNDISTORT)==0)
473                         return 0;
474         }
475         else return 0;
476
477         return 1;
478 }
479
480 static ImBuf *get_undistorted_cache(MovieClip *clip, MovieClipUser *user)
481 {
482         MovieClipCache *cache= clip->cache;
483         MovieTrackingCamera *camera= &clip->tracking.camera;
484         int framenr= user->framenr;
485
486         /* no cache or no cached undistorted image */
487         if(!clip->cache || !clip->cache->undistibuf)
488                 return NULL;
489
490         /* undistortion happened for other frame */
491         if(cache->undist_framenr!=framenr)
492                 return NULL;
493
494         /* check for distortion model changes */
495         if(!equals_v2v2(camera->principal, cache->principal))
496                 return NULL;
497
498         if(!equals_v3v3(&camera->k1, &cache->k1))
499                 return NULL;
500
501         IMB_refImBuf(cache->undistibuf);
502
503         return cache->undistibuf;
504 }
505
506 static ImBuf *get_undistorted_ibuf(MovieClip *clip, struct MovieDistortion *distortion, ImBuf *ibuf)
507 {
508         ImBuf *undistibuf;
509
510         /* XXX: because of #27997 do not use float buffers to undistort,
511                 otherwise, undistorted proxy can be darker than it should */
512         imb_freerectfloatImBuf(ibuf);
513
514         if(distortion)
515                 undistibuf= BKE_tracking_distortion_exec(distortion, &clip->tracking, ibuf, ibuf->x, ibuf->y, 0.0f, 1);
516         else
517                 undistibuf= BKE_tracking_undistort(&clip->tracking, ibuf, ibuf->x, ibuf->y, 0.0f);
518
519         if(undistibuf->userflags&IB_RECT_INVALID) {
520                 ibuf->userflags&= ~IB_RECT_INVALID;
521                 IMB_rect_from_float(undistibuf);
522         }
523
524         IMB_scaleImBuf(undistibuf, ibuf->x, ibuf->y);
525
526         return undistibuf;
527 }
528
529 static ImBuf *put_undistorted_cache(MovieClip *clip, MovieClipUser *user, ImBuf *ibuf)
530 {
531         MovieClipCache *cache= clip->cache;
532         MovieTrackingCamera *camera= &clip->tracking.camera;
533
534         copy_v2_v2(cache->principal, camera->principal);
535         copy_v3_v3(&cache->k1, &camera->k1);
536         cache->undist_framenr= user->framenr;
537
538         if(cache->undistibuf)
539                 IMB_freeImBuf(cache->undistibuf);
540
541         cache->undistibuf= get_undistorted_ibuf(clip, NULL, ibuf);
542
543         if(cache->stableibuf) {
544                 /* force stable buffer be re-calculated */
545                 IMB_freeImBuf(cache->stableibuf);
546                 cache->stableibuf= NULL;
547         }
548
549         IMB_refImBuf(cache->undistibuf);
550
551         return cache->undistibuf;
552 }
553
554 ImBuf *BKE_movieclip_get_ibuf(MovieClip *clip, MovieClipUser *user)
555 {
556         ImBuf *ibuf= NULL;
557         int framenr= user->framenr;
558         int cache_undistorted= 0;
559
560         /* cache isn't threadsafe itself and also loading of movies
561            can't happen from concurent threads that's why we use lock here */
562         BLI_lock_thread(LOCK_MOVIECLIP);
563
564         /* try to obtain cached undistorted image first */
565         if(need_undistorted_cache(user, clip->flag)) {
566                 ibuf= get_undistorted_cache(clip, user);
567                 if(!ibuf)
568                         cache_undistorted= 1;
569         }
570
571         if(!ibuf)
572                 ibuf= get_imbuf_cache(clip, user, clip->flag);
573
574         if(!ibuf) {
575                 int use_sequence= 0;
576
577                 /* undistorted proxies for movies should be read as image sequence */
578                 use_sequence= (user->render_flag&MCLIP_PROXY_RENDER_UNDISTORT) &&
579                         (user->render_size!=MCLIP_PROXY_RENDER_SIZE_FULL);
580
581                 if(clip->source==MCLIP_SRC_SEQUENCE || use_sequence)
582                         ibuf= movieclip_load_sequence_file(clip, user, framenr, clip->flag);
583                 else {
584                         ibuf= movieclip_load_movie_file(clip, user, framenr, clip->flag);
585                 }
586
587                 if(ibuf)
588                         put_imbuf_cache(clip, user, ibuf, clip->flag);
589         }
590
591         if(ibuf) {
592                 clip->lastframe= framenr;
593                 real_ibuf_size(clip, user, ibuf, &clip->lastsize[0], &clip->lastsize[1]);
594
595                 /* put undistorted frame to cache */
596                 if(cache_undistorted) {
597                         ImBuf *tmpibuf= ibuf;
598                         ibuf= put_undistorted_cache(clip, user, tmpibuf);
599                         IMB_freeImBuf(tmpibuf);
600                 }
601         }
602
603         BLI_unlock_thread(LOCK_MOVIECLIP);
604
605         return ibuf;
606 }
607
608 ImBuf *BKE_movieclip_get_ibuf_flag(MovieClip *clip, MovieClipUser *user, int flag)
609 {
610         ImBuf *ibuf= NULL;
611         int framenr= user->framenr;
612         int cache_undistorted= 0;
613
614         /* cache isn't threadsafe itself and also loading of movies
615            can't happen from concurent threads that's why we use lock here */
616         BLI_lock_thread(LOCK_MOVIECLIP);
617
618         /* try to obtain cached undistorted image first */
619         if(need_undistorted_cache(user, flag)) {
620                 ibuf= get_undistorted_cache(clip, user);
621                 if(!ibuf)
622                         cache_undistorted= 1;
623         }
624
625         ibuf= get_imbuf_cache(clip, user, flag);
626
627         if(!ibuf) {
628                 if(clip->source==MCLIP_SRC_SEQUENCE) {
629                         ibuf= movieclip_load_sequence_file(clip, user, framenr, flag);
630                 } else {
631                         ibuf= movieclip_load_movie_file(clip, user, framenr, flag);
632                 }
633
634                 if(ibuf) {
635                         int bits= MCLIP_USE_PROXY|MCLIP_USE_PROXY_CUSTOM_DIR;
636
637                         if((flag&bits)==(clip->flag&bits))
638                                 put_imbuf_cache(clip, user, ibuf, clip->flag);
639                 }
640         }
641
642         /* put undistorted frame to cache */
643         if(ibuf && cache_undistorted) {
644                 ImBuf *tmpibuf= ibuf;
645                 ibuf= put_undistorted_cache(clip, user, tmpibuf);
646                 IMB_freeImBuf(tmpibuf);
647         }
648
649         BLI_unlock_thread(LOCK_MOVIECLIP);
650
651         return ibuf;
652 }
653
654 ImBuf *BKE_movieclip_get_stable_ibuf(MovieClip *clip, MovieClipUser *user, float loc[2], float *scale, float *angle)
655 {
656         ImBuf *ibuf, *stableibuf= NULL;
657         int framenr= user->framenr;
658
659         ibuf= BKE_movieclip_get_ibuf(clip, user);
660
661         if(!ibuf)
662                 return NULL;
663
664         if(clip->tracking.stabilization.flag&TRACKING_2D_STABILIZATION) {
665                 float tloc[2], tscale, tangle;
666                 short proxy= IMB_PROXY_NONE;
667                 int render_flag= 0;
668
669                 if(clip->flag&MCLIP_USE_PROXY) {
670                         proxy= rendersize_to_proxy(user, clip->flag);
671                         render_flag= user->render_flag;
672                 }
673
674                 if(clip->cache->stableibuf && clip->cache->stable_framenr==framenr) {   /* there's cached ibuf */
675                         if(clip->cache->render_flag==render_flag && clip->cache->proxy==proxy) {        /* cached ibuf used the same proxy settings */
676                                 stableibuf= clip->cache->stableibuf;
677
678                                 BKE_tracking_stabilization_data(&clip->tracking, framenr, stableibuf->x, stableibuf->y, tloc, &tscale, &tangle);
679
680                                 /* check for stabilization parameters */
681                                 if(!equals_v2v2(tloc, clip->cache->stable_loc) || tscale!=clip->cache->stable_scale || tangle!=clip->cache->stable_angle) {
682                                         stableibuf= NULL;
683                                 }
684                         }
685                 }
686
687                 if(!stableibuf) {
688                         if(clip->cache->stableibuf)
689                                 IMB_freeImBuf(clip->cache->stableibuf);
690
691                         stableibuf= BKE_tracking_stabilize(&clip->tracking, framenr, ibuf, tloc, &tscale, &tangle);
692
693                         copy_v2_v2(clip->cache->stable_loc, tloc);
694                         clip->cache->stable_scale= tscale;
695                         clip->cache->stable_angle= tangle;
696                         clip->cache->stable_framenr= framenr;
697                         clip->cache->stableibuf= stableibuf;
698                         clip->cache->proxy= proxy;
699                         clip->cache->render_flag= render_flag;
700                 }
701
702                 IMB_refImBuf(stableibuf);
703
704                 if(loc)         copy_v2_v2(loc, tloc);
705                 if(scale)       *scale= tscale;
706                 if(angle)       *angle= tangle;
707         } else {
708                 if(loc)         zero_v2(loc);
709                 if(scale)       *scale= 1.0f;
710                 if(angle)       *angle= 0.0f;
711
712                 stableibuf= ibuf;
713         }
714
715         if(stableibuf!=ibuf) {
716                 IMB_freeImBuf(ibuf);
717                 ibuf= stableibuf;
718         }
719
720         return ibuf;
721
722 }
723
724 int BKE_movieclip_has_frame(MovieClip *clip, MovieClipUser *user)
725 {
726         ImBuf *ibuf= BKE_movieclip_get_ibuf(clip, user);
727
728         if(ibuf) {
729                 IMB_freeImBuf(ibuf);
730                 return 1;
731         }
732
733         return 0;
734 }
735
736 void BKE_movieclip_get_size(MovieClip *clip, MovieClipUser *user, int *width, int *height)
737 {
738         if(user->framenr==clip->lastframe) {
739                 *width= clip->lastsize[0];
740                 *height= clip->lastsize[1];
741         } else {
742                 ImBuf *ibuf= BKE_movieclip_get_ibuf(clip, user);
743
744                 if(ibuf && ibuf->x && ibuf->y) {
745                         real_ibuf_size(clip, user, ibuf, width, height);
746                 } else {
747                         *width= 0;
748                         *height= 0;
749                 }
750
751                 if(ibuf)
752                         IMB_freeImBuf(ibuf);
753         }
754 }
755
756 void BKE_movieclip_aspect(MovieClip *clip, float *aspx, float *aspy)
757 {
758         *aspx= *aspy= 1.0;
759
760         /* x is always 1 */
761         *aspy = clip->aspy/clip->aspx/clip->tracking.camera.pixel_aspect;
762 }
763
764 /* get segments of cached frames. useful for debugging cache policies */
765 void BKE_movieclip_get_cache_segments(MovieClip *clip, MovieClipUser *user, int *totseg_r, int **points_r)
766 {
767         *totseg_r= 0;
768         *points_r= NULL;
769
770         if(clip->cache) {
771                 int proxy= rendersize_to_proxy(user, clip->flag);
772
773                 IMB_moviecache_get_cache_segments(clip->cache->moviecache, proxy, user->render_flag, totseg_r, points_r);
774         }
775 }
776
777 void BKE_movieclip_user_set_frame(MovieClipUser *iuser, int framenr)
778 {
779         /* TODO: clamp framenr here? */
780
781         iuser->framenr= framenr;
782 }
783
784 static void free_buffers(MovieClip *clip)
785 {
786         if(clip->cache) {
787                 IMB_moviecache_free(clip->cache->moviecache);
788
789                 if(clip->cache->stableibuf)
790                         IMB_freeImBuf(clip->cache->stableibuf);
791
792                 if(clip->cache->undistibuf)
793                         IMB_freeImBuf(clip->cache->undistibuf);
794
795                 MEM_freeN(clip->cache);
796                 clip->cache= NULL;
797         }
798
799         if(clip->anim) {
800                 IMB_free_anim(clip->anim);
801                 clip->anim= FALSE;
802         }
803 }
804
805 void BKE_movieclip_reload(MovieClip *clip)
806 {
807         /* clear cache */
808         free_buffers(clip);
809
810         clip->tracking.stabilization.ok= 0;
811
812         /* update clip source */
813         if(BLI_testextensie_array(clip->name, imb_ext_movie)) clip->source= MCLIP_SRC_MOVIE;
814         else clip->source= MCLIP_SRC_SEQUENCE;
815 }
816
817 void BKE_movieclip_update_scopes(MovieClip *clip, MovieClipUser *user, MovieClipScopes *scopes)
818 {
819         if(scopes->ok) return;
820
821         if(scopes->track_preview) {
822                 IMB_freeImBuf(scopes->track_preview);
823                 scopes->track_preview= NULL;
824         }
825
826         scopes->marker= NULL;
827         scopes->track= NULL;
828
829         if(clip) {
830                 if(clip->tracking.act_track) {
831                         MovieTrackingTrack *track= clip->tracking.act_track;
832                         MovieTrackingMarker *marker= BKE_tracking_get_marker(track, user->framenr);
833
834                         if(marker->flag&MARKER_DISABLED) {
835                                 scopes->track_disabled= 1;
836                         } else {
837                                 ImBuf *ibuf= BKE_movieclip_get_ibuf(clip, user);
838
839                                 scopes->track_disabled= 0;
840
841                                 if(ibuf && ibuf->rect) {
842                                         ImBuf *tmpibuf;
843                                         MovieTrackingMarker undist_marker= *marker;
844
845                                         if(user->render_flag&MCLIP_PROXY_RENDER_UNDISTORT) {
846                                                 int width, height;
847                                                 float aspy= 1.0f/clip->tracking.camera.pixel_aspect;;
848
849                                                 BKE_movieclip_get_size(clip, user, &width, &height);
850
851                                                 undist_marker.pos[0]*= width;
852                                                 undist_marker.pos[1]*= height*aspy;
853
854                                                 BKE_tracking_invert_intrinsics(&clip->tracking, undist_marker.pos, undist_marker.pos);
855
856                                                 undist_marker.pos[0]/= width;
857                                                 undist_marker.pos[1]/= height*aspy;
858                                         }
859
860                                         tmpibuf= BKE_tracking_get_pattern_imbuf(ibuf, track, &undist_marker, 1, 1, scopes->track_pos, NULL);
861
862                                         if(tmpibuf->rect_float)
863                                                 IMB_rect_from_float(tmpibuf);
864
865                                         if(tmpibuf->rect)
866                                                 scopes->track_preview= tmpibuf;
867                                         else
868                                                 IMB_freeImBuf(tmpibuf);
869                                 }
870
871                                 IMB_freeImBuf(ibuf);
872                         }
873
874                         if((track->flag&TRACK_LOCKED)==0) {
875                                 scopes->marker= marker;
876                                 scopes->track= track;
877                                 scopes->slide_scale[0]= track->pat_max[0]-track->pat_min[0];
878                                 scopes->slide_scale[1]= track->pat_max[1]-track->pat_min[1];
879                         }
880                 }
881         }
882
883         scopes->framenr= user->framenr;
884         scopes->ok= 1;
885 }
886
887 static void movieclip_build_proxy_ibuf(MovieClip *clip, ImBuf *ibuf, int cfra, int proxy_render_size, int undistorted)
888 {
889         char name[FILE_MAX];
890         int quality, rectx, recty;
891         int size= size= rendersize_to_number(proxy_render_size);
892         ImBuf *scaleibuf;
893
894         get_proxy_fname(clip, proxy_render_size, undistorted, cfra, name);
895
896         rectx= ibuf->x*size/100.0f;
897         recty= ibuf->y*size/100.0f;
898
899         scaleibuf= IMB_dupImBuf(ibuf);
900
901         IMB_scaleImBuf(scaleibuf, (short)rectx, (short)recty);
902
903         quality= clip->proxy.quality;
904         scaleibuf->ftype= JPG | quality;
905
906         /* unsupported feature only confuses other s/w */
907         if(scaleibuf->planes==32)
908                 scaleibuf->planes= 24;
909
910         BLI_lock_thread(LOCK_MOVIECLIP);
911
912         BLI_make_existing_file(name);
913         if(IMB_saveiff(scaleibuf, name, IB_rect)==0)
914                 perror(name);
915
916         BLI_unlock_thread(LOCK_MOVIECLIP);
917
918         IMB_freeImBuf(scaleibuf);
919 }
920
921 void BKE_movieclip_build_proxy_frame(MovieClip *clip, struct MovieDistortion *distortion,
922                         int cfra, int *build_sizes, int build_count, int undistorted)
923 {
924         ImBuf *ibuf;
925         MovieClipUser user;
926
927         user.framenr= cfra;
928
929         ibuf= BKE_movieclip_get_ibuf_flag(clip, &user, 0);
930
931         if(ibuf) {
932                 ImBuf *tmpibuf= ibuf;
933                 int i;
934
935                 if(undistorted)
936                         tmpibuf= get_undistorted_ibuf(clip, distortion, ibuf);
937
938                 for(i= 0; i<build_count; i++)
939                         movieclip_build_proxy_ibuf(clip, tmpibuf, cfra, build_sizes[i], undistorted);
940
941                 IMB_freeImBuf(ibuf);
942
943                 if(tmpibuf!=ibuf)
944                         IMB_freeImBuf(tmpibuf);
945         }
946 }
947
948 void free_movieclip(MovieClip *clip)
949 {
950         free_buffers(clip);
951
952         BKE_tracking_free(&clip->tracking);
953 }
954
955 void unlink_movieclip(Main *bmain, MovieClip *clip)
956 {
957         bScreen *scr;
958         ScrArea *area;
959         SpaceLink *sl;
960         Scene *sce;
961         Object *ob;
962
963         for(scr= bmain->screen.first; scr; scr= scr->id.next) {
964                 for(area= scr->areabase.first; area; area= area->next) {
965                         for(sl= area->spacedata.first; sl; sl= sl->next) {
966                                 if(sl->spacetype==SPACE_CLIP) {
967                                         SpaceClip *sc= (SpaceClip *) sl;
968
969                                         if(sc->clip==clip)
970                                                 sc->clip= NULL;
971                                 }
972                                 else if(sl->spacetype==SPACE_VIEW3D) {
973                                         View3D *v3d= (View3D *) sl;
974                                         BGpic *bgpic;
975
976                                         for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next) {
977                                                 if(bgpic->clip==clip)
978                                                         bgpic->clip= NULL;
979                                         }
980                                 }
981                         }
982                 }
983         }
984
985         for(sce= bmain->scene.first; sce; sce= sce->id.next) {
986                 if(sce->clip==clip)
987                         sce->clip= NULL;
988         }
989
990         for(ob= bmain->object.first; ob; ob= ob->id.next) {
991                 bConstraint *con;
992
993                 for(con= ob->constraints.first; con; con= con->next) {
994                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
995
996                         if(cti->type==CONSTRAINT_TYPE_FOLLOWTRACK) {
997                                 bFollowTrackConstraint *data= (bFollowTrackConstraint *) con->data;
998
999                                 if(data->clip==clip)
1000                                         data->clip= NULL;
1001                         }
1002                         else if(cti->type==CONSTRAINT_TYPE_CAMERASOLVER) {
1003                                 bCameraSolverConstraint *data= (bCameraSolverConstraint *) con->data;
1004
1005                                 if(data->clip==clip)
1006                                         data->clip= NULL;
1007                         }
1008                 }
1009         }
1010
1011         clip->id.us= 0;
1012 }