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