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