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