9044661f3691b93768df5df487c8886207acb553
[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
52 #include "BKE_global.h"
53 #include "BKE_tracking.h"
54 #include "BKE_movieclip.h"
55 #include "BKE_object.h"
56 #include "BKE_scene.h"
57
58 #include "IMB_imbuf_types.h"
59 #include "IMB_imbuf.h"
60
61 #ifdef WITH_LIBMV
62 #  include "libmv-capi.h"
63 #else
64 struct libmv_Features;
65 #endif
66
67 typedef struct MovieDistortion {
68         struct libmv_CameraIntrinsics *intrinsics;
69 } MovieDistortion;
70
71 /*********************** common functions *************************/
72
73 void BKE_tracking_init_settings(MovieTracking *tracking)
74 {
75         tracking->camera.sensor_width= 35.0f;
76         tracking->camera.pixel_aspect= 1.0f;
77         tracking->camera.units= CAMERA_UNITS_MM;
78
79         tracking->settings.default_tracker= TRACKER_HYBRID;
80         tracking->settings.default_pyramid_levels= 2;
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
734         int first_time, frames;
735
736         MovieTrackingSettings settings;
737         TracksMap *tracks_map;
738
739         short backwards, disable_failed;
740         int sync_frame;
741 } MovieTrackingContext;
742
743 MovieTrackingContext *BKE_tracking_context_new(MovieClip *clip, MovieClipUser *user, short backwards, short disable_failed)
744 {
745         MovieTrackingContext *context= MEM_callocN(sizeof(MovieTrackingContext), "trackingContext");
746         MovieTracking *tracking= &clip->tracking;
747         MovieTrackingSettings *settings= &tracking->settings;
748         MovieTrackingTrack *track;
749         int num_tracks= 0;
750
751         context->settings= *settings;
752         context->backwards= backwards;
753         context->disable_failed= disable_failed;
754         context->sync_frame= user->framenr;
755         context->first_time= 1;
756
757         /* count */
758         track= tracking->tracks.first;
759         while(track) {
760                 if(TRACK_SELECTED(track) && (track->flag&TRACK_LOCKED)==0) {
761                         MovieTrackingMarker *marker= BKE_tracking_get_marker(track, user->framenr);
762
763                         if((marker->flag&MARKER_DISABLED)==0)
764                                 num_tracks++;
765                 }
766
767                 track= track->next;
768         }
769
770         if(num_tracks) {
771                 int width, height;
772
773                 context->tracks_map= tracks_map_new(num_tracks, sizeof(TrackContext));
774
775                 BKE_movieclip_get_size(clip, user, &width, &height);
776
777                 /* create tracking data */
778                 track= tracking->tracks.first;
779                 while(track) {
780                         if(TRACK_SELECTED(track) && (track->flag&TRACK_LOCKED)==0) {
781                                 MovieTrackingMarker *marker= BKE_tracking_get_marker(track, user->framenr);
782
783                                 if((marker->flag&MARKER_DISABLED)==0) {
784                                         TrackContext track_context;
785
786                                         memset(&track_context, 0, sizeof(TrackContext));
787
788 #ifdef WITH_LIBMV
789                                         {
790                                                 float patx, paty;
791                                                 patx= (int)((track->pat_max[0]-track->pat_min[0])*width);
792                                                 paty= (int)((track->pat_max[1]-track->pat_min[1])*height);
793
794                                                 if(ELEM(track->tracker, TRACKER_KLT, TRACKER_HYBRID)) {
795                                                         float search_size_x= (track->search_max[0]-track->search_min[0])*width;
796                                                         float search_size_y= (track->search_max[1]-track->search_min[1])*height;
797                                                         float pattern_size_x= (track->pat_max[0]-track->pat_min[0])*width;
798                                                         float pattern_size_y= (track->pat_max[1]-track->pat_min[1])*height;
799                                                         int wndx= (int)patx/2, wndy= (int)paty/2;
800
801                                                         /* compute the maximum pyramid size */
802                                                         float search_to_pattern_ratio= MIN2(search_size_x,  search_size_y)
803                                                                 / MAX2(pattern_size_x, pattern_size_y);
804                                                         float log2_search_to_pattern_ratio = log(floor(search_to_pattern_ratio)) / M_LN2;
805                                                         int max_pyramid_levels= floor(log2_search_to_pattern_ratio + 1);
806
807                                                         /* try to accomodate the user's choice of pyramid level in a way
808                                                          * that doesn't cause the coarsest pyramid pattern to be larger
809                                                          * than the search size */
810                                                         int level= MIN2(track->pyramid_levels, max_pyramid_levels);
811
812                                                         if(track->tracker==TRACKER_KLT)
813                                                                 track_context.region_tracker= libmv_pyramidRegionTrackerNew(100, level, MAX2(wndx, wndy));
814                                                         else
815                                                                 track_context.region_tracker= libmv_hybridRegionTrackerNew(100, MAX2(wndx, wndy));
816                                                 }
817                                                 else if(track->tracker==TRACKER_SAD) {
818                                                         track_context.pattern_size= MAX2(patx, paty);
819                                                 }
820                                         }
821 #endif
822
823                                         tracks_map_insert(context->tracks_map, track, &track_context);
824                                 }
825                         }
826
827                         track= track->next;
828                 }
829         }
830
831         context->clip= clip;
832         context->user= *user;
833
834         return context;
835 }
836
837 static void track_context_free(void *customdata)
838 {
839         TrackContext *track_context= (TrackContext *)customdata;
840
841 #if WITH_LIBMV
842         if(track_context->region_tracker)
843                 libmv_regionTrackerDestroy(track_context->region_tracker);
844
845         if(track_context->patch)
846                 MEM_freeN(track_context->patch);
847
848         if(track_context->pattern)
849                 MEM_freeN(track_context->pattern);
850
851         if(track_context->warped)
852                 MEM_freeN(track_context->warped);
853 #else
854                 (void) track_context;
855 #endif
856 }
857
858 void BKE_tracking_context_free(MovieTrackingContext *context)
859 {
860         tracks_map_free(context->tracks_map, track_context_free);
861
862         MEM_freeN(context);
863 }
864
865 static void disable_imbuf_channels(ImBuf *ibuf, MovieTrackingTrack *track)
866 {
867         int x, y;
868
869         if((track->flag&(TRACK_DISABLE_RED|TRACK_DISABLE_GREEN|TRACK_DISABLE_BLUE))==0)
870                 return;
871
872         for(y= 0; y<ibuf->y; y++) {
873                 for (x= 0; x<ibuf->x; x++) {
874                         int pixel= ibuf->x*y + x;
875
876                         if(ibuf->rect_float) {
877                                 float *rrgbf= ibuf->rect_float + pixel*4;
878
879                                 if(track->flag&TRACK_DISABLE_RED)       rrgbf[0]= 0;
880                                 if(track->flag&TRACK_DISABLE_GREEN)     rrgbf[1]= 0;
881                                 if(track->flag&TRACK_DISABLE_BLUE)      rrgbf[2]= 0;
882                         } else {
883                                 char *rrgb= (char*)ibuf->rect + pixel*4;
884
885                                 if(track->flag&TRACK_DISABLE_RED)       rrgb[0]= 0;
886                                 if(track->flag&TRACK_DISABLE_GREEN)     rrgb[1]= 0;
887                                 if(track->flag&TRACK_DISABLE_BLUE)      rrgb[2]= 0;
888                         }
889                 }
890         }
891 }
892
893 static ImBuf *get_area_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
894                         float min[2], float max[2], int margin, int anchored, float pos[2], int origin[2])
895 {
896         ImBuf *tmpibuf;
897         int x, y;
898         int x1, y1, x2, y2, w, h;
899         float mpos[2];
900
901         copy_v2_v2(mpos, marker->pos);
902         if(anchored)
903                 add_v2_v2(mpos, track->offset);
904
905         x= mpos[0]*ibuf->x;
906         y= mpos[1]*ibuf->y;
907         x1= x-(int)(-min[0]*ibuf->x);
908         y1= y-(int)(-min[1]*ibuf->y);
909         x2= x+(int)(max[0]*ibuf->x);
910         y2= y+(int)(max[1]*ibuf->y);
911
912         /* dimensions should be odd */
913         w= (x2-x1)|1;
914         h= (y2-y1)|1;
915
916         tmpibuf= IMB_allocImBuf(w+margin*2, h+margin*2, 32, IB_rect);
917         IMB_rectcpy(tmpibuf, ibuf, 0, 0, x1-margin, y1-margin, w+margin*2, h+margin*2);
918
919         if(pos != NULL) {
920                 pos[0]= mpos[0]*ibuf->x-x1+margin;
921                 pos[1]= mpos[1]*ibuf->y-y1+margin;
922         }
923
924         if(origin != NULL) {
925                 origin[0]= x1-margin;
926                 origin[1]= y1-margin;
927         }
928
929         disable_imbuf_channels(tmpibuf, track);
930
931         return tmpibuf;
932 }
933
934 ImBuf *BKE_tracking_get_pattern_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
935                         int margin, int anchored, float pos[2], int origin[2])
936 {
937         return get_area_imbuf(ibuf, track, marker, track->pat_min, track->pat_max, margin, anchored, pos, origin);
938 }
939
940 ImBuf *BKE_tracking_get_search_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
941                         int margin, int anchored, float pos[2], int origin[2])
942 {
943         return get_area_imbuf(ibuf, track, marker, track->search_min, track->search_max, margin, anchored, pos, origin);
944 }
945
946 #ifdef WITH_LIBMV
947 static float *get_search_floatbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
948                         int *width_r, int *height_r, float pos[2], int origin[2])
949 {
950         ImBuf *tmpibuf;
951         float *pixels, *fp;
952         int x, y, width, height;
953
954         width= (track->search_max[0]-track->search_min[0])*ibuf->x;
955         height= (track->search_max[1]-track->search_min[1])*ibuf->y;
956
957         tmpibuf= BKE_tracking_get_search_imbuf(ibuf, track, marker, 0, 0, pos, origin);
958         disable_imbuf_channels(tmpibuf, track);
959
960         *width_r= width;
961         *height_r= height;
962
963         fp= pixels= MEM_callocN(width*height*sizeof(float), "tracking floatBuf");
964         for(y= 0; y<(int)height; y++) {
965                 for (x= 0; x<(int)width; x++) {
966                         int pixel= tmpibuf->x*y + x;
967
968                         if(tmpibuf->rect_float) {
969                                 float *rrgbf= tmpibuf->rect_float + pixel*4;
970
971                                 *fp= 0.2126*rrgbf[0] + 0.7152*rrgbf[1] + 0.0722*rrgbf[2];
972                         } else {
973                                 unsigned char *rrgb= (unsigned char*)tmpibuf->rect + pixel*4;
974
975                                 *fp= (0.2126*rrgb[0] + 0.7152*rrgb[1] + 0.0722*rrgb[2])/255.0f;
976                         }
977
978                         fp++;
979                 }
980         }
981
982         IMB_freeImBuf(tmpibuf);
983
984         return pixels;
985 }
986
987 static unsigned char *get_ucharbuf(ImBuf *ibuf)
988 {
989         int x, y;
990         unsigned char *pixels, *cp;
991
992         cp= pixels= MEM_callocN(ibuf->x*ibuf->y*sizeof(unsigned char), "tracking ucharBuf");
993         for(y= 0; y<ibuf->y; y++) {
994                 for (x= 0; x<ibuf->x; x++) {
995                         int pixel= ibuf->x*y + x;
996
997                         if(ibuf->rect_float) {
998                                 float *rrgbf= ibuf->rect_float + pixel*4;
999
1000                                 *cp= FTOCHAR(0.2126f*rrgbf[0] + 0.7152f*rrgbf[1] + 0.0722f*rrgbf[2]);
1001                         } else {
1002                                 unsigned char *rrgb= (unsigned char*)ibuf->rect + pixel*4;
1003
1004                                 *cp= 0.2126f*rrgb[0] + 0.7152f*rrgb[1] + 0.0722f*rrgb[2];
1005                         }
1006
1007                         cp++;
1008                 }
1009         }
1010
1011         return pixels;
1012 }
1013
1014 static unsigned char *get_search_bytebuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
1015                         int *width_r, int *height_r, float pos[2], int origin[2])
1016 {
1017         ImBuf *tmpibuf;
1018         unsigned char *pixels;
1019
1020         tmpibuf= BKE_tracking_get_search_imbuf(ibuf, track, marker, 0, 0, pos, origin);
1021         disable_imbuf_channels(tmpibuf, track);
1022
1023         *width_r= tmpibuf->x;
1024         *height_r= tmpibuf->y;
1025
1026         pixels= get_ucharbuf(tmpibuf);
1027
1028         IMB_freeImBuf(tmpibuf);
1029
1030         return pixels;
1031 }
1032
1033 static ImBuf *get_frame_ibuf(MovieTrackingContext *context, int framenr)
1034 {
1035         ImBuf *ibuf;
1036         MovieClipUser user= context->user;
1037
1038         user.framenr= framenr;
1039
1040         ibuf= BKE_movieclip_get_ibuf_flag(context->clip, &user, 0);
1041
1042         return ibuf;
1043 }
1044
1045 static ImBuf *get_keyframed_ibuf(MovieTrackingContext *context, MovieTrackingTrack *track,
1046                         MovieTrackingMarker *marker, MovieTrackingMarker **marker_keyed)
1047 {
1048         int framenr= marker->framenr;
1049         int a= marker-track->markers;
1050
1051         *marker_keyed= marker;
1052
1053         while(a>=0 && a<track->markersnr) {
1054                 int next= (context->backwards) ? a+1 : a-1;
1055                 int is_keyframed= 0;
1056                 MovieTrackingMarker *cur_marker= &track->markers[a];
1057                 MovieTrackingMarker *next_marker= NULL;
1058
1059                 if(next>=0 && next<track->markersnr)
1060                         next_marker= &track->markers[next];
1061
1062                 /* if next mrker is disabled, stop searching keyframe and use current frame as keyframe */
1063                 if(next_marker && next_marker->flag&MARKER_DISABLED)
1064                         is_keyframed= 1;
1065
1066                 is_keyframed|= (cur_marker->flag&MARKER_TRACKED)==0;
1067
1068                 if(is_keyframed) {
1069                         framenr= cur_marker->framenr;
1070                         *marker_keyed= cur_marker;
1071                         break;
1072                 }
1073
1074                 a= next;
1075         }
1076
1077         return get_frame_ibuf(context, framenr);
1078 }
1079
1080 static ImBuf *get_adjust_ibuf(MovieTrackingContext *context, MovieTrackingTrack *track, MovieTrackingMarker *marker,
1081                         int curfra, MovieTrackingMarker **marker_keyed)
1082 {
1083         ImBuf *ibuf= NULL;
1084
1085         if(track->pattern_match == TRACK_MATCH_KEYFRAME) {
1086                 ibuf= get_keyframed_ibuf(context, track, marker, marker_keyed);
1087         } else {
1088                 ibuf= get_frame_ibuf(context, curfra);
1089
1090                 /* use current marker as keyframed position */
1091                 *marker_keyed= marker;
1092         }
1093
1094         return ibuf;
1095 }
1096
1097 static void get_warped(TrackContext *track_context, int x, int y, int width, unsigned char *image)
1098 {
1099         int i, j;
1100
1101         for(i=0; i<track_context->pattern_size; i++) {
1102                 for(j=0; j<track_context->pattern_size; j++) {
1103                         track_context->warped[i*track_context->pattern_size+j]=
1104                                         image[(y+i-track_context->pattern_size/2)*width+x+j-track_context->pattern_size/2];
1105                 }
1106         }
1107 }
1108
1109 #endif
1110
1111 void BKE_tracking_sync(MovieTrackingContext *context)
1112 {
1113         MovieTracking *tracking= &context->clip->tracking;
1114         int newframe;
1115
1116         tracks_map_merge(context->tracks_map, tracking);
1117
1118         if(context->backwards) newframe= context->user.framenr+1;
1119         else newframe= context->user.framenr-1;
1120
1121         context->sync_frame= newframe;
1122 }
1123
1124 void BKE_tracking_sync_user(MovieClipUser *user, MovieTrackingContext *context)
1125 {
1126         user->framenr= context->sync_frame;
1127 }
1128
1129 int BKE_tracking_next(MovieTrackingContext *context)
1130 {
1131         ImBuf *ibuf_new;
1132         int curfra= context->user.framenr;
1133         int a, ok= 0, map_size;
1134
1135         map_size= tracks_map_size(context->tracks_map);
1136
1137         /* nothing to track, avoid unneeded frames reading to save time and memory */
1138         if(!map_size)
1139                 return 0;
1140
1141         if(context->backwards) context->user.framenr--;
1142         else context->user.framenr++;
1143
1144         ibuf_new= BKE_movieclip_get_ibuf_flag(context->clip, &context->user, 0);
1145         if(!ibuf_new)
1146                 return 0;
1147
1148         #pragma omp parallel for private(a) shared(ibuf_new, ok) if(map_size>1)
1149         for(a= 0; a<map_size; a++) {
1150                 TrackContext *track_context;
1151                 MovieTrackingTrack *track;
1152                 MovieTrackingMarker *marker;
1153
1154                 tracks_map_get(context->tracks_map, a, &track, (void**)&track_context);
1155
1156                 marker= BKE_tracking_exact_marker(track, curfra);
1157
1158                 if(marker && (marker->flag&MARKER_DISABLED)==0) {
1159 #ifdef WITH_LIBMV
1160                         int width, height, origin[2], tracked= 0, need_readjust= 0;
1161                         float pos[2], margin[2], dim[2];
1162                         double x1, y1, x2, y2;
1163                         ImBuf *ibuf= NULL;
1164                         MovieTrackingMarker marker_new, *marker_keyed;
1165                         int onbound= 0, coords_correct= 0;
1166                         int nextfra;
1167
1168                         if(track->pattern_match==TRACK_MATCH_KEYFRAME)
1169                                 need_readjust= context->first_time;
1170                         else
1171                                 need_readjust= 1;
1172
1173                         if(context->backwards) nextfra= curfra-1;
1174                         else nextfra= curfra+1;
1175
1176                         /* margin from frame boundaries */
1177                         sub_v2_v2v2(dim, track->pat_max, track->pat_min);
1178                         margin[0]= margin[1]= MAX2(dim[0], dim[1]) / 2.0f;
1179
1180                         margin[0]= MAX2(margin[0], (float)track->margin / ibuf_new->x);
1181                         margin[1]= MAX2(margin[1], (float)track->margin / ibuf_new->y);
1182
1183                         /* do not track markers which are too close to boundary */
1184                         if(marker->pos[0]<margin[0] || marker->pos[0]>1.0f-margin[0] ||
1185                            marker->pos[1]<margin[1] || marker->pos[1]>1.0f-margin[1]) {
1186                                 onbound= 1;
1187                         }
1188                         else if(ELEM(track->tracker, TRACKER_KLT, TRACKER_HYBRID)) {
1189                                 float *patch_new;
1190
1191                                 if(need_readjust) {
1192                                         /* calculate patch for keyframed position */
1193                                         ibuf= get_adjust_ibuf(context, track, marker, curfra, &marker_keyed);
1194
1195                                         if(track_context->patch)
1196                                                 MEM_freeN(track_context->patch);
1197
1198                                         track_context->patch= get_search_floatbuf(ibuf, track, marker_keyed, &width, &height, track_context->keyframed_pos, origin);
1199
1200                                         IMB_freeImBuf(ibuf);
1201                                 }
1202
1203                                 patch_new= get_search_floatbuf(ibuf_new, track, marker, &width, &height, pos, origin);
1204
1205                                 x1= track_context->keyframed_pos[0];
1206                                 y1= track_context->keyframed_pos[1];
1207
1208                                 x2= pos[0];
1209                                 y2= pos[1];
1210
1211                                 tracked= libmv_regionTrackerTrack(track_context->region_tracker, track_context->patch, patch_new,
1212                                                         width, height, x1, y1, &x2, &y2);
1213
1214                                 MEM_freeN(patch_new);
1215                         }
1216                         else if(track->tracker==TRACKER_SAD) {
1217                                 unsigned char *image_new;
1218                                 float correlation;
1219                                 float warp[3][2]={{0}};
1220
1221                                 if(need_readjust) {
1222                                         unsigned char *image;
1223
1224                                         /* calculate pattern for keyframed position */
1225                                         ibuf= get_adjust_ibuf(context, track, marker, curfra, &marker_keyed);
1226
1227                                         image= get_search_bytebuf(ibuf, track, marker_keyed, &width, &height, pos, origin);
1228
1229                                         memset(warp, 0, sizeof(warp));
1230                                         warp[0][0]= 1;
1231                                         warp[1][1]= 1;
1232                                         warp[2][0]= pos[0];
1233                                         warp[2][1]= pos[1];
1234
1235                                         if(!track_context->pattern) {
1236                                                 int square= track_context->pattern_size*track_context->pattern_size;
1237                                                 track_context->pattern= MEM_callocN(sizeof(unsigned char)*square, "trackking pattern");
1238                                         }
1239
1240                                         libmv_SADSamplePattern(image, width, warp, track_context->pattern, track_context->pattern_size);
1241
1242                                         MEM_freeN(image);
1243                                         IMB_freeImBuf(ibuf);
1244                                 }
1245
1246                                 image_new= get_search_bytebuf(ibuf_new, track, marker, &width, &height, pos, origin);
1247
1248                                 if(track_context->warped==NULL) {
1249                                         unsigned char *image_old;
1250
1251                                         ibuf= get_frame_ibuf(context, curfra);
1252
1253                                         if(track_context->warped==NULL) {
1254                                                 int square= track_context->pattern_size*track_context->pattern_size;
1255                                                 track_context->warped= MEM_callocN(sizeof(unsigned char)*square, "trackking warped");
1256                                         }
1257
1258                                         image_old= get_search_bytebuf(ibuf, track, marker, &width, &height, pos, origin);
1259                                         get_warped(track_context, pos[0], pos[1], width, image_old);
1260                                         IMB_freeImBuf(ibuf);
1261                                         MEM_freeN(image_old);
1262                                 }
1263
1264                                 memset(warp, 0, sizeof(warp));
1265                                 warp[0][0]= 1;
1266                                 warp[1][1]= 1;
1267                                 warp[2][0]= pos[0];
1268                                 warp[2][1]= pos[1];
1269
1270                                 correlation= libmv_SADTrackerTrack(track_context->pattern, track_context->warped,
1271                                                         track_context->pattern_size, image_new, width, width, height, warp);
1272
1273                                 x2= warp[2][0];
1274                                 y2= warp[2][1];
1275
1276                                 tracked= track->minimum_correlation < correlation;
1277
1278                                 if(tracked)
1279                                         get_warped(track_context, x2, y2, width, image_new);
1280
1281                                 MEM_freeN(image_new);
1282                         }
1283
1284                         coords_correct= !isnan(x2) && !isnan(y2) && finite(x2) && finite(y2);
1285                         if(coords_correct && !onbound && (tracked || !context->disable_failed)) {
1286                                 if(context->first_time) {
1287                                         #pragma omp critical
1288                                         {
1289                                                 /* check if there's no keyframe/tracked markers before tracking marker.
1290                                                    if so -- create disabled marker before currently tracking "segment" */
1291                                                 put_disabled_marker(track, marker, !context->backwards, 0);
1292                                         }
1293                                 }
1294
1295                                 memset(&marker_new, 0, sizeof(marker_new));
1296
1297                                 if(!onbound) {
1298                                         marker_new.pos[0]= (origin[0]+x2)/ibuf_new->x;
1299                                         marker_new.pos[1]= (origin[1]+y2)/ibuf_new->y;
1300                                 } else {
1301                                         copy_v2_v2(marker_new.pos, marker->pos);
1302                                 }
1303
1304                                 marker_new.flag|= MARKER_TRACKED;
1305                                 marker_new.framenr= nextfra;
1306
1307                                 #pragma omp critical
1308                                 {
1309                                         BKE_tracking_insert_marker(track, &marker_new);
1310                                 }
1311
1312                                 /* make currently tracked segment be finished with disabled marker */
1313                                 #pragma omp critical
1314                                 {
1315                                         put_disabled_marker(track, &marker_new, context->backwards, 0);
1316                                 }
1317                         } else {
1318                                 marker_new= *marker;
1319
1320                                 marker_new.framenr= nextfra;
1321                                 marker_new.flag|= MARKER_DISABLED;
1322
1323                                 #pragma omp critical
1324                                 {
1325                                         BKE_tracking_insert_marker(track, &marker_new);
1326                                 }
1327                         }
1328
1329                         ok= 1;
1330 #endif
1331                 }
1332         }
1333
1334         IMB_freeImBuf(ibuf_new);
1335
1336         context->first_time= 0;
1337         context->frames++;
1338
1339         return ok;
1340 }
1341
1342 /*********************** camera solving *************************/
1343
1344 typedef struct MovieReconstructContext {
1345 #ifdef WITH_LIBMV
1346         struct libmv_Tracks *tracks;
1347         int keyframe1, keyframe2;
1348         short refine_flags;
1349
1350         struct libmv_Reconstruction *reconstruction;
1351 #endif
1352
1353         float focal_length;
1354         float principal_point[2];
1355         float k1, k2, k3;
1356
1357         float reprojection_error;
1358
1359         TracksMap *tracks_map;
1360
1361         int sfra, efra;
1362 } MovieReconstructContext;
1363
1364 typedef struct ReconstructProgressData {
1365         short *stop;
1366         short *do_update;
1367         float *progress;
1368         char *stats_message;
1369         int message_size;
1370 } ReconstructProgressData;
1371
1372 #if WITH_LIBMV
1373 static struct libmv_Tracks *create_libmv_tracks(MovieTracking *tracking, int width, int height)
1374 {
1375         int tracknr= 0;
1376         MovieTrackingTrack *track;
1377         struct libmv_Tracks *tracks= libmv_tracksNew();
1378
1379         track= tracking->tracks.first;
1380         while(track) {
1381                 int a= 0;
1382
1383                 for(a= 0; a<track->markersnr; a++) {
1384                         MovieTrackingMarker *marker= &track->markers[a];
1385
1386                         if((marker->flag&MARKER_DISABLED)==0)
1387                                 libmv_tracksInsert(tracks, marker->framenr, tracknr,
1388                                                         marker->pos[0]*width, marker->pos[1]*height);
1389                 }
1390
1391                 track= track->next;
1392                 tracknr++;
1393         }
1394
1395         return tracks;
1396 }
1397
1398 static void retrieve_libmv_reconstruct_intrinscis(MovieReconstructContext *context, MovieTracking *tracking)
1399 {
1400         struct libmv_Reconstruction *libmv_reconstruction= context->reconstruction;
1401         struct libmv_CameraIntrinsics *libmv_intrinsics = libmv_ReconstructionExtractIntrinsics(libmv_reconstruction);
1402
1403         float aspy= 1.0f/tracking->camera.pixel_aspect;
1404
1405         double focal_length, principal_x, principal_y, k1, k2, k3;
1406         int width, height;
1407
1408         libmv_CameraIntrinsicsExtract(libmv_intrinsics, &focal_length, &principal_x, &principal_y,
1409                         &k1, &k2, &k3, &width, &height);
1410
1411         tracking->camera.focal= focal_length;
1412         tracking->camera.principal[0]= principal_x;
1413
1414         /* todo: verify divide by aspy is correct */
1415         tracking->camera.principal[1]= principal_y / aspy;
1416         tracking->camera.k1= k1;
1417         tracking->camera.k2= k2;
1418 }
1419
1420 static int retrieve_libmv_reconstruct_tracks(MovieReconstructContext *context, MovieTracking *tracking)
1421 {
1422         struct libmv_Reconstruction *libmv_reconstruction= context->reconstruction;
1423         MovieTrackingReconstruction *reconstruction= &tracking->reconstruction;
1424         MovieReconstructedCamera *reconstructed;
1425         MovieTrackingTrack *track;
1426         int ok= 1, tracknr= 0, a, origin_set= 0;
1427         int sfra= context->sfra, efra= context->efra;
1428         float imat[4][4];
1429
1430         unit_m4(imat);
1431
1432         track= tracking->tracks.first;
1433         while(track) {
1434                 double pos[3];
1435
1436                 if(libmv_reporojectionPointForTrack(libmv_reconstruction, tracknr, pos)) {
1437                         track->bundle_pos[0]= pos[0];
1438                         track->bundle_pos[1]= pos[1];
1439                         track->bundle_pos[2]= pos[2];
1440
1441                         track->flag|= TRACK_HAS_BUNDLE;
1442                         track->error= libmv_reporojectionErrorForTrack(libmv_reconstruction, tracknr);
1443                 } else {
1444                         track->flag&= ~TRACK_HAS_BUNDLE;
1445                         ok= 0;
1446
1447                         printf("No bundle for track #%d '%s'\n", tracknr, track->name);
1448                 }
1449
1450                 track= track->next;
1451                 tracknr++;
1452         }
1453
1454         if(reconstruction->cameras)
1455                 MEM_freeN(reconstruction->cameras);
1456
1457         reconstruction->camnr= 0;
1458         reconstruction->cameras= NULL;
1459         reconstructed= MEM_callocN((efra-sfra+1)*sizeof(MovieReconstructedCamera), "temp reconstructed camera");
1460
1461         for(a= sfra; a<=efra; a++) {
1462                 double matd[4][4];
1463
1464                 if(libmv_reporojectionCameraForImage(libmv_reconstruction, a, matd)) {
1465                         int i, j;
1466                         float mat[4][4];
1467                         float error= libmv_reporojectionErrorForImage(libmv_reconstruction, a);
1468
1469                         for(i=0; i<4; i++)
1470                                 for(j= 0; j<4; j++)
1471                                         mat[i][j]= matd[i][j];
1472
1473                         if(!origin_set) {
1474                                 copy_m4_m4(imat, mat);
1475                                 invert_m4(imat);
1476                                 origin_set= 1;
1477                         }
1478
1479                         if(origin_set)
1480                                 mul_m4_m4m4(mat, mat, imat);
1481
1482                         copy_m4_m4(reconstructed[reconstruction->camnr].mat, mat);
1483                         reconstructed[reconstruction->camnr].framenr= a;
1484                         reconstructed[reconstruction->camnr].error= error;
1485                         reconstruction->camnr++;
1486                 } else {
1487                         ok= 0;
1488                         printf("No camera for frame %d\n", a);
1489                 }
1490         }
1491
1492         if(reconstruction->camnr) {
1493                 reconstruction->cameras= MEM_callocN(reconstruction->camnr*sizeof(MovieReconstructedCamera), "reconstructed camera");
1494                 memcpy(reconstruction->cameras, reconstructed, reconstruction->camnr*sizeof(MovieReconstructedCamera));
1495         }
1496
1497         if(origin_set) {
1498                 track= tracking->tracks.first;
1499                 while(track) {
1500                         if(track->flag&TRACK_HAS_BUNDLE)
1501                                 mul_v3_m4v3(track->bundle_pos, imat, track->bundle_pos);
1502
1503                         track= track->next;
1504                 }
1505         }
1506
1507         MEM_freeN(reconstructed);
1508
1509         return ok;
1510 }
1511
1512 static int retrieve_libmv_reconstruct(MovieReconstructContext *context, MovieTracking *tracking)
1513 {
1514         tracks_map_merge(context->tracks_map, tracking);
1515
1516         /* take the intrinscis back from libmv */
1517         retrieve_libmv_reconstruct_intrinscis(context, tracking);
1518
1519         return retrieve_libmv_reconstruct_tracks(context, tracking);
1520 }
1521
1522 static int get_refine_intrinsics_flags(MovieTracking *tracking)
1523 {
1524         int refine= tracking->settings.refine_camera_intrinsics;
1525         int flags= 0;
1526
1527         if(refine&REFINE_FOCAL_LENGTH)
1528                 flags|= LIBMV_REFINE_FOCAL_LENGTH;
1529
1530         if(refine&REFINE_PRINCIPAL_POINT)
1531                 flags|= LIBMV_REFINE_PRINCIPAL_POINT;
1532
1533         if(refine&REFINE_RADIAL_DISTORTION_K1)
1534                 flags|= REFINE_RADIAL_DISTORTION_K1;
1535
1536         if(refine&REFINE_RADIAL_DISTORTION_K2)
1537                 flags|= REFINE_RADIAL_DISTORTION_K2;
1538
1539         return flags;
1540 }
1541
1542 static int count_tracks_on_both_keyframes(MovieTracking *tracking)
1543 {
1544         int tot= 0;
1545         int frame1= tracking->settings.keyframe1, frame2= tracking->settings.keyframe2;
1546         MovieTrackingTrack *track;
1547
1548         track= tracking->tracks.first;
1549         while(track) {
1550                 if(BKE_tracking_has_marker(track, frame1))
1551                         if(BKE_tracking_has_marker(track, frame2))
1552                                 tot++;
1553
1554                 track= track->next;
1555         }
1556
1557         return tot;
1558 }
1559 #endif
1560
1561 int BKE_tracking_can_reconstruct(MovieTracking *tracking, char *error_msg, int error_size)
1562 {
1563 #if WITH_LIBMV
1564         if(count_tracks_on_both_keyframes(tracking)<8) {
1565                 BLI_strncpy(error_msg, "At least 8 tracks on both of keyframes are needed for reconstruction", error_size);
1566                 return 0;
1567         }
1568
1569         return 1;
1570 #else
1571         BLI_strncpy(error_msg, "Blender is compiled without motion tracking library", error_size);
1572         (void) tracking;
1573
1574         return 0;
1575 #endif
1576 }
1577
1578 MovieReconstructContext* BKE_tracking_reconstruction_context_new(MovieTracking *tracking,
1579                         int keyframe1, int keyframe2, int width, int height)
1580 {
1581         MovieReconstructContext *context= MEM_callocN(sizeof(MovieReconstructContext), "MovieReconstructContext data");
1582         MovieTrackingCamera *camera= &tracking->camera;
1583         float aspy= 1.0f/tracking->camera.pixel_aspect;
1584         int num_tracks= BLI_countlist(&tracking->tracks);
1585         int sfra= INT_MAX, efra= INT_MIN;
1586         MovieTrackingTrack *track;
1587
1588         context->tracks_map= tracks_map_new(num_tracks, 0);
1589         track= tracking->tracks.first;
1590         while(track) {
1591                 int first= 0, last= track->markersnr;
1592                 MovieTrackingMarker *first_marker= &track->markers[0];
1593                 MovieTrackingMarker *last_marker= &track->markers[track->markersnr-1];
1594
1595                 /* find first not-disabled marker */
1596                 while(first<track->markersnr-1 && first_marker->flag&MARKER_DISABLED) {
1597                         first++;
1598                         first_marker++;
1599                 }
1600
1601                 /* find last not-disabled marker */
1602                 while(last>=0 && last_marker->flag&MARKER_DISABLED) {
1603                         last--;
1604                         last_marker--;
1605                 }
1606
1607                 if(first<track->markersnr-1)
1608                         sfra= MIN2(sfra, first_marker->framenr);
1609
1610                 if(last>=0)
1611                         efra= MAX2(efra, last_marker->framenr);
1612
1613                 tracks_map_insert(context->tracks_map, track, NULL);
1614
1615                 track= track->next;
1616         }
1617
1618         context->sfra= sfra;
1619         context->efra= efra;
1620
1621 #ifdef WITH_LIBMV
1622         context->tracks= create_libmv_tracks(tracking, width, height*aspy);
1623         context->keyframe1= keyframe1;
1624         context->keyframe2= keyframe2;
1625         context->refine_flags= get_refine_intrinsics_flags(tracking);
1626 #else
1627         (void) width;
1628         (void) height;
1629         (void) keyframe1;
1630         (void) keyframe2;
1631 #endif
1632
1633         context->focal_length= camera->focal;
1634         context->principal_point[0]= camera->principal[0];
1635         context->principal_point[1]= camera->principal[1]*aspy;
1636
1637         context->k1= camera->k1;
1638         context->k2= camera->k2;
1639         context->k2= camera->k2;
1640
1641         return context;
1642 }
1643
1644 void BKE_tracking_reconstruction_context_free(MovieReconstructContext *context)
1645 {
1646 #ifdef WITH_LIBMV
1647         if(context->reconstruction)
1648                         libmv_destroyReconstruction(context->reconstruction);
1649
1650         libmv_tracksDestroy(context->tracks);
1651 #endif
1652
1653         tracks_map_free(context->tracks_map, NULL);
1654
1655         MEM_freeN(context);
1656 }
1657
1658 #ifdef WITH_LIBMV
1659 static void solve_reconstruction_update_cb(void *customdata, double progress, const char *message)
1660 {
1661         ReconstructProgressData *progressdata= customdata;
1662
1663         if(progressdata->progress) {
1664                 *progressdata->progress= progress;
1665                 *progressdata->do_update= 1;
1666         }
1667
1668         BLI_snprintf(progressdata->stats_message, progressdata->message_size,
1669                         "Solving camera | %s", message);
1670 }
1671 #endif
1672
1673 #if 0
1674 static int solve_reconstruction_testbreak_cb(void *customdata)
1675 {
1676         ReconstructProgressData *progressdata= customdata;
1677
1678         if(progressdata->stop && *progressdata->stop)
1679                 return 1;
1680
1681         return G.afbreek;
1682 }
1683 #endif
1684
1685 void BKE_tracking_solve_reconstruction(MovieReconstructContext *context, short *stop,
1686                         short *do_update, float *progress, char *stats_message, int message_size)
1687 {
1688 #ifdef WITH_LIBMV
1689         float error;
1690
1691         ReconstructProgressData progressdata;
1692
1693         progressdata.stop= stop;
1694         progressdata.do_update= do_update;
1695         progressdata.progress= progress;
1696         progressdata.stats_message= stats_message;
1697         progressdata.message_size= message_size;
1698
1699         context->reconstruction = libmv_solveReconstruction(context->tracks,
1700                 context->keyframe1, context->keyframe2,
1701                 context->refine_flags,
1702                 context->focal_length,
1703                 context->principal_point[0], context->principal_point[1],
1704                 context->k1, context->k2, context->k3,
1705                 solve_reconstruction_update_cb, &progressdata);
1706
1707         error= libmv_reprojectionError(context->reconstruction);
1708
1709         context->reprojection_error= error;
1710 #else
1711         (void) context;
1712         (void) stop;
1713         (void) do_update;
1714         (void) progress;
1715         (void) stats_message;
1716         (void) message_size;
1717 #endif
1718 }
1719
1720 int BKE_tracking_finish_reconstruction(MovieReconstructContext *context, MovieTracking *tracking)
1721 {
1722         tracking->reconstruction.error= context->reprojection_error;
1723         tracking->reconstruction.flag|= TRACKING_RECONSTRUCTED;
1724
1725 #ifdef WITH_LIBMV
1726         if(!retrieve_libmv_reconstruct(context, tracking))
1727                 return 0;
1728 #endif
1729
1730         return 1;
1731 }
1732
1733 void BKE_track_unique_name(MovieTracking *tracking, MovieTrackingTrack *track)
1734 {
1735         BLI_uniquename(&tracking->tracks, track, "Track", '.', offsetof(MovieTrackingTrack, name), sizeof(track->name));
1736 }
1737
1738 MovieTrackingTrack *BKE_tracking_named_track(MovieTracking *tracking, const char *name)
1739 {
1740         MovieTrackingTrack *track= tracking->tracks.first;
1741
1742         while(track) {
1743                 if(!strcmp(track->name, name))
1744                         return track;
1745
1746                 track= track->next;
1747         }
1748
1749         return NULL;
1750 }
1751
1752 static int reconstruction_camera_index(MovieTracking *tracking, int framenr, int nearest)
1753 {
1754         MovieTrackingReconstruction *reconstruction= &tracking->reconstruction;
1755         MovieReconstructedCamera *cameras= reconstruction->cameras;
1756         int a= 0, d= 1;
1757
1758         if(!reconstruction->camnr)
1759                 return -1;
1760
1761         if(framenr<cameras[0].framenr) {
1762                 if(nearest) return 0;
1763                 else return -1;
1764         }
1765
1766         if(framenr>cameras[reconstruction->camnr-1].framenr) {
1767                 if(nearest) return reconstruction->camnr-1;
1768                 else return -1;
1769         }
1770
1771         if(reconstruction->last_camera<reconstruction->camnr)
1772                 a= reconstruction->last_camera;
1773
1774         if(cameras[a].framenr>=framenr)
1775                 d= -1;
1776
1777         while(a>=0 && a<reconstruction->camnr) {
1778                 int cfra= cameras[a].framenr;
1779
1780                 /* check if needed framenr was "skipped" -- no data for requested frame */
1781
1782                 if(d>0 && cfra>framenr) {
1783                         /* interpolate with previous position */
1784                         if(nearest) return a-1;
1785                         else break;
1786                 }
1787
1788                 if(d<0 && cfra<framenr) {
1789                         /* interpolate with next position */
1790                         if(nearest) return a;
1791                         else break;
1792                 }
1793
1794                 if(cfra==framenr) {
1795                         reconstruction->last_camera= a;
1796
1797                         return a;
1798                 }
1799
1800                 a+= d;
1801         }
1802
1803         return -1;
1804 }
1805
1806 MovieReconstructedCamera *BKE_tracking_get_reconstructed_camera(MovieTracking *tracking, int framenr)
1807 {
1808         int a= reconstruction_camera_index(tracking, framenr, 0);
1809
1810         if(a==-1)
1811                 return NULL;
1812
1813         return &tracking->reconstruction.cameras[a];
1814 }
1815
1816 void BKE_tracking_get_interpolated_camera(MovieTracking *tracking, int framenr, float mat[4][4])
1817 {
1818         MovieTrackingReconstruction *reconstruction= &tracking->reconstruction;
1819         MovieReconstructedCamera *cameras= reconstruction->cameras;
1820         int a= reconstruction_camera_index(tracking, framenr, 1);
1821
1822         if(a==-1) {
1823                 unit_m4(mat);
1824                 return;
1825         }
1826
1827         if(cameras[a].framenr!=framenr && a>0 && a<reconstruction->camnr-1) {
1828                 float t= ((float)framenr-cameras[a].framenr) / (cameras[a+1].framenr-cameras[a].framenr);
1829
1830                 blend_m4_m4m4(mat, cameras[a].mat, cameras[a+1].mat, t);
1831         } else {
1832                 copy_m4_m4(mat, cameras[a].mat);
1833         }
1834 }
1835
1836 void BKE_get_tracking_mat(Scene *scene, Object *ob, float mat[4][4])
1837 {
1838         if(!ob) {
1839                 if(scene->camera) ob= scene->camera;
1840                 else ob= scene_find_camera(scene);
1841         }
1842
1843         if(ob)
1844                 where_is_object_mat(scene, ob, mat);
1845         else
1846                 unit_m4(mat);
1847 }
1848
1849 void BKE_tracking_camera_shift(MovieTracking *tracking, int winx, int winy, float *shiftx, float *shifty)
1850 {
1851         *shiftx= (0.5f*winx-tracking->camera.principal[0]) / winx;
1852         *shifty= (0.5f*winy-tracking->camera.principal[1]) / winx;
1853 }
1854
1855 void BKE_tracking_camera_to_blender(MovieTracking *tracking, Scene *scene, Camera *camera, int width, int height)
1856 {
1857         float focal= tracking->camera.focal;
1858
1859         camera->sensor_x= tracking->camera.sensor_width;
1860         camera->sensor_fit= CAMERA_SENSOR_FIT_AUTO;
1861         camera->lens= focal*camera->sensor_x/width;
1862
1863         scene->r.xsch= width*tracking->camera.pixel_aspect;
1864         scene->r.ysch= height;
1865
1866         scene->r.xasp= 1.0f;
1867         scene->r.yasp= 1.0f;
1868
1869         BKE_tracking_camera_shift(tracking, width, height, &camera->shiftx, &camera->shifty);
1870 }
1871
1872 void BKE_tracking_projection_matrix(MovieTracking *tracking, int framenr, int winx, int winy, float mat[4][4])
1873 {
1874         MovieReconstructedCamera *camera;
1875         float lens= tracking->camera.focal*tracking->camera.sensor_width/(float)winx;
1876         float viewfac, pixsize, left, right, bottom, top, clipsta, clipend;
1877         float winmat[4][4];
1878         float ycor= 1.0f/tracking->camera.pixel_aspect;
1879         float shiftx, shifty, winside= MAX2(winx, winy);
1880
1881         BKE_tracking_camera_shift(tracking, winx, winy, &shiftx, &shifty);
1882
1883         clipsta= 0.1f;
1884         clipend= 1000.0f;
1885
1886         if(winx >= winy)
1887                 viewfac= (lens*winx)/tracking->camera.sensor_width;
1888         else
1889                 viewfac= (ycor*lens*winy)/tracking->camera.sensor_width;
1890
1891         pixsize= clipsta/viewfac;
1892
1893         left= -0.5f*(float)winx + shiftx*winside;
1894         bottom= -0.5f*(ycor)*(float)winy + shifty*winside;
1895         right=  0.5f*(float)winx + shiftx*winside;
1896         top=  0.5f*(ycor)*(float)winy + shifty*winside;
1897
1898         left *= pixsize;
1899         right *= pixsize;
1900         bottom *= pixsize;
1901         top *= pixsize;
1902
1903         perspective_m4(winmat, left, right, bottom, top, clipsta, clipend);
1904
1905         camera= BKE_tracking_get_reconstructed_camera(tracking, framenr);
1906         if(camera) {
1907                 float imat[4][4];
1908
1909                 invert_m4_m4(imat, camera->mat);
1910                 mul_m4_m4m4(mat, imat, winmat);
1911         } else copy_m4_m4(mat, winmat);
1912 }
1913
1914 void BKE_tracking_apply_intrinsics(MovieTracking *tracking, float co[2], float nco[2])
1915 {
1916         MovieTrackingCamera *camera= &tracking->camera;
1917
1918 #ifdef WITH_LIBMV
1919         double x, y;
1920         float aspy= 1.0f/tracking->camera.pixel_aspect;
1921
1922         /* normalize coords */
1923         x= (co[0]-camera->principal[0]) / camera->focal;
1924         y= (co[1]-camera->principal[1] * aspy) / camera->focal;
1925
1926         libmv_applyCameraIntrinsics(camera->focal, camera->principal[0], camera->principal[1] * aspy,
1927                                 camera->k1, camera->k2, camera->k3, x, y, &x, &y);
1928
1929         /* result is in image coords already */
1930         nco[0]= x;
1931         nco[1]= y;
1932 #else
1933         (void)camera;
1934         (void)co;
1935         (void)nco;
1936 #endif
1937 }
1938
1939 void BKE_tracking_invert_intrinsics(MovieTracking *tracking, float co[2], float nco[2])
1940 {
1941         MovieTrackingCamera *camera= &tracking->camera;
1942
1943 #ifdef WITH_LIBMV
1944         double x= co[0], y= co[1];
1945         float aspy= 1.0f/tracking->camera.pixel_aspect;
1946
1947         libmv_InvertIntrinsics(camera->focal, camera->principal[0], camera->principal[1] * aspy,
1948                                 camera->k1, camera->k2, camera->k3, x, y, &x, &y);
1949
1950         nco[0]= x * camera->focal + camera->principal[0];
1951         nco[1]= y * camera->focal + camera->principal[1] * aspy;
1952 #else
1953         (void)camera;
1954         (void)co;
1955         (void)nco;
1956 #endif
1957 }
1958
1959 #ifdef WITH_LIBMV
1960 static int point_in_stroke(bGPDstroke *stroke, float x, float y)
1961 {
1962         int i, prev;
1963         int count= 0;
1964         bGPDspoint *points= stroke->points;
1965
1966         prev= stroke->totpoints-1;
1967
1968         for(i= 0; i<stroke->totpoints; i++) {
1969                 if((points[i].y<y && points[prev].y>=y) || (points[prev].y<y && points[i].y>=y)) {
1970                         float fac= (y-points[i].y)/(points[prev].y-points[i].y);
1971
1972                         if (points[i].x+fac*(points[prev].x-points[i].x)<x)
1973                                 count++;
1974                 }
1975
1976                 prev= i;
1977         }
1978
1979         return count%2;
1980 }
1981
1982 static int point_in_layer(bGPDlayer *layer, float x, float y)
1983 {
1984         bGPDframe *frame= layer->frames.first;
1985
1986         while(frame) {
1987                 bGPDstroke *stroke= frame->strokes.first;
1988                 while(stroke) {
1989                         if(point_in_stroke(stroke, x, y))
1990                                 return 1;
1991
1992                         stroke= stroke->next;
1993                 }
1994                 frame= frame->next;
1995         }
1996
1997         return 0;
1998 }
1999
2000 static void retrieve_libmv_features(MovieTracking *tracking, struct libmv_Features *features,
2001                         int framenr, int width, int height, bGPDlayer *layer, int place_outside_layer)
2002 {
2003         int a;
2004
2005         a= libmv_countFeatures(features);
2006         while(a--) {
2007                 MovieTrackingTrack *track;
2008                 double x, y, size, score;
2009                 int ok= 1;
2010                 float xu, yu;
2011
2012                 libmv_getFeature(features, a, &x, &y, &score, &size);
2013
2014                 xu= x/width;
2015                 yu= y/height;
2016
2017                 if(layer)
2018                         ok= point_in_layer(layer, xu, yu)!=place_outside_layer;
2019
2020                 if(ok) {
2021                         track= BKE_tracking_add_track(tracking, xu, yu, framenr, width, height);
2022                         track->flag|= SELECT;
2023                         track->pat_flag|= SELECT;
2024                         track->search_flag|= SELECT;
2025                 }
2026         }
2027 }
2028 #endif
2029
2030 void BKE_tracking_detect_fast(MovieTracking *tracking, ImBuf *ibuf,
2031                         int framenr, int margin, int min_trackness, int min_distance, bGPDlayer *layer,
2032                         int place_outside_layer)
2033 {
2034 #ifdef WITH_LIBMV
2035         struct libmv_Features *features;
2036         unsigned char *pixels= get_ucharbuf(ibuf);
2037
2038         features= libmv_detectFeaturesFAST(pixels, ibuf->x, ibuf->y, ibuf->x, margin, min_trackness, min_distance);
2039
2040         MEM_freeN(pixels);
2041
2042         retrieve_libmv_features(tracking, features, framenr, ibuf->x, ibuf->y, layer, place_outside_layer);
2043
2044         libmv_destroyFeatures(features);
2045 #else
2046         (void)tracking;
2047         (void)ibuf;
2048         (void)framenr;
2049         (void)margin;
2050         (void)min_trackness;
2051         (void)min_distance;
2052         (void)layer;
2053         (void)place_outside_layer;
2054 #endif
2055 }
2056
2057 MovieTrackingTrack *BKE_tracking_indexed_track(MovieTracking *tracking, int tracknr)
2058 {
2059         MovieTrackingTrack *track= tracking->tracks.first;
2060         int cur= 1;
2061
2062         while(track) {
2063                 if(track->flag&TRACK_HAS_BUNDLE) {
2064                         if(cur==tracknr)
2065                                 return track;
2066
2067                         cur++;
2068                 }
2069
2070                 track= track->next;
2071         }
2072
2073         return NULL;
2074 }
2075
2076 static int stabilization_median_point(MovieTracking *tracking, int framenr, float median[2])
2077 {
2078         int ok= 0;
2079         float min[2], max[2];
2080         MovieTrackingTrack *track;
2081
2082         INIT_MINMAX2(min, max);
2083
2084         track= tracking->tracks.first;
2085         while(track) {
2086                 if(track->flag&TRACK_USE_2D_STAB) {
2087                         MovieTrackingMarker *marker= BKE_tracking_get_marker(track, framenr);
2088
2089                         DO_MINMAX2(marker->pos, min, max);
2090
2091                         ok= 1;
2092                 }
2093
2094                 track= track->next;
2095         }
2096
2097         median[0]= (max[0]+min[0])/2.0f;
2098         median[1]= (max[1]+min[1])/2.0f;
2099
2100         return ok;
2101 }
2102
2103 static void calculate_stabdata(MovieTracking *tracking, int framenr, float width, float height,
2104                         float firstmedian[2], float median[2], float loc[2], float *scale, float *angle)
2105 {
2106         MovieTrackingStabilization *stab= &tracking->stabilization;
2107
2108         *scale= (stab->scale-1.0f)*stab->scaleinf+1.0f;
2109         *angle= 0.0f;
2110
2111         loc[0]= (firstmedian[0]-median[0])*width*(*scale);
2112         loc[1]= (firstmedian[1]-median[1])*height*(*scale);
2113
2114         mul_v2_fl(loc, stab->locinf);
2115
2116         if((stab->flag&TRACKING_STABILIZE_ROTATION) && stab->rot_track && stab->rotinf) {
2117                 MovieTrackingMarker *marker;
2118                 float a[2], b[2];
2119                 float x0= (float)width/2.0f, y0= (float)height/2.0f;
2120                 float x= median[0]*width, y= median[1]*height;
2121
2122                 marker= BKE_tracking_get_marker(stab->rot_track, 1);
2123                 sub_v2_v2v2(a, marker->pos, firstmedian);
2124                 a[0]*= width;
2125                 a[1]*= height;
2126
2127                 marker= BKE_tracking_get_marker(stab->rot_track, framenr);
2128                 sub_v2_v2v2(b, marker->pos, median);
2129                 b[0]*= width;
2130                 b[1]*= height;
2131
2132                 *angle= -atan2(a[0]*b[1]-a[1]*b[0], a[0]*b[0]+a[1]*b[1]);
2133                 *angle*= stab->rotinf;
2134
2135                 /* convert to rotation around image center */
2136                 loc[0]-= (x0 + (x-x0)*cosf(*angle)-(y-y0)*sinf(*angle) - x)*(*scale);
2137                 loc[1]-= (y0 + (x-x0)*sinf(*angle)+(y-y0)*cosf(*angle) - y)*(*scale);
2138         }
2139 }
2140
2141 static float stabilization_auto_scale_factor(MovieTracking *tracking, int width, int height)
2142 {
2143         float firstmedian[2];
2144         MovieTrackingStabilization *stab= &tracking->stabilization;
2145
2146         if(stab->ok)
2147                 return stab->scale;
2148
2149         if(stabilization_median_point(tracking, 1, firstmedian)) {
2150                 int sfra= INT_MAX, efra= INT_MIN, cfra;
2151                 float delta[2]= {0.0f, 0.0f}, scalex= 1.0f, scaley= 1.0f;
2152                 MovieTrackingTrack *track;
2153
2154                 stab->scale= 1.0f;
2155
2156                 track= tracking->tracks.first;
2157                 while(track) {
2158                         if(track->flag&TRACK_USE_2D_STAB ||
2159                            ((stab->flag&TRACKING_STABILIZE_ROTATION) && track==stab->rot_track)) {
2160                                 sfra= MIN2(sfra, track->markers[0].framenr);
2161                                 efra= MAX2(efra, track->markers[track->markersnr-1].framenr);
2162                         }
2163
2164                         track= track->next;
2165                 }
2166
2167                 for(cfra=sfra; cfra<=efra; cfra++) {
2168                         float median[2], near[2];
2169                         float loc[2], scale, angle;
2170
2171                         stabilization_median_point(tracking, cfra, median);
2172
2173                         calculate_stabdata(tracking, cfra, width, height, firstmedian, median,
2174                                                 loc, &scale, &angle);
2175
2176                         if(angle==0.0f) {
2177                                 loc[0]= fabsf(loc[0]);
2178                                 loc[1]= fabsf(loc[1]);
2179
2180                                 delta[0]= MAX2(delta[0], loc[0]);
2181                                 delta[1]= MAX2(delta[1], loc[1]);
2182
2183                                 near[0]= MIN2(median[0], 1.0f-median[0]);
2184                                 near[1]= MIN2(median[1], 1.0f-median[1]);
2185                                 near[0]= MAX2(near[0], 0.05f);
2186                                 near[1]= MAX2(near[1], 0.05f);
2187
2188                                 scalex= 1.0f+delta[0]/(near[0]*width);
2189                                 scaley= 1.0f+delta[1]/(near[1]*height);
2190                         } else {
2191                                 int i;
2192                                 float mat[4][4];
2193                                 float points[4][2]={{0.0f, 0.0f}, {0.0f, height}, {width, height}, {width, 0.0f}};
2194
2195                                 BKE_tracking_stabdata_to_mat4(width, height, loc, scale, angle, mat);
2196
2197                                 for(i= 0; i<4; i++) {
2198                                         int j;
2199                                         float a[3]= {0.0f, 0.0f, 0.0f}, b[3]= {0.0f, 0.0f, 0.0f};
2200
2201                                         copy_v3_v3(a, points[i]);
2202                                         copy_v3_v3(b, points[(i+1)%4]);
2203
2204                                         mul_m4_v3(mat, a);
2205                                         mul_m4_v3(mat, b);
2206
2207                                         for(j= 0; j<4; j++) {
2208                                                 float point[3]= {points[j][0], points[j][1], 0.0f};
2209                                                 float v1[3], v2[3];
2210
2211                                                 sub_v3_v3v3(v1, b, a);
2212                                                 sub_v3_v3v3(v2, point, a);
2213
2214                                                 if(cross_v2v2(v1, v2) >= 0.0f) {
2215                                                         float dist= dist_to_line_v2(point, a, b);
2216                                                         if(i%2==0) {
2217                                                                 scalex= MAX2(scalex, (width+2*dist)/width);
2218                                                         } else {
2219                                                                 scaley= MAX2(scaley, (height+2*dist)/height);
2220                                                         }
2221                                                 }
2222                                         }
2223                                 }
2224                         }
2225                 }
2226
2227                 stab->scale= MAX2(scalex, scaley);
2228
2229                 if(stab->maxscale>0.0f)
2230                         stab->scale= MIN2(stab->scale, stab->maxscale);
2231         } else {
2232                 stab->scale= 1.0f;
2233         }
2234
2235         stab->ok= 1;
2236
2237         return stab->scale;
2238 }
2239
2240 static ImBuf* stabilize_alloc_ibuf(ImBuf *cacheibuf, ImBuf *srcibuf, int fill)
2241 {
2242         int flags;
2243
2244         if(cacheibuf && (cacheibuf->x != srcibuf->x || cacheibuf->y != srcibuf->y)) {
2245                 IMB_freeImBuf(cacheibuf);
2246                 cacheibuf= NULL;
2247         }
2248
2249         flags= IB_rect;
2250
2251         if(srcibuf->rect_float)
2252                 flags|= IB_rectfloat;
2253
2254         if(cacheibuf) {
2255                 if(fill) {
2256                         float col[4]= {0.0f, 0.0f, 0.0f, 0.0f};
2257                         IMB_rectfill(cacheibuf, col);
2258                 }
2259         }
2260         else {
2261                 cacheibuf= IMB_allocImBuf(srcibuf->x, srcibuf->y, srcibuf->planes, flags);
2262                 cacheibuf->profile= srcibuf->profile;
2263         }
2264
2265         return cacheibuf;
2266 }
2267
2268 void BKE_tracking_stabilization_data(MovieTracking *tracking, int framenr, int width, int height, float loc[2], float *scale, float *angle)
2269 {
2270         float firstmedian[2], median[2];
2271         MovieTrackingStabilization *stab= &tracking->stabilization;
2272
2273         if((stab->flag&TRACKING_2D_STABILIZATION)==0) {
2274                 zero_v2(loc);
2275                 *scale= 1.0f;
2276                 *angle= 0.0f;
2277
2278                 return;
2279         }
2280
2281         if(stabilization_median_point(tracking, 1, firstmedian)) {
2282                 stabilization_median_point(tracking, framenr, median);
2283
2284                 if((stab->flag&TRACKING_AUTOSCALE)==0)
2285                         stab->scale= 1.0f;
2286
2287                 if(!stab->ok) {
2288                         if(stab->flag&TRACKING_AUTOSCALE)
2289                                 stabilization_auto_scale_factor(tracking, width, height);
2290
2291                         calculate_stabdata(tracking, framenr, width, height, firstmedian, median, loc, scale, angle);
2292
2293                         stab->ok= 1;
2294                 } else {
2295                         calculate_stabdata(tracking, framenr, width, height, firstmedian, median, loc, scale, angle);
2296                 }
2297         } else {
2298                 zero_v2(loc);
2299                 *scale= 1.0f;
2300                 *angle= 0.0f;
2301         }
2302 }
2303
2304 ImBuf *BKE_tracking_stabilize(MovieTracking *tracking, int framenr, ImBuf *ibuf, float loc[2], float *scale, float *angle)
2305 {
2306         float tloc[2], tscale, tangle;
2307         MovieTrackingStabilization *stab= &tracking->stabilization;
2308         ImBuf *tmpibuf;
2309         float width= ibuf->x, height= ibuf->y;
2310
2311         if(loc)         copy_v2_v2(tloc, loc);
2312         if(scale)       tscale= *scale;
2313
2314         if((stab->flag&TRACKING_2D_STABILIZATION)==0) {
2315                 if(loc)         zero_v2(loc);
2316                 if(scale)       *scale= 1.0f;
2317
2318                 return ibuf;
2319         }
2320
2321         BKE_tracking_stabilization_data(tracking, framenr, width, height, tloc, &tscale, &tangle);
2322
2323         tmpibuf= stabilize_alloc_ibuf(NULL, ibuf, 1);
2324
2325         /* scale would be handled by matrix transformation when angle is non-zero */
2326         if(tscale!=1.0f && tangle==0.0f) {
2327                 ImBuf *scaleibuf;
2328
2329                 stabilization_auto_scale_factor(tracking, width, height);
2330
2331                 scaleibuf= stabilize_alloc_ibuf(stab->scaleibuf, ibuf, 0);
2332                 stab->scaleibuf= scaleibuf;
2333
2334                 IMB_rectcpy(scaleibuf, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
2335                 IMB_scalefastImBuf(scaleibuf, ibuf->x*tscale, ibuf->y*tscale);
2336
2337                 ibuf= scaleibuf;
2338         }
2339
2340         if(tangle==0.0f) {
2341                 /* if angle is zero, then it's much faster to use rect copy
2342                    but could be issues with subpixel precisions */
2343                 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);
2344         } else {
2345                 float mat[4][4];
2346                 int i, j;
2347
2348                 BKE_tracking_stabdata_to_mat4(ibuf->x, ibuf->y, tloc, tscale, tangle, mat);
2349                 invert_m4(mat);
2350
2351                 for(j=0; j<tmpibuf->y; j++) {
2352                         for(i=0; i<tmpibuf->x;i++) {
2353                                 float vec[3]= {i, j, 0};
2354
2355                                 mul_v3_m4v3(vec, mat, vec);
2356
2357                                 /* TODO: add selector for interpolation method */
2358                                 neareast_interpolation(ibuf, tmpibuf, vec[0], vec[1], i, j);
2359                         }
2360                 }
2361         }
2362
2363         tmpibuf->userflags|= IB_MIPMAP_INVALID;
2364
2365         if(tmpibuf->rect_float)
2366                 tmpibuf->userflags|= IB_RECT_INVALID;
2367
2368         if(loc)         copy_v2_v2(loc, tloc);
2369         if(scale)       *scale= tscale;
2370         if(angle)       *angle= tangle;
2371
2372         return tmpibuf;
2373 }
2374
2375 void BKE_tracking_stabdata_to_mat4(int width, int height, float loc[2], float scale, float angle, float mat[4][4])
2376 {
2377         float lmat[4][4], rmat[4][4], smat[4][4], cmat[4][4], icmat[4][4];
2378         float svec[3]= {scale, scale, scale};
2379
2380         unit_m4(rmat);
2381         unit_m4(lmat);
2382         unit_m4(smat);
2383         unit_m4(cmat);
2384
2385         /* image center as rotation center */
2386         cmat[3][0]= (float)width/2.0f;
2387         cmat[3][1]= (float)height/2.0f;
2388         invert_m4_m4(icmat, cmat);
2389
2390         size_to_mat4(smat, svec);               /* scale matrix */
2391         add_v2_v2(lmat[3], loc);                /* tranlation matrix */
2392         rotate_m4(rmat, 'Z', angle);    /* rotation matrix */
2393
2394         /* compose transformation matrix */
2395         mul_serie_m4(mat, lmat, cmat, rmat, smat, icmat, NULL, NULL, NULL);
2396 }
2397
2398 MovieDistortion *BKE_tracking_distortion_create(void)
2399 {
2400         MovieDistortion *distortion;
2401
2402         distortion= MEM_callocN(sizeof(MovieDistortion), "BKE_tracking_distortion_create");
2403
2404         return distortion;
2405 }
2406
2407 MovieDistortion *BKE_tracking_distortion_copy(MovieDistortion *distortion)
2408 {
2409         MovieDistortion *new_distortion;
2410
2411         new_distortion= MEM_callocN(sizeof(MovieDistortion), "BKE_tracking_distortion_create");
2412
2413 #ifdef WITH_LIBMV
2414         new_distortion->intrinsics= libmv_CameraIntrinsicsCopy(distortion->intrinsics);
2415 #else
2416         (void)distortion;
2417 #endif
2418
2419         return new_distortion;
2420 }
2421
2422 void BKE_tracking_distortion_update(MovieDistortion *distortion, MovieTracking *tracking, int width, int height)
2423 {
2424         MovieTrackingCamera *camera= &tracking->camera;
2425         float aspy= 1.0f/tracking->camera.pixel_aspect;
2426
2427 #ifdef WITH_LIBMV
2428         if(!distortion->intrinsics) {
2429                 distortion->intrinsics= libmv_CameraIntrinsicsNew(camera->focal,
2430                                 camera->principal[0], camera->principal[1] * aspy,
2431                                 camera->k1, camera->k2, camera->k3, width, height * aspy);
2432         } else {
2433                 libmv_CameraIntrinsicsUpdate(distortion->intrinsics, camera->focal,
2434                                 camera->principal[0], camera->principal[1] * aspy,
2435                                 camera->k1, camera->k2, camera->k3, width, height * aspy);
2436         }
2437 #else
2438         (void)distortion;
2439         (void)width;
2440         (void)height;
2441         (void)camera;
2442         (void)aspy;
2443 #endif
2444 }
2445
2446 ImBuf *BKE_tracking_distortion_exec(MovieDistortion *distortion, MovieTracking *tracking,
2447                         ImBuf *ibuf, int width, int height, float overscan, int undistort)
2448 {
2449         ImBuf *resibuf;
2450
2451         BKE_tracking_distortion_update(distortion, tracking, width, height);
2452
2453         resibuf= IMB_dupImBuf(ibuf);
2454
2455         if(ibuf->rect_float) {
2456 #ifdef WITH_LIBMV
2457                 if(undistort) {
2458                         libmv_CameraIntrinsicsUndistortFloat(distortion->intrinsics,
2459                                                 ibuf->rect_float, resibuf->rect_float,
2460                                                 ibuf->x, ibuf->y, overscan, ibuf->channels);
2461                 } else {
2462                         libmv_CameraIntrinsicsDistortFloat(distortion->intrinsics,
2463                                                 ibuf->rect_float, resibuf->rect_float,
2464                                                 ibuf->x, ibuf->y, overscan, ibuf->channels);
2465                 }
2466 #endif
2467
2468                 ibuf->userflags|= IB_RECT_INVALID;
2469         } else {
2470 #ifdef WITH_LIBMV
2471                 if(undistort) {
2472                                 libmv_CameraIntrinsicsUndistortByte(distortion->intrinsics,
2473                                                         (unsigned char*)ibuf->rect, (unsigned char*)resibuf->rect,
2474                                                         ibuf->x, ibuf->y, overscan, ibuf->channels);
2475                 } else {
2476                         libmv_CameraIntrinsicsDistortByte(distortion->intrinsics,
2477                                                 (unsigned char*)ibuf->rect, (unsigned char*)resibuf->rect,
2478                                                 ibuf->x, ibuf->y, overscan, ibuf->channels);
2479                 }
2480 #endif
2481         }
2482
2483 #ifndef WITH_LIBMV
2484         (void)overscan;
2485         (void)undistort;
2486 #endif
2487
2488         return resibuf;
2489 }
2490
2491 void BKE_tracking_distortion_destroy(MovieDistortion *distortion)
2492 {
2493 #ifdef WITH_LIBMV
2494         libmv_CameraIntrinsicsDestroy(distortion->intrinsics);
2495 #endif
2496
2497         MEM_freeN(distortion);
2498 }
2499
2500 ImBuf *BKE_tracking_undistort(MovieTracking *tracking, ImBuf *ibuf, int width, int height, float overscan)
2501 {
2502         MovieTrackingCamera *camera= &tracking->camera;
2503
2504         if(camera->intrinsics == NULL)
2505                 camera->intrinsics= BKE_tracking_distortion_create();
2506
2507         return BKE_tracking_distortion_exec(camera->intrinsics, tracking, ibuf, width, height, overscan, 1);
2508 }
2509
2510 ImBuf *BKE_tracking_distort(MovieTracking *tracking, ImBuf *ibuf, int width, int height, float overscan)
2511 {
2512         MovieTrackingCamera *camera= &tracking->camera;
2513
2514         if(camera->intrinsics == NULL)
2515                 camera->intrinsics= BKE_tracking_distortion_create();
2516
2517         return BKE_tracking_distortion_exec(camera->intrinsics, tracking, ibuf, width, height, overscan, 0);
2518 }
2519
2520 /* area - which part of marker should be selected. see TRACK_AREA_* constants */
2521 void BKE_tracking_select_track(MovieTracking *tracking, MovieTrackingTrack *track, int area, int extend)
2522 {
2523         if(extend) {
2524                 BKE_tracking_track_flag(track, area, SELECT, 0);
2525         } else {
2526                 MovieTrackingTrack *cur= tracking->tracks.first;
2527
2528                 while(cur) {
2529                         if(cur==track) {
2530                                 BKE_tracking_track_flag(cur, TRACK_AREA_ALL, SELECT, 1);
2531                                 BKE_tracking_track_flag(cur, area, SELECT, 0);
2532                         }
2533                         else {
2534                                 BKE_tracking_track_flag(cur, TRACK_AREA_ALL, SELECT, 1);
2535                         }
2536
2537                         cur= cur->next;
2538                 }
2539         }
2540 }
2541
2542 void BKE_tracking_deselect_track(MovieTrackingTrack *track, int area)
2543 {
2544         BKE_tracking_track_flag(track, area, SELECT, 1);
2545 }