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