Camera tracking: tracks copy/paste operator
[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[32];
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, 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         x2= x+(int)(w/2.0f);
1089         y2= y+(int)(h/2.0f);
1090
1091         /* dimensions should be odd */
1092         tmpibuf= IMB_allocImBuf(w+margin*2, h+margin*2, 32, IB_rect);
1093         IMB_rectcpy(tmpibuf, ibuf, 0, 0, x1-margin, y1-margin, w+margin*2, h+margin*2);
1094
1095         if(pos != NULL) {
1096                 pos[0]= mpos[0]*ibuf->x-x1+margin;
1097                 pos[1]= mpos[1]*ibuf->y-y1+margin;
1098         }
1099
1100         if(origin != NULL) {
1101                 origin[0]= x1-margin;
1102                 origin[1]= y1-margin;
1103         }
1104
1105         if((track->flag & TRACK_PREVIEW_GRAYSCALE) ||
1106            (track->flag & TRACK_DISABLE_RED)       ||
1107            (track->flag & TRACK_DISABLE_GREEN)     ||
1108            (track->flag & TRACK_DISABLE_BLUE))
1109         {
1110                 disable_imbuf_channels(tmpibuf, track, 1 /* grayscale */);
1111         }
1112
1113         tmpibuf->ftype= PNG;
1114         IMB_saveiff(tmpibuf, "/tmp/1.png", IB_rect);
1115
1116         return tmpibuf;
1117 }
1118
1119 ImBuf *BKE_tracking_get_pattern_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
1120                         int margin, int anchored, float pos[2], int origin[2])
1121 {
1122         return get_area_imbuf(ibuf, track, marker, track->pat_min, track->pat_max, margin, anchored, pos, origin);
1123 }
1124
1125 ImBuf *BKE_tracking_get_search_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
1126                         int margin, int anchored, float pos[2], int origin[2])
1127 {
1128         return get_area_imbuf(ibuf, track, marker, track->search_min, track->search_max, margin, anchored, pos, origin);
1129 }
1130
1131 #ifdef WITH_LIBMV
1132 static float *get_search_floatbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
1133                         int *width_r, int *height_r, float pos[2], int origin[2])
1134 {
1135         ImBuf *tmpibuf;
1136         float *pixels, *fp;
1137         int x, y, width, height;
1138
1139         width= (track->search_max[0]-track->search_min[0])*ibuf->x;
1140         height= (track->search_max[1]-track->search_min[1])*ibuf->y;
1141
1142         tmpibuf= BKE_tracking_get_search_imbuf(ibuf, track, marker, 0, 0, pos, origin);
1143         disable_imbuf_channels(tmpibuf, track, 0 /* don't grayscale */);
1144
1145         *width_r= width;
1146         *height_r= height;
1147
1148         fp= pixels= MEM_callocN(width*height*sizeof(float), "tracking floatBuf");
1149         for(y= 0; y<(int)height; y++) {
1150                 for (x= 0; x<(int)width; x++) {
1151                         int pixel= tmpibuf->x*y + x;
1152
1153                         if(tmpibuf->rect_float) {
1154                                 float *rrgbf= tmpibuf->rect_float + pixel*4;
1155                                 *fp= 0.2126*rrgbf[0] + 0.7152*rrgbf[1] + 0.0722*rrgbf[2];
1156                         } else {
1157                                 unsigned char *rrgb= (unsigned char*)tmpibuf->rect + pixel*4;
1158                                 *fp= (0.2126*rrgb[0] + 0.7152*rrgb[1] + 0.0722*rrgb[2])/255.0f;
1159                         }
1160                         fp++;
1161                 }
1162         }
1163
1164         IMB_freeImBuf(tmpibuf);
1165
1166         return pixels;
1167 }
1168
1169 static unsigned char *get_ucharbuf(ImBuf *ibuf)
1170 {
1171         int x, y;
1172         unsigned char *pixels, *cp;
1173
1174         cp= pixels= MEM_callocN(ibuf->x*ibuf->y*sizeof(unsigned char), "tracking ucharBuf");
1175         for(y= 0; y<ibuf->y; y++) {
1176                 for (x= 0; x<ibuf->x; x++) {
1177                         int pixel= ibuf->x*y + x;
1178
1179                         if(ibuf->rect_float) {
1180                                 float *rrgbf= ibuf->rect_float + pixel*4;
1181                                 *cp= FTOCHAR(0.2126f*rrgbf[0] + 0.7152f*rrgbf[1] + 0.0722f*rrgbf[2]);
1182                         } else {
1183                                 unsigned char *rrgb= (unsigned char*)ibuf->rect + pixel*4;
1184                                 *cp= 0.2126f*rrgb[0] + 0.7152f*rrgb[1] + 0.0722f*rrgb[2];
1185                         }
1186                         cp++;
1187                 }
1188         }
1189
1190         return pixels;
1191 }
1192
1193 static unsigned char *get_search_bytebuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
1194                         int *width_r, int *height_r, float pos[2], int origin[2])
1195 {
1196         ImBuf *tmpibuf;
1197         unsigned char *pixels;
1198
1199         tmpibuf= BKE_tracking_get_search_imbuf(ibuf, track, marker, 0, 0, pos, origin);
1200         disable_imbuf_channels(tmpibuf, track, 0 /* don't grayscale */);
1201
1202         *width_r= tmpibuf->x;
1203         *height_r= tmpibuf->y;
1204
1205         pixels= get_ucharbuf(tmpibuf);
1206
1207         IMB_freeImBuf(tmpibuf);
1208
1209         return pixels;
1210 }
1211
1212 static ImBuf *get_frame_ibuf(MovieTrackingContext *context, int framenr)
1213 {
1214         ImBuf *ibuf;
1215         MovieClipUser user= context->user;
1216
1217         user.framenr= framenr;
1218
1219         ibuf= BKE_movieclip_get_ibuf_flag(context->clip, &user, context->clip_flag);
1220
1221         return ibuf;
1222 }
1223
1224 static ImBuf *get_keyframed_ibuf(MovieTrackingContext *context, MovieTrackingTrack *track,
1225                         MovieTrackingMarker *marker, MovieTrackingMarker **marker_keyed)
1226 {
1227         int framenr= marker->framenr;
1228         int a= marker-track->markers;
1229
1230         *marker_keyed= marker;
1231
1232         while(a>=0 && a<track->markersnr) {
1233                 int next= (context->backwards) ? a+1 : a-1;
1234                 int is_keyframed= 0;
1235                 MovieTrackingMarker *cur_marker= &track->markers[a];
1236                 MovieTrackingMarker *next_marker= NULL;
1237
1238                 if(next>=0 && next<track->markersnr)
1239                         next_marker= &track->markers[next];
1240
1241                 /* if next mrker is disabled, stop searching keyframe and use current frame as keyframe */
1242                 if(next_marker && next_marker->flag&MARKER_DISABLED)
1243                         is_keyframed= 1;
1244
1245                 is_keyframed|= (cur_marker->flag&MARKER_TRACKED)==0;
1246
1247                 if(is_keyframed) {
1248                         framenr= cur_marker->framenr;
1249                         *marker_keyed= cur_marker;
1250                         break;
1251                 }
1252
1253                 a= next;
1254         }
1255
1256         return get_frame_ibuf(context, framenr);
1257 }
1258
1259 static ImBuf *get_adjust_ibuf(MovieTrackingContext *context, MovieTrackingTrack *track, MovieTrackingMarker *marker,
1260                         int curfra, MovieTrackingMarker **marker_keyed)
1261 {
1262         ImBuf *ibuf= NULL;
1263
1264         if(track->pattern_match == TRACK_MATCH_KEYFRAME) {
1265                 ibuf= get_keyframed_ibuf(context, track, marker, marker_keyed);
1266         } else {
1267                 ibuf= get_frame_ibuf(context, curfra);
1268
1269                 /* use current marker as keyframed position */
1270                 *marker_keyed= marker;
1271         }
1272
1273         return ibuf;
1274 }
1275
1276 static void get_warped(TrackContext *track_context, int x, int y, int width, unsigned char *image)
1277 {
1278         int i, j;
1279
1280         for(i=0; i<track_context->pattern_size; i++) {
1281                 for(j=0; j<track_context->pattern_size; j++) {
1282                         track_context->warped[i*track_context->pattern_size+j]=
1283                                         image[(y+i-track_context->pattern_size/2)*width+x+j-track_context->pattern_size/2];
1284                 }
1285         }
1286 }
1287
1288 #endif
1289
1290 void BKE_tracking_sync(MovieTrackingContext *context)
1291 {
1292         MovieTracking *tracking= &context->clip->tracking;
1293         int newframe;
1294
1295         tracks_map_merge(context->tracks_map, tracking);
1296
1297         if(context->backwards) newframe= context->user.framenr+1;
1298         else newframe= context->user.framenr-1;
1299
1300         context->sync_frame= newframe;
1301 }
1302
1303 void BKE_tracking_sync_user(MovieClipUser *user, MovieTrackingContext *context)
1304 {
1305         user->framenr= context->sync_frame;
1306 }
1307
1308 int BKE_tracking_next(MovieTrackingContext *context)
1309 {
1310         ImBuf *ibuf_new;
1311         int curfra= context->user.framenr;
1312         int a, ok= 0, map_size;
1313
1314         map_size= tracks_map_size(context->tracks_map);
1315
1316         /* nothing to track, avoid unneeded frames reading to save time and memory */
1317         if(!map_size)
1318                 return 0;
1319
1320         if(context->backwards) context->user.framenr--;
1321         else context->user.framenr++;
1322
1323         ibuf_new= BKE_movieclip_get_ibuf_flag(context->clip, &context->user, context->clip_flag);
1324         if(!ibuf_new)
1325                 return 0;
1326
1327         #pragma omp parallel for private(a) shared(ibuf_new, ok) if(map_size>1)
1328         for(a= 0; a<map_size; a++) {
1329                 TrackContext *track_context = NULL;
1330                 MovieTrackingTrack *track;
1331                 MovieTrackingMarker *marker;
1332
1333                 tracks_map_get(context->tracks_map, a, &track, (void**)&track_context);
1334
1335                 marker= BKE_tracking_exact_marker(track, curfra);
1336
1337                 if(marker && (marker->flag&MARKER_DISABLED)==0) {
1338 #ifdef WITH_LIBMV
1339                         int width, height, origin[2], tracked= 0, need_readjust= 0;
1340                         float pos[2], margin[2], dim[2];
1341                         double x1, y1, x2, y2;
1342                         ImBuf *ibuf= NULL;
1343                         MovieTrackingMarker marker_new, *marker_keyed;
1344                         int onbound= 0, nextfra;
1345
1346                         if(track->pattern_match==TRACK_MATCH_KEYFRAME)
1347                                 need_readjust= context->first_time;
1348                         else
1349                                 need_readjust= 1;
1350
1351                         if(context->backwards) nextfra= curfra-1;
1352                         else nextfra= curfra+1;
1353
1354                         /* margin from frame boundaries */
1355                         sub_v2_v2v2(dim, track->pat_max, track->pat_min);
1356                         margin[0]= margin[1]= MAX2(dim[0], dim[1]) / 2.0f;
1357
1358                         margin[0]= MAX2(margin[0], (float)track->margin / ibuf_new->x);
1359                         margin[1]= MAX2(margin[1], (float)track->margin / ibuf_new->y);
1360
1361                         /* do not track markers which are too close to boundary */
1362                         if(marker->pos[0]<margin[0] || marker->pos[0]>1.0f-margin[0] ||
1363                            marker->pos[1]<margin[1] || marker->pos[1]>1.0f-margin[1]) {
1364                                 onbound= 1;
1365                         }
1366                         else if(ELEM(track->tracker, TRACKER_KLT, TRACKER_HYBRID)) {
1367                                 float *patch_new;
1368
1369                                 if(need_readjust) {
1370                                         /* calculate patch for keyframed position */
1371                                         ibuf= get_adjust_ibuf(context, track, marker, curfra, &marker_keyed);
1372
1373                                         if(track_context->patch)
1374                                                 MEM_freeN(track_context->patch);
1375
1376                                         track_context->patch= get_search_floatbuf(ibuf, track, marker_keyed, &width, &height, track_context->keyframed_pos, origin);
1377
1378                                         IMB_freeImBuf(ibuf);
1379                                 }
1380
1381                                 patch_new= get_search_floatbuf(ibuf_new, track, marker, &width, &height, pos, origin);
1382
1383                                 x1= track_context->keyframed_pos[0];
1384                                 y1= track_context->keyframed_pos[1];
1385
1386                                 x2= pos[0];
1387                                 y2= pos[1];
1388
1389                                 tracked= libmv_regionTrackerTrack(track_context->region_tracker, track_context->patch, patch_new,
1390                                                         width, height, x1, y1, &x2, &y2);
1391
1392                                 MEM_freeN(patch_new);
1393                         }
1394                         else if(track->tracker==TRACKER_SAD) {
1395                                 unsigned char *image_new;
1396                                 float correlation;
1397                                 float warp[3][2]={{0}};
1398
1399                                 if(need_readjust) {
1400                                         unsigned char *image;
1401
1402                                         /* calculate pattern for keyframed position */
1403                                         ibuf= get_adjust_ibuf(context, track, marker, curfra, &marker_keyed);
1404
1405                                         image= get_search_bytebuf(ibuf, track, marker_keyed, &width, &height, pos, origin);
1406
1407                                         memset(warp, 0, sizeof(warp));
1408                                         warp[0][0]= 1;
1409                                         warp[1][1]= 1;
1410                                         warp[2][0]= pos[0];
1411                                         warp[2][1]= pos[1];
1412
1413                                         if(!track_context->pattern) {
1414                                                 int square= track_context->pattern_size*track_context->pattern_size;
1415                                                 track_context->pattern= MEM_callocN(sizeof(unsigned char)*square, "trackking pattern");
1416                                         }
1417
1418                                         libmv_SADSamplePattern(image, width, warp, track_context->pattern, track_context->pattern_size);
1419
1420                                         MEM_freeN(image);
1421                                         IMB_freeImBuf(ibuf);
1422                                 }
1423
1424                                 image_new= get_search_bytebuf(ibuf_new, track, marker, &width, &height, pos, origin);
1425
1426                                 if(track_context->warped==NULL) {
1427                                         unsigned char *image_old;
1428
1429                                         ibuf= get_frame_ibuf(context, curfra);
1430
1431                                         if(track_context->warped==NULL) {
1432                                                 int square= track_context->pattern_size*track_context->pattern_size;
1433                                                 track_context->warped= MEM_callocN(sizeof(unsigned char)*square, "trackking warped");
1434                                         }
1435
1436                                         image_old= get_search_bytebuf(ibuf, track, marker, &width, &height, pos, origin);
1437                                         get_warped(track_context, pos[0], pos[1], width, image_old);
1438                                         IMB_freeImBuf(ibuf);
1439                                         MEM_freeN(image_old);
1440                                 }
1441
1442                                 memset(warp, 0, sizeof(warp));
1443                                 warp[0][0]= 1;
1444                                 warp[1][1]= 1;
1445                                 warp[2][0]= pos[0];
1446                                 warp[2][1]= pos[1];
1447
1448                                 correlation= libmv_SADTrackerTrack(track_context->pattern, track_context->warped,
1449                                                         track_context->pattern_size, image_new, width, width, height, warp);
1450
1451                                 x2= warp[2][0];
1452                                 y2= warp[2][1];
1453
1454                                 tracked= track->minimum_correlation < correlation;
1455
1456                                 if(tracked)
1457                                         get_warped(track_context, x2, y2, width, image_new);
1458
1459                                 MEM_freeN(image_new);
1460                         }
1461
1462                         if(tracked && !onbound && finite(x2) && finite(y2)) {
1463                                 if(context->first_time) {
1464                                         #pragma omp critical
1465                                         {
1466                                                 /* check if there's no keyframe/tracked markers before tracking marker.
1467                                                    if so -- create disabled marker before currently tracking "segment" */
1468                                                 put_disabled_marker(track, marker, !context->backwards, 0);
1469                                         }
1470                                 }
1471
1472                                 memset(&marker_new, 0, sizeof(marker_new));
1473
1474                                 if(!onbound) {
1475                                         marker_new.pos[0]= (origin[0]+x2)/ibuf_new->x;
1476                                         marker_new.pos[1]= (origin[1]+y2)/ibuf_new->y;
1477                                 } else {
1478                                         copy_v2_v2(marker_new.pos, marker->pos);
1479                                 }
1480
1481                                 marker_new.flag|= MARKER_TRACKED;
1482                                 marker_new.framenr= nextfra;
1483
1484                                 #pragma omp critical
1485                                 {
1486                                         BKE_tracking_insert_marker(track, &marker_new);
1487                                 }
1488
1489                                 /* make currently tracked segment be finished with disabled marker */
1490                                 #pragma omp critical
1491                                 {
1492                                         put_disabled_marker(track, &marker_new, context->backwards, 0);
1493                                 }
1494                         } else {
1495                                 marker_new= *marker;
1496
1497                                 marker_new.framenr= nextfra;
1498                                 marker_new.flag|= MARKER_DISABLED;
1499
1500                                 #pragma omp critical
1501                                 {
1502                                         BKE_tracking_insert_marker(track, &marker_new);
1503                                 }
1504                         }
1505
1506                         ok= 1;
1507 #endif
1508                 }
1509         }
1510
1511         IMB_freeImBuf(ibuf_new);
1512
1513         context->first_time= 0;
1514         context->frames++;
1515
1516         return ok;
1517 }
1518
1519 /*********************** camera solving *************************/
1520
1521 typedef struct MovieReconstructContext {
1522 #ifdef WITH_LIBMV
1523         struct libmv_Tracks *tracks;
1524         int keyframe1, keyframe2;
1525         short refine_flags;
1526
1527         struct libmv_Reconstruction *reconstruction;
1528 #endif
1529         char object_name[32];
1530         int is_camera;
1531
1532         float focal_length;
1533         float principal_point[2];
1534         float k1, k2, k3;
1535
1536         float reprojection_error;
1537
1538         TracksMap *tracks_map;
1539
1540         int sfra, efra;
1541 } MovieReconstructContext;
1542
1543 typedef struct ReconstructProgressData {
1544         short *stop;
1545         short *do_update;
1546         float *progress;
1547         char *stats_message;
1548         int message_size;
1549 } ReconstructProgressData;
1550
1551 #if WITH_LIBMV
1552 static struct libmv_Tracks *create_libmv_tracks(ListBase *tracksbase, int width, int height)
1553 {
1554         int tracknr= 0;
1555         MovieTrackingTrack *track;
1556         struct libmv_Tracks *tracks= libmv_tracksNew();
1557
1558         track= tracksbase->first;
1559         while(track) {
1560                 int a= 0;
1561
1562                 for(a= 0; a<track->markersnr; a++) {
1563                         MovieTrackingMarker *marker= &track->markers[a];
1564
1565                         if((marker->flag&MARKER_DISABLED)==0)
1566                                 libmv_tracksInsert(tracks, marker->framenr, tracknr,
1567                                                         marker->pos[0]*width, marker->pos[1]*height);
1568                 }
1569
1570                 track= track->next;
1571                 tracknr++;
1572         }
1573
1574         return tracks;
1575 }
1576
1577 static void retrieve_libmv_reconstruct_intrinscis(MovieReconstructContext *context, MovieTracking *tracking)
1578 {
1579         struct libmv_Reconstruction *libmv_reconstruction= context->reconstruction;
1580         struct libmv_CameraIntrinsics *libmv_intrinsics = libmv_ReconstructionExtractIntrinsics(libmv_reconstruction);
1581
1582         float aspy= 1.0f/tracking->camera.pixel_aspect;
1583
1584         double focal_length, principal_x, principal_y, k1, k2, k3;
1585         int width, height;
1586
1587         libmv_CameraIntrinsicsExtract(libmv_intrinsics, &focal_length, &principal_x, &principal_y,
1588                         &k1, &k2, &k3, &width, &height);
1589
1590         tracking->camera.focal= focal_length;
1591         tracking->camera.principal[0]= principal_x;
1592
1593         /* todo: verify divide by aspy is correct */
1594         tracking->camera.principal[1]= principal_y / aspy;
1595         tracking->camera.k1= k1;
1596         tracking->camera.k2= k2;
1597 }
1598
1599 static int retrieve_libmv_reconstruct_tracks(MovieReconstructContext *context, MovieTracking *tracking)
1600 {
1601         struct libmv_Reconstruction *libmv_reconstruction= context->reconstruction;
1602         MovieTrackingReconstruction *reconstruction= NULL;
1603         MovieReconstructedCamera *reconstructed;
1604         MovieTrackingTrack *track;
1605         ListBase *tracksbase=  NULL;
1606         int ok= 1, tracknr= 0, a, origin_set= 0;
1607         int sfra= context->sfra, efra= context->efra;
1608         float imat[4][4];
1609
1610         if(context->is_camera) {
1611                 tracksbase= &tracking->tracks;
1612                 reconstruction= &tracking->reconstruction;
1613         }
1614         else {
1615                 MovieTrackingObject *object= BKE_tracking_named_object(tracking, context->object_name);
1616
1617                 tracksbase= &object->tracks;
1618                 reconstruction= &object->reconstruction;
1619         }
1620
1621         unit_m4(imat);
1622
1623         track= tracksbase->first;
1624         while(track) {
1625                 double pos[3];
1626
1627                 if(libmv_reporojectionPointForTrack(libmv_reconstruction, tracknr, pos)) {
1628                         track->bundle_pos[0]= pos[0];
1629                         track->bundle_pos[1]= pos[1];
1630                         track->bundle_pos[2]= pos[2];
1631
1632                         track->flag|= TRACK_HAS_BUNDLE;
1633                         track->error= libmv_reporojectionErrorForTrack(libmv_reconstruction, tracknr);
1634                 } else {
1635                         track->flag&= ~TRACK_HAS_BUNDLE;
1636                         ok= 0;
1637
1638                         printf("No bundle for track #%d '%s'\n", tracknr, track->name);
1639                 }
1640
1641                 track= track->next;
1642                 tracknr++;
1643         }
1644
1645         if(reconstruction->cameras)
1646                 MEM_freeN(reconstruction->cameras);
1647
1648         reconstruction->camnr= 0;
1649         reconstruction->cameras= NULL;
1650         reconstructed= MEM_callocN((efra-sfra+1)*sizeof(MovieReconstructedCamera), "temp reconstructed camera");
1651
1652         for(a= sfra; a<=efra; a++) {
1653                 double matd[4][4];
1654
1655                 if(libmv_reporojectionCameraForImage(libmv_reconstruction, a, matd)) {
1656                         int i, j;
1657                         float mat[4][4];
1658                         float error= libmv_reporojectionErrorForImage(libmv_reconstruction, a);
1659
1660                         for(i=0; i<4; i++)
1661                                 for(j= 0; j<4; j++)
1662                                         mat[i][j]= matd[i][j];
1663
1664                         if(!origin_set) {
1665                                 copy_m4_m4(imat, mat);
1666                                 invert_m4(imat);
1667                                 origin_set= 1;
1668                         }
1669
1670                         if(origin_set)
1671                                 mult_m4_m4m4(mat, imat, mat);
1672
1673                         copy_m4_m4(reconstructed[reconstruction->camnr].mat, mat);
1674                         reconstructed[reconstruction->camnr].framenr= a;
1675                         reconstructed[reconstruction->camnr].error= error;
1676                         reconstruction->camnr++;
1677                 } else {
1678                         ok= 0;
1679                         printf("No camera for frame %d\n", a);
1680                 }
1681         }
1682
1683         if(reconstruction->camnr) {
1684                 reconstruction->cameras= MEM_callocN(reconstruction->camnr*sizeof(MovieReconstructedCamera), "reconstructed camera");
1685                 memcpy(reconstruction->cameras, reconstructed, reconstruction->camnr*sizeof(MovieReconstructedCamera));
1686         }
1687
1688         if(origin_set) {
1689                 track= tracksbase->first;
1690                 while(track) {
1691                         if(track->flag&TRACK_HAS_BUNDLE)
1692                                 mul_v3_m4v3(track->bundle_pos, imat, track->bundle_pos);
1693
1694                         track= track->next;
1695                 }
1696         }
1697
1698         MEM_freeN(reconstructed);
1699
1700         return ok;
1701 }
1702
1703 static int retrieve_libmv_reconstruct(MovieReconstructContext *context, MovieTracking *tracking)
1704 {
1705         /* take the intrinscis back from libmv */
1706         retrieve_libmv_reconstruct_intrinscis(context, tracking);
1707
1708         return retrieve_libmv_reconstruct_tracks(context, tracking);
1709 }
1710
1711 static int get_refine_intrinsics_flags(MovieTracking *tracking, MovieTrackingObject *object)
1712 {
1713         int refine= tracking->settings.refine_camera_intrinsics;
1714         int flags= 0;
1715
1716         if((object->flag&TRACKING_OBJECT_CAMERA)==0)
1717                 return 0;
1718
1719         if(refine&REFINE_FOCAL_LENGTH)
1720                 flags|= LIBMV_REFINE_FOCAL_LENGTH;
1721
1722         if(refine&REFINE_PRINCIPAL_POINT)
1723                 flags|= LIBMV_REFINE_PRINCIPAL_POINT;
1724
1725         if(refine&REFINE_RADIAL_DISTORTION_K1)
1726                 flags|= REFINE_RADIAL_DISTORTION_K1;
1727
1728         if(refine&REFINE_RADIAL_DISTORTION_K2)
1729                 flags|= REFINE_RADIAL_DISTORTION_K2;
1730
1731         return flags;
1732 }
1733
1734 static int count_tracks_on_both_keyframes(MovieTracking *tracking, ListBase *tracksbase)
1735 {
1736         int tot= 0;
1737         int frame1= tracking->settings.keyframe1, frame2= tracking->settings.keyframe2;
1738         MovieTrackingTrack *track;
1739
1740         track= tracksbase->first;
1741         while(track) {
1742                 if(BKE_tracking_has_marker(track, frame1))
1743                         if(BKE_tracking_has_marker(track, frame2))
1744                                 tot++;
1745
1746                 track= track->next;
1747         }
1748
1749         return tot;
1750 }
1751 #endif
1752
1753 int BKE_tracking_can_reconstruct(MovieTracking *tracking, MovieTrackingObject *object, char *error_msg, int error_size)
1754 {
1755 #if WITH_LIBMV
1756         ListBase *tracksbase= BKE_tracking_object_tracks(tracking, object);
1757
1758         if(count_tracks_on_both_keyframes(tracking, tracksbase)<8) {
1759                 BLI_strncpy(error_msg, "At least 8 tracks on both of keyframes are needed for reconstruction", error_size);
1760                 return 0;
1761         }
1762
1763         return 1;
1764 #else
1765         BLI_strncpy(error_msg, "Blender is compiled without motion tracking library", error_size);
1766         (void)tracking;
1767         (void)object;
1768
1769         return 0;
1770 #endif
1771 }
1772
1773 MovieReconstructContext* BKE_tracking_reconstruction_context_new(MovieTracking *tracking,
1774                         MovieTrackingObject *object, int keyframe1, int keyframe2, int width, int height)
1775 {
1776         MovieReconstructContext *context= MEM_callocN(sizeof(MovieReconstructContext), "MovieReconstructContext data");
1777         MovieTrackingCamera *camera= &tracking->camera;
1778         ListBase *tracksbase= BKE_tracking_object_tracks(tracking, object);
1779         float aspy= 1.0f/tracking->camera.pixel_aspect;
1780         int num_tracks= BLI_countlist(tracksbase);
1781         int sfra= INT_MAX, efra= INT_MIN;
1782         MovieTrackingTrack *track;
1783
1784         strcpy(context->object_name, object->name);
1785         context->is_camera = object->flag&TRACKING_OBJECT_CAMERA;
1786
1787         context->tracks_map= tracks_map_new(context->object_name, context->is_camera, num_tracks, 0);
1788
1789         track= tracksbase->first;
1790         while(track) {
1791                 int first= 0, last= track->markersnr-1;
1792                 MovieTrackingMarker *first_marker= &track->markers[0];
1793                 MovieTrackingMarker *last_marker= &track->markers[track->markersnr-1];
1794
1795                 /* find first not-disabled marker */
1796                 while(first<=track->markersnr-1 && first_marker->flag&MARKER_DISABLED) {
1797                         first++;
1798                         first_marker++;
1799                 }
1800
1801                 /* find last not-disabled marker */
1802                 while(last>=0 && last_marker->flag&MARKER_DISABLED) {
1803                         last--;
1804                         last_marker--;
1805                 }
1806
1807                 if(first<track->markersnr-1)
1808                         sfra= MIN2(sfra, first_marker->framenr);
1809
1810                 if(last>=0)
1811                         efra= MAX2(efra, last_marker->framenr);
1812
1813                 tracks_map_insert(context->tracks_map, track, NULL);
1814
1815                 track= track->next;
1816         }
1817
1818         context->sfra= sfra;
1819         context->efra= efra;
1820
1821 #ifdef WITH_LIBMV
1822         context->tracks= create_libmv_tracks(tracksbase, width, height*aspy);
1823         context->keyframe1= keyframe1;
1824         context->keyframe2= keyframe2;
1825         context->refine_flags= get_refine_intrinsics_flags(tracking, object);
1826 #else
1827         (void) width;
1828         (void) height;
1829         (void) keyframe1;
1830         (void) keyframe2;
1831 #endif
1832
1833         context->focal_length= camera->focal;
1834         context->principal_point[0]= camera->principal[0];
1835         context->principal_point[1]= camera->principal[1]*aspy;
1836
1837         context->k1= camera->k1;
1838         context->k2= camera->k2;
1839         context->k2= camera->k2;
1840
1841         return context;
1842 }
1843
1844 void BKE_tracking_reconstruction_context_free(MovieReconstructContext *context)
1845 {
1846 #ifdef WITH_LIBMV
1847         if(context->reconstruction)
1848                         libmv_destroyReconstruction(context->reconstruction);
1849
1850         libmv_tracksDestroy(context->tracks);
1851 #endif
1852
1853         tracks_map_free(context->tracks_map, NULL);
1854
1855         MEM_freeN(context);
1856 }
1857
1858 #ifdef WITH_LIBMV
1859 static void solve_reconstruction_update_cb(void *customdata, double progress, const char *message)
1860 {
1861         ReconstructProgressData *progressdata= customdata;
1862
1863         if(progressdata->progress) {
1864                 *progressdata->progress= progress;
1865                 *progressdata->do_update= 1;
1866         }
1867
1868         BLI_snprintf(progressdata->stats_message, progressdata->message_size,
1869                         "Solving camera | %s", message);
1870 }
1871 #endif
1872
1873 #if 0
1874 static int solve_reconstruction_testbreak_cb(void *customdata)
1875 {
1876         ReconstructProgressData *progressdata= customdata;
1877
1878         if(progressdata->stop && *progressdata->stop)
1879                 return 1;
1880
1881         return G.afbreek;
1882 }
1883 #endif
1884
1885 void BKE_tracking_solve_reconstruction(MovieReconstructContext *context, short *stop,
1886                         short *do_update, float *progress, char *stats_message, int message_size)
1887 {
1888 #ifdef WITH_LIBMV
1889         float error;
1890
1891         ReconstructProgressData progressdata;
1892
1893         progressdata.stop= stop;
1894         progressdata.do_update= do_update;
1895         progressdata.progress= progress;
1896         progressdata.stats_message= stats_message;
1897         progressdata.message_size= message_size;
1898
1899         context->reconstruction = libmv_solveReconstruction(context->tracks,
1900                 context->keyframe1, context->keyframe2,
1901                 context->refine_flags,
1902                 context->focal_length,
1903                 context->principal_point[0], context->principal_point[1],
1904                 context->k1, context->k2, context->k3,
1905                 solve_reconstruction_update_cb, &progressdata);
1906
1907         error= libmv_reprojectionError(context->reconstruction);
1908
1909         context->reprojection_error= error;
1910 #else
1911         (void) context;
1912         (void) stop;
1913         (void) do_update;
1914         (void) progress;
1915         (void) stats_message;
1916         (void) message_size;
1917 #endif
1918 }
1919
1920 int BKE_tracking_finish_reconstruction(MovieReconstructContext *context, MovieTracking *tracking)
1921 {
1922         MovieTrackingReconstruction *reconstruction;
1923
1924         tracks_map_merge(context->tracks_map, tracking);
1925
1926         if(context->is_camera) {
1927                 reconstruction= &tracking->reconstruction;
1928         }
1929         else {
1930                 MovieTrackingObject *object;
1931
1932                 object= BKE_tracking_named_object(tracking, context->object_name);
1933                 reconstruction= &object->reconstruction;
1934         }
1935
1936         reconstruction->error= context->reprojection_error;
1937         reconstruction->flag|= TRACKING_RECONSTRUCTED;
1938
1939 #ifdef WITH_LIBMV
1940         if(!retrieve_libmv_reconstruct(context, tracking))
1941                 return 0;
1942 #endif
1943
1944         return 1;
1945 }
1946
1947 void BKE_track_unique_name(ListBase *tracksbase, MovieTrackingTrack *track)
1948 {
1949         BLI_uniquename(tracksbase, track, "Track", '.', offsetof(MovieTrackingTrack, name), sizeof(track->name));
1950 }
1951
1952 MovieTrackingTrack *BKE_tracking_named_track(MovieTracking *tracking, MovieTrackingObject *object, const char *name)
1953 {
1954         ListBase *tracksbase= BKE_tracking_object_tracks(tracking, object);
1955         MovieTrackingTrack *track= tracksbase->first;
1956
1957         while(track) {
1958                 if(!strcmp(track->name, name))
1959                         return track;
1960
1961                 track= track->next;
1962         }
1963
1964         return NULL;
1965 }
1966
1967 static int reconstruction_camera_index(MovieTrackingReconstruction *reconstruction, int framenr, int nearest)
1968 {
1969         MovieReconstructedCamera *cameras= reconstruction->cameras;
1970         int a= 0, d= 1;
1971
1972         if(!reconstruction->camnr)
1973                 return -1;
1974
1975         if(framenr<cameras[0].framenr) {
1976                 if(nearest) return 0;
1977                 else return -1;
1978         }
1979
1980         if(framenr>cameras[reconstruction->camnr-1].framenr) {
1981                 if(nearest) return reconstruction->camnr-1;
1982                 else return -1;
1983         }
1984
1985         if(reconstruction->last_camera<reconstruction->camnr)
1986                 a= reconstruction->last_camera;
1987
1988         if(cameras[a].framenr>=framenr)
1989                 d= -1;
1990
1991         while(a>=0 && a<reconstruction->camnr) {
1992                 int cfra= cameras[a].framenr;
1993
1994                 /* check if needed framenr was "skipped" -- no data for requested frame */
1995
1996                 if(d>0 && cfra>framenr) {
1997                         /* interpolate with previous position */
1998                         if(nearest) return a-1;
1999                         else break;
2000                 }
2001
2002                 if(d<0 && cfra<framenr) {
2003                         /* interpolate with next position */
2004                         if(nearest) return a;
2005                         else break;
2006                 }
2007
2008                 if(cfra==framenr) {
2009                         reconstruction->last_camera= a;
2010
2011                         return a;
2012                 }
2013
2014                 a+= d;
2015         }
2016
2017         return -1;
2018 }
2019
2020 static void scale_reconstructed_camera(MovieTrackingObject *object, float mat[4][4])
2021 {
2022         if((object->flag&TRACKING_OBJECT_CAMERA)==0) {
2023                 float smat[4][4];
2024
2025                 scale_m4_fl(smat, 1.0f/object->scale);
2026                 mult_m4_m4m4(mat, mat, smat);
2027         }
2028 }
2029
2030 MovieReconstructedCamera *BKE_tracking_get_reconstructed_camera(MovieTracking *tracking,
2031                         MovieTrackingObject *object, int framenr)
2032 {
2033         MovieTrackingReconstruction *reconstruction;
2034         int a;
2035
2036         reconstruction= BKE_tracking_object_reconstruction(tracking, object);
2037         a= reconstruction_camera_index(reconstruction, framenr, 0);
2038
2039         if(a==-1)
2040                 return NULL;
2041
2042         return &reconstruction->cameras[a];
2043 }
2044
2045 void BKE_tracking_get_interpolated_camera(MovieTracking *tracking, MovieTrackingObject *object,
2046                         int framenr, float mat[4][4])
2047 {
2048         MovieTrackingReconstruction *reconstruction;
2049         MovieReconstructedCamera *cameras;
2050         int a;
2051
2052         reconstruction= BKE_tracking_object_reconstruction(tracking, object);
2053         cameras= reconstruction->cameras;
2054         a= reconstruction_camera_index(reconstruction, framenr, 1);
2055
2056         if(a==-1) {
2057                 unit_m4(mat);
2058                 return;
2059         }
2060
2061         if(cameras[a].framenr!=framenr && a>0 && a<reconstruction->camnr-1) {
2062                 float t= ((float)framenr-cameras[a].framenr) / (cameras[a+1].framenr-cameras[a].framenr);
2063
2064                 blend_m4_m4m4(mat, cameras[a].mat, cameras[a+1].mat, t);
2065         } else {
2066                 copy_m4_m4(mat, cameras[a].mat);
2067         }
2068
2069         scale_reconstructed_camera(object, mat);
2070 }
2071
2072 void BKE_get_tracking_mat(Scene *scene, Object *ob, float mat[4][4])
2073 {
2074         if(!ob) {
2075                 if(scene->camera) ob= scene->camera;
2076                 else ob= scene_find_camera(scene);
2077         }
2078
2079         if(ob)
2080                 where_is_object_mat(scene, ob, mat);
2081         else
2082                 unit_m4(mat);
2083 }
2084
2085 void BKE_tracking_camera_shift(MovieTracking *tracking, int winx, int winy, float *shiftx, float *shifty)
2086 {
2087         *shiftx= (0.5f*winx-tracking->camera.principal[0]) / winx;
2088         *shifty= (0.5f*winy-tracking->camera.principal[1]) / winx;
2089 }
2090
2091 void BKE_tracking_camera_to_blender(MovieTracking *tracking, Scene *scene, Camera *camera, int width, int height)
2092 {
2093         float focal= tracking->camera.focal;
2094
2095         camera->sensor_x= tracking->camera.sensor_width;
2096         camera->sensor_fit= CAMERA_SENSOR_FIT_AUTO;
2097         camera->lens= focal*camera->sensor_x/width;
2098
2099         scene->r.xsch= width*tracking->camera.pixel_aspect;
2100         scene->r.ysch= height;
2101
2102         scene->r.xasp= 1.0f;
2103         scene->r.yasp= 1.0f;
2104
2105         BKE_tracking_camera_shift(tracking, width, height, &camera->shiftx, &camera->shifty);
2106 }
2107
2108 void BKE_tracking_projection_matrix(MovieTracking *tracking, MovieTrackingObject *object,
2109                         int framenr, int winx, int winy, float mat[4][4])
2110 {
2111         MovieReconstructedCamera *camera;
2112         float lens= tracking->camera.focal*tracking->camera.sensor_width/(float)winx;
2113         float viewfac, pixsize, left, right, bottom, top, clipsta, clipend;
2114         float winmat[4][4];
2115         float ycor= 1.0f/tracking->camera.pixel_aspect;
2116         float shiftx, shifty, winside= MAX2(winx, winy);
2117
2118         BKE_tracking_camera_shift(tracking, winx, winy, &shiftx, &shifty);
2119
2120         clipsta= 0.1f;
2121         clipend= 1000.0f;
2122
2123         if(winx >= winy)
2124                 viewfac= (lens*winx)/tracking->camera.sensor_width;
2125         else
2126                 viewfac= (ycor*lens*winy)/tracking->camera.sensor_width;
2127
2128         pixsize= clipsta/viewfac;
2129
2130         left= -0.5f*(float)winx + shiftx*winside;
2131         bottom= -0.5f*(ycor)*(float)winy + shifty*winside;
2132         right=  0.5f*(float)winx + shiftx*winside;
2133         top=  0.5f*(ycor)*(float)winy + shifty*winside;
2134
2135         left *= pixsize;
2136         right *= pixsize;
2137         bottom *= pixsize;
2138         top *= pixsize;
2139
2140         perspective_m4(winmat, left, right, bottom, top, clipsta, clipend);
2141
2142         camera= BKE_tracking_get_reconstructed_camera(tracking, object, framenr);
2143
2144         if(camera) {
2145                 float imat[4][4];
2146
2147                 invert_m4_m4(imat, camera->mat);
2148                 mult_m4_m4m4(mat, winmat, imat);
2149         } else copy_m4_m4(mat, winmat);
2150 }
2151
2152 ListBase *BKE_tracking_get_tracks(MovieTracking *tracking)
2153 {
2154         MovieTrackingObject *object= BKE_tracking_active_object(tracking);
2155
2156         if(object && (object->flag & TRACKING_OBJECT_CAMERA) == 0) {
2157                 return &object->tracks;
2158         }
2159
2160         return &tracking->tracks;
2161 }
2162
2163 MovieTrackingTrack *BKE_tracking_active_track(MovieTracking *tracking)
2164 {
2165         ListBase *tracksbase;
2166
2167         if(!tracking->act_track)
2168                 return NULL;
2169
2170         tracksbase= BKE_tracking_get_tracks(tracking);
2171
2172         /* check that active track is in current tracks list */
2173         if(BLI_findindex(tracksbase, tracking->act_track) >= 0)
2174                 return tracking->act_track;
2175
2176         return NULL;
2177 }
2178
2179 MovieTrackingObject *BKE_tracking_active_object(MovieTracking *tracking)
2180 {
2181         return BLI_findlink(&tracking->objects, tracking->objectnr);
2182 }
2183
2184 MovieTrackingObject *BKE_tracking_get_camera_object(MovieTracking *tracking)
2185 {
2186         MovieTrackingObject *object= tracking->objects.first;
2187
2188         while(object) {
2189                 if(object->flag & TRACKING_OBJECT_CAMERA)
2190                         return object;
2191
2192                 object= object->next;
2193         }
2194
2195         return NULL;
2196 }
2197
2198 ListBase *BKE_tracking_object_tracks(MovieTracking *tracking, MovieTrackingObject *object)
2199 {
2200         if(object->flag & TRACKING_OBJECT_CAMERA) {
2201                 return &tracking->tracks;
2202         }
2203
2204         return &object->tracks;
2205 }
2206
2207 MovieTrackingReconstruction *BKE_tracking_object_reconstruction(MovieTracking *tracking, MovieTrackingObject *object)
2208 {
2209         if(object->flag & TRACKING_OBJECT_CAMERA) {
2210                 return &tracking->reconstruction;
2211         }
2212
2213         return &object->reconstruction;
2214 }
2215
2216 MovieTrackingReconstruction *BKE_tracking_get_reconstruction(MovieTracking *tracking)
2217 {
2218         MovieTrackingObject *object= BKE_tracking_active_object(tracking);
2219
2220         return BKE_tracking_object_reconstruction(tracking, object);
2221 }
2222
2223 void BKE_tracking_apply_intrinsics(MovieTracking *tracking, float co[2], float nco[2])
2224 {
2225         MovieTrackingCamera *camera= &tracking->camera;
2226
2227 #ifdef WITH_LIBMV
2228         double x, y;
2229         float aspy= 1.0f/tracking->camera.pixel_aspect;
2230
2231         /* normalize coords */
2232         x= (co[0]-camera->principal[0]) / camera->focal;
2233         y= (co[1]-camera->principal[1] * aspy) / camera->focal;
2234
2235         libmv_applyCameraIntrinsics(camera->focal, camera->principal[0], camera->principal[1] * aspy,
2236                                 camera->k1, camera->k2, camera->k3, x, y, &x, &y);
2237
2238         /* result is in image coords already */
2239         nco[0]= x;
2240         nco[1]= y;
2241 #else
2242         (void)camera;
2243         (void)co;
2244         (void)nco;
2245 #endif
2246 }
2247
2248 void BKE_tracking_invert_intrinsics(MovieTracking *tracking, float co[2], float nco[2])
2249 {
2250         MovieTrackingCamera *camera= &tracking->camera;
2251
2252 #ifdef WITH_LIBMV
2253         double x= co[0], y= co[1];
2254         float aspy= 1.0f/tracking->camera.pixel_aspect;
2255
2256         libmv_InvertIntrinsics(camera->focal, camera->principal[0], camera->principal[1] * aspy,
2257                                 camera->k1, camera->k2, camera->k3, x, y, &x, &y);
2258
2259         nco[0]= x * camera->focal + camera->principal[0];
2260         nco[1]= y * camera->focal + camera->principal[1] * aspy;
2261 #else
2262         (void)camera;
2263         (void)co;
2264         (void)nco;
2265 #endif
2266 }
2267
2268 #ifdef WITH_LIBMV
2269 static int point_in_stroke(bGPDstroke *stroke, float x, float y)
2270 {
2271         int i, prev;
2272         int count= 0;
2273         bGPDspoint *points= stroke->points;
2274
2275         prev= stroke->totpoints-1;
2276
2277         for(i= 0; i<stroke->totpoints; i++) {
2278                 if((points[i].y<y && points[prev].y>=y) || (points[prev].y<y && points[i].y>=y)) {
2279                         float fac= (y-points[i].y)/(points[prev].y-points[i].y);
2280
2281                         if (points[i].x+fac*(points[prev].x-points[i].x)<x)
2282                                 count++;
2283                 }
2284
2285                 prev= i;
2286         }
2287
2288         return count%2;
2289 }
2290
2291 static int point_in_layer(bGPDlayer *layer, float x, float y)
2292 {
2293         bGPDframe *frame= layer->frames.first;
2294
2295         while(frame) {
2296                 bGPDstroke *stroke= frame->strokes.first;
2297                 while(stroke) {
2298                         if(point_in_stroke(stroke, x, y))
2299                                 return 1;
2300
2301                         stroke= stroke->next;
2302                 }
2303                 frame= frame->next;
2304         }
2305
2306         return 0;
2307 }
2308
2309 static void retrieve_libmv_features(MovieTracking *tracking, ListBase *tracksbase,
2310                         struct libmv_Features *features, int framenr, int width, int height,
2311                         bGPDlayer *layer, int place_outside_layer)
2312 {
2313         int a;
2314
2315         a= libmv_countFeatures(features);
2316         while(a--) {
2317                 MovieTrackingTrack *track;
2318                 double x, y, size, score;
2319                 int ok= 1;
2320                 float xu, yu;
2321
2322                 libmv_getFeature(features, a, &x, &y, &score, &size);
2323
2324                 xu= x/width;
2325                 yu= y/height;
2326
2327                 if(layer)
2328                         ok= point_in_layer(layer, xu, yu)!=place_outside_layer;
2329
2330                 if(ok) {
2331                         track= BKE_tracking_add_track(tracking, tracksbase, xu, yu, framenr, width, height);
2332                         track->flag|= SELECT;
2333                         track->pat_flag|= SELECT;
2334                         track->search_flag|= SELECT;
2335                 }
2336         }
2337 }
2338 #endif
2339
2340 void BKE_tracking_detect_fast(MovieTracking *tracking, ListBase *tracksbase, ImBuf *ibuf,
2341                         int framenr, int margin, int min_trackness, int min_distance, bGPDlayer *layer,
2342                         int place_outside_layer)
2343 {
2344 #ifdef WITH_LIBMV
2345         struct libmv_Features *features;
2346         unsigned char *pixels= get_ucharbuf(ibuf);
2347
2348         features= libmv_detectFeaturesFAST(pixels, ibuf->x, ibuf->y, ibuf->x,
2349                         margin, min_trackness, min_distance);
2350
2351         MEM_freeN(pixels);
2352
2353         retrieve_libmv_features(tracking, tracksbase, features, framenr,
2354                         ibuf->x, ibuf->y, layer, place_outside_layer);
2355
2356         libmv_destroyFeatures(features);
2357 #else
2358         (void)tracking;
2359         (void)tracksbase;
2360         (void)ibuf;
2361         (void)framenr;
2362         (void)margin;
2363         (void)min_trackness;
2364         (void)min_distance;
2365         (void)layer;
2366         (void)place_outside_layer;
2367 #endif
2368 }
2369
2370 MovieTrackingTrack *BKE_tracking_indexed_track(MovieTracking *tracking, int tracknr, ListBase **tracksbase_r)
2371 {
2372         MovieTrackingObject *object;
2373         int cur= 1;
2374
2375         object= tracking->objects.first;
2376         while(object) {
2377                 ListBase *tracksbase= BKE_tracking_object_tracks(tracking, object);
2378                 MovieTrackingTrack *track= tracksbase->first;
2379
2380                 while(track) {
2381                         if(track->flag&TRACK_HAS_BUNDLE) {
2382                                 if(cur==tracknr) {
2383                                         *tracksbase_r= tracksbase;
2384                                         return track;
2385                                 }
2386
2387                                 cur++;
2388                         }
2389
2390                         track= track->next;
2391                 }
2392
2393                 object= object->next;
2394         }
2395
2396         *tracksbase_r= NULL;
2397
2398         return NULL;
2399 }
2400
2401 static int stabilization_median_point(MovieTracking *tracking, int framenr, float median[2])
2402 {
2403         int ok= 0;
2404         float min[2], max[2];
2405         MovieTrackingTrack *track;
2406
2407         INIT_MINMAX2(min, max);
2408
2409         (void) tracking;
2410
2411         track= tracking->tracks.first;
2412         while(track) {
2413                 if(track->flag&TRACK_USE_2D_STAB) {
2414                         MovieTrackingMarker *marker= BKE_tracking_get_marker(track, framenr);
2415
2416                         DO_MINMAX2(marker->pos, min, max);
2417
2418                         ok= 1;
2419                 }
2420
2421                 track= track->next;
2422         }
2423
2424         median[0]= (max[0]+min[0])/2.0f;
2425         median[1]= (max[1]+min[1])/2.0f;
2426
2427         return ok;
2428 }
2429
2430 static void calculate_stabdata(MovieTracking *tracking, int framenr, float width, float height,
2431                         float firstmedian[2], float median[2], float loc[2], float *scale, float *angle)
2432 {
2433         MovieTrackingStabilization *stab= &tracking->stabilization;
2434
2435         *scale= (stab->scale-1.0f)*stab->scaleinf+1.0f;
2436         *angle= 0.0f;
2437
2438         loc[0]= (firstmedian[0]-median[0])*width*(*scale);
2439         loc[1]= (firstmedian[1]-median[1])*height*(*scale);
2440
2441         mul_v2_fl(loc, stab->locinf);
2442
2443         if((stab->flag&TRACKING_STABILIZE_ROTATION) && stab->rot_track && stab->rotinf) {
2444                 MovieTrackingMarker *marker;
2445                 float a[2], b[2];
2446                 float x0= (float)width/2.0f, y0= (float)height/2.0f;
2447                 float x= median[0]*width, y= median[1]*height;
2448
2449                 marker= BKE_tracking_get_marker(stab->rot_track, 1);
2450                 sub_v2_v2v2(a, marker->pos, firstmedian);
2451                 a[0]*= width;
2452                 a[1]*= height;
2453
2454                 marker= BKE_tracking_get_marker(stab->rot_track, framenr);
2455                 sub_v2_v2v2(b, marker->pos, median);
2456                 b[0]*= width;
2457                 b[1]*= height;
2458
2459                 *angle= -atan2(a[0]*b[1]-a[1]*b[0], a[0]*b[0]+a[1]*b[1]);
2460                 *angle*= stab->rotinf;
2461
2462                 /* convert to rotation around image center */
2463                 loc[0]-= (x0 + (x-x0)*cosf(*angle)-(y-y0)*sinf(*angle) - x)*(*scale);
2464                 loc[1]-= (y0 + (x-x0)*sinf(*angle)+(y-y0)*cosf(*angle) - y)*(*scale);
2465         }
2466 }
2467
2468 static float stabilization_auto_scale_factor(MovieTracking *tracking, int width, int height)
2469 {
2470         float firstmedian[2];
2471         MovieTrackingStabilization *stab= &tracking->stabilization;
2472
2473         if(stab->ok)
2474                 return stab->scale;
2475
2476         if(stabilization_median_point(tracking, 1, firstmedian)) {
2477                 int sfra= INT_MAX, efra= INT_MIN, cfra;
2478                 float delta[2]= {0.0f, 0.0f}, scalex= 1.0f, scaley= 1.0f;
2479                 MovieTrackingTrack *track;
2480
2481                 stab->scale= 1.0f;
2482
2483                 track= tracking->tracks.first;
2484                 while(track) {
2485                         if(track->flag&TRACK_USE_2D_STAB ||
2486                            ((stab->flag&TRACKING_STABILIZE_ROTATION) && track==stab->rot_track)) {
2487                                 sfra= MIN2(sfra, track->markers[0].framenr);
2488                                 efra= MAX2(efra, track->markers[track->markersnr-1].framenr);
2489                         }
2490
2491                         track= track->next;
2492                 }
2493
2494                 for(cfra=sfra; cfra<=efra; cfra++) {
2495                         float median[2], near[2];
2496                         float loc[2], scale, angle;
2497
2498                         stabilization_median_point(tracking, cfra, median);
2499
2500                         calculate_stabdata(tracking, cfra, width, height, firstmedian, median,
2501                                                 loc, &scale, &angle);
2502
2503                         if(angle==0.0f) {
2504                                 loc[0]= fabsf(loc[0]);
2505                                 loc[1]= fabsf(loc[1]);
2506
2507                                 delta[0]= MAX2(delta[0], loc[0]);
2508                                 delta[1]= MAX2(delta[1], loc[1]);
2509
2510                                 near[0]= MIN2(median[0], 1.0f-median[0]);
2511                                 near[1]= MIN2(median[1], 1.0f-median[1]);
2512                                 near[0]= MAX2(near[0], 0.05f);
2513                                 near[1]= MAX2(near[1], 0.05f);
2514
2515                                 scalex= 1.0f+delta[0]/(near[0]*width);
2516                                 scaley= 1.0f+delta[1]/(near[1]*height);
2517                         } else {
2518                                 int i;
2519                                 float mat[4][4];
2520                                 float points[4][2]={{0.0f, 0.0f}, {0.0f, height}, {width, height}, {width, 0.0f}};
2521
2522                                 BKE_tracking_stabdata_to_mat4(width, height, loc, scale, angle, mat);
2523
2524                                 for(i= 0; i<4; i++) {
2525                                         int j;
2526                                         float a[3]= {0.0f, 0.0f, 0.0f}, b[3]= {0.0f, 0.0f, 0.0f};
2527
2528                                         copy_v3_v3(a, points[i]);
2529                                         copy_v3_v3(b, points[(i+1)%4]);
2530
2531                                         mul_m4_v3(mat, a);
2532                                         mul_m4_v3(mat, b);
2533
2534                                         for(j= 0; j<4; j++) {
2535                                                 float point[3]= {points[j][0], points[j][1], 0.0f};
2536                                                 float v1[3], v2[3];
2537
2538                                                 sub_v3_v3v3(v1, b, a);
2539                                                 sub_v3_v3v3(v2, point, a);
2540
2541                                                 if(cross_v2v2(v1, v2) >= 0.0f) {
2542                                                         float dist= dist_to_line_v2(point, a, b);
2543                                                         if(i%2==0) {
2544                                                                 scalex= MAX2(scalex, (width+2*dist)/width);
2545                                                         } else {
2546                                                                 scaley= MAX2(scaley, (height+2*dist)/height);
2547                                                         }
2548                                                 }
2549                                         }
2550                                 }
2551                         }
2552                 }
2553
2554                 stab->scale= MAX2(scalex, scaley);
2555
2556                 if(stab->maxscale>0.0f)
2557                         stab->scale= MIN2(stab->scale, stab->maxscale);
2558         } else {
2559                 stab->scale= 1.0f;
2560         }
2561
2562         stab->ok= 1;
2563
2564         return stab->scale;
2565 }
2566
2567 static ImBuf* stabilize_alloc_ibuf(ImBuf *cacheibuf, ImBuf *srcibuf, int fill)
2568 {
2569         int flags;
2570
2571         if(cacheibuf && (cacheibuf->x != srcibuf->x || cacheibuf->y != srcibuf->y)) {
2572                 IMB_freeImBuf(cacheibuf);
2573                 cacheibuf= NULL;
2574         }
2575
2576         flags= IB_rect;
2577
2578         if(srcibuf->rect_float)
2579                 flags|= IB_rectfloat;
2580
2581         if(cacheibuf) {
2582                 if(fill) {
2583                         float col[4]= {0.0f, 0.0f, 0.0f, 0.0f};
2584                         IMB_rectfill(cacheibuf, col);
2585                 }
2586         }
2587         else {
2588                 cacheibuf= IMB_allocImBuf(srcibuf->x, srcibuf->y, srcibuf->planes, flags);
2589                 cacheibuf->profile= srcibuf->profile;
2590         }
2591
2592         return cacheibuf;
2593 }
2594
2595 void BKE_tracking_stabilization_data(MovieTracking *tracking, int framenr, int width, int height, float loc[2], float *scale, float *angle)
2596 {
2597         float firstmedian[2], median[2];
2598         MovieTrackingStabilization *stab= &tracking->stabilization;
2599
2600         if((stab->flag&TRACKING_2D_STABILIZATION)==0) {
2601                 zero_v2(loc);
2602                 *scale= 1.0f;
2603                 *angle= 0.0f;
2604
2605                 return;
2606         }
2607
2608         if(stabilization_median_point(tracking, 1, firstmedian)) {
2609                 stabilization_median_point(tracking, framenr, median);
2610
2611                 if((stab->flag&TRACKING_AUTOSCALE)==0)
2612                         stab->scale= 1.0f;
2613
2614                 if(!stab->ok) {
2615                         if(stab->flag&TRACKING_AUTOSCALE)
2616                                 stabilization_auto_scale_factor(tracking, width, height);
2617
2618                         calculate_stabdata(tracking, framenr, width, height, firstmedian, median, loc, scale, angle);
2619
2620                         stab->ok= 1;
2621                 } else {
2622                         calculate_stabdata(tracking, framenr, width, height, firstmedian, median, loc, scale, angle);
2623                 }
2624         } else {
2625                 zero_v2(loc);
2626                 *scale= 1.0f;
2627                 *angle= 0.0f;
2628         }
2629 }
2630
2631 ImBuf *BKE_tracking_stabilize(MovieTracking *tracking, int framenr, ImBuf *ibuf, float loc[2], float *scale, float *angle)
2632 {
2633         float tloc[2], tscale, tangle;
2634         MovieTrackingStabilization *stab= &tracking->stabilization;
2635         ImBuf *tmpibuf;
2636         float width= ibuf->x, height= ibuf->y;
2637
2638         if(loc)         copy_v2_v2(tloc, loc);
2639         if(scale)       tscale= *scale;
2640
2641         if((stab->flag&TRACKING_2D_STABILIZATION)==0) {
2642                 if(loc)         zero_v2(loc);
2643                 if(scale)       *scale= 1.0f;
2644
2645                 return ibuf;
2646         }
2647
2648         BKE_tracking_stabilization_data(tracking, framenr, width, height, tloc, &tscale, &tangle);
2649
2650         tmpibuf= stabilize_alloc_ibuf(NULL, ibuf, 1);
2651
2652         /* scale would be handled by matrix transformation when angle is non-zero */
2653         if(tscale!=1.0f && tangle==0.0f) {
2654                 ImBuf *scaleibuf;
2655
2656                 stabilization_auto_scale_factor(tracking, width, height);
2657
2658                 scaleibuf= stabilize_alloc_ibuf(stab->scaleibuf, ibuf, 0);
2659                 stab->scaleibuf= scaleibuf;
2660
2661                 IMB_rectcpy(scaleibuf, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
2662                 IMB_scalefastImBuf(scaleibuf, ibuf->x*tscale, ibuf->y*tscale);
2663
2664                 ibuf= scaleibuf;
2665         }
2666
2667         if(tangle==0.0f) {
2668                 /* if angle is zero, then it's much faster to use rect copy
2669                    but could be issues with subpixel precisions */
2670                 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);
2671         } else {
2672                 float mat[4][4];
2673                 int i, j;
2674
2675                 BKE_tracking_stabdata_to_mat4(ibuf->x, ibuf->y, tloc, tscale, tangle, mat);
2676                 invert_m4(mat);
2677
2678                 for(j=0; j<tmpibuf->y; j++) {
2679                         for(i=0; i<tmpibuf->x;i++) {
2680                                 float vec[3]= {i, j, 0};
2681
2682                                 mul_v3_m4v3(vec, mat, vec);
2683
2684                                 /* TODO: add selector for interpolation method */
2685                                 neareast_interpolation(ibuf, tmpibuf, vec[0], vec[1], i, j);
2686                         }
2687                 }
2688         }
2689
2690         tmpibuf->userflags|= IB_MIPMAP_INVALID;
2691
2692         if(tmpibuf->rect_float)
2693                 tmpibuf->userflags|= IB_RECT_INVALID;
2694
2695         if(loc)         copy_v2_v2(loc, tloc);
2696         if(scale)       *scale= tscale;
2697         if(angle)       *angle= tangle;
2698
2699         return tmpibuf;
2700 }
2701
2702 void BKE_tracking_stabdata_to_mat4(int width, int height, float loc[2], float scale, float angle, float mat[4][4])
2703 {
2704         float lmat[4][4], rmat[4][4], smat[4][4], cmat[4][4], icmat[4][4];
2705         float svec[3]= {scale, scale, scale};
2706
2707         unit_m4(rmat);
2708         unit_m4(lmat);
2709         unit_m4(smat);
2710         unit_m4(cmat);
2711
2712         /* image center as rotation center */
2713         cmat[3][0]= (float)width/2.0f;
2714         cmat[3][1]= (float)height/2.0f;
2715         invert_m4_m4(icmat, cmat);
2716
2717         size_to_mat4(smat, svec);               /* scale matrix */
2718         add_v2_v2(lmat[3], loc);                /* tranlation matrix */
2719         rotate_m4(rmat, 'Z', angle);    /* rotation matrix */
2720
2721         /* compose transformation matrix */
2722         mul_serie_m4(mat, lmat, cmat, rmat, smat, icmat, NULL, NULL, NULL);
2723 }
2724
2725 MovieDistortion *BKE_tracking_distortion_create(void)
2726 {
2727         MovieDistortion *distortion;
2728
2729         distortion= MEM_callocN(sizeof(MovieDistortion), "BKE_tracking_distortion_create");
2730
2731         return distortion;
2732 }
2733
2734 MovieDistortion *BKE_tracking_distortion_copy(MovieDistortion *distortion)
2735 {
2736         MovieDistortion *new_distortion;
2737
2738         new_distortion= MEM_callocN(sizeof(MovieDistortion), "BKE_tracking_distortion_create");
2739
2740 #ifdef WITH_LIBMV
2741         new_distortion->intrinsics= libmv_CameraIntrinsicsCopy(distortion->intrinsics);
2742 #else
2743         (void)distortion;
2744 #endif
2745
2746         return new_distortion;
2747 }
2748
2749 void BKE_tracking_distortion_update(MovieDistortion *distortion, MovieTracking *tracking, int width, int height)
2750 {
2751         MovieTrackingCamera *camera= &tracking->camera;
2752         float aspy= 1.0f/tracking->camera.pixel_aspect;
2753
2754 #ifdef WITH_LIBMV
2755         if(!distortion->intrinsics) {
2756                 distortion->intrinsics= libmv_CameraIntrinsicsNew(camera->focal,
2757                                 camera->principal[0], camera->principal[1] * aspy,
2758                                 camera->k1, camera->k2, camera->k3, width, height * aspy);
2759         } else {
2760                 libmv_CameraIntrinsicsUpdate(distortion->intrinsics, camera->focal,
2761                                 camera->principal[0], camera->principal[1] * aspy,
2762                                 camera->k1, camera->k2, camera->k3, width, height * aspy);
2763         }
2764 #else
2765         (void)distortion;
2766         (void)width;
2767         (void)height;
2768         (void)camera;
2769         (void)aspy;
2770 #endif
2771 }
2772
2773 ImBuf *BKE_tracking_distortion_exec(MovieDistortion *distortion, MovieTracking *tracking,
2774                         ImBuf *ibuf, int width, int height, float overscan, int undistort)
2775 {
2776         ImBuf *resibuf;
2777
2778         BKE_tracking_distortion_update(distortion, tracking, width, height);
2779
2780         resibuf= IMB_dupImBuf(ibuf);
2781
2782         if(ibuf->rect_float) {
2783 #ifdef WITH_LIBMV
2784                 if(undistort) {
2785                         libmv_CameraIntrinsicsUndistortFloat(distortion->intrinsics,
2786                                                 ibuf->rect_float, resibuf->rect_float,
2787                                                 ibuf->x, ibuf->y, overscan, ibuf->channels);
2788                 } else {
2789                         libmv_CameraIntrinsicsDistortFloat(distortion->intrinsics,
2790                                                 ibuf->rect_float, resibuf->rect_float,
2791                                                 ibuf->x, ibuf->y, overscan, ibuf->channels);
2792                 }
2793 #endif
2794
2795                 ibuf->userflags|= IB_RECT_INVALID;
2796         } else {
2797 #ifdef WITH_LIBMV
2798                 if(undistort) {
2799                                 libmv_CameraIntrinsicsUndistortByte(distortion->intrinsics,
2800                                                         (unsigned char*)ibuf->rect, (unsigned char*)resibuf->rect,
2801                                                         ibuf->x, ibuf->y, overscan, ibuf->channels);
2802                 } else {
2803                         libmv_CameraIntrinsicsDistortByte(distortion->intrinsics,
2804                                                 (unsigned char*)ibuf->rect, (unsigned char*)resibuf->rect,
2805                                                 ibuf->x, ibuf->y, overscan, ibuf->channels);
2806                 }
2807 #endif
2808         }
2809
2810 #ifndef WITH_LIBMV
2811         (void)overscan;
2812         (void)undistort;
2813 #endif
2814
2815         return resibuf;
2816 }
2817
2818 void BKE_tracking_distortion_destroy(MovieDistortion *distortion)
2819 {
2820 #ifdef WITH_LIBMV
2821         libmv_CameraIntrinsicsDestroy(distortion->intrinsics);
2822 #endif
2823
2824         MEM_freeN(distortion);
2825 }
2826
2827 ImBuf *BKE_tracking_undistort(MovieTracking *tracking, ImBuf *ibuf, int width, int height, float overscan)
2828 {
2829         MovieTrackingCamera *camera= &tracking->camera;
2830
2831         if(camera->intrinsics == NULL)
2832                 camera->intrinsics= BKE_tracking_distortion_create();
2833
2834         return BKE_tracking_distortion_exec(camera->intrinsics, tracking, ibuf, width, height, overscan, 1);
2835 }
2836
2837 ImBuf *BKE_tracking_distort(MovieTracking *tracking, ImBuf *ibuf, int width, int height, float overscan)
2838 {
2839         MovieTrackingCamera *camera= &tracking->camera;
2840
2841         if(camera->intrinsics == NULL)
2842                 camera->intrinsics= BKE_tracking_distortion_create();
2843
2844         return BKE_tracking_distortion_exec(camera->intrinsics, tracking, ibuf, width, height, overscan, 0);
2845 }
2846
2847 /* area - which part of marker should be selected. see TRACK_AREA_* constants */
2848 void BKE_tracking_select_track(ListBase *tracksbase, MovieTrackingTrack *track, int area, int extend)
2849 {
2850         if(extend) {
2851                 BKE_tracking_track_flag(track, area, SELECT, 0);
2852         } else {
2853                 MovieTrackingTrack *cur= tracksbase->first;
2854
2855                 while(cur) {
2856                         if(cur==track) {
2857                                 BKE_tracking_track_flag(cur, TRACK_AREA_ALL, SELECT, 1);
2858                                 BKE_tracking_track_flag(cur, area, SELECT, 0);
2859                         }
2860                         else {
2861                                 BKE_tracking_track_flag(cur, TRACK_AREA_ALL, SELECT, 1);
2862                         }
2863
2864                         cur= cur->next;
2865                 }
2866         }
2867 }
2868
2869 void BKE_tracking_deselect_track(MovieTrackingTrack *track, int area)
2870 {
2871         BKE_tracking_track_flag(track, area, SELECT, 1);
2872 }
2873
2874 MovieTrackingObject *BKE_tracking_new_object(MovieTracking *tracking, const char *name)
2875 {
2876         MovieTrackingObject *object= MEM_callocN(sizeof(MovieTrackingObject), "tracking object");
2877
2878         if(tracking->tot_object==0) {
2879                 /* first object is always camera */
2880                 BLI_strncpy(object->name, "Camera", sizeof(object->name));
2881
2882                 object->flag|= TRACKING_OBJECT_CAMERA;
2883         }
2884         else {
2885                 BLI_strncpy(object->name, name, sizeof(object->name));
2886         }
2887
2888         BLI_addtail(&tracking->objects, object);
2889
2890         tracking->tot_object++;
2891         tracking->objectnr= BLI_countlist(&tracking->objects) - 1;
2892
2893         BKE_tracking_object_unique_name(tracking, object);
2894
2895         return object;
2896 }
2897
2898 void BKE_tracking_remove_object(MovieTracking *tracking, MovieTrackingObject *object)
2899 {
2900         MovieTrackingTrack *track;
2901         int index= BLI_findindex(&tracking->objects, object);
2902
2903         if(index<0)
2904                 return;
2905
2906         if(object->flag & TRACKING_OBJECT_CAMERA) {
2907                 /* object used for camera solving can't be deleted */
2908                 return;
2909         }
2910
2911         track= object->tracks.first;
2912         while(track) {
2913                 if(track==tracking->act_track)
2914                         tracking->act_track= NULL;
2915
2916                 track= track->next;
2917         }
2918
2919         tracking_object_free(object);
2920         BLI_freelinkN(&tracking->objects, object);
2921
2922         tracking->tot_object--;
2923
2924         if(index>0)
2925                 tracking->objectnr= index-1;
2926         else
2927                 tracking->objectnr= 0;
2928 }
2929
2930 void BKE_tracking_object_unique_name(MovieTracking *tracking, MovieTrackingObject *object)
2931 {
2932         BLI_uniquename(&tracking->objects, object, "Object", '.', offsetof(MovieTrackingObject, name), sizeof(object->name));
2933 }
2934
2935 MovieTrackingObject *BKE_tracking_named_object(MovieTracking *tracking, const char *name)
2936 {
2937         MovieTrackingObject *object= tracking->objects.first;
2938
2939         while(object) {
2940                 if(!strcmp(object->name, name))
2941                         return object;
2942
2943                 object= object->next;
2944         }
2945
2946         return NULL;
2947 }