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