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