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