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