Merging r42193 through r42349 from 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_pyramid_levels= 2;
81         tracking->settings.default_minimum_correlation= 0.75;
82         tracking->settings.default_pattern_size= 11;
83         tracking->settings.default_search_size= 51;
84         tracking->settings.default_pyramid_levels= 2;
85         tracking->settings.keyframe1= 1;
86         tracking->settings.keyframe2= 30;
87         tracking->settings.dist= 1;
88
89         tracking->stabilization.scaleinf= 1.0f;
90         tracking->stabilization.locinf= 1.0f;
91         tracking->stabilization.rotinf= 1.0f;
92         tracking->stabilization.maxscale= 2.0f;
93 }
94
95 void BKE_tracking_clamp_track(MovieTrackingTrack *track, int event)
96 {
97         int a;
98         float pat_min[2];
99         float pat_max[2];
100         float max_pyramid_level_factor = 1.0;
101
102         if (track->tracker == TRACKER_KLT) {
103                 max_pyramid_level_factor= 1 << (track->pyramid_levels - 1);
104         }
105
106         /* sort */
107         for(a= 0; a<2; a++) {
108                 if(track->pat_min[a]>track->pat_max[a])
109                         SWAP(float, track->pat_min[a], track->pat_max[a]);
110
111                 if(track->search_min[a]>track->search_max[a])
112                         SWAP(float, track->search_min[a], track->search_max[a]);
113         }
114
115         /* compute the effective pattern size, which differs from the fine resolution
116          * pattern size for the pyramid KLT tracker */
117         for(a= 0; a<2; a++) {
118                 pat_min[a] = max_pyramid_level_factor * track->pat_min[a];
119                 pat_max[a] = max_pyramid_level_factor * track->pat_max[a];
120         }
121
122         if(event==CLAMP_PAT_DIM) {
123                 for(a= 0; a<2; a++) {
124                         /* search shouldn't be resized smaller than pattern */
125                         track->search_min[a]= MIN2(pat_min[a], track->search_min[a]);
126                         track->search_max[a]= MAX2(pat_max[a], track->search_max[a]);
127                 }
128         }
129         else if(event==CLAMP_PAT_POS) {
130                 float dim[2];
131                 sub_v2_v2v2(dim, track->pat_max, pat_min);
132
133                 for(a= 0; a<2; a++) {
134                         /* pattern shouldn't be moved outside of search */
135                         if(pat_min[a] < track->search_min[a]) {
136                                 track->pat_min[a]= track->search_min[a] - (pat_min[a] - track->pat_min[a]);
137                                 track->pat_max[a]=  (pat_min[a] - track->pat_min[a])+dim[a];
138                         }
139                         if(track->pat_max[a] > track->search_max[a]) {
140                                 track->pat_max[a]= track->search_max[a] - (pat_max[a] - track->pat_max[a]);
141                                 track->pat_min[a]= track->pat_max[a]-dim[a] - (pat_min[a] - track->pat_min[a]);
142                         }
143                 }
144         }
145         else if(event==CLAMP_SEARCH_DIM) {
146                 for(a= 0; a<2; a++) {
147                         /* search shouldn't be resized smaller than pattern */
148                         track->search_min[a]= MIN2(pat_min[a], track->search_min[a]);
149                         track->search_max[a]= MAX2(pat_max[a], track->search_max[a]);
150                 }
151         }
152         else if(event==CLAMP_SEARCH_POS) {
153                 float dim[2];
154                 sub_v2_v2v2(dim, track->search_max, track->search_min);
155
156                 for(a= 0; a<2; a++) {
157                         /* search shouldn't be moved inside pattern */
158                         if(track->search_min[a] > pat_min[a]) {
159                                 track->search_min[a]= pat_min[a];
160                                 track->search_max[a]= track->search_min[a]+dim[a];
161                         }
162                         if(track->search_max[a] < pat_max[a]) {
163                                 track->search_max[a]= pat_max[a];
164                                 track->search_min[a]= track->search_max[a]-dim[a];
165                         }
166                 }
167         }
168         else if(event==CLAMP_PYRAMID_LEVELS || (event==CLAMP_SEARCH_DIM && track->tracker == TRACKER_KLT))  {
169                 float dim[2];
170                 sub_v2_v2v2(dim, track->pat_max, track->pat_min);
171                 {
172                         float search_ratio= 2.3f * max_pyramid_level_factor;
173
174                         /* resize the search area to something sensible based
175                          * on the number of pyramid levels */
176                         for(a= 0; a<2; a++) {
177                                 track->search_min[a]= search_ratio * track->pat_min[a];
178                                 track->search_max[a]= search_ratio * track->pat_max[a];
179                         }
180                 }
181         }
182
183         /* marker's center should be in center of pattern */
184         if(event==CLAMP_PAT_DIM || event==CLAMP_PAT_POS) {
185                 float dim[2];
186                 sub_v2_v2v2(dim, track->pat_max, track->pat_min);
187
188                 for(a= 0; a<2; a++) {
189                         track->pat_min[a]= -dim[a]/2.0f;
190                         track->pat_max[a]= dim[a]/2.0f;
191                 }
192         }
193 }
194
195 void BKE_tracking_track_flag(MovieTrackingTrack *track, int area, int flag, int clear)
196 {
197         if(area==TRACK_AREA_NONE)
198                 return;
199
200         if(clear) {
201                 if(area&TRACK_AREA_POINT)       track->flag&= ~flag;
202                 if(area&TRACK_AREA_PAT)         track->pat_flag&= ~flag;
203                 if(area&TRACK_AREA_SEARCH)      track->search_flag&= ~flag;
204         } else {
205                 if(area&TRACK_AREA_POINT)       track->flag|= flag;
206                 if(area&TRACK_AREA_PAT)         track->pat_flag|= flag;
207                 if(area&TRACK_AREA_SEARCH)      track->search_flag|= flag;
208         }
209 }
210
211 MovieTrackingTrack *BKE_tracking_add_track(MovieTracking *tracking, float x, float y,
212                         int framenr, int width, int height)
213 {
214         MovieTrackingTrack *track;
215         MovieTrackingMarker marker;
216         MovieTrackingSettings *settings= &tracking->settings;
217
218         float half_pattern= (float)settings->default_pattern_size/2.0f;
219         float half_search= (float)settings->default_search_size/2.0f;
220         float pat[2], search[2];
221
222         pat[0]= half_pattern/(float)width;
223         pat[1]= half_pattern/(float)height;
224
225         search[0]= half_search/(float)width;
226         search[1]= half_search/(float)height;
227
228         track= MEM_callocN(sizeof(MovieTrackingTrack), "add_marker_exec track");
229         strcpy(track->name, "Track");
230
231         track->tracker= settings->default_tracker;
232         track->pyramid_levels= settings->default_pyramid_levels;
233         track->minimum_correlation= settings->default_minimum_correlation;
234         track->margin= settings->default_margin;
235         track->pattern_match= settings->default_pattern_match;
236         track->frames_limit= settings->default_frames_limit;
237
238         memset(&marker, 0, sizeof(marker));
239         marker.pos[0]= x;
240         marker.pos[1]= y;
241         marker.framenr= framenr;
242
243         copy_v2_v2(track->pat_max, pat);
244         negate_v2_v2(track->pat_min, pat);
245
246         copy_v2_v2(track->search_max, search);
247         negate_v2_v2(track->search_min, search);
248
249         BKE_tracking_insert_marker(track, &marker);
250
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(track->tracker==TRACKER_KLT) {
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                                                         track_context.region_tracker= libmv_regionTrackerNew(100, level, MAX2(wndx, wndy));
812                                                 }
813                                                 else if(track->tracker==TRACKER_SAD) {
814                                                         track_context.pattern_size= MAX2(patx, paty);
815                                                 }
816                                         }
817 #endif
818
819                                         tracks_map_insert(context->tracks_map, track, &track_context);
820                                 }
821                         }
822
823                         track= track->next;
824                 }
825         }
826
827         context->clip= clip;
828         context->user= *user;
829
830         return context;
831 }
832
833 static void track_context_free(void *customdata)
834 {
835         TrackContext *track_context= (TrackContext *)customdata;
836
837 #if WITH_LIBMV
838         if(track_context->region_tracker)
839                 libmv_regionTrackerDestroy(track_context->region_tracker);
840
841         if(track_context->patch)
842                 MEM_freeN(track_context->patch);
843
844         if(track_context->pattern)
845                 MEM_freeN(track_context->pattern);
846
847         if(track_context->warped)
848                 MEM_freeN(track_context->warped);
849 #else
850                 (void) track_context;
851 #endif
852 }
853
854 void BKE_tracking_context_free(MovieTrackingContext *context)
855 {
856         tracks_map_free(context->tracks_map, track_context_free);
857
858         MEM_freeN(context);
859 }
860
861 static void disable_imbuf_channels(ImBuf *ibuf, MovieTrackingTrack *track)
862 {
863         int x, y;
864
865         if((track->flag&(TRACK_DISABLE_RED|TRACK_DISABLE_GREEN|TRACK_DISABLE_BLUE))==0)
866                 return;
867
868         for(y= 0; y<ibuf->y; y++) {
869                 for (x= 0; x<ibuf->x; x++) {
870                         int pixel= ibuf->x*y + x;
871
872                         if(ibuf->rect_float) {
873                                 float *rrgbf= ibuf->rect_float + pixel*4;
874
875                                 if(track->flag&TRACK_DISABLE_RED)       rrgbf[0]= 0;
876                                 if(track->flag&TRACK_DISABLE_GREEN)     rrgbf[1]= 0;
877                                 if(track->flag&TRACK_DISABLE_BLUE)      rrgbf[2]= 0;
878                         } else {
879                                 char *rrgb= (char*)ibuf->rect + pixel*4;
880
881                                 if(track->flag&TRACK_DISABLE_RED)       rrgb[0]= 0;
882                                 if(track->flag&TRACK_DISABLE_GREEN)     rrgb[1]= 0;
883                                 if(track->flag&TRACK_DISABLE_BLUE)      rrgb[2]= 0;
884                         }
885                 }
886         }
887 }
888
889 static ImBuf *get_area_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
890                         float min[2], float max[2], int margin, int anchored, float pos[2], int origin[2])
891 {
892         ImBuf *tmpibuf;
893         int x, y;
894         int x1, y1, x2, y2, w, h;
895         float mpos[2];
896
897         copy_v2_v2(mpos, marker->pos);
898         if(anchored)
899                 add_v2_v2(mpos, track->offset);
900
901         x= mpos[0]*ibuf->x;
902         y= mpos[1]*ibuf->y;
903         x1= x-(int)(-min[0]*ibuf->x);
904         y1= y-(int)(-min[1]*ibuf->y);
905         x2= x+(int)(max[0]*ibuf->x);
906         y2= y+(int)(max[1]*ibuf->y);
907
908         /* dimensions should be odd */
909         w= (x2-x1)|1;
910         h= (y2-y1)|1;
911
912         tmpibuf= IMB_allocImBuf(w+margin*2, h+margin*2, 32, IB_rect);
913         IMB_rectcpy(tmpibuf, ibuf, 0, 0, x1-margin, y1-margin, w+margin*2, h+margin*2);
914
915         if(pos != NULL) {
916                 pos[0]= mpos[0]*ibuf->x-x1+margin;
917                 pos[1]= mpos[1]*ibuf->y-y1+margin;
918         }
919
920         if(origin != NULL) {
921                 origin[0]= x1-margin;
922                 origin[1]= y1-margin;
923         }
924
925         disable_imbuf_channels(tmpibuf, track);
926
927         return tmpibuf;
928 }
929
930 ImBuf *BKE_tracking_get_pattern_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
931                         int margin, int anchored, float pos[2], int origin[2])
932 {
933         return get_area_imbuf(ibuf, track, marker, track->pat_min, track->pat_max, margin, anchored, pos, origin);
934 }
935
936 ImBuf *BKE_tracking_get_search_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
937                         int margin, int anchored, float pos[2], int origin[2])
938 {
939         return get_area_imbuf(ibuf, track, marker, track->search_min, track->search_max, margin, anchored, pos, origin);
940 }
941
942 #ifdef WITH_LIBMV
943 static float *get_search_floatbuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
944                         int *width_r, int *height_r, float pos[2], int origin[2])
945 {
946         ImBuf *tmpibuf;
947         float *pixels, *fp;
948         int x, y, width, height;
949
950         width= (track->search_max[0]-track->search_min[0])*ibuf->x;
951         height= (track->search_max[1]-track->search_min[1])*ibuf->y;
952
953         tmpibuf= BKE_tracking_get_search_imbuf(ibuf, track, marker, 0, 0, pos, origin);
954         disable_imbuf_channels(tmpibuf, track);
955
956         *width_r= width;
957         *height_r= height;
958
959         fp= pixels= MEM_callocN(width*height*sizeof(float), "tracking floatBuf");
960         for(y= 0; y<(int)height; y++) {
961                 for (x= 0; x<(int)width; x++) {
962                         int pixel= tmpibuf->x*y + x;
963
964                         if(tmpibuf->rect_float) {
965                                 float *rrgbf= tmpibuf->rect_float + pixel*4;
966
967                                 *fp= 0.2126*rrgbf[0] + 0.7152*rrgbf[1] + 0.0722*rrgbf[2];
968                         } else {
969                                 unsigned char *rrgb= (unsigned char*)tmpibuf->rect + pixel*4;
970
971                                 *fp= (0.2126*rrgb[0] + 0.7152*rrgb[1] + 0.0722*rrgb[2])/255.0f;
972                         }
973
974                         fp++;
975                 }
976         }
977
978         IMB_freeImBuf(tmpibuf);
979
980         return pixels;
981 }
982
983 static unsigned char *get_ucharbuf(ImBuf *ibuf)
984 {
985         int x, y;
986         unsigned char *pixels, *cp;
987
988         cp= pixels= MEM_callocN(ibuf->x*ibuf->y*sizeof(unsigned char), "tracking ucharBuf");
989         for(y= 0; y<ibuf->y; y++) {
990                 for (x= 0; x<ibuf->x; x++) {
991                         int pixel= ibuf->x*y + x;
992
993                         if(ibuf->rect_float) {
994                                 float *rrgbf= ibuf->rect_float + pixel*4;
995
996                                 *cp= FTOCHAR(0.2126f*rrgbf[0] + 0.7152f*rrgbf[1] + 0.0722f*rrgbf[2]);
997                         } else {
998                                 unsigned char *rrgb= (unsigned char*)ibuf->rect + pixel*4;
999
1000                                 *cp= 0.2126f*rrgb[0] + 0.7152f*rrgb[1] + 0.0722f*rrgb[2];
1001                         }
1002
1003                         cp++;
1004                 }
1005         }
1006
1007         return pixels;
1008 }
1009
1010 static unsigned char *get_search_bytebuf(ImBuf *ibuf, MovieTrackingTrack *track, MovieTrackingMarker *marker,
1011                         int *width_r, int *height_r, float pos[2], int origin[2])
1012 {
1013         ImBuf *tmpibuf;
1014         unsigned char *pixels;
1015
1016         tmpibuf= BKE_tracking_get_search_imbuf(ibuf, track, marker, 0, 0, pos, origin);
1017         disable_imbuf_channels(tmpibuf, track);
1018
1019         *width_r= tmpibuf->x;
1020         *height_r= tmpibuf->y;
1021
1022         pixels= get_ucharbuf(tmpibuf);
1023
1024         IMB_freeImBuf(tmpibuf);
1025
1026         return pixels;
1027 }
1028
1029 static ImBuf *get_frame_ibuf(MovieTrackingContext *context, int framenr)
1030 {
1031         ImBuf *ibuf;
1032         MovieClipUser user= context->user;
1033
1034         user.framenr= framenr;
1035
1036         ibuf= BKE_movieclip_get_ibuf_flag(context->clip, &user, 0);
1037
1038         return ibuf;
1039 }
1040
1041 static ImBuf *get_keyframed_ibuf(MovieTrackingContext *context, MovieTrackingTrack *track,
1042                         MovieTrackingMarker *marker, MovieTrackingMarker **marker_keyed)
1043 {
1044         int framenr= marker->framenr;
1045         int a= marker-track->markers;
1046
1047         *marker_keyed= marker;
1048
1049         while(a>=0 && a<track->markersnr) {
1050                 int next= (context->backwards) ? a+1 : a-1;
1051                 int is_keyframed= 0;
1052                 MovieTrackingMarker *cur_marker= &track->markers[a];
1053                 MovieTrackingMarker *next_marker= NULL;
1054
1055                 if(next>=0 && next<track->markersnr)
1056                         next_marker= &track->markers[next];
1057
1058                 /* if next mrker is disabled, stop searching keyframe and use current frame as keyframe */
1059                 if(next_marker && next_marker->flag&MARKER_DISABLED)
1060                         is_keyframed= 1;
1061
1062                 is_keyframed|= (cur_marker->flag&MARKER_TRACKED)==0;
1063
1064                 if(is_keyframed) {
1065                         framenr= cur_marker->framenr;
1066                         *marker_keyed= cur_marker;
1067                         break;
1068                 }
1069
1070                 a= next;
1071         }
1072
1073         return get_frame_ibuf(context, framenr);
1074 }
1075
1076 static ImBuf *get_adjust_ibuf(MovieTrackingContext *context, MovieTrackingTrack *track, MovieTrackingMarker *marker,
1077                         int curfra, MovieTrackingMarker **marker_keyed)
1078 {
1079         ImBuf *ibuf= NULL;
1080
1081         if(track->pattern_match == TRACK_MATCH_KEYFRAME) {
1082                 ibuf= get_keyframed_ibuf(context, track, marker, marker_keyed);
1083         } else {
1084                 ibuf= get_frame_ibuf(context, curfra);
1085
1086                 /* use current marker as keyframed position */
1087                 *marker_keyed= marker;
1088         }
1089
1090         return ibuf;
1091 }
1092
1093 static void get_warped(TrackContext *track_context, int x, int y, int width, unsigned char *image)
1094 {
1095         int i, j;
1096
1097         for(i=0; i<track_context->pattern_size; i++) {
1098                 for(j=0; j<track_context->pattern_size; j++) {
1099                         track_context->warped[i*track_context->pattern_size+j]=
1100                                         image[(y+i-track_context->pattern_size/2)*width+x+j-track_context->pattern_size/2];
1101                 }
1102         }
1103 }
1104
1105 #endif
1106
1107 void BKE_tracking_sync(MovieTrackingContext *context)
1108 {
1109         MovieTracking *tracking= &context->clip->tracking;
1110         int newframe;
1111
1112         tracks_map_merge(context->tracks_map, tracking);
1113
1114         if(context->backwards) newframe= context->user.framenr+1;
1115         else newframe= context->user.framenr-1;
1116
1117         context->sync_frame= newframe;
1118 }
1119
1120 void BKE_tracking_sync_user(MovieClipUser *user, MovieTrackingContext *context)
1121 {
1122         user->framenr= context->sync_frame;
1123 }
1124
1125 int BKE_tracking_next(MovieTrackingContext *context)
1126 {
1127         ImBuf *ibuf_new;
1128         int curfra= context->user.framenr;
1129         int a, ok= 0, map_size;
1130
1131         map_size= tracks_map_size(context->tracks_map);
1132
1133         /* nothing to track, avoid unneeded frames reading to save time and memory */
1134         if(!map_size)
1135                 return 0;
1136
1137         if(context->backwards) context->user.framenr--;
1138         else context->user.framenr++;
1139
1140         ibuf_new= BKE_movieclip_get_ibuf_flag(context->clip, &context->user, 0);
1141         if(!ibuf_new)
1142                 return 0;
1143
1144     #pragma omp parallel for private(a) shared(ibuf_new, ok) if(map_size>1)
1145         for(a= 0; a<map_size; a++) {
1146                 TrackContext *track_context;
1147                 MovieTrackingTrack *track;
1148                 MovieTrackingMarker *marker;
1149
1150                 tracks_map_get(context->tracks_map, a, &track, (void**)&track_context);
1151
1152                 marker= BKE_tracking_exact_marker(track, curfra);
1153
1154                 if(marker && (marker->flag&MARKER_DISABLED)==0) {
1155 #ifdef WITH_LIBMV
1156                         int width, height, origin[2], tracked= 0, need_readjust= 0;
1157                         float pos[2], margin[2];
1158                         double x1, y1, x2, y2;
1159                         ImBuf *ibuf= NULL;
1160                         MovieTrackingMarker marker_new, *marker_keyed;
1161                         int onbound= 0, coords_correct= 0;
1162                         int nextfra;
1163
1164                         if(track->pattern_match==TRACK_MATCH_KEYFRAME)
1165                                 need_readjust= context->first_time;
1166                         else
1167                                 need_readjust= 1;
1168
1169                         if(context->backwards) nextfra= curfra-1;
1170                         else nextfra= curfra+1;
1171
1172                         /* margin from frame boundaries */
1173                         sub_v2_v2v2(margin, track->pat_max, track->pat_min);
1174
1175                         margin[0]= MAX2(margin[0], (float)track->margin / ibuf_new->x);
1176                         margin[1]= MAX2(margin[1], (float)track->margin / ibuf_new->y);
1177
1178                         /* do not track markers which are too close to boundary */
1179                         if(marker->pos[0]<margin[0] || marker->pos[0]>1.0f-margin[0] ||
1180                            marker->pos[1]<margin[1] || marker->pos[1]>1.0f-margin[1]) {
1181                                 onbound= 1;
1182                         }
1183                         else if(track->tracker==TRACKER_KLT) {
1184                                 float *patch_new;
1185
1186                                 if(need_readjust) {
1187                                         /* calculate patch for keyframed position */
1188                                         ibuf= get_adjust_ibuf(context, track, marker, curfra, &marker_keyed);
1189
1190                                         if(track_context->patch)
1191                                                 MEM_freeN(track_context->patch);
1192
1193                                         track_context->patch= get_search_floatbuf(ibuf, track, marker_keyed, &width, &height, track_context->keyframed_pos, origin);
1194
1195                                         IMB_freeImBuf(ibuf);
1196                                 }
1197
1198                                 patch_new= get_search_floatbuf(ibuf_new, track, marker, &width, &height, pos, origin);
1199
1200                                 x1= track_context->keyframed_pos[0];
1201                                 y1= track_context->keyframed_pos[1];
1202
1203                                 x2= pos[0];
1204                                 y2= pos[1];
1205
1206                                 tracked= libmv_regionTrackerTrack(track_context->region_tracker, track_context->patch, patch_new,
1207                                                         width, height, x1, y1, &x2, &y2);
1208
1209                                 MEM_freeN(patch_new);
1210                         }
1211                         else if(track->tracker==TRACKER_SAD) {
1212                                 unsigned char *image_new;
1213                                 float correlation;
1214                                 float warp[3][2]={{0}};
1215
1216                                 if(need_readjust) {
1217                                         unsigned char *image;
1218
1219                                         /* calculate pattern for keyframed position */
1220                                         ibuf= get_adjust_ibuf(context, track, marker, curfra, &marker_keyed);
1221
1222                                         image= get_search_bytebuf(ibuf, track, marker_keyed, &width, &height, pos, origin);
1223
1224                                         memset(warp, 0, sizeof(warp));
1225                                         warp[0][0]= 1;
1226                                         warp[1][1]= 1;
1227                                         warp[2][0]= pos[0];
1228                                         warp[2][1]= pos[1];
1229
1230                                         if(!track_context->pattern) {
1231                                                 int square= track_context->pattern_size*track_context->pattern_size;
1232                                                 track_context->pattern= MEM_callocN(sizeof(unsigned char)*square, "trackking pattern");
1233                                         }
1234
1235                                         libmv_SADSamplePattern(image, width, warp, track_context->pattern, track_context->pattern_size);
1236
1237                                         MEM_freeN(image);
1238                                         IMB_freeImBuf(ibuf);
1239                                 }
1240
1241                                 image_new= get_search_bytebuf(ibuf_new, track, marker, &width, &height, pos, origin);
1242
1243                                 if(track_context->warped==NULL) {
1244                                         unsigned char *image_old;
1245
1246                                         ibuf= get_frame_ibuf(context, curfra);
1247
1248                                         if(track_context->warped==NULL) {
1249                                                 int square= track_context->pattern_size*track_context->pattern_size;
1250                                                 track_context->warped= MEM_callocN(sizeof(unsigned char)*square, "trackking warped");
1251                                         }
1252
1253                                         image_old= get_search_bytebuf(ibuf, track, marker, &width, &height, pos, origin);
1254                                         get_warped(track_context, pos[0], pos[1], width, image_old);
1255                                         IMB_freeImBuf(ibuf);
1256                                         MEM_freeN(image_old);
1257                                 }
1258
1259                                 memset(warp, 0, sizeof(warp));
1260                                 warp[0][0]= 1;
1261                                 warp[1][1]= 1;
1262                                 warp[2][0]= pos[0];
1263                                 warp[2][1]= pos[1];
1264
1265                                 correlation= libmv_SADTrackerTrack(track_context->pattern, track_context->warped,
1266                                                         track_context->pattern_size, image_new, width, width, height, warp);
1267
1268                                 x2= warp[2][0];
1269                                 y2= warp[2][1];
1270
1271                                 tracked= track->minimum_correlation < correlation;
1272
1273                                 if(tracked)
1274                                         get_warped(track_context, x2, y2, width, image_new);
1275
1276                                 MEM_freeN(image_new);
1277                         }
1278
1279                         coords_correct= !isnan(x2) && !isnan(y2) && finite(x2) && finite(y2);
1280                         if(coords_correct && (tracked || !context->disable_failed)) {
1281                                 if(context->first_time) {
1282                                         #pragma omp critical
1283                                         {
1284                                                 /* check if there's no keyframe/tracked markers before tracking marker.
1285                                                    if so -- create disabled marker before currently tracking "segment" */
1286                                                 put_disabled_marker(track, marker, 1, 0);
1287                                         }
1288                                 }
1289
1290                                 memset(&marker_new, 0, sizeof(marker_new));
1291
1292                                 if(!onbound) {
1293                                         marker_new.pos[0]= (origin[0]+x2)/ibuf_new->x;
1294                                         marker_new.pos[1]= (origin[1]+y2)/ibuf_new->y;
1295                                 } else {
1296                                         copy_v2_v2(marker_new.pos, marker->pos);
1297                                 }
1298
1299                                 marker_new.flag|= MARKER_TRACKED;
1300                                 marker_new.framenr= nextfra;
1301
1302                                 #pragma omp critical
1303                                 {
1304                                         BKE_tracking_insert_marker(track, &marker_new);
1305                                 }
1306
1307                                 /* make currently tracked segment be finished with disabled marker */
1308                                 #pragma omp critical
1309                                 {
1310                                         put_disabled_marker(track, &marker_new, 0, 0);
1311                                 }
1312                         } else {
1313                                 marker_new= *marker;
1314
1315                                 marker_new.framenr= nextfra;
1316                                 marker_new.flag|= MARKER_DISABLED;
1317
1318                                 #pragma omp critical
1319                                 {
1320                                         BKE_tracking_insert_marker(track, &marker_new);
1321                                 }
1322                         }
1323
1324                         ok= 1;
1325 #endif
1326                 }
1327         }
1328
1329         IMB_freeImBuf(ibuf_new);
1330
1331         context->first_time= 0;
1332         context->frames++;
1333
1334         return ok;
1335 }
1336
1337 /*********************** camera solving *************************/
1338
1339 typedef struct MovieReconstructContext {
1340 #ifdef WITH_LIBMV
1341         struct libmv_Tracks *tracks;
1342         int keyframe1, keyframe2;
1343         short refine_flags;
1344
1345         struct libmv_Reconstruction *reconstruction;
1346 #endif
1347
1348         float focal_length;
1349         float principal_point[2];
1350         float k1, k2, k3;
1351
1352         float reprojection_error;
1353
1354         TracksMap *tracks_map;
1355
1356         int sfra, efra;
1357 } MovieReconstructContext;
1358
1359 typedef struct ReconstructProgressData {
1360         short *stop;
1361         short *do_update;
1362         float *progress;
1363         char *stats_message;
1364         int message_size;
1365 } ReconstructProgressData;
1366
1367 #if WITH_LIBMV
1368 static struct libmv_Tracks *create_libmv_tracks(MovieTracking *tracking, int width, int height)
1369 {
1370         int tracknr= 0;
1371         MovieTrackingTrack *track;
1372         struct libmv_Tracks *tracks= libmv_tracksNew();
1373
1374         track= tracking->tracks.first;
1375         while(track) {
1376                 int a= 0;
1377
1378                 for(a= 0; a<track->markersnr; a++) {
1379                         MovieTrackingMarker *marker= &track->markers[a];
1380
1381                         if((marker->flag&MARKER_DISABLED)==0)
1382                                 libmv_tracksInsert(tracks, marker->framenr, tracknr,
1383                                                         marker->pos[0]*width, marker->pos[1]*height);
1384                 }
1385
1386                 track= track->next;
1387                 tracknr++;
1388         }
1389
1390         return tracks;
1391 }
1392
1393 static void retrieve_libmv_reconstruct_intrinscis(MovieReconstructContext *context, MovieTracking *tracking)
1394 {
1395         struct libmv_Reconstruction *libmv_reconstruction= context->reconstruction;
1396         struct libmv_CameraIntrinsics *libmv_intrinsics = libmv_ReconstructionExtractIntrinsics(libmv_reconstruction);
1397
1398         float aspy= 1.0f/tracking->camera.pixel_aspect;
1399
1400         double focal_length, principal_x, principal_y, k1, k2, k3;
1401         int width, height;
1402
1403         libmv_CameraIntrinsicsExtract(libmv_intrinsics, &focal_length, &principal_x, &principal_y,
1404                         &k1, &k2, &k3, &width, &height);
1405
1406         tracking->camera.focal= focal_length;
1407         tracking->camera.principal[0]= principal_x;
1408
1409         /* todo: verify divide by aspy is correct */
1410         tracking->camera.principal[1]= principal_y / aspy;
1411         tracking->camera.k1= k1;
1412         tracking->camera.k2= k2;
1413 }
1414
1415 static int retrieve_libmv_reconstruct_tracks(MovieReconstructContext *context, MovieTracking *tracking)
1416 {
1417         struct libmv_Reconstruction *libmv_reconstruction= context->reconstruction;
1418         MovieTrackingReconstruction *reconstruction= &tracking->reconstruction;
1419         MovieReconstructedCamera *reconstructed;
1420         MovieTrackingTrack *track;
1421         int ok= 1, tracknr= 0, a, origin_set= 0;
1422         int sfra= context->sfra, efra= context->efra;
1423         float imat[4][4];
1424
1425         unit_m4(imat);
1426
1427         track= tracking->tracks.first;
1428         while(track) {
1429                 double pos[3];
1430
1431                 if(libmv_reporojectionPointForTrack(libmv_reconstruction, tracknr, pos)) {
1432                         track->bundle_pos[0]= pos[0];
1433                         track->bundle_pos[1]= pos[1];
1434                         track->bundle_pos[2]= pos[2];
1435
1436                         track->flag|= TRACK_HAS_BUNDLE;
1437                         track->error= libmv_reporojectionErrorForTrack(libmv_reconstruction, tracknr);
1438                 } else {
1439                         track->flag&= ~TRACK_HAS_BUNDLE;
1440                         ok= 0;
1441
1442                         printf("No bundle for track #%d '%s'\n", tracknr, track->name);
1443                 }
1444
1445                 track= track->next;
1446                 tracknr++;
1447         }
1448
1449         if(reconstruction->cameras)
1450                 MEM_freeN(reconstruction->cameras);
1451
1452         reconstruction->camnr= 0;
1453         reconstruction->cameras= NULL;
1454         reconstructed= MEM_callocN((efra-sfra+1)*sizeof(MovieReconstructedCamera), "temp reconstructed camera");
1455
1456         for(a= sfra; a<=efra; a++) {
1457                 double matd[4][4];
1458
1459                 if(libmv_reporojectionCameraForImage(libmv_reconstruction, a, matd)) {
1460                         int i, j;
1461                         float mat[4][4];
1462                         float error= libmv_reporojectionErrorForImage(libmv_reconstruction, a);
1463
1464                         for(i=0; i<4; i++)
1465                                 for(j= 0; j<4; j++)
1466                                         mat[i][j]= matd[i][j];
1467
1468                         if(!origin_set) {
1469                                 copy_m4_m4(imat, mat);
1470                                 invert_m4(imat);
1471                                 origin_set= 1;
1472                         }
1473
1474                         if(origin_set)
1475                                 mul_m4_m4m4(mat, mat, imat);
1476
1477                         copy_m4_m4(reconstructed[reconstruction->camnr].mat, mat);
1478                         reconstructed[reconstruction->camnr].framenr= a;
1479                         reconstructed[reconstruction->camnr].error= error;
1480                         reconstruction->camnr++;
1481                 } else {
1482                         ok= 0;
1483                         printf("No camera for frame %d\n", a);
1484                 }
1485         }
1486
1487         if(reconstruction->camnr) {
1488                 reconstruction->cameras= MEM_callocN(reconstruction->camnr*sizeof(MovieReconstructedCamera), "reconstructed camera");
1489                 memcpy(reconstruction->cameras, reconstructed, reconstruction->camnr*sizeof(MovieReconstructedCamera));
1490         }
1491
1492         if(origin_set) {
1493                 track= tracking->tracks.first;
1494                 while(track) {
1495                         if(track->flag&TRACK_HAS_BUNDLE)
1496                                 mul_v3_m4v3(track->bundle_pos, imat, track->bundle_pos);
1497
1498                         track= track->next;
1499                 }
1500         }
1501
1502         MEM_freeN(reconstructed);
1503
1504         return ok;
1505 }
1506
1507 static int retrieve_libmv_reconstruct(MovieReconstructContext *context, MovieTracking *tracking)
1508 {
1509         tracks_map_merge(context->tracks_map, tracking);
1510
1511         /* take the intrinscis back from libmv */
1512         retrieve_libmv_reconstruct_intrinscis(context, tracking);
1513
1514         return retrieve_libmv_reconstruct_tracks(context, tracking);
1515 }
1516
1517 static int get_refine_intrinsics_flags(MovieTracking *tracking)
1518 {
1519         int refine= tracking->settings.refine_camera_intrinsics;
1520         int flags= 0;
1521
1522         if(refine&REFINE_FOCAL_LENGTH)
1523                 flags|= LIBMV_REFINE_FOCAL_LENGTH;
1524
1525         if(refine&REFINE_PRINCIPAL_POINT)
1526                 flags|= LIBMV_REFINE_PRINCIPAL_POINT;
1527
1528         if(refine&REFINE_RADIAL_DISTORTION_K1)
1529                 flags|= REFINE_RADIAL_DISTORTION_K1;
1530
1531         if(refine&REFINE_RADIAL_DISTORTION_K2)
1532                 flags|= REFINE_RADIAL_DISTORTION_K2;
1533
1534         return flags;
1535 }
1536
1537 static int count_tracks_on_both_keyframes(MovieTracking *tracking)
1538 {
1539         int tot= 0;
1540         int frame1= tracking->settings.keyframe1, frame2= tracking->settings.keyframe2;
1541         MovieTrackingTrack *track;
1542
1543         track= tracking->tracks.first;
1544         while(track) {
1545                 if(BKE_tracking_has_marker(track, frame1))
1546                         if(BKE_tracking_has_marker(track, frame2))
1547                                 tot++;
1548
1549                 track= track->next;
1550         }
1551
1552         return tot;
1553 }
1554 #endif
1555
1556 int BKE_tracking_can_reconstruct(MovieTracking *tracking, char *error_msg, int error_size)
1557 {
1558 #if WITH_LIBMV
1559         if(count_tracks_on_both_keyframes(tracking)<8) {
1560                 BLI_strncpy(error_msg, "At least 8 tracks on both of keyframes are needed for reconstruction", error_size);
1561                 return 0;
1562         }
1563
1564         return 1;
1565 #else
1566         BLI_strncpy(error_msg, "Blender is compiled without motion tracking library", error_size);
1567         (void) tracking;
1568
1569         return 0;
1570 #endif
1571 }
1572
1573 MovieReconstructContext* BKE_tracking_reconstruction_context_new(MovieTracking *tracking,
1574                         int keyframe1, int keyframe2, int width, int height)
1575 {
1576         MovieReconstructContext *context= MEM_callocN(sizeof(MovieReconstructContext), "MovieReconstructContext data");
1577         MovieTrackingCamera *camera= &tracking->camera;
1578         float aspy= 1.0f/tracking->camera.pixel_aspect;
1579         int num_tracks= BLI_countlist(&tracking->tracks);
1580         int sfra= INT_MAX, efra= INT_MIN;
1581         MovieTrackingTrack *track;
1582
1583         context->tracks_map= tracks_map_new(num_tracks, 0);
1584         track= tracking->tracks.first;
1585         while(track) {
1586                 int first= 0, last= track->markersnr;
1587                 MovieTrackingMarker *first_marker= &track->markers[0];
1588                 MovieTrackingMarker *last_marker= &track->markers[track->markersnr-1];
1589
1590                 /* find first not-disabled marker */
1591                 while(first<track->markersnr-1 && first_marker->flag&MARKER_DISABLED) {
1592                         first++;
1593                         first_marker++;
1594                 }
1595
1596                 /* find last not-disabled marker */
1597                 while(last>=0 && last_marker->flag&MARKER_DISABLED) {
1598                         last--;
1599                         last_marker--;
1600                 }
1601
1602                 if(first<track->markersnr-1)
1603                         sfra= MIN2(sfra, first_marker->framenr);
1604
1605                 if(last>=0)
1606                         efra= MAX2(efra, last_marker->framenr);
1607
1608                 tracks_map_insert(context->tracks_map, track, NULL);
1609
1610                 track= track->next;
1611         }
1612
1613         context->sfra= sfra;
1614         context->efra= efra;
1615
1616 #ifdef WITH_LIBMV
1617         context->tracks= create_libmv_tracks(tracking, width, height*aspy);
1618         context->keyframe1= keyframe1;
1619         context->keyframe2= keyframe2;
1620         context->refine_flags= get_refine_intrinsics_flags(tracking);
1621 #else
1622         (void) width;
1623         (void) height;
1624         (void) keyframe1;
1625         (void) keyframe2;
1626 #endif
1627
1628         context->focal_length= camera->focal;
1629         context->principal_point[0]= camera->principal[0];
1630         context->principal_point[1]= camera->principal[1]*aspy;
1631
1632         context->k1= camera->k1;
1633         context->k2= camera->k2;
1634         context->k2= camera->k2;
1635
1636         return context;
1637 }
1638
1639 void BKE_tracking_reconstruction_context_free(MovieReconstructContext *context)
1640 {
1641 #ifdef WITH_LIBMV
1642         if(context->reconstruction)
1643                         libmv_destroyReconstruction(context->reconstruction);
1644
1645         libmv_tracksDestroy(context->tracks);
1646 #endif
1647
1648         tracks_map_free(context->tracks_map, NULL);
1649
1650         MEM_freeN(context);
1651 }
1652
1653 static void solve_reconstruction_update_cb(void *customdata, double progress, const char *message)
1654 {
1655         ReconstructProgressData *progressdata= customdata;
1656
1657         if(progressdata->progress) {
1658                 *progressdata->progress= progress;
1659                 *progressdata->do_update= 1;
1660         }
1661
1662         BLI_snprintf(progressdata->stats_message, progressdata->message_size,
1663                         "Solving camera | %s", message);
1664 }
1665
1666 #if 0
1667 static int solve_reconstruction_testbreak_cb(void *customdata)
1668 {
1669         ReconstructProgressData *progressdata= customdata;
1670
1671         if(progressdata->stop && *progressdata->stop)
1672                 return 1;
1673
1674         return G.afbreek;
1675 }
1676 #endif
1677
1678 void BKE_tracking_solve_reconstruction(MovieReconstructContext *context, short *stop,
1679                         short *do_update, float *progress, char *stats_message, int message_size)
1680 {
1681 #ifdef WITH_LIBMV
1682         float error;
1683
1684         ReconstructProgressData progressdata;
1685
1686         progressdata.stop= stop;
1687         progressdata.do_update= do_update;
1688         progressdata.progress= progress;
1689         progressdata.stats_message= stats_message;
1690         progressdata.message_size= message_size;
1691
1692         context->reconstruction = libmv_solveReconstruction(context->tracks,
1693                 context->keyframe1, context->keyframe2,
1694                 context->refine_flags,
1695                 context->focal_length,
1696                 context->principal_point[0], context->principal_point[1],
1697                 context->k1, context->k2, context->k3,
1698                 solve_reconstruction_update_cb, &progressdata);
1699
1700         error= libmv_reprojectionError(context->reconstruction);
1701
1702         context->reprojection_error= error;
1703 #else
1704         (void) context;
1705         (void) stop;
1706         (void) do_update;
1707         (void) progress;
1708         (void) stats_message;
1709         (void) message_size;
1710 #endif
1711 }
1712
1713 int BKE_tracking_finish_reconstruction(MovieReconstructContext *context, MovieTracking *tracking)
1714 {
1715         tracking->reconstruction.error= context->reprojection_error;
1716         tracking->reconstruction.flag|= TRACKING_RECONSTRUCTED;
1717
1718 #ifdef WITH_LIBMV
1719         if(!retrieve_libmv_reconstruct(context, tracking))
1720                 return 0;
1721 #endif
1722
1723         return 1;
1724 }
1725
1726 void BKE_track_unique_name(MovieTracking *tracking, MovieTrackingTrack *track)
1727 {
1728         BLI_uniquename(&tracking->tracks, track, "Track", '.', offsetof(MovieTrackingTrack, name), sizeof(track->name));
1729 }
1730
1731 MovieTrackingTrack *BKE_tracking_named_track(MovieTracking *tracking, const char *name)
1732 {
1733         MovieTrackingTrack *track= tracking->tracks.first;
1734
1735         while(track) {
1736                 if(!strcmp(track->name, name))
1737                         return track;
1738
1739                 track= track->next;
1740         }
1741
1742         return NULL;
1743 }
1744
1745 static int reconstruction_camera_index(MovieTracking *tracking, int framenr, int nearest)
1746 {
1747         MovieTrackingReconstruction *reconstruction= &tracking->reconstruction;
1748         MovieReconstructedCamera *cameras= reconstruction->cameras;
1749         int a= 0, d= 1;
1750
1751         if(!reconstruction->camnr)
1752                 return -1;
1753
1754         if(framenr<cameras[0].framenr) {
1755                 if(nearest) return 0;
1756                 else return -1;
1757         }
1758
1759         if(framenr>cameras[reconstruction->camnr-1].framenr) {
1760                 if(nearest) return reconstruction->camnr-1;
1761                 else return -1;
1762         }
1763
1764         if(reconstruction->last_camera<reconstruction->camnr)
1765                 a= reconstruction->last_camera;
1766
1767         if(cameras[a].framenr>=framenr)
1768                 d= -1;
1769
1770         while(a>=0 && a<reconstruction->camnr) {
1771                 int cfra= cameras[a].framenr;
1772
1773                 /* check if needed framenr was "skipped" -- no data for requested frame */
1774
1775                 if(d>0 && cfra>framenr) {
1776                         /* interpolate with previous position */
1777                         if(nearest) return a-1;
1778                         else break;
1779                 }
1780
1781                 if(d<0 && cfra<framenr) {
1782                         /* interpolate with next position */
1783                         if(nearest) return a;
1784                         else break;
1785                 }
1786
1787                 if(cfra==framenr) {
1788                         reconstruction->last_camera= a;
1789
1790                         return a;
1791                 }
1792
1793                 a+= d;
1794         }
1795
1796         return -1;
1797 }
1798
1799 MovieReconstructedCamera *BKE_tracking_get_reconstructed_camera(MovieTracking *tracking, int framenr)
1800 {
1801         int a= reconstruction_camera_index(tracking, framenr, 0);
1802
1803         if(a==-1)
1804                 return NULL;
1805
1806         return &tracking->reconstruction.cameras[a];
1807 }
1808
1809 void BKE_tracking_get_interpolated_camera(MovieTracking *tracking, int framenr, float mat[4][4])
1810 {
1811         MovieTrackingReconstruction *reconstruction= &tracking->reconstruction;
1812         MovieReconstructedCamera *cameras= reconstruction->cameras;
1813         int a= reconstruction_camera_index(tracking, framenr, 1);
1814
1815         if(a==-1) {
1816                 unit_m4(mat);
1817                 return;
1818         }
1819
1820         if(cameras[a].framenr!=framenr && a>0 && a<reconstruction->camnr-1) {
1821                 float t= ((float)framenr-cameras[a].framenr) / (cameras[a+1].framenr-cameras[a].framenr);
1822
1823                 blend_m4_m4m4(mat, cameras[a].mat, cameras[a+1].mat, t);
1824         } else {
1825                 copy_m4_m4(mat, cameras[a].mat);
1826         }
1827 }
1828
1829 void BKE_get_tracking_mat(Scene *scene, Object *ob, float mat[4][4])
1830 {
1831         if(!ob) {
1832                 if(scene->camera) ob= scene->camera;
1833                 else ob= scene_find_camera(scene);
1834         }
1835
1836         if(ob)
1837                 where_is_object_mat(scene, ob, mat);
1838         else
1839                 unit_m4(mat);
1840 }
1841
1842 void BKE_tracking_camera_shift(MovieTracking *tracking, int winx, int winy, float *shiftx, float *shifty)
1843 {
1844         *shiftx= (0.5f*winx-tracking->camera.principal[0]) / winx;
1845         *shifty= (0.5f*winy-tracking->camera.principal[1]) / winx;
1846 }
1847
1848 void BKE_tracking_camera_to_blender(MovieTracking *tracking, Scene *scene, Camera *camera, int width, int height)
1849 {
1850         float focal= tracking->camera.focal;
1851
1852         camera->sensor_x= tracking->camera.sensor_width;
1853         camera->sensor_fit= CAMERA_SENSOR_FIT_AUTO;
1854         camera->lens= focal*camera->sensor_x/width;
1855
1856         scene->r.xsch= width*tracking->camera.pixel_aspect;
1857         scene->r.ysch= height;
1858
1859         scene->r.xasp= 1.0f;
1860         scene->r.yasp= 1.0f;
1861
1862         BKE_tracking_camera_shift(tracking, width, height, &camera->shiftx, &camera->shifty);
1863 }
1864
1865 void BKE_tracking_projection_matrix(MovieTracking *tracking, int framenr, int winx, int winy, float mat[4][4])
1866 {
1867         MovieReconstructedCamera *camera;
1868         float lens= tracking->camera.focal*tracking->camera.sensor_width/(float)winx;
1869         float viewfac, pixsize, left, right, bottom, top, clipsta, clipend;
1870         float winmat[4][4];
1871         float ycor= 1.0f/tracking->camera.pixel_aspect;
1872         float shiftx, shifty, winside= MAX2(winx, winy);
1873
1874         BKE_tracking_camera_shift(tracking, winx, winy, &shiftx, &shifty);
1875
1876         clipsta= 0.1f;
1877         clipend= 1000.0f;
1878
1879         if(winx >= winy)
1880                 viewfac= (lens*winx)/tracking->camera.sensor_width;
1881         else
1882                 viewfac= (ycor*lens*winy)/tracking->camera.sensor_width;
1883
1884         pixsize= clipsta/viewfac;
1885
1886         left= -0.5f*(float)winx + shiftx*winside;
1887         bottom= -0.5f*(ycor)*(float)winy + shifty*winside;
1888         right=  0.5f*(float)winx + shiftx*winside;
1889         top=  0.5f*(ycor)*(float)winy + shifty*winside;
1890
1891         left *= pixsize;
1892         right *= pixsize;
1893         bottom *= pixsize;
1894         top *= pixsize;
1895
1896         perspective_m4(winmat, left, right, bottom, top, clipsta, clipend);
1897
1898         camera= BKE_tracking_get_reconstructed_camera(tracking, framenr);
1899         if(camera) {
1900                 float imat[4][4];
1901
1902                 invert_m4_m4(imat, camera->mat);
1903                 mul_m4_m4m4(mat, imat, winmat);
1904         } else copy_m4_m4(mat, winmat);
1905 }
1906
1907 void BKE_tracking_apply_intrinsics(MovieTracking *tracking, float co[2], float nco[2])
1908 {
1909         MovieTrackingCamera *camera= &tracking->camera;
1910
1911 #ifdef WITH_LIBMV
1912         double x, y;
1913         float aspy= 1.0f/tracking->camera.pixel_aspect;
1914
1915         /* normalize coords */
1916         x= (co[0]-camera->principal[0]) / camera->focal;
1917         y= (co[1]-camera->principal[1] * aspy) / camera->focal;
1918
1919         libmv_applyCameraIntrinsics(camera->focal, camera->principal[0], camera->principal[1] * aspy,
1920                                 camera->k1, camera->k2, camera->k3, x, y, &x, &y);
1921
1922         /* result is in image coords already */
1923         nco[0]= x;
1924         nco[1]= y;
1925 #else
1926         (void)camera;
1927         (void)co;
1928         (void)nco;
1929 #endif
1930 }
1931
1932 void BKE_tracking_invert_intrinsics(MovieTracking *tracking, float co[2], float nco[2])
1933 {
1934         MovieTrackingCamera *camera= &tracking->camera;
1935
1936 #ifdef WITH_LIBMV
1937         double x= co[0], y= co[1];
1938         float aspy= 1.0f/tracking->camera.pixel_aspect;
1939
1940         libmv_InvertIntrinsics(camera->focal, camera->principal[0], camera->principal[1] * aspy,
1941                                 camera->k1, camera->k2, camera->k3, x, y, &x, &y);
1942
1943         nco[0]= x * camera->focal + camera->principal[0];
1944         nco[1]= y * camera->focal + camera->principal[1] * aspy;
1945 #else
1946         (void)camera;
1947         (void)co;
1948         (void)nco;
1949 #endif
1950 }
1951
1952 #ifdef WITH_LIBMV
1953 static int point_in_stroke(bGPDstroke *stroke, float x, float y)
1954 {
1955         int i, prev;
1956         int count= 0;
1957         bGPDspoint *points= stroke->points;
1958
1959         prev= stroke->totpoints-1;
1960
1961         for(i= 0; i<stroke->totpoints; i++) {
1962                 if((points[i].y<y && points[prev].y>=y) || (points[prev].y<y && points[i].y>=y)) {
1963                         float fac= (y-points[i].y)/(points[prev].y-points[i].y);
1964
1965                         if (points[i].x+fac*(points[prev].x-points[i].x)<x)
1966                                 count++;
1967                 }
1968
1969                 prev= i;
1970         }
1971
1972         return count%2;
1973 }
1974
1975 static int point_in_layer(bGPDlayer *layer, float x, float y)
1976 {
1977         bGPDframe *frame= layer->frames.first;
1978
1979         while(frame) {
1980                 bGPDstroke *stroke= frame->strokes.first;
1981                 while(stroke) {
1982                         if(point_in_stroke(stroke, x, y))
1983                                 return 1;
1984
1985                         stroke= stroke->next;
1986                 }
1987                 frame= frame->next;
1988         }
1989
1990         return 0;
1991 }
1992
1993 static void retrieve_libmv_features(MovieTracking *tracking, struct libmv_Features *features,
1994                         int framenr, int width, int height, bGPDlayer *layer, int place_outside_layer)
1995 {
1996         int a;
1997
1998         a= libmv_countFeatures(features);
1999         while(a--) {
2000                 MovieTrackingTrack *track;
2001                 double x, y, size, score;
2002                 int ok= 1;
2003                 float xu, yu;
2004
2005                 libmv_getFeature(features, a, &x, &y, &score, &size);
2006
2007                 xu= x/width;
2008                 yu= y/height;
2009
2010                 if(layer)
2011                         ok= point_in_layer(layer, xu, yu)!=place_outside_layer;
2012
2013                 if(ok) {
2014                         track= BKE_tracking_add_track(tracking, xu, yu, framenr, width, height);
2015                         track->flag|= SELECT;
2016                         track->pat_flag|= SELECT;
2017                         track->search_flag|= SELECT;
2018                 }
2019         }
2020 }
2021 #endif
2022
2023 void BKE_tracking_detect_fast(MovieTracking *tracking, ImBuf *ibuf,
2024                         int framenr, int margin, int min_trackness, int min_distance, bGPDlayer *layer,
2025                         int place_outside_layer)
2026 {
2027 #ifdef WITH_LIBMV
2028         struct libmv_Features *features;
2029         unsigned char *pixels= get_ucharbuf(ibuf);
2030
2031         features= libmv_detectFeaturesFAST(pixels, ibuf->x, ibuf->y, ibuf->x, margin, min_trackness, min_distance);
2032
2033         MEM_freeN(pixels);
2034
2035         retrieve_libmv_features(tracking, features, framenr, ibuf->x, ibuf->y, layer, place_outside_layer);
2036
2037         libmv_destroyFeatures(features);
2038 #else
2039         (void)tracking;
2040         (void)ibuf;
2041         (void)framenr;
2042         (void)margin;
2043         (void)min_trackness;
2044         (void)min_distance;
2045         (void)layer;
2046         (void)place_outside_layer;
2047 #endif
2048 }
2049
2050 MovieTrackingTrack *BKE_tracking_indexed_track(MovieTracking *tracking, int tracknr)
2051 {
2052         MovieTrackingTrack *track= tracking->tracks.first;
2053         int cur= 1;
2054
2055         while(track) {
2056                 if(track->flag&TRACK_HAS_BUNDLE) {
2057                         if(cur==tracknr)
2058                                 return track;
2059
2060                         cur++;
2061                 }
2062
2063                 track= track->next;
2064         }
2065
2066         return NULL;
2067 }
2068
2069 static int stabilization_median_point(MovieTracking *tracking, int framenr, float median[2])
2070 {
2071         int ok= 0;
2072         float min[2], max[2];
2073         MovieTrackingTrack *track;
2074
2075         INIT_MINMAX2(min, max);
2076
2077         track= tracking->tracks.first;
2078         while(track) {
2079                 if(track->flag&TRACK_USE_2D_STAB) {
2080                         MovieTrackingMarker *marker= BKE_tracking_get_marker(track, framenr);
2081
2082                         DO_MINMAX2(marker->pos, min, max);
2083
2084                         ok= 1;
2085                 }
2086
2087                 track= track->next;
2088         }
2089
2090         median[0]= (max[0]+min[0])/2.0f;
2091         median[1]= (max[1]+min[1])/2.0f;
2092
2093         return ok;
2094 }
2095
2096 static void calculate_stabdata(MovieTracking *tracking, int framenr, float width, float height,
2097                         float firstmedian[2], float median[2], float loc[2], float *scale, float *angle)
2098 {
2099         MovieTrackingStabilization *stab= &tracking->stabilization;
2100
2101         *scale= (stab->scale-1.0f)*stab->scaleinf+1.0f;
2102         *angle= 0.0f;
2103
2104         loc[0]= (firstmedian[0]-median[0])*width*(*scale);
2105         loc[1]= (firstmedian[1]-median[1])*height*(*scale);
2106
2107         mul_v2_fl(loc, stab->locinf);
2108
2109         if((stab->flag&TRACKING_STABILIZE_ROTATION) && stab->rot_track && stab->rotinf) {
2110                 MovieTrackingMarker *marker;
2111                 float a[2], b[2];
2112                 float x0= (float)width/2.0f, y0= (float)height/2.0f;
2113                 float x= median[0]*width, y= median[1]*height;
2114
2115                 marker= BKE_tracking_get_marker(stab->rot_track, 1);
2116                 sub_v2_v2v2(a, marker->pos, firstmedian);
2117                 a[0]*= width;
2118                 a[1]*= height;
2119
2120                 marker= BKE_tracking_get_marker(stab->rot_track, framenr);
2121                 sub_v2_v2v2(b, marker->pos, median);
2122                 b[0]*= width;
2123                 b[1]*= height;
2124
2125                 *angle= -atan2(a[0]*b[1]-a[1]*b[0], a[0]*b[0]+a[1]*b[1]);
2126                 *angle*= stab->rotinf;
2127
2128                 /* convert to rotation around image center */
2129                 loc[0]-= (x0 + (x-x0)*cosf(*angle)-(y-y0)*sinf(*angle) - x)*(*scale);
2130                 loc[1]-= (y0 + (x-x0)*sinf(*angle)+(y-y0)*cosf(*angle) - y)*(*scale);
2131         }
2132 }
2133
2134 static float stabilization_auto_scale_factor(MovieTracking *tracking, int width, int height)
2135 {
2136         float firstmedian[2];
2137         MovieTrackingStabilization *stab= &tracking->stabilization;
2138
2139         if(stab->ok)
2140                 return stab->scale;
2141
2142         if(stabilization_median_point(tracking, 1, firstmedian)) {
2143                 int sfra= INT_MAX, efra= INT_MIN, cfra;
2144                 float delta[2]= {0.0f, 0.0f}, scalex= 1.0f, scaley= 1.0f;
2145                 MovieTrackingTrack *track;
2146
2147                 stab->scale= 1.0f;
2148
2149                 track= tracking->tracks.first;
2150                 while(track) {
2151                         if(track->flag&TRACK_USE_2D_STAB ||
2152                            ((stab->flag&TRACKING_STABILIZE_ROTATION) && track==stab->rot_track)) {
2153                                 sfra= MIN2(sfra, track->markers[0].framenr);
2154                                 efra= MAX2(efra, track->markers[track->markersnr-1].framenr);
2155                         }
2156
2157                         track= track->next;
2158                 }
2159
2160                 for(cfra=sfra; cfra<=efra; cfra++) {
2161                         float median[2], near[2];
2162                         float loc[2], scale, angle;
2163
2164                         stabilization_median_point(tracking, cfra, median);
2165
2166                         calculate_stabdata(tracking, cfra, width, height, firstmedian, median,
2167                                                 loc, &scale, &angle);
2168
2169                         if(angle==0.0f) {
2170                                 loc[0]= fabsf(loc[0]);
2171                                 loc[1]= fabsf(loc[1]);
2172
2173                                 delta[0]= MAX2(delta[0], loc[0]);
2174                                 delta[1]= MAX2(delta[1], loc[1]);
2175
2176                                 near[0]= MIN2(median[0], 1.0f-median[0]);
2177                                 near[1]= MIN2(median[1], 1.0f-median[1]);
2178                                 near[0]= MAX2(near[0], 0.05f);
2179                                 near[1]= MAX2(near[1], 0.05f);
2180
2181                                 scalex= 1.0f+delta[0]/(near[0]*width);
2182                                 scaley= 1.0f+delta[1]/(near[1]*height);
2183                         } else {
2184                                 int i;
2185                                 float mat[4][4];
2186                                 float points[4][2]={{0.0f, 0.0f}, {0.0f, height}, {width, height}, {width, 0.0f}};
2187
2188                                 BKE_tracking_stabdata_to_mat4(width, height, loc, scale, angle, mat);
2189
2190                                 for(i= 0; i<4; i++) {
2191                                         int j;
2192                                         float a[3]= {0.0f, 0.0f, 0.0f}, b[3]= {0.0f, 0.0f, 0.0f};
2193
2194                                         copy_v3_v3(a, points[i]);
2195                                         copy_v3_v3(b, points[(i+1)%4]);
2196
2197                                         mul_m4_v3(mat, a);
2198                                         mul_m4_v3(mat, b);
2199
2200                                         for(j= 0; j<4; j++) {
2201                                                 float point[3]= {points[j][0], points[j][1], 0.0f};
2202                                                 float v1[3], v2[3];
2203
2204                                                 sub_v3_v3v3(v1, b, a);
2205                                                 sub_v3_v3v3(v2, point, a);
2206
2207                                                 if(cross_v2v2(v1, v2) >= 0.0f) {
2208                                                         float dist= dist_to_line_v2(point, a, b);
2209                                                         if(i%2==0) {
2210                                                                 scalex= MAX2(scalex, (width+2*dist)/width);
2211                                                         } else {
2212                                                                 scaley= MAX2(scaley, (height+2*dist)/height);
2213                                                         }
2214                                                 }
2215                                         }
2216                                 }
2217                         }
2218                 }
2219
2220                 stab->scale= MAX2(scalex, scaley);
2221
2222                 if(stab->maxscale>0.0f)
2223                         stab->scale= MIN2(stab->scale, stab->maxscale);
2224         } else {
2225                 stab->scale= 1.0f;
2226         }
2227
2228         stab->ok= 1;
2229
2230         return stab->scale;
2231 }
2232
2233 static ImBuf* stabilize_alloc_ibuf(ImBuf *cacheibuf, ImBuf *srcibuf, int fill)
2234 {
2235         int flags;
2236
2237         if(cacheibuf && (cacheibuf->x != srcibuf->x || cacheibuf->y != srcibuf->y)) {
2238                 IMB_freeImBuf(cacheibuf);
2239                 cacheibuf= NULL;
2240         }
2241
2242         flags= IB_rect;
2243
2244         if(srcibuf->rect_float)
2245                 flags|= IB_rectfloat;
2246
2247         if(cacheibuf) {
2248                 if(fill) {
2249                         float col[4]= {0.0f, 0.0f, 0.0f, 0.0f};
2250                         IMB_rectfill(cacheibuf, col);
2251                 }
2252         }
2253         else {
2254                 cacheibuf= IMB_allocImBuf(srcibuf->x, srcibuf->y, srcibuf->planes, flags);
2255                 cacheibuf->profile= srcibuf->profile;
2256         }
2257
2258         return cacheibuf;
2259 }
2260
2261 void BKE_tracking_stabilization_data(MovieTracking *tracking, int framenr, int width, int height, float loc[2], float *scale, float *angle)
2262 {
2263         float firstmedian[2], median[2];
2264         MovieTrackingStabilization *stab= &tracking->stabilization;
2265
2266         if((stab->flag&TRACKING_2D_STABILIZATION)==0) {
2267                 zero_v2(loc);
2268                 *scale= 1.0f;
2269                 *angle= 0.0f;
2270
2271                 return;
2272         }
2273
2274         if(stabilization_median_point(tracking, 1, firstmedian)) {
2275                 stabilization_median_point(tracking, framenr, median);
2276
2277                 if((stab->flag&TRACKING_AUTOSCALE)==0)
2278                         stab->scale= 1.0f;
2279
2280                 if(!stab->ok) {
2281                         if(stab->flag&TRACKING_AUTOSCALE)
2282                                 stabilization_auto_scale_factor(tracking, width, height);
2283
2284                         calculate_stabdata(tracking, framenr, width, height, firstmedian, median, loc, scale, angle);
2285
2286                         stab->ok= 1;
2287                 } else {
2288                         calculate_stabdata(tracking, framenr, width, height, firstmedian, median, loc, scale, angle);
2289                 }
2290         } else {
2291                 zero_v2(loc);
2292                 *scale= 1.0f;
2293                 *angle= 0.0f;
2294         }
2295 }
2296
2297 ImBuf *BKE_tracking_stabilize(MovieTracking *tracking, int framenr, ImBuf *ibuf, float loc[2], float *scale, float *angle)
2298 {
2299         float tloc[2], tscale, tangle;
2300         MovieTrackingStabilization *stab= &tracking->stabilization;
2301         ImBuf *tmpibuf;
2302         float width= ibuf->x, height= ibuf->y;
2303
2304         if(loc)         copy_v2_v2(tloc, loc);
2305         if(scale)       tscale= *scale;
2306
2307         if((stab->flag&TRACKING_2D_STABILIZATION)==0) {
2308                 if(loc)         zero_v2(loc);
2309                 if(scale)       *scale= 1.0f;
2310
2311                 return ibuf;
2312         }
2313
2314         BKE_tracking_stabilization_data(tracking, framenr, width, height, tloc, &tscale, &tangle);
2315
2316         tmpibuf= stabilize_alloc_ibuf(NULL, ibuf, 1);
2317
2318         /* scale would be handled by matrix transformation when angle is non-zero */
2319         if(tscale!=1.0f && tangle==0.0f) {
2320                 ImBuf *scaleibuf;
2321
2322                 stabilization_auto_scale_factor(tracking, width, height);
2323
2324                 scaleibuf= stabilize_alloc_ibuf(stab->scaleibuf, ibuf, 0);
2325                 stab->scaleibuf= scaleibuf;
2326
2327                 IMB_rectcpy(scaleibuf, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
2328                 IMB_scalefastImBuf(scaleibuf, ibuf->x*tscale, ibuf->y*tscale);
2329
2330                 ibuf= scaleibuf;
2331         }
2332
2333         if(tangle==0.0f) {
2334                 /* if angle is zero, then it's much faster to use rect copy
2335                    but could be issues with subpixel precisions */
2336                 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);
2337         } else {
2338                 float mat[4][4];
2339                 int i, j;
2340
2341                 BKE_tracking_stabdata_to_mat4(ibuf->x, ibuf->y, tloc, tscale, tangle, mat);
2342                 invert_m4(mat);
2343
2344                 for(j=0; j<tmpibuf->y; j++) {
2345                         for(i=0; i<tmpibuf->x;i++) {
2346                                 float vec[3]= {i, j, 0};
2347
2348                                 mul_v3_m4v3(vec, mat, vec);
2349
2350                                 /* TODO: add selector for interpolation method */
2351                                 neareast_interpolation(ibuf, tmpibuf, vec[0], vec[1], i, j);
2352                         }
2353                 }
2354         }
2355
2356         tmpibuf->userflags|= IB_MIPMAP_INVALID;
2357
2358         if(tmpibuf->rect_float)
2359                 tmpibuf->userflags|= IB_RECT_INVALID;
2360
2361         if(loc)         copy_v2_v2(loc, tloc);
2362         if(scale)       *scale= tscale;
2363         if(angle)       *angle= tangle;
2364
2365         return tmpibuf;
2366 }
2367
2368 void BKE_tracking_stabdata_to_mat4(int width, int height, float loc[2], float scale, float angle, float mat[4][4])
2369 {
2370         float lmat[4][4], rmat[4][4], smat[4][4], cmat[4][4], icmat[4][4];
2371         float svec[3]= {scale, scale, scale};
2372
2373         unit_m4(rmat);
2374         unit_m4(lmat);
2375         unit_m4(smat);
2376         unit_m4(cmat);
2377
2378         /* image center as rotation center */
2379         cmat[3][0]= (float)width/2.0f;
2380         cmat[3][1]= (float)height/2.0f;
2381         invert_m4_m4(icmat, cmat);
2382
2383         size_to_mat4(smat, svec);               /* scale matrix */
2384         add_v2_v2(lmat[3], loc);                /* tranlation matrix */
2385         rotate_m4(rmat, 'Z', angle);    /* rotation matrix */
2386
2387         /* compose transformation matrix */
2388         mul_serie_m4(mat, lmat, cmat, rmat, smat, icmat, NULL, NULL, NULL);
2389 }
2390
2391 MovieDistortion *BKE_tracking_distortion_create(void)
2392 {
2393         MovieDistortion *distortion;
2394
2395         distortion= MEM_callocN(sizeof(MovieDistortion), "BKE_tracking_distortion_create");
2396
2397         return distortion;
2398 }
2399
2400 MovieDistortion *BKE_tracking_distortion_copy(MovieDistortion *distortion)
2401 {
2402         MovieDistortion *new_distortion;
2403
2404         new_distortion= MEM_callocN(sizeof(MovieDistortion), "BKE_tracking_distortion_create");
2405
2406 #ifdef WITH_LIBMV
2407         new_distortion->intrinsics= libmv_CameraIntrinsicsCopy(distortion->intrinsics);
2408 #else
2409         (void)distortion;
2410 #endif
2411
2412         return new_distortion;
2413 }
2414
2415 void BKE_tracking_distortion_update(MovieDistortion *distortion, MovieTracking *tracking, int width, int height)
2416 {
2417         MovieTrackingCamera *camera= &tracking->camera;
2418         float aspy= 1.0f/tracking->camera.pixel_aspect;
2419
2420 #ifdef WITH_LIBMV
2421         if(!distortion->intrinsics) {
2422                 distortion->intrinsics= libmv_CameraIntrinsicsNew(camera->focal,
2423                                 camera->principal[0], camera->principal[1] * aspy,
2424                                 camera->k1, camera->k2, camera->k3, width, height * aspy);
2425         } else {
2426                 libmv_CameraIntrinsicsUpdate(distortion->intrinsics, camera->focal,
2427                                 camera->principal[0], camera->principal[1] * aspy,
2428                                 camera->k1, camera->k2, camera->k3, width, height * aspy);
2429         }
2430 #else
2431         (void)distortion;
2432         (void)width;
2433         (void)height;
2434         (void)camera;
2435         (void)aspy;
2436 #endif
2437 }
2438
2439 ImBuf *BKE_tracking_distortion_exec(MovieDistortion *distortion, MovieTracking *tracking,
2440                         ImBuf *ibuf, int width, int height, float overscan, int undistort)
2441 {
2442         ImBuf *resibuf;
2443
2444         BKE_tracking_distortion_update(distortion, tracking, width, height);
2445
2446         resibuf= IMB_dupImBuf(ibuf);
2447
2448         if(ibuf->rect_float) {
2449 #ifdef WITH_LIBMV
2450                 if(undistort) {
2451                         libmv_CameraIntrinsicsUndistortFloat(distortion->intrinsics,
2452                                                 ibuf->rect_float, resibuf->rect_float,
2453                                                 ibuf->x, ibuf->y, overscan, ibuf->channels);
2454                 } else {
2455                         libmv_CameraIntrinsicsDistortFloat(distortion->intrinsics,
2456                                                 ibuf->rect_float, resibuf->rect_float,
2457                                                 ibuf->x, ibuf->y, overscan, ibuf->channels);
2458                 }
2459 #endif
2460
2461                 ibuf->userflags|= IB_RECT_INVALID;
2462         } else {
2463 #ifdef WITH_LIBMV
2464                 if(undistort) {
2465                                 libmv_CameraIntrinsicsUndistortByte(distortion->intrinsics,
2466                                                         (unsigned char*)ibuf->rect, (unsigned char*)resibuf->rect,
2467                                                         ibuf->x, ibuf->y, overscan, ibuf->channels);
2468                 } else {
2469                         libmv_CameraIntrinsicsDistortByte(distortion->intrinsics,
2470                                                 (unsigned char*)ibuf->rect, (unsigned char*)resibuf->rect,
2471                                                 ibuf->x, ibuf->y, overscan, ibuf->channels);
2472                 }
2473 #endif
2474         }
2475
2476 #ifndef WITH_LIBMV
2477         (void)overscan;
2478         (void)undistort;
2479 #endif
2480
2481         return resibuf;
2482 }
2483
2484 void BKE_tracking_distortion_destroy(MovieDistortion *distortion)
2485 {
2486 #ifdef WITH_LIBMV
2487         libmv_CameraIntrinsicsDestroy(distortion->intrinsics);
2488 #endif
2489
2490         MEM_freeN(distortion);
2491 }
2492
2493 ImBuf *BKE_tracking_undistort(MovieTracking *tracking, ImBuf *ibuf, int width, int height, float overscan)
2494 {
2495         MovieTrackingCamera *camera= &tracking->camera;
2496
2497         if(camera->intrinsics == NULL)
2498                 camera->intrinsics= BKE_tracking_distortion_create();
2499
2500         return BKE_tracking_distortion_exec(camera->intrinsics, tracking, ibuf, width, height, overscan, 1);
2501 }
2502
2503 ImBuf *BKE_tracking_distort(MovieTracking *tracking, ImBuf *ibuf, int width, int height, float overscan)
2504 {
2505         MovieTrackingCamera *camera= &tracking->camera;
2506
2507         if(camera->intrinsics == NULL)
2508                 camera->intrinsics= BKE_tracking_distortion_create();
2509
2510         return BKE_tracking_distortion_exec(camera->intrinsics, tracking, ibuf, width, height, overscan, 0);
2511 }
2512
2513 /* area - which part of marker should be selected. see TRACK_AREA_* constants */
2514 void BKE_tracking_select_track(MovieTracking *tracking, MovieTrackingTrack *track, int area, int extend)
2515 {
2516         if(extend) {
2517                 BKE_tracking_track_flag(track, area, SELECT, 0);
2518         } else {
2519                 MovieTrackingTrack *cur= tracking->tracks.first;
2520
2521                 while(cur) {
2522                         if(cur==track) {
2523                                 BKE_tracking_track_flag(cur, TRACK_AREA_ALL, SELECT, 1);
2524                                 BKE_tracking_track_flag(cur, area, SELECT, 0);
2525                         }
2526                         else {
2527                                 BKE_tracking_track_flag(cur, TRACK_AREA_ALL, SELECT, 1);
2528                         }
2529
2530                         cur= cur->next;
2531                 }
2532         }
2533 }
2534
2535 void BKE_tracking_deselect_track(MovieTrackingTrack *track, int area)
2536 {
2537         BKE_tracking_track_flag(track, area, SELECT, 1);
2538 }