svn merge ^/trunk/blender -r42973:42991
[blender.git] / source / blender / blenkernel / intern / tracking.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/tracking.c
28  *  \ingroup bke
29  */
30
31 #include <stddef.h>
32 #include <limits.h>
33 #include <math.h>
34 #include <memory.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "DNA_gpencil_types.h"
39 #include "DNA_camera_types.h"
40 #include "DNA_movieclip_types.h"
41 #include "DNA_object_types.h"   /* SELECT */
42 #include "DNA_scene_types.h"
43
44 #include "BLI_utildefines.h"
45 #include "BLI_math.h"
46 #include "BLI_math_base.h"
47 #include "BLI_listbase.h"
48 #include "BLI_ghash.h"
49 #include "BLI_path_util.h"
50 #include "BLI_string.h"
51 #include "BLI_threads.h"
52
53 #include "BKE_global.h"
54 #include "BKE_tracking.h"
55 #include "BKE_movieclip.h"
56 #include "BKE_object.h"
57 #include "BKE_scene.h"
58
59 #include "IMB_imbuf_types.h"
60 #include "IMB_imbuf.h"
61
62 #ifdef WITH_LIBMV
63 #  include "libmv-capi.h"
64 #else
65 struct libmv_Features;
66 #endif
67
68 typedef struct MovieDistortion {
69         struct libmv_CameraIntrinsics *intrinsics;
70 } MovieDistortion;
71
72 /*********************** common functions *************************/
73
74 void BKE_tracking_init_settings(MovieTracking *tracking)
75 {
76         tracking->camera.sensor_width= 35.0f;
77         tracking->camera.pixel_aspect= 1.0f;
78         tracking->camera.units= CAMERA_UNITS_MM;
79
80         tracking->settings.default_tracker= TRACKER_HYBRID;
81         tracking->settings.default_minimum_correlation= 0.75;
82         tracking->settings.default_pattern_size= 11;
83         tracking->settings.default_search_size= 51;
84         tracking->settings.default_pyramid_levels= 2;
85         tracking->settings.keyframe1= 1;
86         tracking->settings.keyframe2= 30;
87         tracking->settings.dist= 1;
88
89         tracking->stabilization.scaleinf= 1.0f;
90         tracking->stabilization.locinf= 1.0f;
91         tracking->stabilization.rotinf= 1.0f;
92         tracking->stabilization.maxscale= 2.0f;
93 }
94
95 void BKE_tracking_clamp_track(MovieTrackingTrack *track, int event)
96 {
97         int a;
98         float pat_min[2];
99         float pat_max[2];
100         float max_pyramid_level_factor = 1.0;
101
102         if (track->tracker == TRACKER_KLT) {
103                 max_pyramid_level_factor= 1 << (track->pyramid_levels - 1);
104         }
105
106         /* sort */
107         for(a= 0; a<2; a++) {
108                 if(track->pat_min[a]>track->pat_max[a])
109                         SWAP(float, track->pat_min[a], track->pat_max[a]);
110
111                 if(track->search_min[a]>track->search_max[a])
112                         SWAP(float, track->search_min[a], track->search_max[a]);
113         }
114
115         /* compute the effective pattern size, which differs from the fine resolution
116          * pattern size for the pyramid KLT tracker */
117         for(a= 0; a<2; a++) {
118                 pat_min[a] = max_pyramid_level_factor * track->pat_min[a];
119                 pat_max[a] = max_pyramid_level_factor * track->pat_max[a];
120         }
121
122         if(event==CLAMP_PAT_DIM) {
123                 for(a= 0; a<2; a++) {
124                         /* search shouldn't be resized smaller than pattern */
125                         track->search_min[a]= MIN2(pat_min[a], track->search_min[a]);
126                         track->search_max[a]= MAX2(pat_max[a], track->search_max[a]);
127                 }
128         }
129         else if(event==CLAMP_PAT_POS) {
130                 float dim[2];
131                 sub_v2_v2v2(dim, track->pat_max, track->pat_min);
132
133                 for(a= 0; a<2; a++) {
134                         /* pattern shouldn't be moved outside of search */
135                         if(pat_min[a] < track->search_min[a]) {
136                                 track->pat_min[a]= track->search_min[a] - (pat_min[a] - track->pat_min[a]);
137                                 track->pat_max[a]= track->pat_min[a] + dim[a];
138                         }
139                         if(track->pat_max[a] > track->search_max[a]) {
140                                 track->pat_max[a]= track->search_max[a] - (pat_max[a] - track->pat_max[a]);
141                                 track->pat_min[a]= track->pat_max[a] - dim[a];
142                         }
143                 }
144         }
145         else if(event==CLAMP_SEARCH_DIM) {
146                 for(a= 0; a<2; a++) {
147                         /* search shouldn't be resized smaller than pattern */
148                         track->search_min[a]= MIN2(pat_min[a], track->search_min[a]);
149                         track->search_max[a]= MAX2(pat_max[a], track->search_max[a]);
150                 }
151         }
152         else if(event==CLAMP_SEARCH_POS) {
153                 float dim[2];
154                 sub_v2_v2v2(dim, track->search_max, track->search_min);
155
156                 for(a= 0; a<2; a++) {
157                         /* search shouldn't be moved inside pattern */
158                         if(track->search_min[a] > pat_min[a]) {
159                                 track->search_min[a]= pat_min[a];
160                                 track->search_max[a]= track->search_min[a]+dim[a];
161                         }
162                         if(track->search_max[a] < pat_max[a]) {
163                                 track->search_max[a]= pat_max[a];
164                                 track->search_min[a]= track->search_max[a]-dim[a];
165                         }
166                 }
167         }
168         else if(event==CLAMP_PYRAMID_LEVELS || (event==CLAMP_SEARCH_DIM && track->tracker == TRACKER_KLT))  {
169                 float dim[2];
170                 sub_v2_v2v2(dim, track->pat_max, track->pat_min);
171                 {
172                         float search_ratio= 2.3f * max_pyramid_level_factor;
173
174                         /* resize the search area to something sensible based
175                          * on the number of pyramid levels */
176                         for(a= 0; a<2; a++) {
177                                 track->search_min[a]= search_ratio * track->pat_min[a];
178                                 track->search_max[a]= search_ratio * track->pat_max[a];
179                         }
180                 }
181         }
182
183         /* marker's center should be in center of pattern */
184         if(event==CLAMP_PAT_DIM || event==CLAMP_PAT_POS) {
185                 float dim[2];
186                 sub_v2_v2v2(dim, track->pat_max, track->pat_min);
187
188                 for(a= 0; a<2; a++) {
189                         track->pat_min[a]= -dim[a]/2.0f;
190                         track->pat_max[a]= dim[a]/2.0f;
191                 }
192         }
193 }
194
195 void BKE_tracking_track_flag(MovieTrackingTrack *track, int area, int flag, int clear)
196 {
197         if(area==TRACK_AREA_NONE)
198                 return;
199
200         if(clear) {
201                 if(area&TRACK_AREA_POINT)       track->flag&= ~flag;
202                 if(area&TRACK_AREA_PAT)         track->pat_flag&= ~flag;
203                 if(area&TRACK_AREA_SEARCH)      track->search_flag&= ~flag;
204         } else {
205                 if(area&TRACK_AREA_POINT)       track->flag|= flag;
206                 if(area&TRACK_AREA_PAT)         track->pat_flag|= flag;
207                 if(area&TRACK_AREA_SEARCH)      track->search_flag|= flag;
208         }
209 }
210
211 MovieTrackingTrack *BKE_tracking_add_track(MovieTracking *tracking, float x, float y,
212                         int framenr, int width, int height)
213 {
214         MovieTrackingTrack *track;
215         MovieTrackingMarker marker;
216         MovieTrackingSettings *settings= &tracking->settings;
217
218         float half_pattern= (float)settings->default_pattern_size/2.0f;
219         float half_search= (float)settings->default_search_size/2.0f;
220         float pat[2], search[2];
221
222         pat[0]= half_pattern/(float)width;
223         pat[1]= half_pattern/(float)height;
224
225         search[0]= half_search/(float)width;
226         search[1]= half_search/(float)height;
227
228         track= MEM_callocN(sizeof(MovieTrackingTrack), "add_marker_exec track");
229         strcpy(track->name, "Track");
230
231         track->tracker= settings->default_tracker;
232         track->pyramid_levels= settings->default_pyramid_levels;
233         track->minimum_correlation= settings->default_minimum_correlation;
234         track->margin= settings->default_margin;
235         track->pattern_match= settings->default_pattern_match;
236         track->frames_limit= settings->default_frames_limit;
237
238         memset(&marker, 0, sizeof(marker));
239         marker.pos[0]= x;
240         marker.pos[1]= y;
241         marker.framenr= framenr;
242
243         copy_v2_v2(track->pat_max, pat);
244         negate_v2_v2(track->pat_min, pat);
245
246         copy_v2_v2(track->search_max, search);
247         negate_v2_v2(track->search_min, search);
248
249         BKE_tracking_insert_marker(track, &marker);
250
251         if(track->tracker == TRACKER_KLT)
252                 BKE_tracking_clamp_track(track, CLAMP_PYRAMID_LEVELS);
253
254         BLI_addtail(&tracking->tracks, track);
255         BKE_track_unique_name(tracking, track);
256
257         return track;
258 }
259
260 void BKE_tracking_insert_marker(MovieTrackingTrack *track, MovieTrackingMarker *marker)
261 {
262         MovieTrackingMarker *old_marker= NULL;
263
264         if(track->markersnr)
265                 old_marker= BKE_tracking_exact_marker(track, marker->framenr);
266
267         if(old_marker) {
268                 *old_marker= *marker;
269         } else {
270                 int a= track->markersnr;
271
272                 while(a--) {
273                         if(track->markers[a].framenr<marker->framenr)
274                                 break;
275                 }
276
277                 track->markersnr++;
278
279                 if(track->markers) track->markers= MEM_reallocN(track->markers, sizeof(MovieTrackingMarker)*track->markersnr);
280                 else track->markers= MEM_callocN(sizeof(MovieTrackingMarker), "MovieTracking markers");
281
282                 memmove(track->markers+a+2, track->markers+a+1, (track->markersnr-a-2)*sizeof(MovieTrackingMarker));
283                 track->markers[a+1]= *marker;
284
285                 track->last_marker= a+1;
286         }
287 }
288
289 void BKE_tracking_delete_marker(MovieTrackingTrack *track, int framenr)
290 {
291         int a= 0;
292
293         while(a<track->markersnr) {
294                 if(track->markers[a].framenr==framenr) {
295                         if(track->markersnr>1) {
296                                 memmove(track->markers+a, track->markers+a+1, (track->markersnr-a-1)*sizeof(MovieTrackingMarker));
297                                 track->markersnr--;
298                                 track->markers= MEM_reallocN(track->markers, sizeof(MovieTrackingMarker)*track->markersnr);
299                         } else {
300                                 MEM_freeN(track->markers);
301                                 track->markers= NULL;
302                                 track->markersnr= 0;
303                         }
304
305                         break;
306                 }
307
308                 a++;
309         }
310 }
311
312 MovieTrackingMarker *BKE_tracking_get_marker(MovieTrackingTrack *track, int framenr)
313 {
314         int a= track->markersnr-1;
315
316         if(!track->markersnr)
317                 return NULL;
318
319         /* approximate pre-first framenr marker with first marker */
320         if(framenr<track->markers[0].framenr)
321                 return &track->markers[0];
322
323         if(track->last_marker<track->markersnr)
324                 a= track->last_marker;
325
326         if(track->markers[a].framenr<=framenr) {
327                 while(a<track->markersnr && track->markers[a].framenr<=framenr) {
328                         if(track->markers[a].framenr==framenr) {
329                                 track->last_marker= a;
330                                 return &track->markers[a];
331                         }
332                         a++;
333                 }
334
335                 /* if there's no marker for exact position, use nearest marker from left side */
336                 return &track->markers[a-1];
337         } else {
338                 while(a>=0 && track->markers[a].framenr>=framenr) {
339                         if(track->markers[a].framenr==framenr) {
340                                 track->last_marker= a;
341                                 return &track->markers[a];
342                         }
343
344                         a--;
345                 }
346
347                 /* if there's no marker for exact position, use nearest marker from left side */
348                 return &track->markers[a];
349         }
350
351         return NULL;
352 }
353
354 MovieTrackingMarker *BKE_tracking_ensure_marker(MovieTrackingTrack *track, int framenr)
355 {
356         MovieTrackingMarker *marker= BKE_tracking_get_marker(track, framenr);
357
358         if(marker->framenr!=framenr) {
359                 MovieTrackingMarker marker_new;
360
361                 marker_new= *marker;
362                 marker_new.framenr= framenr;
363
364                 BKE_tracking_insert_marker(track, &marker_new);
365                 marker= BKE_tracking_get_marker(track, framenr);
366         }
367
368         return marker;
369 }
370
371 MovieTrackingMarker *BKE_tracking_exact_marker(MovieTrackingTrack *track, int framenr)
372 {
373         MovieTrackingMarker *marker= BKE_tracking_get_marker(track, framenr);
374
375         if(marker->framenr!=framenr)
376                 return NULL;
377
378         return marker;
379 }
380
381 int BKE_tracking_has_marker(MovieTrackingTrack *track, int framenr)
382 {
383         return BKE_tracking_exact_marker(track, framenr) != 0;
384 }
385
386 void BKE_tracking_free_track(MovieTrackingTrack *track)
387 {
388         if(track->markers) MEM_freeN(track->markers);
389 }
390
391 static void put_disabled_marker(MovieTrackingTrack *track, MovieTrackingMarker *ref_marker, int before, int overwrite)
392 {
393         MovieTrackingMarker marker_new;
394
395         marker_new= *ref_marker;
396         marker_new.flag&= ~MARKER_TRACKED;
397         marker_new.flag|= MARKER_DISABLED;
398
399         if(before) marker_new.framenr--;
400         else marker_new.framenr++;
401
402         if(!BKE_tracking_has_marker(track, marker_new.framenr) || overwrite)
403                 BKE_tracking_insert_marker(track, &marker_new);
404 }
405
406 void BKE_tracking_clear_path(MovieTrackingTrack *track, int ref_frame, int action)
407 {
408         int a;
409
410         if(action==TRACK_CLEAR_REMAINED) {
411                 a= 1;
412                 while(a<track->markersnr) {
413                         if(track->markers[a].framenr>ref_frame) {
414                                 track->markersnr= a;
415                                 track->markers= MEM_reallocN(track->markers, sizeof(MovieTrackingMarker)*track->markersnr);
416
417                                 break;
418                         }
419
420                         a++;
421                 }
422
423                 if(track->markersnr)
424                         put_disabled_marker(track, &track->markers[track->markersnr-1], 0, 1);
425         } else if(action==TRACK_CLEAR_UPTO) {
426                 a= track->markersnr-1;
427                 while(a>=0) {
428                         if(track->markers[a].framenr<=ref_frame) {
429                                 memmove(track->markers, track->markers+a, (track->markersnr-a)*sizeof(MovieTrackingMarker));
430
431                                 track->markersnr= track->markersnr-a;
432                                 track->markers= MEM_reallocN(track->markers, sizeof(MovieTrackingMarker)*track->markersnr);
433
434                                 break;
435                         }
436
437                         a--;
438                 }
439
440                 if(track->markersnr)
441                         put_disabled_marker(track, &track->markers[0], 1, 1);
442         } else if(action==TRACK_CLEAR_ALL) {
443                 MovieTrackingMarker *marker, marker_new;
444
445                 marker= BKE_tracking_get_marker(track, ref_frame);
446                 marker_new= *marker;
447
448                 MEM_freeN(track->markers);
449                 track->markers= NULL;
450                 track->markersnr= 0;
451
452                 BKE_tracking_insert_marker(track, &marker_new);
453
454                 put_disabled_marker(track, &marker_new, 1, 1);
455                 put_disabled_marker(track, &marker_new, 0, 1);
456         }
457 }
458
459 int BKE_tracking_test_join_tracks(MovieTrackingTrack *dst_track, MovieTrackingTrack *src_track)
460 {
461         int a= 0, b= 0;
462         int count= 0;
463
464         while(a<src_track->markersnr || b<dst_track->markersnr) {
465                 if(b>=dst_track->markersnr) {
466                         a++;
467                         count++;
468                 }
469                 else if(a>=src_track->markersnr) {
470                         b++;
471                         count++;
472                 }
473                 else if(src_track->markers[a].framenr<dst_track->markers[b].framenr) {
474                         a++;
475                         count++;
476                 } else if(src_track->markers[a].framenr>dst_track->markers[b].framenr) {
477                         b++;
478                         count++;
479                 } else {
480                         if((src_track->markers[a].flag&MARKER_DISABLED)==0 && (dst_track->markers[b].flag&MARKER_DISABLED)==0)
481                                 return 0;
482
483                         a++;
484                         b++;
485                         count++;
486                 }
487         }
488
489         return count;
490 }
491
492 void BKE_tracking_join_tracks(MovieTrackingTrack *dst_track, MovieTrackingTrack *src_track)
493 {
494         int i, a= 0, b= 0, tot;
495         MovieTrackingMarker *markers;
496
497         tot= BKE_tracking_test_join_tracks(dst_track, src_track);
498
499         markers= MEM_callocN(tot*sizeof(MovieTrackingMarker), "tracking joined tracks");
500
501         for(i= 0; i<tot; i++) {
502                 if(b>=dst_track->markersnr) {
503                         markers[i]= src_track->markers[a++];
504                 }
505                 else if(a>=src_track->markersnr) {
506                         markers[i]= dst_track->markers[b++];
507                 }
508                 else if(src_track->markers[a].framenr<dst_track->markers[b].framenr) {
509                         markers[i]= src_track->markers[a++];
510                 } else if(src_track->markers[a].framenr>dst_track->markers[b].framenr) {
511                         markers[i]= dst_track->markers[b++];
512                 } else {
513                         if((src_track->markers[a].flag&MARKER_DISABLED)) markers[i]= dst_track->markers[b];
514                         else markers[i]= src_track->markers[a++];
515
516                         a++;
517                         b++;
518                 }
519         }
520
521         MEM_freeN(dst_track->markers);
522
523         dst_track->markers= markers;
524         dst_track->markersnr= tot;
525 }
526
527 void BKE_tracking_free(MovieTracking *tracking)
528 {
529         MovieTrackingTrack *track;
530
531         for(track= tracking->tracks.first; track; track= track->next) {
532                 BKE_tracking_free_track(track);
533         }
534
535         BLI_freelistN(&tracking->tracks);
536
537         if(tracking->reconstruction.cameras)
538                 MEM_freeN(tracking->reconstruction.cameras);
539
540         if(tracking->stabilization.scaleibuf)
541                 IMB_freeImBuf(tracking->stabilization.scaleibuf);
542
543         if(tracking->camera.intrinsics)
544                 BKE_tracking_distortion_destroy(tracking->camera.intrinsics);
545 }
546
547 /*********************** tracks map *************************/
548
549 typedef struct TracksMap {
550         int num_tracks;
551         int customdata_size;
552
553         char *customdata;
554         MovieTrackingTrack *tracks;
555
556         GHash *hash;
557
558         int ptr;
559 } TracksMap;
560
561 static TracksMap *tracks_map_new(int num_tracks, int customdata_size)
562 {
563         TracksMap *map= MEM_callocN(sizeof(TracksMap), "TrackingsMap");
564
565         map->num_tracks= num_tracks;
566         map->customdata_size= customdata_size;
567
568         map->tracks= MEM_callocN(sizeof(MovieTrackingTrack)*num_tracks, "TrackingsMap tracks");
569
570         if(customdata_size)
571                 map->customdata= MEM_callocN(customdata_size*num_tracks, "TracksMap customdata");
572
573         map->hash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "TracksMap hash");
574
575         return map;
576 }
577
578 static int tracks_map_size(TracksMap *map)
579 {
580         return map->num_tracks;
581 }
582
583 static void tracks_map_get(TracksMap *map, int index, MovieTrackingTrack **track, void **customdata)
584 {
585         *track= &map->tracks[index];
586
587         if(map->customdata)
588                 *customdata= &map->customdata[index*map->customdata_size];
589 }
590
591 static void tracks_map_insert(TracksMap *map, MovieTrackingTrack *track, void *customdata)
592 {
593         MovieTrackingTrack new_track= *track;
594
595         new_track.markers= MEM_dupallocN(new_track.markers);
596
597         map->tracks[map->ptr]= new_track;
598
599         if(customdata)
600                 memcpy(&map->customdata[map->ptr*map->customdata_size], customdata, map->customdata_size);
601
602         BLI_ghash_insert(map->hash, &map->tracks[map->ptr], track);
603
604         map->ptr++;
605 }
606
607 static void tracks_map_merge(TracksMap *map, MovieTracking *tracking)
608 {
609         MovieTrackingTrack *track;
610         ListBase tracks= {NULL, NULL}, new_tracks= {NULL, NULL};
611         ListBase *old_tracks= &tracking->tracks;
612         int a;
613
614         /* duplicate currently operating tracks to temporary list.
615            this is needed to keep names in unique state and it's faster to change names
616            of currently operating tracks (if needed) */
617         for(a= 0; a<map->num_tracks; a++) {
618                 int replace_sel= 0;
619                 MovieTrackingTrack *new_track, *old;
620
621                 track= &map->tracks[a];
622
623                 /* find original of operating track in list of previously displayed tracks */
624                 old= BLI_ghash_lookup(map->hash, track);
625                 if(old) {
626                         MovieTrackingTrack *cur= old_tracks->first;
627
628                         while(cur) {
629                                 if(cur==old)
630                                         break;
631
632                                 cur= cur->next;
633                         }
634
635                         /* original track was found, re-use flags and remove this track */
636                         if(cur) {
637                                 if(cur==tracking->act_track)
638                                         replace_sel= 1;
639
640                                 track->flag= cur->flag;
641                                 track->pat_flag= cur->pat_flag;
642                                 track->search_flag= cur->search_flag;
643
644                                 BKE_tracking_free_track(cur);
645                                 BLI_freelinkN(old_tracks, cur);
646                         }
647                 }
648
649                 new_track= MEM_callocN(sizeof(MovieTrackingTrack), "tracksMapMerge new_track");
650                 *new_track= *track;
651                 new_track->markers= MEM_dupallocN(new_track->markers);
652
653                 BLI_ghash_remove(map->hash, track, NULL, NULL); /* XXX: are we actually need this */
654                 BLI_ghash_insert(map->hash, track, new_track);
655
656                 if(replace_sel)         /* update current selection in clip */
657                         tracking->act_track= new_track;
658
659                 BLI_addtail(&tracks, new_track);
660         }
661
662         /* move all tracks, which aren't operating */
663         track= old_tracks->first;
664         while(track) {
665                 MovieTrackingTrack *next= track->next;
666
667                 track->next= track->prev= NULL;
668                 BLI_addtail(&new_tracks, track);
669
670                 track= next;
671         }
672
673         /* now move all tracks which are currently operating and keep their names unique */
674         track= tracks.first;
675         while(track) {
676                 MovieTrackingTrack *next= track->next;
677
678                 BLI_remlink(&tracks, track);
679
680                 track->next= track->prev= NULL;
681                 BLI_addtail(&new_tracks, track);
682
683                 BLI_uniquename(&new_tracks, track, "Track", '.', offsetof(MovieTrackingTrack, name), sizeof(track->name));
684
685                 track= next;
686         }
687
688         tracking->tracks= new_tracks;
689 }
690
691 static void tracks_map_free(TracksMap *map, void (*customdata_free) (void *customdata))
692 {
693         int i= 0;
694
695         BLI_ghash_free(map->hash, NULL, NULL);
696
697         for(i= 0; i<map->num_tracks; i++) {
698                 if(map->customdata && customdata_free)
699                         customdata_free(&map->customdata[i*map->customdata_size]);
700
701                 BKE_tracking_free_track(&map->tracks[i]);
702         }
703
704         if(map->customdata)
705                 MEM_freeN(map->customdata);
706
707         MEM_freeN(map->tracks);
708         MEM_freeN(map);
709 }
710
711 /*********************** tracking *************************/
712
713 typedef struct TrackContext {
714 #ifdef WITH_LIBMV
715         float keyframed_pos[2];
716
717         /* ** KLT tracker ** */
718         struct libmv_RegionTracker *region_tracker;
719         float *patch;                   /* keyframed patch */
720
721         /* ** SAD tracker ** */
722         int pattern_size;               /* size of pattern */
723         unsigned char *pattern; /* keyframed pattern */
724         unsigned char *warped;  /* warped version of reference */
725 #else
726         int pad;
727 #endif
728 } TrackContext;
729
730 typedef struct MovieTrackingContext {
731         MovieClipUser user;
732         MovieClip *clip;
733         int clip_flag;
734
735         int first_time, frames;
736
737         MovieTrackingSettings settings;
738         TracksMap *tracks_map;
739
740         short backwards, disable_failed, sequence;
741         int sync_frame;
742 } MovieTrackingContext;
743
744 MovieTrackingContext *BKE_tracking_context_new(MovieClip *clip, MovieClipUser *user, short backwards, short disable_failed, short sequence)
745 {
746         MovieTrackingContext *context= MEM_callocN(sizeof(MovieTrackingContext), "trackingContext");
747         MovieTracking *tracking= &clip->tracking;
748         MovieTrackingSettings *settings= &tracking->settings;
749         MovieTrackingTrack *track;
750         int num_tracks= 0;
751
752         context->settings= *settings;
753         context->backwards= backwards;
754         context->disable_failed= disable_failed;
755         context->sync_frame= user->framenr;
756         context->first_time= 1;
757         context->sequence= sequence;
758
759         /* count */
760         track= tracking->tracks.first;
761         while(track) {
762                 if(TRACK_SELECTED(track) && (track->flag&TRACK_LOCKED)==0) {
763                         MovieTrackingMarker *marker= BKE_tracking_get_marker(track, user->framenr);
764
765                         if((marker->flag&MARKER_DISABLED)==0)
766                                 num_tracks++;
767                 }
768
769                 track= track->next;
770         }
771
772         if(num_tracks) {
773                 int width, height;
774
775                 context->tracks_map= tracks_map_new(num_tracks, sizeof(TrackContext));
776
777                 BKE_movieclip_get_size(clip, user, &width, &height);
778
779                 /* create tracking data */
780                 track= tracking->tracks.first;
781                 while(track) {
782                         if(TRACK_SELECTED(track) && (track->flag&TRACK_LOCKED)==0) {
783                                 MovieTrackingMarker *marker= BKE_tracking_get_marker(track, user->framenr);
784
785                                 if((marker->flag&MARKER_DISABLED)==0) {
786                                         TrackContext track_context;
787
788                                         memset(&track_context, 0, sizeof(TrackContext));
789
790 #ifdef WITH_LIBMV
791                                         {
792                                                 float patx, paty;
793                                                 patx= (int)((track->pat_max[0]-track->pat_min[0])*width);
794                                                 paty= (int)((track->pat_max[1]-track->pat_min[1])*height);
795
796                                                 if(ELEM(track->tracker, TRACKER_KLT, TRACKER_HYBRID)) {
797                                                         float search_size_x= (track->search_max[0]-track->search_min[0])*width;
798                                                         float search_size_y= (track->search_max[1]-track->search_min[1])*height;
799                                                         float pattern_size_x= (track->pat_max[0]-track->pat_min[0])*width;
800                                                         float pattern_size_y= (track->pat_max[1]-track->pat_min[1])*height;
801                                                         int wndx= (int)patx/2, wndy= (int)paty/2;
802
803                                                         /* compute the maximum pyramid size */
804                                                         float search_to_pattern_ratio= MIN2(search_size_x,  search_size_y)
805                                                                 / MAX2(pattern_size_x, pattern_size_y);
806                                                         float log2_search_to_pattern_ratio = log(floor(search_to_pattern_ratio)) / M_LN2;
807                                                         int max_pyramid_levels= floor(log2_search_to_pattern_ratio + 1);
808
809                                                         /* try to accomodate the user's choice of pyramid level in a way
810                                                          * that doesn't cause the coarsest pyramid pattern to be larger
811                                                          * than the search size */
812                                                         int level= MIN2(track->pyramid_levels, max_pyramid_levels);
813
814                                                         if(track->tracker==TRACKER_KLT)
815                                                                 track_context.region_tracker= libmv_pyramidRegionTrackerNew(100, level, MAX2(wndx, wndy), track->minimum_correlation);
816                                                         else
817                                                                 track_context.region_tracker= libmv_hybridRegionTrackerNew(100, MAX2(wndx, wndy), track->minimum_correlation);
818                                                 }
819                                                 else if(track->tracker==TRACKER_SAD) {
820                                                         track_context.pattern_size= MAX2(patx, paty);
821                                                 }
822                                         }
823 #endif
824
825                                         tracks_map_insert(context->tracks_map, track, &track_context);
826                                 }
827                         }
828
829                         track= track->next;
830                 }
831         }
832
833         context->clip= clip;
834
835         /* store needed clip flags passing to get_buffer functions
836          * - MCLIP_USE_PROXY is needed to because timecode affects on movie clip
837          *   only in case Proxy/Timecode flag is set, so store this flag to use
838          *   timecodes properly but reset render size to SIZE_FULL so correct resolution
839          *   would be used for images
840          * - MCLIP_USE_PROXY_CUSTOM_DIR is needed because proxy/timecode files might
841          *   be stored in a different location
842          * ignore all the rest pssible flags for now */
843         context->clip_flag= clip->flag&MCLIP_TIMECODE_FLAGS;
844
845         context->user= *user;
846         context->user.render_size= 0;
847         context->user.render_flag= MCLIP_PROXY_RENDER_SIZE_FULL;
848
849         if(!sequence)
850                 BLI_begin_threaded_malloc();
851
852         return context;
853 }
854
855 static void track_context_free(void *customdata)
856 {
857         TrackContext *track_context= (TrackContext *)customdata;
858
859 #if WITH_LIBMV
860         if(track_context->region_tracker)
861                 libmv_regionTrackerDestroy(track_context->region_tracker);
862
863         if(track_context->patch)
864                 MEM_freeN(track_context->patch);
865
866         if(track_context->pattern)
867                 MEM_freeN(track_context->pattern);
868
869         if(track_context->warped)
870                 MEM_freeN(track_context->warped);
871 #else
872                 (void) track_context;
873 #endif
874 }
875
876 void BKE_tracking_context_free(MovieTrackingContext *context)
877 {
878         if(!context->sequence)
879                 BLI_end_threaded_malloc();
880
881         tracks_map_free(context->tracks_map, track_context_free);
882
883         MEM_freeN(context);
884 }
885
886 static void disable_imbuf_channels(ImBuf *ibuf, MovieTrackingTrack *track)
887 {
888         int x, y;
889
890         if((track->flag&(TRACK_DISABLE_RED|TRACK_DISABLE_GREEN|TRACK_DISABLE_BLUE))==0)
891                 return;
892
893         for(y= 0; y<ibuf->y; y++) {
894                 for (x= 0; x<ibuf->x; x++) {
895                         int pixel= ibuf->x*y + x;
896
897                         if(ibuf->rect_float) {
898                                 float *rrgbf= ibuf->rect_float + pixel*4;
899
900                                 if(track->flag&TRACK_DISABLE_RED)       rrgbf[0]= 0;
901                                 if(track->flag&TRACK_DISABLE_GREEN)     rrgbf[1]= 0;
902                                 if(track->flag&TRACK_DISABLE_BLUE)      rrgbf[2]= 0;
903                         } else {
904                                 char *rrgb= (char*)ibuf->rect + pixel*4;
905
906                                 if(track->flag&TRACK_DISABLE_RED)       rrgb[0]= 0;
907                                 if(track->flag&TRACK_DISABLE_GREEN)     rrgb[1]= 0;
908                                 if(track->flag&TRACK_DISABLE_BLUE)      rrgb[2]= 0;
909                         }
910                 }
911         }
912 }
913
914 static ImBuf *get_area_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
915                         float min[2], float max[2], int margin, int anchored, float pos[2], int origin[2])
916 {
917         ImBuf *tmpibuf;
918         int x, y;
919         int x1, y1, x2, y2, w, h;
920         float mpos[2];
921
922         copy_v2_v2(mpos, marker->pos);
923         if(anchored)
924                 add_v2_v2(mpos, track->offset);
925
926         x= mpos[0]*ibuf->x;
927         y= mpos[1]*ibuf->y;
928         x1= x-(int)(-min[0]*ibuf->x);
929         y1= y-(int)(-min[1]*ibuf->y);
930         x2= x+(int)(max[0]*ibuf->x);
931         y2= y+(int)(max[1]*ibuf->y);
932
933         /* dimensions should be odd */
934         w= (x2-x1)|1;
935         h= (y2-y1)|1;
936
937         tmpibuf= IMB_allocImBuf(w+margin*2, h+margin*2, 32, IB_rect);
938         IMB_rectcpy(tmpibuf, ibuf, 0, 0, x1-margin, y1-margin, w+margin*2, h+margin*2);
939
940         if(pos != NULL) {
941                 pos[0]= mpos[0]*ibuf->x-x1+margin;
942                 pos[1]= mpos[1]*ibuf->y-y1+margin;
943         }
944
945         if(origin != NULL) {
946                 origin[0]= x1-margin;
947                 origin[1]= y1-margin;
948         }
949
950         disable_imbuf_channels(tmpibuf, track);
951
952         return tmpibuf;
953 }
954
955 ImBuf *BKE_tracking_get_pattern_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
956                         int margin, int anchored, float pos[2], int origin[2])
957 {
958         return get_area_imbuf(ibuf, track, marker, track->pat_min, track->pat_max, margin, anchored, pos, origin);
959 }
960
961 ImBuf *BKE_tracking_get_search_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
962                         int margin, int anchored, float pos[2], int origin[2])
963 {
964         return get_area_imbuf(ibuf, track, marker, track->search_min, track->search_max, margin, anchored, pos, origin);
965 }
966
967 #ifdef WITH_LIBMV
968 static float *get_search_floatbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
969                         int *width_r, int *height_r, float pos[2], int origin[2])
970 {
971         ImBuf *tmpibuf;
972         float *pixels, *fp;
973         int x, y, width, height;
974
975         width= (track->search_max[0]-track->search_min[0])*ibuf->x;
976         height= (track->search_max[1]-track->search_min[1])*ibuf->y;
977
978         tmpibuf= BKE_tracking_get_search_imbuf(ibuf, track, marker, 0, 0, pos, origin);
979         disable_imbuf_channels(tmpibuf, track);
980
981         *width_r= width;
982         *height_r= height;
983
984         fp= pixels= MEM_callocN(width*height*sizeof(float), "tracking floatBuf");
985         for(y= 0; y<(int)height; y++) {
986                 for (x= 0; x<(int)width; x++) {
987                         int pixel= tmpibuf->x*y + x;
988
989                         if(tmpibuf->rect_float) {
990                                 float *rrgbf= tmpibuf->rect_float + pixel*4;
991
992                                 *fp= 0.2126*rrgbf[0] + 0.7152*rrgbf[1] + 0.0722*rrgbf[2];
993                         } else {
994                                 unsigned char *rrgb= (unsigned char*)tmpibuf->rect + pixel*4;
995
996                                 *fp= (0.2126*rrgb[0] + 0.7152*rrgb[1] + 0.0722*rrgb[2])/255.0f;
997                         }
998
999                         fp++;
1000                 }
1001         }
1002
1003         IMB_freeImBuf(tmpibuf);
1004
1005         return pixels;
1006 }
1007
1008 static unsigned char *get_ucharbuf(ImBuf *ibuf)
1009 {
1010         int x, y;
1011         unsigned char *pixels, *cp;
1012
1013         cp= pixels= MEM_callocN(ibuf->x*ibuf->y*sizeof(unsigned char), "tracking ucharBuf");
1014         for(y= 0; y<ibuf->y; y++) {
1015                 for (x= 0; x<ibuf->x; x++) {
1016                         int pixel= ibuf->x*y + x;
1017
1018                         if(ibuf->rect_float) {
1019                                 float *rrgbf= ibuf->rect_float + pixel*4;
1020
1021                                 *cp= FTOCHAR(0.2126f*rrgbf[0] + 0.7152f*rrgbf[1] + 0.0722f*rrgbf[2]);
1022                         } else {
1023                                 unsigned char *rrgb= (unsigned char*)ibuf->rect + pixel*4;
1024
1025                                 *cp= 0.2126f*rrgb[0] + 0.7152f*rrgb[1] + 0.0722f*rrgb[2];
1026                         }
1027
1028                         cp++;
1029                 }
1030         }
1031
1032         return pixels;
1033 }
1034
1035 static unsigned char *get_search_bytebuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
1036                         int *width_r, int *height_r, float pos[2], int origin[2])
1037 {
1038         ImBuf *tmpibuf;
1039         unsigned char *pixels;
1040
1041         tmpibuf= BKE_tracking_get_search_imbuf(ibuf, track, marker, 0, 0, pos, origin);
1042         disable_imbuf_channels(tmpibuf, track);
1043
1044         *width_r= tmpibuf->x;
1045         *height_r= tmpibuf->y;
1046
1047         pixels= get_ucharbuf(tmpibuf);
1048
1049         IMB_freeImBuf(tmpibuf);
1050
1051         return pixels;
1052 }
1053
1054 static ImBuf *get_frame_ibuf(MovieTrackingContext *context, int framenr)
1055 {
1056         ImBuf *ibuf;
1057         MovieClipUser user= context->user;
1058
1059         user.framenr= framenr;
1060
1061         ibuf= BKE_movieclip_get_ibuf_flag(context->clip, &user, context->clip_flag);
1062
1063         return ibuf;
1064 }
1065
1066 static ImBuf *get_keyframed_ibuf(MovieTrackingContext *context, MovieTrackingTrack *track,
1067                         MovieTrackingMarker *marker, MovieTrackingMarker **marker_keyed)
1068 {
1069         int framenr= marker->framenr;
1070         int a= marker-track->markers;
1071
1072         *marker_keyed= marker;
1073
1074         while(a>=0 && a<track->markersnr) {
1075                 int next= (context->backwards) ? a+1 : a-1;
1076                 int is_keyframed= 0;
1077                 MovieTrackingMarker *cur_marker= &track->markers[a];
1078                 MovieTrackingMarker *next_marker= NULL;
1079
1080                 if(next>=0 && next<track->markersnr)
1081                         next_marker= &track->markers[next];
1082
1083                 /* if next mrker is disabled, stop searching keyframe and use current frame as keyframe */
1084                 if(next_marker && next_marker->flag&MARKER_DISABLED)
1085                         is_keyframed= 1;
1086
1087                 is_keyframed|= (cur_marker->flag&MARKER_TRACKED)==0;
1088
1089                 if(is_keyframed) {
1090                         framenr= cur_marker->framenr;
1091                         *marker_keyed= cur_marker;
1092                         break;
1093                 }
1094
1095                 a= next;
1096         }
1097
1098         return get_frame_ibuf(context, framenr);
1099 }
1100
1101 static ImBuf *get_adjust_ibuf(MovieTrackingContext *context, MovieTrackingTrack *track, MovieTrackingMarker *marker,
1102                         int curfra, MovieTrackingMarker **marker_keyed)
1103 {
1104         ImBuf *ibuf= NULL;
1105
1106         if(track->pattern_match == TRACK_MATCH_KEYFRAME) {
1107                 ibuf= get_keyframed_ibuf(context, track, marker, marker_keyed);
1108         } else {
1109                 ibuf= get_frame_ibuf(context, curfra);
1110
1111                 /* use current marker as keyframed position */
1112                 *marker_keyed= marker;
1113         }
1114
1115         return ibuf;
1116 }
1117
1118 static void get_warped(TrackContext *track_context, int x, int y, int width, unsigned char *image)
1119 {
1120         int i, j;
1121
1122         for(i=0; i<track_context->pattern_size; i++) {
1123                 for(j=0; j<track_context->pattern_size; j++) {
1124                         track_context->warped[i*track_context->pattern_size+j]=
1125                                         image[(y+i-track_context->pattern_size/2)*width+x+j-track_context->pattern_size/2];
1126                 }
1127         }
1128 }
1129
1130 #endif
1131
1132 void BKE_tracking_sync(MovieTrackingContext *context)
1133 {
1134         MovieTracking *tracking= &context->clip->tracking;
1135         int newframe;
1136
1137         tracks_map_merge(context->tracks_map, tracking);
1138
1139         if(context->backwards) newframe= context->user.framenr+1;
1140         else newframe= context->user.framenr-1;
1141
1142         context->sync_frame= newframe;
1143 }
1144
1145 void BKE_tracking_sync_user(MovieClipUser *user, MovieTrackingContext *context)
1146 {
1147         user->framenr= context->sync_frame;
1148 }
1149
1150 int BKE_tracking_next(MovieTrackingContext *context)
1151 {
1152         ImBuf *ibuf_new;
1153         int curfra= context->user.framenr;
1154         int a, ok= 0, map_size;
1155
1156         map_size= tracks_map_size(context->tracks_map);
1157
1158         /* nothing to track, avoid unneeded frames reading to save time and memory */
1159         if(!map_size)
1160                 return 0;
1161
1162         if(context->backwards) context->user.framenr--;
1163         else context->user.framenr++;
1164
1165         ibuf_new= BKE_movieclip_get_ibuf_flag(context->clip, &context->user, context->clip_flag);
1166         if(!ibuf_new)
1167                 return 0;
1168
1169         #pragma omp parallel for private(a) shared(ibuf_new, ok) if(map_size>1)
1170         for(a= 0; a<map_size; a++) {
1171                 TrackContext *track_context = NULL;
1172                 MovieTrackingTrack *track;
1173                 MovieTrackingMarker *marker;
1174
1175                 tracks_map_get(context->tracks_map, a, &track, (void**)&track_context);
1176
1177                 marker= BKE_tracking_exact_marker(track, curfra);
1178
1179                 if(marker && (marker->flag&MARKER_DISABLED)==0) {
1180 #ifdef WITH_LIBMV
1181                         int width, height, origin[2], tracked= 0, need_readjust= 0;
1182                         float pos[2], margin[2], dim[2];
1183                         double x1, y1, x2, y2;
1184                         ImBuf *ibuf= NULL;
1185                         MovieTrackingMarker marker_new, *marker_keyed;
1186                         int onbound= 0, coords_correct= 0;
1187                         int nextfra;
1188
1189                         if(track->pattern_match==TRACK_MATCH_KEYFRAME)
1190                                 need_readjust= context->first_time;
1191                         else
1192                                 need_readjust= 1;
1193
1194                         if(context->backwards) nextfra= curfra-1;
1195                         else nextfra= curfra+1;
1196
1197                         /* margin from frame boundaries */
1198                         sub_v2_v2v2(dim, track->pat_max, track->pat_min);
1199                         margin[0]= margin[1]= MAX2(dim[0], dim[1]) / 2.0f;
1200
1201                         margin[0]= MAX2(margin[0], (float)track->margin / ibuf_new->x);
1202                         margin[1]= MAX2(margin[1], (float)track->margin / ibuf_new->y);
1203
1204                         /* do not track markers which are too close to boundary */
1205                         if(marker->pos[0]<margin[0] || marker->pos[0]>1.0f-margin[0] ||
1206                            marker->pos[1]<margin[1] || marker->pos[1]>1.0f-margin[1]) {
1207                                 onbound= 1;
1208                         }
1209                         else if(ELEM(track->tracker, TRACKER_KLT, TRACKER_HYBRID)) {
1210                                 float *patch_new;
1211
1212                                 if(need_readjust) {
1213                                         /* calculate patch for keyframed position */
1214                                         ibuf= get_adjust_ibuf(context, track, marker, curfra, &marker_keyed);
1215
1216                                         if(track_context->patch)
1217                                                 MEM_freeN(track_context->patch);
1218
1219                                         track_context->patch= get_search_floatbuf(ibuf, track, marker_keyed, &width, &height, track_context->keyframed_pos, origin);
1220
1221                                         IMB_freeImBuf(ibuf);
1222                                 }
1223
1224                                 patch_new= get_search_floatbuf(ibuf_new, track, marker, &width, &height, pos, origin);
1225
1226                                 x1= track_context->keyframed_pos[0];
1227                                 y1= track_context->keyframed_pos[1];
1228
1229                                 x2= pos[0];
1230                                 y2= pos[1];
1231
1232                                 tracked= libmv_regionTrackerTrack(track_context->region_tracker, track_context->patch, patch_new,
1233                                                         width, height, x1, y1, &x2, &y2);
1234
1235                                 MEM_freeN(patch_new);
1236                         }
1237                         else if(track->tracker==TRACKER_SAD) {
1238                                 unsigned char *image_new;
1239                                 float correlation;
1240                                 float warp[3][2]={{0}};
1241
1242                                 if(need_readjust) {
1243                                         unsigned char *image;
1244
1245                                         /* calculate pattern for keyframed position */
1246                                         ibuf= get_adjust_ibuf(context, track, marker, curfra, &marker_keyed);
1247
1248                                         image= get_search_bytebuf(ibuf, track, marker_keyed, &width, &height, pos, origin);
1249
1250                                         memset(warp, 0, sizeof(warp));
1251                                         warp[0][0]= 1;
1252                                         warp[1][1]= 1;
1253                                         warp[2][0]= pos[0];
1254                                         warp[2][1]= pos[1];
1255
1256                                         if(!track_context->pattern) {
1257                                                 int square= track_context->pattern_size*track_context->pattern_size;
1258                                                 track_context->pattern= MEM_callocN(sizeof(unsigned char)*square, "trackking pattern");
1259                                         }
1260
1261                                         libmv_SADSamplePattern(image, width, warp, track_context->pattern, track_context->pattern_size);
1262
1263                                         MEM_freeN(image);
1264                                         IMB_freeImBuf(ibuf);
1265                                 }
1266
1267                                 image_new= get_search_bytebuf(ibuf_new, track, marker, &width, &height, pos, origin);
1268
1269                                 if(track_context->warped==NULL) {
1270                                         unsigned char *image_old;
1271
1272                                         ibuf= get_frame_ibuf(context, curfra);
1273
1274                                         if(track_context->warped==NULL) {
1275                                                 int square= track_context->pattern_size*track_context->pattern_size;
1276                                                 track_context->warped= MEM_callocN(sizeof(unsigned char)*square, "trackking warped");
1277                                         }
1278
1279                                         image_old= get_search_bytebuf(ibuf, track, marker, &width, &height, pos, origin);
1280                                         get_warped(track_context, pos[0], pos[1], width, image_old);
1281                                         IMB_freeImBuf(ibuf);
1282                                         MEM_freeN(image_old);
1283                                 }
1284
1285                                 memset(warp, 0, sizeof(warp));
1286                                 warp[0][0]= 1;
1287                                 warp[1][1]= 1;
1288                                 warp[2][0]= pos[0];
1289                                 warp[2][1]= pos[1];
1290
1291                                 correlation= libmv_SADTrackerTrack(track_context->pattern, track_context->warped,
1292                                                         track_context->pattern_size, image_new, width, width, height, warp);
1293
1294                                 x2= warp[2][0];
1295                                 y2= warp[2][1];
1296
1297                                 tracked= track->minimum_correlation < correlation;
1298
1299                                 if(tracked)
1300                                         get_warped(track_context, x2, y2, width, image_new);
1301
1302                                 MEM_freeN(image_new);
1303                         }
1304
1305                         coords_correct= !onbound && !isnan(x2) && !isnan(y2) && finite(x2) && finite(y2);
1306                         if(coords_correct && (tracked || !context->disable_failed)) {
1307                                 if(context->first_time) {
1308                                         #pragma omp critical
1309                                         {
1310                                                 /* check if there's no keyframe/tracked markers before tracking marker.
1311                                                    if so -- create disabled marker before currently tracking "segment" */
1312                                                 put_disabled_marker(track, marker, !context->backwards, 0);
1313                                         }
1314                                 }
1315
1316                                 memset(&marker_new, 0, sizeof(marker_new));
1317
1318                                 if(!onbound) {
1319                                         marker_new.pos[0]= (origin[0]+x2)/ibuf_new->x;
1320                                         marker_new.pos[1]= (origin[1]+y2)/ibuf_new->y;
1321                                 } else {
1322                                         copy_v2_v2(marker_new.pos, marker->pos);
1323                                 }
1324
1325                                 marker_new.flag|= MARKER_TRACKED;
1326                                 marker_new.framenr= nextfra;
1327
1328                                 #pragma omp critical
1329                                 {
1330                                         BKE_tracking_insert_marker(track, &marker_new);
1331                                 }
1332
1333                                 /* make currently tracked segment be finished with disabled marker */
1334                                 #pragma omp critical
1335                                 {
1336                                         put_disabled_marker(track, &marker_new, context->backwards, 0);
1337                                 }
1338                         } else {
1339                                 marker_new= *marker;
1340
1341                                 marker_new.framenr= nextfra;
1342                                 marker_new.flag|= MARKER_DISABLED;
1343
1344                                 #pragma omp critical
1345                                 {
1346                                         BKE_tracking_insert_marker(track, &marker_new);
1347                                 }
1348                         }
1349
1350                         ok= 1;
1351 #endif
1352                 }
1353         }
1354
1355         IMB_freeImBuf(ibuf_new);
1356
1357         context->first_time= 0;
1358         context->frames++;
1359
1360         return ok;
1361 }
1362
1363 /*********************** camera solving *************************/
1364
1365 typedef struct MovieReconstructContext {
1366 #ifdef WITH_LIBMV
1367         struct libmv_Tracks *tracks;
1368         int keyframe1, keyframe2;
1369         short refine_flags;
1370
1371         struct libmv_Reconstruction *reconstruction;
1372 #endif
1373
1374         float focal_length;
1375         float principal_point[2];
1376         float k1, k2, k3;
1377
1378         float reprojection_error;
1379
1380         TracksMap *tracks_map;
1381
1382         int sfra, efra;
1383 } MovieReconstructContext;
1384
1385 typedef struct ReconstructProgressData {
1386         short *stop;
1387         short *do_update;
1388         float *progress;
1389         char *stats_message;
1390         int message_size;
1391 } ReconstructProgressData;
1392
1393 #if WITH_LIBMV
1394 static struct libmv_Tracks *create_libmv_tracks(MovieTracking *tracking, int width, int height)
1395 {
1396         int tracknr= 0;
1397         MovieTrackingTrack *track;
1398         struct libmv_Tracks *tracks= libmv_tracksNew();
1399
1400         track= tracking->tracks.first;
1401         while(track) {
1402                 int a= 0;
1403
1404                 for(a= 0; a<track->markersnr; a++) {
1405                         MovieTrackingMarker *marker= &track->markers[a];
1406
1407                         if((marker->flag&MARKER_DISABLED)==0)
1408                                 libmv_tracksInsert(tracks, marker->framenr, tracknr,
1409                                                         marker->pos[0]*width, marker->pos[1]*height);
1410                 }
1411
1412                 track= track->next;
1413                 tracknr++;
1414         }
1415
1416         return tracks;
1417 }
1418
1419 static void retrieve_libmv_reconstruct_intrinscis(MovieReconstructContext *context, MovieTracking *tracking)
1420 {
1421         struct libmv_Reconstruction *libmv_reconstruction= context->reconstruction;
1422         struct libmv_CameraIntrinsics *libmv_intrinsics = libmv_ReconstructionExtractIntrinsics(libmv_reconstruction);
1423
1424         float aspy= 1.0f/tracking->camera.pixel_aspect;
1425
1426         double focal_length, principal_x, principal_y, k1, k2, k3;
1427         int width, height;
1428
1429         libmv_CameraIntrinsicsExtract(libmv_intrinsics, &focal_length, &principal_x, &principal_y,
1430                         &k1, &k2, &k3, &width, &height);
1431
1432         tracking->camera.focal= focal_length;
1433         tracking->camera.principal[0]= principal_x;
1434
1435         /* todo: verify divide by aspy is correct */
1436         tracking->camera.principal[1]= principal_y / aspy;
1437         tracking->camera.k1= k1;
1438         tracking->camera.k2= k2;
1439 }
1440
1441 static int retrieve_libmv_reconstruct_tracks(MovieReconstructContext *context, MovieTracking *tracking)
1442 {
1443         struct libmv_Reconstruction *libmv_reconstruction= context->reconstruction;
1444         MovieTrackingReconstruction *reconstruction= &tracking->reconstruction;
1445         MovieReconstructedCamera *reconstructed;
1446         MovieTrackingTrack *track;
1447         int ok= 1, tracknr= 0, a, origin_set= 0;
1448         int sfra= context->sfra, efra= context->efra;
1449         float imat[4][4];
1450
1451         unit_m4(imat);
1452
1453         track= tracking->tracks.first;
1454         while(track) {
1455                 double pos[3];
1456
1457                 if(libmv_reporojectionPointForTrack(libmv_reconstruction, tracknr, pos)) {
1458                         track->bundle_pos[0]= pos[0];
1459                         track->bundle_pos[1]= pos[1];
1460                         track->bundle_pos[2]= pos[2];
1461
1462                         track->flag|= TRACK_HAS_BUNDLE;
1463                         track->error= libmv_reporojectionErrorForTrack(libmv_reconstruction, tracknr);
1464                 } else {
1465                         track->flag&= ~TRACK_HAS_BUNDLE;
1466                         ok= 0;
1467
1468                         printf("No bundle for track #%d '%s'\n", tracknr, track->name);
1469                 }
1470
1471                 track= track->next;
1472                 tracknr++;
1473         }
1474
1475         if(reconstruction->cameras)
1476                 MEM_freeN(reconstruction->cameras);
1477
1478         reconstruction->camnr= 0;
1479         reconstruction->cameras= NULL;
1480         reconstructed= MEM_callocN((efra-sfra+1)*sizeof(MovieReconstructedCamera), "temp reconstructed camera");
1481
1482         for(a= sfra; a<=efra; a++) {
1483                 double matd[4][4];
1484
1485                 if(libmv_reporojectionCameraForImage(libmv_reconstruction, a, matd)) {
1486                         int i, j;
1487                         float mat[4][4];
1488                         float error= libmv_reporojectionErrorForImage(libmv_reconstruction, a);
1489
1490                         for(i=0; i<4; i++)
1491                                 for(j= 0; j<4; j++)
1492                                         mat[i][j]= matd[i][j];
1493
1494                         if(!origin_set) {
1495                                 copy_m4_m4(imat, mat);
1496                                 invert_m4(imat);
1497                                 origin_set= 1;
1498                         }
1499
1500                         if(origin_set)
1501                                 mult_m4_m4m4(mat, imat, mat);
1502
1503                         copy_m4_m4(reconstructed[reconstruction->camnr].mat, mat);
1504                         reconstructed[reconstruction->camnr].framenr= a;
1505                         reconstructed[reconstruction->camnr].error= error;
1506                         reconstruction->camnr++;
1507                 } else {
1508                         ok= 0;
1509                         printf("No camera for frame %d\n", a);
1510                 }
1511         }
1512
1513         if(reconstruction->camnr) {
1514                 reconstruction->cameras= MEM_callocN(reconstruction->camnr*sizeof(MovieReconstructedCamera), "reconstructed camera");
1515                 memcpy(reconstruction->cameras, reconstructed, reconstruction->camnr*sizeof(MovieReconstructedCamera));
1516         }
1517
1518         if(origin_set) {
1519                 track= tracking->tracks.first;
1520                 while(track) {
1521                         if(track->flag&TRACK_HAS_BUNDLE)
1522                                 mul_v3_m4v3(track->bundle_pos, imat, track->bundle_pos);
1523
1524                         track= track->next;
1525                 }
1526         }
1527
1528         MEM_freeN(reconstructed);
1529
1530         return ok;
1531 }
1532
1533 static int retrieve_libmv_reconstruct(MovieReconstructContext *context, MovieTracking *tracking)
1534 {
1535         tracks_map_merge(context->tracks_map, tracking);
1536
1537         /* take the intrinscis back from libmv */
1538         retrieve_libmv_reconstruct_intrinscis(context, tracking);
1539
1540         return retrieve_libmv_reconstruct_tracks(context, tracking);
1541 }
1542
1543 static int get_refine_intrinsics_flags(MovieTracking *tracking)
1544 {
1545         int refine= tracking->settings.refine_camera_intrinsics;
1546         int flags= 0;
1547
1548         if(refine&REFINE_FOCAL_LENGTH)
1549                 flags|= LIBMV_REFINE_FOCAL_LENGTH;
1550
1551         if(refine&REFINE_PRINCIPAL_POINT)
1552                 flags|= LIBMV_REFINE_PRINCIPAL_POINT;
1553
1554         if(refine&REFINE_RADIAL_DISTORTION_K1)
1555                 flags|= REFINE_RADIAL_DISTORTION_K1;
1556
1557         if(refine&REFINE_RADIAL_DISTORTION_K2)
1558                 flags|= REFINE_RADIAL_DISTORTION_K2;
1559
1560         return flags;
1561 }
1562
1563 static int count_tracks_on_both_keyframes(MovieTracking *tracking)
1564 {
1565         int tot= 0;
1566         int frame1= tracking->settings.keyframe1, frame2= tracking->settings.keyframe2;
1567         MovieTrackingTrack *track;
1568
1569         track= tracking->tracks.first;
1570         while(track) {
1571                 if(BKE_tracking_has_marker(track, frame1))
1572                         if(BKE_tracking_has_marker(track, frame2))
1573                                 tot++;
1574
1575                 track= track->next;
1576         }
1577
1578         return tot;
1579 }
1580 #endif
1581
1582 int BKE_tracking_can_reconstruct(MovieTracking *tracking, char *error_msg, int error_size)
1583 {
1584 #if WITH_LIBMV
1585         if(count_tracks_on_both_keyframes(tracking)<8) {
1586                 BLI_strncpy(error_msg, "At least 8 tracks on both of keyframes are needed for reconstruction", error_size);
1587                 return 0;
1588         }
1589
1590         return 1;
1591 #else
1592         BLI_strncpy(error_msg, "Blender is compiled without motion tracking library", error_size);
1593         (void) tracking;
1594
1595         return 0;
1596 #endif
1597 }
1598
1599 MovieReconstructContext* BKE_tracking_reconstruction_context_new(MovieTracking *tracking,
1600                         int keyframe1, int keyframe2, int width, int height)
1601 {
1602         MovieReconstructContext *context= MEM_callocN(sizeof(MovieReconstructContext), "MovieReconstructContext data");
1603         MovieTrackingCamera *camera= &tracking->camera;
1604         float aspy= 1.0f/tracking->camera.pixel_aspect;
1605         int num_tracks= BLI_countlist(&tracking->tracks);
1606         int sfra= INT_MAX, efra= INT_MIN;
1607         MovieTrackingTrack *track;
1608
1609         context->tracks_map= tracks_map_new(num_tracks, 0);
1610         track= tracking->tracks.first;
1611         while(track) {
1612                 int first= 0, last= track->markersnr;
1613                 MovieTrackingMarker *first_marker= &track->markers[0];
1614                 MovieTrackingMarker *last_marker= &track->markers[track->markersnr-1];
1615
1616                 /* find first not-disabled marker */
1617                 while(first<track->markersnr-1 && first_marker->flag&MARKER_DISABLED) {
1618                         first++;
1619                         first_marker++;
1620                 }
1621
1622                 /* find last not-disabled marker */
1623                 while(last>=0 && last_marker->flag&MARKER_DISABLED) {
1624                         last--;
1625                         last_marker--;
1626                 }
1627
1628                 if(first<track->markersnr-1)
1629                         sfra= MIN2(sfra, first_marker->framenr);
1630
1631                 if(last>=0)
1632                         efra= MAX2(efra, last_marker->framenr);
1633
1634                 tracks_map_insert(context->tracks_map, track, NULL);
1635
1636                 track= track->next;
1637         }
1638
1639         context->sfra= sfra;
1640         context->efra= efra;
1641
1642 #ifdef WITH_LIBMV
1643         context->tracks= create_libmv_tracks(tracking, width, height*aspy);
1644         context->keyframe1= keyframe1;
1645         context->keyframe2= keyframe2;
1646         context->refine_flags= get_refine_intrinsics_flags(tracking);
1647 #else
1648         (void) width;
1649         (void) height;
1650         (void) keyframe1;
1651         (void) keyframe2;
1652 #endif
1653
1654         context->focal_length= camera->focal;
1655         context->principal_point[0]= camera->principal[0];
1656         context->principal_point[1]= camera->principal[1]*aspy;
1657
1658         context->k1= camera->k1;
1659         context->k2= camera->k2;
1660         context->k2= camera->k2;
1661
1662         return context;
1663 }
1664
1665 void BKE_tracking_reconstruction_context_free(MovieReconstructContext *context)
1666 {
1667 #ifdef WITH_LIBMV
1668         if(context->reconstruction)
1669                         libmv_destroyReconstruction(context->reconstruction);
1670
1671         libmv_tracksDestroy(context->tracks);
1672 #endif
1673
1674         tracks_map_free(context->tracks_map, NULL);
1675
1676         MEM_freeN(context);
1677 }
1678
1679 #ifdef WITH_LIBMV
1680 static void solve_reconstruction_update_cb(void *customdata, double progress, const char *message)
1681 {
1682         ReconstructProgressData *progressdata= customdata;
1683
1684         if(progressdata->progress) {
1685                 *progressdata->progress= progress;
1686                 *progressdata->do_update= 1;
1687         }
1688
1689         BLI_snprintf(progressdata->stats_message, progressdata->message_size,
1690                         "Solving camera | %s", message);
1691 }
1692 #endif
1693
1694 #if 0
1695 static int solve_reconstruction_testbreak_cb(void *customdata)
1696 {
1697         ReconstructProgressData *progressdata= customdata;
1698
1699         if(progressdata->stop && *progressdata->stop)
1700                 return 1;
1701
1702         return G.afbreek;
1703 }
1704 #endif
1705
1706 void BKE_tracking_solve_reconstruction(MovieReconstructContext *context, short *stop,
1707                         short *do_update, float *progress, char *stats_message, int message_size)
1708 {
1709 #ifdef WITH_LIBMV
1710         float error;
1711
1712         ReconstructProgressData progressdata;
1713
1714         progressdata.stop= stop;
1715         progressdata.do_update= do_update;
1716         progressdata.progress= progress;
1717         progressdata.stats_message= stats_message;
1718         progressdata.message_size= message_size;
1719
1720         context->reconstruction = libmv_solveReconstruction(context->tracks,
1721                 context->keyframe1, context->keyframe2,
1722                 context->refine_flags,
1723                 context->focal_length,
1724                 context->principal_point[0], context->principal_point[1],
1725                 context->k1, context->k2, context->k3,
1726                 solve_reconstruction_update_cb, &progressdata);
1727
1728         error= libmv_reprojectionError(context->reconstruction);
1729
1730         context->reprojection_error= error;
1731 #else
1732         (void) context;
1733         (void) stop;
1734         (void) do_update;
1735         (void) progress;
1736         (void) stats_message;
1737         (void) message_size;
1738 #endif
1739 }
1740
1741 int BKE_tracking_finish_reconstruction(MovieReconstructContext *context, MovieTracking *tracking)
1742 {
1743         tracking->reconstruction.error= context->reprojection_error;
1744         tracking->reconstruction.flag|= TRACKING_RECONSTRUCTED;
1745
1746 #ifdef WITH_LIBMV
1747         if(!retrieve_libmv_reconstruct(context, tracking))
1748                 return 0;
1749 #endif
1750
1751         return 1;
1752 }
1753
1754 void BKE_track_unique_name(MovieTracking *tracking, MovieTrackingTrack *track)
1755 {
1756         BLI_uniquename(&tracking->tracks, track, "Track", '.', offsetof(MovieTrackingTrack, name), sizeof(track->name));
1757 }
1758
1759 MovieTrackingTrack *BKE_tracking_named_track(MovieTracking *tracking, const char *name)
1760 {
1761         MovieTrackingTrack *track= tracking->tracks.first;
1762
1763         while(track) {
1764                 if(!strcmp(track->name, name))
1765                         return track;
1766
1767                 track= track->next;
1768         }
1769
1770         return NULL;
1771 }
1772
1773 static int reconstruction_camera_index(MovieTracking *tracking, int framenr, int nearest)
1774 {
1775         MovieTrackingReconstruction *reconstruction= &tracking->reconstruction;
1776         MovieReconstructedCamera *cameras= reconstruction->cameras;
1777         int a= 0, d= 1;
1778
1779         if(!reconstruction->camnr)
1780                 return -1;
1781
1782         if(framenr<cameras[0].framenr) {
1783                 if(nearest) return 0;
1784                 else return -1;
1785         }
1786
1787         if(framenr>cameras[reconstruction->camnr-1].framenr) {
1788                 if(nearest) return reconstruction->camnr-1;
1789                 else return -1;
1790         }
1791
1792         if(reconstruction->last_camera<reconstruction->camnr)
1793                 a= reconstruction->last_camera;
1794
1795         if(cameras[a].framenr>=framenr)
1796                 d= -1;
1797
1798         while(a>=0 && a<reconstruction->camnr) {
1799                 int cfra= cameras[a].framenr;
1800
1801                 /* check if needed framenr was "skipped" -- no data for requested frame */
1802
1803                 if(d>0 && cfra>framenr) {
1804                         /* interpolate with previous position */
1805                         if(nearest) return a-1;
1806                         else break;
1807                 }
1808
1809                 if(d<0 && cfra<framenr) {
1810                         /* interpolate with next position */
1811                         if(nearest) return a;
1812                         else break;
1813                 }
1814
1815                 if(cfra==framenr) {
1816                         reconstruction->last_camera= a;
1817
1818                         return a;
1819                 }
1820
1821                 a+= d;
1822         }
1823
1824         return -1;
1825 }
1826
1827 MovieReconstructedCamera *BKE_tracking_get_reconstructed_camera(MovieTracking *tracking, int framenr)
1828 {
1829         int a= reconstruction_camera_index(tracking, framenr, 0);
1830
1831         if(a==-1)
1832                 return NULL;
1833
1834         return &tracking->reconstruction.cameras[a];
1835 }
1836
1837 void BKE_tracking_get_interpolated_camera(MovieTracking *tracking, int framenr, float mat[4][4])
1838 {
1839         MovieTrackingReconstruction *reconstruction= &tracking->reconstruction;
1840         MovieReconstructedCamera *cameras= reconstruction->cameras;
1841         int a= reconstruction_camera_index(tracking, framenr, 1);
1842
1843         if(a==-1) {
1844                 unit_m4(mat);
1845                 return;
1846         }
1847
1848         if(cameras[a].framenr!=framenr && a>0 && a<reconstruction->camnr-1) {
1849                 float t= ((float)framenr-cameras[a].framenr) / (cameras[a+1].framenr-cameras[a].framenr);
1850
1851                 blend_m4_m4m4(mat, cameras[a].mat, cameras[a+1].mat, t);
1852         } else {
1853                 copy_m4_m4(mat, cameras[a].mat);
1854         }
1855 }
1856
1857 void BKE_get_tracking_mat(Scene *scene, Object *ob, float mat[4][4])
1858 {
1859         if(!ob) {
1860                 if(scene->camera) ob= scene->camera;
1861                 else ob= scene_find_camera(scene);
1862         }
1863
1864         if(ob)
1865                 where_is_object_mat(scene, ob, mat);
1866         else
1867                 unit_m4(mat);
1868 }
1869
1870 void BKE_tracking_camera_shift(MovieTracking *tracking, int winx, int winy, float *shiftx, float *shifty)
1871 {
1872         *shiftx= (0.5f*winx-tracking->camera.principal[0]) / winx;
1873         *shifty= (0.5f*winy-tracking->camera.principal[1]) / winx;
1874 }
1875
1876 void BKE_tracking_camera_to_blender(MovieTracking *tracking, Scene *scene, Camera *camera, int width, int height)
1877 {
1878         float focal= tracking->camera.focal;
1879
1880         camera->sensor_x= tracking->camera.sensor_width;
1881         camera->sensor_fit= CAMERA_SENSOR_FIT_AUTO;
1882         camera->lens= focal*camera->sensor_x/width;
1883
1884         scene->r.xsch= width*tracking->camera.pixel_aspect;
1885         scene->r.ysch= height;
1886
1887         scene->r.xasp= 1.0f;
1888         scene->r.yasp= 1.0f;
1889
1890         BKE_tracking_camera_shift(tracking, width, height, &camera->shiftx, &camera->shifty);
1891 }
1892
1893 void BKE_tracking_projection_matrix(MovieTracking *tracking, int framenr, int winx, int winy, float mat[4][4])
1894 {
1895         MovieReconstructedCamera *camera;
1896         float lens= tracking->camera.focal*tracking->camera.sensor_width/(float)winx;
1897         float viewfac, pixsize, left, right, bottom, top, clipsta, clipend;
1898         float winmat[4][4];
1899         float ycor= 1.0f/tracking->camera.pixel_aspect;
1900         float shiftx, shifty, winside= MAX2(winx, winy);
1901
1902         BKE_tracking_camera_shift(tracking, winx, winy, &shiftx, &shifty);
1903
1904         clipsta= 0.1f;
1905         clipend= 1000.0f;
1906
1907         if(winx >= winy)
1908                 viewfac= (lens*winx)/tracking->camera.sensor_width;
1909         else
1910                 viewfac= (ycor*lens*winy)/tracking->camera.sensor_width;
1911
1912         pixsize= clipsta/viewfac;
1913
1914         left= -0.5f*(float)winx + shiftx*winside;
1915         bottom= -0.5f*(ycor)*(float)winy + shifty*winside;
1916         right=  0.5f*(float)winx + shiftx*winside;
1917         top=  0.5f*(ycor)*(float)winy + shifty*winside;
1918
1919         left *= pixsize;
1920         right *= pixsize;
1921         bottom *= pixsize;
1922         top *= pixsize;
1923
1924         perspective_m4(winmat, left, right, bottom, top, clipsta, clipend);
1925
1926         camera= BKE_tracking_get_reconstructed_camera(tracking, framenr);
1927         if(camera) {
1928                 float imat[4][4];
1929
1930                 invert_m4_m4(imat, camera->mat);
1931                 mult_m4_m4m4(mat, winmat, imat);
1932         } else copy_m4_m4(mat, winmat);
1933 }
1934
1935 void BKE_tracking_apply_intrinsics(MovieTracking *tracking, float co[2], float nco[2])
1936 {
1937         MovieTrackingCamera *camera= &tracking->camera;
1938
1939 #ifdef WITH_LIBMV
1940         double x, y;
1941         float aspy= 1.0f/tracking->camera.pixel_aspect;
1942
1943         /* normalize coords */
1944         x= (co[0]-camera->principal[0]) / camera->focal;
1945         y= (co[1]-camera->principal[1] * aspy) / camera->focal;
1946
1947         libmv_applyCameraIntrinsics(camera->focal, camera->principal[0], camera->principal[1] * aspy,
1948                                 camera->k1, camera->k2, camera->k3, x, y, &x, &y);
1949
1950         /* result is in image coords already */
1951         nco[0]= x;
1952         nco[1]= y;
1953 #else
1954         (void)camera;
1955         (void)co;
1956         (void)nco;
1957 #endif
1958 }
1959
1960 void BKE_tracking_invert_intrinsics(MovieTracking *tracking, float co[2], float nco[2])
1961 {
1962         MovieTrackingCamera *camera= &tracking->camera;
1963
1964 #ifdef WITH_LIBMV
1965         double x= co[0], y= co[1];
1966         float aspy= 1.0f/tracking->camera.pixel_aspect;
1967
1968         libmv_InvertIntrinsics(camera->focal, camera->principal[0], camera->principal[1] * aspy,
1969                                 camera->k1, camera->k2, camera->k3, x, y, &x, &y);
1970
1971         nco[0]= x * camera->focal + camera->principal[0];
1972         nco[1]= y * camera->focal + camera->principal[1] * aspy;
1973 #else
1974         (void)camera;
1975         (void)co;
1976         (void)nco;
1977 #endif
1978 }
1979
1980 #ifdef WITH_LIBMV
1981 static int point_in_stroke(bGPDstroke *stroke, float x, float y)
1982 {
1983         int i, prev;
1984         int count= 0;
1985         bGPDspoint *points= stroke->points;
1986
1987         prev= stroke->totpoints-1;
1988
1989         for(i= 0; i<stroke->totpoints; i++) {
1990                 if((points[i].y<y && points[prev].y>=y) || (points[prev].y<y && points[i].y>=y)) {
1991                         float fac= (y-points[i].y)/(points[prev].y-points[i].y);
1992
1993                         if (points[i].x+fac*(points[prev].x-points[i].x)<x)
1994                                 count++;
1995                 }
1996
1997                 prev= i;
1998         }
1999
2000         return count%2;
2001 }
2002
2003 static int point_in_layer(bGPDlayer *layer, float x, float y)
2004 {
2005         bGPDframe *frame= layer->frames.first;
2006
2007         while(frame) {
2008                 bGPDstroke *stroke= frame->strokes.first;
2009                 while(stroke) {
2010                         if(point_in_stroke(stroke, x, y))
2011                                 return 1;
2012
2013                         stroke= stroke->next;
2014                 }
2015                 frame= frame->next;
2016         }
2017
2018         return 0;
2019 }
2020
2021 static void retrieve_libmv_features(MovieTracking *tracking, struct libmv_Features *features,
2022                         int framenr, int width, int height, bGPDlayer *layer, int place_outside_layer)
2023 {
2024         int a;
2025
2026         a= libmv_countFeatures(features);
2027         while(a--) {
2028                 MovieTrackingTrack *track;
2029                 double x, y, size, score;
2030                 int ok= 1;
2031                 float xu, yu;
2032
2033                 libmv_getFeature(features, a, &x, &y, &score, &size);
2034
2035                 xu= x/width;
2036                 yu= y/height;
2037
2038                 if(layer)
2039                         ok= point_in_layer(layer, xu, yu)!=place_outside_layer;
2040
2041                 if(ok) {
2042                         track= BKE_tracking_add_track(tracking, xu, yu, framenr, width, height);
2043                         track->flag|= SELECT;
2044                         track->pat_flag|= SELECT;
2045                         track->search_flag|= SELECT;
2046                 }
2047         }
2048 }
2049 #endif
2050
2051 void BKE_tracking_detect_fast(MovieTracking *tracking, ImBuf *ibuf,
2052                         int framenr, int margin, int min_trackness, int min_distance, bGPDlayer *layer,
2053                         int place_outside_layer)
2054 {
2055 #ifdef WITH_LIBMV
2056         struct libmv_Features *features;
2057         unsigned char *pixels= get_ucharbuf(ibuf);
2058
2059         features= libmv_detectFeaturesFAST(pixels, ibuf->x, ibuf->y, ibuf->x, margin, min_trackness, min_distance);
2060
2061         MEM_freeN(pixels);
2062
2063         retrieve_libmv_features(tracking, features, framenr, ibuf->x, ibuf->y, layer, place_outside_layer);
2064
2065         libmv_destroyFeatures(features);
2066 #else
2067         (void)tracking;
2068         (void)ibuf;
2069         (void)framenr;
2070         (void)margin;
2071         (void)min_trackness;
2072         (void)min_distance;
2073         (void)layer;
2074         (void)place_outside_layer;
2075 #endif
2076 }
2077
2078 MovieTrackingTrack *BKE_tracking_indexed_track(MovieTracking *tracking, int tracknr)
2079 {
2080         MovieTrackingTrack *track= tracking->tracks.first;
2081         int cur= 1;
2082
2083         while(track) {
2084                 if(track->flag&TRACK_HAS_BUNDLE) {
2085                         if(cur==tracknr)
2086                                 return track;
2087
2088                         cur++;
2089                 }
2090
2091                 track= track->next;
2092         }
2093
2094         return NULL;
2095 }
2096
2097 static int stabilization_median_point(MovieTracking *tracking, int framenr, float median[2])
2098 {
2099         int ok= 0;
2100         float min[2], max[2];
2101         MovieTrackingTrack *track;
2102
2103         INIT_MINMAX2(min, max);
2104
2105         track= tracking->tracks.first;
2106         while(track) {
2107                 if(track->flag&TRACK_USE_2D_STAB) {
2108                         MovieTrackingMarker *marker= BKE_tracking_get_marker(track, framenr);
2109
2110                         DO_MINMAX2(marker->pos, min, max);
2111
2112                         ok= 1;
2113                 }
2114
2115                 track= track->next;
2116         }
2117
2118         median[0]= (max[0]+min[0])/2.0f;
2119         median[1]= (max[1]+min[1])/2.0f;
2120
2121         return ok;
2122 }
2123
2124 static void calculate_stabdata(MovieTracking *tracking, int framenr, float width, float height,
2125                         float firstmedian[2], float median[2], float loc[2], float *scale, float *angle)
2126 {
2127         MovieTrackingStabilization *stab= &tracking->stabilization;
2128
2129         *scale= (stab->scale-1.0f)*stab->scaleinf+1.0f;
2130         *angle= 0.0f;
2131
2132         loc[0]= (firstmedian[0]-median[0])*width*(*scale);
2133         loc[1]= (firstmedian[1]-median[1])*height*(*scale);
2134
2135         mul_v2_fl(loc, stab->locinf);
2136
2137         if((stab->flag&TRACKING_STABILIZE_ROTATION) && stab->rot_track && stab->rotinf) {
2138                 MovieTrackingMarker *marker;
2139                 float a[2], b[2];
2140                 float x0= (float)width/2.0f, y0= (float)height/2.0f;
2141                 float x= median[0]*width, y= median[1]*height;
2142
2143                 marker= BKE_tracking_get_marker(stab->rot_track, 1);
2144                 sub_v2_v2v2(a, marker->pos, firstmedian);
2145                 a[0]*= width;
2146                 a[1]*= height;
2147
2148                 marker= BKE_tracking_get_marker(stab->rot_track, framenr);
2149                 sub_v2_v2v2(b, marker->pos, median);
2150                 b[0]*= width;
2151                 b[1]*= height;
2152
2153                 *angle= -atan2(a[0]*b[1]-a[1]*b[0], a[0]*b[0]+a[1]*b[1]);
2154                 *angle*= stab->rotinf;
2155
2156                 /* convert to rotation around image center */
2157                 loc[0]-= (x0 + (x-x0)*cosf(*angle)-(y-y0)*sinf(*angle) - x)*(*scale);
2158                 loc[1]-= (y0 + (x-x0)*sinf(*angle)+(y-y0)*cosf(*angle) - y)*(*scale);
2159         }
2160 }
2161
2162 static float stabilization_auto_scale_factor(MovieTracking *tracking, int width, int height)
2163 {
2164         float firstmedian[2];
2165         MovieTrackingStabilization *stab= &tracking->stabilization;
2166
2167         if(stab->ok)
2168                 return stab->scale;
2169
2170         if(stabilization_median_point(tracking, 1, firstmedian)) {
2171                 int sfra= INT_MAX, efra= INT_MIN, cfra;
2172                 float delta[2]= {0.0f, 0.0f}, scalex= 1.0f, scaley= 1.0f;
2173                 MovieTrackingTrack *track;
2174
2175                 stab->scale= 1.0f;
2176
2177                 track= tracking->tracks.first;
2178                 while(track) {
2179                         if(track->flag&TRACK_USE_2D_STAB ||
2180                            ((stab->flag&TRACKING_STABILIZE_ROTATION) && track==stab->rot_track)) {
2181                                 sfra= MIN2(sfra, track->markers[0].framenr);
2182                                 efra= MAX2(efra, track->markers[track->markersnr-1].framenr);
2183                         }
2184
2185                         track= track->next;
2186                 }
2187
2188                 for(cfra=sfra; cfra<=efra; cfra++) {
2189                         float median[2], near[2];
2190                         float loc[2], scale, angle;
2191
2192                         stabilization_median_point(tracking, cfra, median);
2193
2194                         calculate_stabdata(tracking, cfra, width, height, firstmedian, median,
2195                                                 loc, &scale, &angle);
2196
2197                         if(angle==0.0f) {
2198                                 loc[0]= fabsf(loc[0]);
2199                                 loc[1]= fabsf(loc[1]);
2200
2201                                 delta[0]= MAX2(delta[0], loc[0]);
2202                                 delta[1]= MAX2(delta[1], loc[1]);
2203
2204                                 near[0]= MIN2(median[0], 1.0f-median[0]);
2205                                 near[1]= MIN2(median[1], 1.0f-median[1]);
2206                                 near[0]= MAX2(near[0], 0.05f);
2207                                 near[1]= MAX2(near[1], 0.05f);
2208
2209                                 scalex= 1.0f+delta[0]/(near[0]*width);
2210                                 scaley= 1.0f+delta[1]/(near[1]*height);
2211                         } else {
2212                                 int i;
2213                                 float mat[4][4];
2214                                 float points[4][2]={{0.0f, 0.0f}, {0.0f, height}, {width, height}, {width, 0.0f}};
2215
2216                                 BKE_tracking_stabdata_to_mat4(width, height, loc, scale, angle, mat);
2217
2218                                 for(i= 0; i<4; i++) {
2219                                         int j;
2220                                         float a[3]= {0.0f, 0.0f, 0.0f}, b[3]= {0.0f, 0.0f, 0.0f};
2221
2222                                         copy_v3_v3(a, points[i]);
2223                                         copy_v3_v3(b, points[(i+1)%4]);
2224
2225                                         mul_m4_v3(mat, a);
2226                                         mul_m4_v3(mat, b);
2227
2228                                         for(j= 0; j<4; j++) {
2229                                                 float point[3]= {points[j][0], points[j][1], 0.0f};
2230                                                 float v1[3], v2[3];
2231
2232                                                 sub_v3_v3v3(v1, b, a);
2233                                                 sub_v3_v3v3(v2, point, a);
2234
2235                                                 if(cross_v2v2(v1, v2) >= 0.0f) {
2236                                                         float dist= dist_to_line_v2(point, a, b);
2237                                                         if(i%2==0) {
2238                                                                 scalex= MAX2(scalex, (width+2*dist)/width);
2239                                                         } else {
2240                                                                 scaley= MAX2(scaley, (height+2*dist)/height);
2241                                                         }
2242                                                 }
2243                                         }
2244                                 }
2245                         }
2246                 }
2247
2248                 stab->scale= MAX2(scalex, scaley);
2249
2250                 if(stab->maxscale>0.0f)
2251                         stab->scale= MIN2(stab->scale, stab->maxscale);
2252         } else {
2253                 stab->scale= 1.0f;
2254         }
2255
2256         stab->ok= 1;
2257
2258         return stab->scale;
2259 }
2260
2261 static ImBuf* stabilize_alloc_ibuf(ImBuf *cacheibuf, ImBuf *srcibuf, int fill)
2262 {
2263         int flags;
2264
2265         if(cacheibuf && (cacheibuf->x != srcibuf->x || cacheibuf->y != srcibuf->y)) {
2266                 IMB_freeImBuf(cacheibuf);
2267                 cacheibuf= NULL;
2268         }
2269
2270         flags= IB_rect;
2271
2272         if(srcibuf->rect_float)
2273                 flags|= IB_rectfloat;
2274
2275         if(cacheibuf) {
2276                 if(fill) {
2277                         float col[4]= {0.0f, 0.0f, 0.0f, 0.0f};
2278                         IMB_rectfill(cacheibuf, col);
2279                 }
2280         }
2281         else {
2282                 cacheibuf= IMB_allocImBuf(srcibuf->x, srcibuf->y, srcibuf->planes, flags);
2283                 cacheibuf->profile= srcibuf->profile;
2284         }
2285
2286         return cacheibuf;
2287 }
2288
2289 void BKE_tracking_stabilization_data(MovieTracking *tracking, int framenr, int width, int height, float loc[2], float *scale, float *angle)
2290 {
2291         float firstmedian[2], median[2];
2292         MovieTrackingStabilization *stab= &tracking->stabilization;
2293
2294         if((stab->flag&TRACKING_2D_STABILIZATION)==0) {
2295                 zero_v2(loc);
2296                 *scale= 1.0f;
2297                 *angle= 0.0f;
2298
2299                 return;
2300         }
2301
2302         if(stabilization_median_point(tracking, 1, firstmedian)) {
2303                 stabilization_median_point(tracking, framenr, median);
2304
2305                 if((stab->flag&TRACKING_AUTOSCALE)==0)
2306                         stab->scale= 1.0f;
2307
2308                 if(!stab->ok) {
2309                         if(stab->flag&TRACKING_AUTOSCALE)
2310                                 stabilization_auto_scale_factor(tracking, width, height);
2311
2312                         calculate_stabdata(tracking, framenr, width, height, firstmedian, median, loc, scale, angle);
2313
2314                         stab->ok= 1;
2315                 } else {
2316                         calculate_stabdata(tracking, framenr, width, height, firstmedian, median, loc, scale, angle);
2317                 }
2318         } else {
2319                 zero_v2(loc);
2320                 *scale= 1.0f;
2321                 *angle= 0.0f;
2322         }
2323 }
2324
2325 ImBuf *BKE_tracking_stabilize(MovieTracking *tracking, int framenr, ImBuf *ibuf, float loc[2], float *scale, float *angle)
2326 {
2327         float tloc[2], tscale, tangle;
2328         MovieTrackingStabilization *stab= &tracking->stabilization;
2329         ImBuf *tmpibuf;
2330         float width= ibuf->x, height= ibuf->y;
2331
2332         if(loc)         copy_v2_v2(tloc, loc);
2333         if(scale)       tscale= *scale;
2334
2335         if((stab->flag&TRACKING_2D_STABILIZATION)==0) {
2336                 if(loc)         zero_v2(loc);
2337                 if(scale)       *scale= 1.0f;
2338
2339                 return ibuf;
2340         }
2341
2342         BKE_tracking_stabilization_data(tracking, framenr, width, height, tloc, &tscale, &tangle);
2343
2344         tmpibuf= stabilize_alloc_ibuf(NULL, ibuf, 1);
2345
2346         /* scale would be handled by matrix transformation when angle is non-zero */
2347         if(tscale!=1.0f && tangle==0.0f) {
2348                 ImBuf *scaleibuf;
2349
2350                 stabilization_auto_scale_factor(tracking, width, height);
2351
2352                 scaleibuf= stabilize_alloc_ibuf(stab->scaleibuf, ibuf, 0);
2353                 stab->scaleibuf= scaleibuf;
2354
2355                 IMB_rectcpy(scaleibuf, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
2356                 IMB_scalefastImBuf(scaleibuf, ibuf->x*tscale, ibuf->y*tscale);
2357
2358                 ibuf= scaleibuf;
2359         }
2360
2361         if(tangle==0.0f) {
2362                 /* if angle is zero, then it's much faster to use rect copy
2363                    but could be issues with subpixel precisions */
2364                 IMB_rectcpy(tmpibuf, ibuf, tloc[0]-(tscale-1.0f)*width/2.0f, tloc[1]-(tscale-1.0f)*height/2.0f, 0, 0, ibuf->x, ibuf->y);
2365         } else {
2366                 float mat[4][4];
2367                 int i, j;
2368
2369                 BKE_tracking_stabdata_to_mat4(ibuf->x, ibuf->y, tloc, tscale, tangle, mat);
2370                 invert_m4(mat);
2371
2372                 for(j=0; j<tmpibuf->y; j++) {
2373                         for(i=0; i<tmpibuf->x;i++) {
2374                                 float vec[3]= {i, j, 0};
2375
2376                                 mul_v3_m4v3(vec, mat, vec);
2377
2378                                 /* TODO: add selector for interpolation method */
2379                                 neareast_interpolation(ibuf, tmpibuf, vec[0], vec[1], i, j);
2380                         }
2381                 }
2382         }
2383
2384         tmpibuf->userflags|= IB_MIPMAP_INVALID;
2385
2386         if(tmpibuf->rect_float)
2387                 tmpibuf->userflags|= IB_RECT_INVALID;
2388
2389         if(loc)         copy_v2_v2(loc, tloc);
2390         if(scale)       *scale= tscale;
2391         if(angle)       *angle= tangle;
2392
2393         return tmpibuf;
2394 }
2395
2396 void BKE_tracking_stabdata_to_mat4(int width, int height, float loc[2], float scale, float angle, float mat[4][4])
2397 {
2398         float lmat[4][4], rmat[4][4], smat[4][4], cmat[4][4], icmat[4][4];
2399         float svec[3]= {scale, scale, scale};
2400
2401         unit_m4(rmat);
2402         unit_m4(lmat);
2403         unit_m4(smat);
2404         unit_m4(cmat);
2405
2406         /* image center as rotation center */
2407         cmat[3][0]= (float)width/2.0f;
2408         cmat[3][1]= (float)height/2.0f;
2409         invert_m4_m4(icmat, cmat);
2410
2411         size_to_mat4(smat, svec);               /* scale matrix */
2412         add_v2_v2(lmat[3], loc);                /* tranlation matrix */
2413         rotate_m4(rmat, 'Z', angle);    /* rotation matrix */
2414
2415         /* compose transformation matrix */
2416         mul_serie_m4(mat, lmat, cmat, rmat, smat, icmat, NULL, NULL, NULL);
2417 }
2418
2419 MovieDistortion *BKE_tracking_distortion_create(void)
2420 {
2421         MovieDistortion *distortion;
2422
2423         distortion= MEM_callocN(sizeof(MovieDistortion), "BKE_tracking_distortion_create");
2424
2425         return distortion;
2426 }
2427
2428 MovieDistortion *BKE_tracking_distortion_copy(MovieDistortion *distortion)
2429 {
2430         MovieDistortion *new_distortion;
2431
2432         new_distortion= MEM_callocN(sizeof(MovieDistortion), "BKE_tracking_distortion_create");
2433
2434 #ifdef WITH_LIBMV
2435         new_distortion->intrinsics= libmv_CameraIntrinsicsCopy(distortion->intrinsics);
2436 #else
2437         (void)distortion;
2438 #endif
2439
2440         return new_distortion;
2441 }
2442
2443 void BKE_tracking_distortion_update(MovieDistortion *distortion, MovieTracking *tracking, int width, int height)
2444 {
2445         MovieTrackingCamera *camera= &tracking->camera;
2446         float aspy= 1.0f/tracking->camera.pixel_aspect;
2447
2448 #ifdef WITH_LIBMV
2449         if(!distortion->intrinsics) {
2450                 distortion->intrinsics= libmv_CameraIntrinsicsNew(camera->focal,
2451                                 camera->principal[0], camera->principal[1] * aspy,
2452                                 camera->k1, camera->k2, camera->k3, width, height * aspy);
2453         } else {
2454                 libmv_CameraIntrinsicsUpdate(distortion->intrinsics, camera->focal,
2455                                 camera->principal[0], camera->principal[1] * aspy,
2456                                 camera->k1, camera->k2, camera->k3, width, height * aspy);
2457         }
2458 #else
2459         (void)distortion;
2460         (void)width;
2461         (void)height;
2462         (void)camera;
2463         (void)aspy;
2464 #endif
2465 }
2466
2467 ImBuf *BKE_tracking_distortion_exec(MovieDistortion *distortion, MovieTracking *tracking,
2468                         ImBuf *ibuf, int width, int height, float overscan, int undistort)
2469 {
2470         ImBuf *resibuf;
2471
2472         BKE_tracking_distortion_update(distortion, tracking, width, height);
2473
2474         resibuf= IMB_dupImBuf(ibuf);
2475
2476         if(ibuf->rect_float) {
2477 #ifdef WITH_LIBMV
2478                 if(undistort) {
2479                         libmv_CameraIntrinsicsUndistortFloat(distortion->intrinsics,
2480                                                 ibuf->rect_float, resibuf->rect_float,
2481                                                 ibuf->x, ibuf->y, overscan, ibuf->channels);
2482                 } else {
2483                         libmv_CameraIntrinsicsDistortFloat(distortion->intrinsics,
2484                                                 ibuf->rect_float, resibuf->rect_float,
2485                                                 ibuf->x, ibuf->y, overscan, ibuf->channels);
2486                 }
2487 #endif
2488
2489                 ibuf->userflags|= IB_RECT_INVALID;
2490         } else {
2491 #ifdef WITH_LIBMV
2492                 if(undistort) {
2493                                 libmv_CameraIntrinsicsUndistortByte(distortion->intrinsics,
2494                                                         (unsigned char*)ibuf->rect, (unsigned char*)resibuf->rect,
2495                                                         ibuf->x, ibuf->y, overscan, ibuf->channels);
2496                 } else {
2497                         libmv_CameraIntrinsicsDistortByte(distortion->intrinsics,
2498                                                 (unsigned char*)ibuf->rect, (unsigned char*)resibuf->rect,
2499                                                 ibuf->x, ibuf->y, overscan, ibuf->channels);
2500                 }
2501 #endif
2502         }
2503
2504 #ifndef WITH_LIBMV
2505         (void)overscan;
2506         (void)undistort;
2507 #endif
2508
2509         return resibuf;
2510 }
2511
2512 void BKE_tracking_distortion_destroy(MovieDistortion *distortion)
2513 {
2514 #ifdef WITH_LIBMV
2515         libmv_CameraIntrinsicsDestroy(distortion->intrinsics);
2516 #endif
2517
2518         MEM_freeN(distortion);
2519 }
2520
2521 ImBuf *BKE_tracking_undistort(MovieTracking *tracking, ImBuf *ibuf, int width, int height, float overscan)
2522 {
2523         MovieTrackingCamera *camera= &tracking->camera;
2524
2525         if(camera->intrinsics == NULL)
2526                 camera->intrinsics= BKE_tracking_distortion_create();
2527
2528         return BKE_tracking_distortion_exec(camera->intrinsics, tracking, ibuf, width, height, overscan, 1);
2529 }
2530
2531 ImBuf *BKE_tracking_distort(MovieTracking *tracking, ImBuf *ibuf, int width, int height, float overscan)
2532 {
2533         MovieTrackingCamera *camera= &tracking->camera;
2534
2535         if(camera->intrinsics == NULL)
2536                 camera->intrinsics= BKE_tracking_distortion_create();
2537
2538         return BKE_tracking_distortion_exec(camera->intrinsics, tracking, ibuf, width, height, overscan, 0);
2539 }
2540
2541 /* area - which part of marker should be selected. see TRACK_AREA_* constants */
2542 void BKE_tracking_select_track(MovieTracking *tracking, MovieTrackingTrack *track, int area, int extend)
2543 {
2544         if(extend) {
2545                 BKE_tracking_track_flag(track, area, SELECT, 0);
2546         } else {
2547                 MovieTrackingTrack *cur= tracking->tracks.first;
2548
2549                 while(cur) {
2550                         if(cur==track) {
2551                                 BKE_tracking_track_flag(cur, TRACK_AREA_ALL, SELECT, 1);
2552                                 BKE_tracking_track_flag(cur, area, SELECT, 0);
2553                         }
2554                         else {
2555                                 BKE_tracking_track_flag(cur, TRACK_AREA_ALL, SELECT, 1);
2556                         }
2557
2558                         cur= cur->next;
2559                 }
2560         }
2561 }
2562
2563 void BKE_tracking_deselect_track(MovieTrackingTrack *track, int area)
2564 {
2565         BKE_tracking_track_flag(track, area, SELECT, 1);
2566 }