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