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