style cleanup
[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 #else
1805                         (void)frame_height;
1806                         (void)frame_width;
1807 #endif
1808                 }
1809         }
1810
1811         IMB_freeImBuf(destination_ibuf);
1812
1813         context->first_time = FALSE;
1814         context->frames++;
1815
1816         return ok;
1817 }
1818
1819 /*********************** camera solving *************************/
1820
1821 typedef struct MovieReconstructContext {
1822 #ifdef WITH_LIBMV
1823         struct libmv_Tracks *tracks;
1824         int keyframe1, keyframe2;
1825         short refine_flags;
1826
1827         struct libmv_Reconstruction *reconstruction;
1828 #endif
1829         char object_name[MAX_NAME];
1830         int is_camera;
1831         short motion_flag;
1832
1833         float focal_length;
1834         float principal_point[2];
1835         float k1, k2, k3;
1836
1837         float reprojection_error;
1838
1839         TracksMap *tracks_map;
1840
1841         int sfra, efra;
1842 } MovieReconstructContext;
1843
1844 typedef struct ReconstructProgressData {
1845         short *stop;
1846         short *do_update;
1847         float *progress;
1848         char *stats_message;
1849         int message_size;
1850 } ReconstructProgressData;
1851
1852 #if WITH_LIBMV
1853 static struct libmv_Tracks *create_libmv_tracks(ListBase *tracksbase, int width, int height)
1854 {
1855         int tracknr = 0;
1856         MovieTrackingTrack *track;
1857         struct libmv_Tracks *tracks = libmv_tracksNew();
1858
1859         track = tracksbase->first;
1860         while (track) {
1861                 int a = 0;
1862
1863                 for (a = 0; a < track->markersnr; a++) {
1864                         MovieTrackingMarker *marker = &track->markers[a];
1865
1866                         if ((marker->flag & MARKER_DISABLED) == 0) {
1867                                 libmv_tracksInsert(tracks, marker->framenr, tracknr,
1868                                                    marker->pos[0] * width, marker->pos[1] * height);
1869                         }
1870                 }
1871
1872                 track = track->next;
1873                 tracknr++;
1874         }
1875
1876         return tracks;
1877 }
1878
1879 static void retrieve_libmv_reconstruct_intrinscis(MovieReconstructContext *context, MovieTracking *tracking)
1880 {
1881         struct libmv_Reconstruction *libmv_reconstruction = context->reconstruction;
1882         struct libmv_CameraIntrinsics *libmv_intrinsics = libmv_ReconstructionExtractIntrinsics(libmv_reconstruction);
1883
1884         float aspy = 1.0f / tracking->camera.pixel_aspect;
1885
1886         double focal_length, principal_x, principal_y, k1, k2, k3;
1887         int width, height;
1888
1889         libmv_CameraIntrinsicsExtract(libmv_intrinsics, &focal_length, &principal_x, &principal_y,
1890                                       &k1, &k2, &k3, &width, &height);
1891
1892         tracking->camera.focal = focal_length;
1893         tracking->camera.principal[0] = principal_x;
1894
1895         tracking->camera.principal[1] = principal_y / aspy;
1896         tracking->camera.k1 = k1;
1897         tracking->camera.k2 = k2;
1898 }
1899
1900 static int retrieve_libmv_reconstruct_tracks(MovieReconstructContext *context, MovieTracking *tracking)
1901 {
1902         struct libmv_Reconstruction *libmv_reconstruction = context->reconstruction;
1903         MovieTrackingReconstruction *reconstruction = NULL;
1904         MovieReconstructedCamera *reconstructed;
1905         MovieTrackingTrack *track;
1906         ListBase *tracksbase =  NULL;
1907         int ok = TRUE, tracknr = 0, a, origin_set = FALSE;
1908         int sfra = context->sfra, efra = context->efra;
1909         float imat[4][4];
1910
1911         if (context->is_camera) {
1912                 tracksbase = &tracking->tracks;
1913                 reconstruction = &tracking->reconstruction;
1914         }
1915         else {
1916                 MovieTrackingObject *object = BKE_tracking_named_object(tracking, context->object_name);
1917
1918                 tracksbase = &object->tracks;
1919                 reconstruction = &object->reconstruction;
1920         }
1921
1922         unit_m4(imat);
1923
1924         track = tracksbase->first;
1925         while (track) {
1926                 double pos[3];
1927
1928                 if (libmv_reporojectionPointForTrack(libmv_reconstruction, tracknr, pos)) {
1929                         track->bundle_pos[0] = pos[0];
1930                         track->bundle_pos[1] = pos[1];
1931                         track->bundle_pos[2] = pos[2];
1932
1933                         track->flag |= TRACK_HAS_BUNDLE;
1934                         track->error = libmv_reporojectionErrorForTrack(libmv_reconstruction, tracknr);
1935                 }
1936                 else {
1937                         track->flag &= ~TRACK_HAS_BUNDLE;
1938                         ok = FALSE;
1939
1940                         printf("No bundle for track #%d '%s'\n", tracknr, track->name);
1941                 }
1942
1943                 track = track->next;
1944                 tracknr++;
1945         }
1946
1947         if (reconstruction->cameras)
1948                 MEM_freeN(reconstruction->cameras);
1949
1950         reconstruction->camnr = 0;
1951         reconstruction->cameras = NULL;
1952         reconstructed = MEM_callocN((efra - sfra + 1) * sizeof(MovieReconstructedCamera),
1953                                     "temp reconstructed camera");
1954
1955         for (a = sfra; a <= efra; a++) {
1956                 double matd[4][4];
1957
1958                 if (libmv_reporojectionCameraForImage(libmv_reconstruction, a, matd)) {
1959                         int i, j;
1960                         float mat[4][4];
1961                         float error = libmv_reporojectionErrorForImage(libmv_reconstruction, a);
1962
1963                         for (i = 0; i < 4; i++)
1964                                 for (j = 0; j < 4; j++)
1965                                         mat[i][j] = matd[i][j];
1966
1967                         if (!origin_set) {
1968                                 copy_m4_m4(imat, mat);
1969                                 invert_m4(imat);
1970                                 origin_set = TRUE;
1971                         }
1972
1973                         if (origin_set)
1974                                 mult_m4_m4m4(mat, imat, mat);
1975
1976                         copy_m4_m4(reconstructed[reconstruction->camnr].mat, mat);
1977                         reconstructed[reconstruction->camnr].framenr = a;
1978                         reconstructed[reconstruction->camnr].error = error;
1979                         reconstruction->camnr++;
1980                 }
1981                 else {
1982                         ok = FALSE;
1983                         printf("No camera for frame %d\n", a);
1984                 }
1985         }
1986
1987         if (reconstruction->camnr) {
1988                 int size = reconstruction->camnr * sizeof(MovieReconstructedCamera);
1989                 reconstruction->cameras = MEM_callocN(size, "reconstructed camera");
1990                 memcpy(reconstruction->cameras, reconstructed, size);
1991         }
1992
1993         if (origin_set) {
1994                 track = tracksbase->first;
1995                 while (track) {
1996                         if (track->flag & TRACK_HAS_BUNDLE)
1997                                 mul_v3_m4v3(track->bundle_pos, imat, track->bundle_pos);
1998
1999                         track = track->next;
2000                 }
2001         }
2002
2003         MEM_freeN(reconstructed);
2004
2005         return ok;
2006 }
2007
2008 static int retrieve_libmv_reconstruct(MovieReconstructContext *context, MovieTracking *tracking)
2009 {
2010         /* take the intrinscis back from libmv */
2011         retrieve_libmv_reconstruct_intrinscis(context, tracking);
2012
2013         return retrieve_libmv_reconstruct_tracks(context, tracking);
2014 }
2015
2016 static int get_refine_intrinsics_flags(MovieTracking *tracking, MovieTrackingObject *object)
2017 {
2018         int refine = tracking->settings.refine_camera_intrinsics;
2019         int flags = 0;
2020
2021         if ((object->flag & TRACKING_OBJECT_CAMERA) == 0)
2022                 return 0;
2023
2024         if (refine & REFINE_FOCAL_LENGTH)
2025                 flags |= LIBMV_REFINE_FOCAL_LENGTH;
2026
2027         if (refine & REFINE_PRINCIPAL_POINT)
2028                 flags |= LIBMV_REFINE_PRINCIPAL_POINT;
2029
2030         if (refine & REFINE_RADIAL_DISTORTION_K1)
2031                 flags |= REFINE_RADIAL_DISTORTION_K1;
2032
2033         if (refine & REFINE_RADIAL_DISTORTION_K2)
2034                 flags |= REFINE_RADIAL_DISTORTION_K2;
2035
2036         return flags;
2037 }
2038
2039 static int count_tracks_on_both_keyframes(MovieTracking *tracking, ListBase *tracksbase)
2040 {
2041         int tot = 0;
2042         int frame1 = tracking->settings.keyframe1, frame2 = tracking->settings.keyframe2;
2043         MovieTrackingTrack *track;
2044
2045         track = tracksbase->first;
2046         while (track) {
2047                 if (BKE_tracking_has_enabled_marker(track, frame1))
2048                         if (BKE_tracking_has_enabled_marker(track, frame2))
2049                                 tot++;
2050
2051                 track = track->next;
2052         }
2053
2054         return tot;
2055 }
2056 #endif
2057
2058 int BKE_tracking_can_reconstruct(MovieTracking *tracking, MovieTrackingObject *object, char *error_msg, int error_size)
2059 {
2060 #if WITH_LIBMV
2061         ListBase *tracksbase = BKE_tracking_object_tracks(tracking, object);
2062
2063         if (tracking->settings.motion_flag & TRACKING_MOTION_MODAL) {
2064                 /* TODO: check for number of tracks? */
2065                 return TRUE;
2066         }
2067         else if (count_tracks_on_both_keyframes(tracking, tracksbase) < 8) {
2068                 BLI_strncpy(error_msg, "At least 8 common tracks on both of keyframes are needed for reconstruction",
2069                             error_size);
2070
2071                 return FALSE;
2072         }
2073
2074         return TRUE;
2075 #else
2076         BLI_strncpy(error_msg, "Blender is compiled without motion tracking library", error_size);
2077
2078         (void) tracking;
2079         (void) object;
2080
2081         return 0;
2082 #endif
2083 }
2084
2085 MovieReconstructContext *BKE_tracking_reconstruction_context_new(MovieTracking *tracking, MovieTrackingObject *object,
2086                                                                  int keyframe1, int keyframe2, int width, int height)
2087 {
2088         MovieReconstructContext *context = MEM_callocN(sizeof(MovieReconstructContext), "MovieReconstructContext data");
2089         MovieTrackingCamera *camera = &tracking->camera;
2090         ListBase *tracksbase = BKE_tracking_object_tracks(tracking, object);
2091         float aspy = 1.0f / tracking->camera.pixel_aspect;
2092         int num_tracks = BLI_countlist(tracksbase);
2093         int sfra = INT_MAX, efra = INT_MIN;
2094         MovieTrackingTrack *track;
2095
2096         BLI_strncpy(context->object_name, object->name, sizeof(context->object_name));
2097         context->is_camera = object->flag & TRACKING_OBJECT_CAMERA;
2098         context->motion_flag = tracking->settings.motion_flag;
2099
2100         context->tracks_map = tracks_map_new(context->object_name, context->is_camera, num_tracks, 0);
2101
2102         track = tracksbase->first;
2103         while (track) {
2104                 int first = 0, last = track->markersnr - 1;
2105                 MovieTrackingMarker *first_marker = &track->markers[0];
2106                 MovieTrackingMarker *last_marker = &track->markers[track->markersnr - 1];
2107
2108                 /* find first not-disabled marker */
2109                 while (first <= track->markersnr - 1 && first_marker->flag & MARKER_DISABLED) {
2110                         first++;
2111                         first_marker++;
2112                 }
2113
2114                 /* find last not-disabled marker */
2115                 while (last >= 0 && last_marker->flag & MARKER_DISABLED) {
2116                         last--;
2117                         last_marker--;
2118                 }
2119
2120                 if (first < track->markersnr - 1)
2121                         sfra = MIN2(sfra, first_marker->framenr);
2122
2123                 if (last >= 0)
2124                         efra = MAX2(efra, last_marker->framenr);
2125
2126                 tracks_map_insert(context->tracks_map, track, NULL);
2127
2128                 track = track->next;
2129         }
2130
2131         context->sfra = sfra;
2132         context->efra = efra;
2133
2134 #ifdef WITH_LIBMV
2135         context->tracks = create_libmv_tracks(tracksbase, width, height * aspy);
2136         context->keyframe1 = keyframe1;
2137         context->keyframe2 = keyframe2;
2138         context->refine_flags = get_refine_intrinsics_flags(tracking, object);
2139 #else
2140         (void) width;
2141         (void) height;
2142         (void) keyframe1;
2143         (void) keyframe2;
2144 #endif
2145
2146         context->focal_length = camera->focal;
2147         context->principal_point[0] = camera->principal[0];
2148         context->principal_point[1] = camera->principal[1] * aspy;
2149
2150         context->k1 = camera->k1;
2151         context->k2 = camera->k2;
2152         context->k3 = camera->k3;
2153
2154         return context;
2155 }
2156
2157 void BKE_tracking_reconstruction_context_free(MovieReconstructContext *context)
2158 {
2159 #ifdef WITH_LIBMV
2160         if (context->reconstruction)
2161                 libmv_destroyReconstruction(context->reconstruction);
2162
2163         libmv_tracksDestroy(context->tracks);
2164 #endif
2165
2166         tracks_map_free(context->tracks_map, NULL);
2167
2168         MEM_freeN(context);
2169 }
2170
2171 #ifdef WITH_LIBMV
2172 static void solve_reconstruction_update_cb(void *customdata, double progress, const char *message)
2173 {
2174         ReconstructProgressData *progressdata = customdata;
2175
2176         if (progressdata->progress) {
2177                 *progressdata->progress = progress;
2178                 *progressdata->do_update = TRUE;
2179         }
2180
2181         BLI_snprintf(progressdata->stats_message, progressdata->message_size, "Solving camera | %s", message);
2182 }
2183 #endif
2184
2185 #if 0
2186 static int solve_reconstruction_testbreak_cb(void *customdata)
2187 {
2188         ReconstructProgressData *progressdata = customdata;
2189
2190         if (progressdata->stop && *progressdata->stop)
2191                 return TRUE;
2192
2193         return G.afbreek;
2194 }
2195 #endif
2196
2197 void BKE_tracking_solve_reconstruction(MovieReconstructContext *context, short *stop, short *do_update,
2198                                        float *progress, char *stats_message, int message_size)
2199 {
2200 #ifdef WITH_LIBMV
2201         float error;
2202
2203         ReconstructProgressData progressdata;
2204
2205         progressdata.stop = stop;
2206         progressdata.do_update = do_update;
2207         progressdata.progress = progress;
2208         progressdata.stats_message = stats_message;
2209         progressdata.message_size = message_size;
2210
2211         if (context->motion_flag & TRACKING_MOTION_MODAL) {
2212                 context->reconstruction = libmv_solveModal(context->tracks,
2213                                                            context->focal_length,
2214                                                            context->principal_point[0], context->principal_point[1],
2215                                                            context->k1, context->k2, context->k3,
2216                                                            solve_reconstruction_update_cb, &progressdata);
2217         }
2218         else {
2219                 context->reconstruction = libmv_solveReconstruction(context->tracks,
2220                                                                     context->keyframe1, context->keyframe2,
2221                                                                     context->refine_flags,
2222                                                                     context->focal_length,
2223                                                                     context->principal_point[0], context->principal_point[1],
2224                                                                     context->k1, context->k2, context->k3,
2225                                                                     solve_reconstruction_update_cb, &progressdata);
2226         }
2227
2228         error = libmv_reprojectionError(context->reconstruction);
2229
2230         context->reprojection_error = error;
2231 #else
2232         (void) context;
2233         (void) stop;
2234         (void) do_update;
2235         (void) progress;
2236         (void) stats_message;
2237         (void) message_size;
2238 #endif
2239 }
2240
2241 int BKE_tracking_finish_reconstruction(MovieReconstructContext *context, MovieTracking *tracking)
2242 {
2243         MovieTrackingReconstruction *reconstruction;
2244
2245         tracks_map_merge(context->tracks_map, tracking);
2246
2247         if (context->is_camera) {
2248                 reconstruction = &tracking->reconstruction;
2249         }
2250         else {
2251                 MovieTrackingObject *object;
2252
2253                 object = BKE_tracking_named_object(tracking, context->object_name);
2254                 reconstruction = &object->reconstruction;
2255         }
2256
2257         reconstruction->error = context->reprojection_error;
2258         reconstruction->flag |= TRACKING_RECONSTRUCTED;
2259
2260 #ifdef WITH_LIBMV
2261         if (!retrieve_libmv_reconstruct(context, tracking))
2262                 return FALSE;
2263 #endif
2264
2265         return TRUE;
2266 }
2267
2268 void BKE_track_unique_name(ListBase *tracksbase, MovieTrackingTrack *track)
2269 {
2270         BLI_uniquename(tracksbase, track, "Track", '.', offsetof(MovieTrackingTrack, name), sizeof(track->name));
2271 }
2272
2273 MovieTrackingTrack *BKE_tracking_named_track(MovieTracking *tracking, MovieTrackingObject *object, const char *name)
2274 {
2275         ListBase *tracksbase = BKE_tracking_object_tracks(tracking, object);
2276         MovieTrackingTrack *track = tracksbase->first;
2277
2278         while (track) {
2279                 if (!strcmp(track->name, name))
2280                         return track;
2281
2282                 track = track->next;
2283         }
2284
2285         return NULL;
2286 }
2287
2288 static int reconstruction_camera_index(MovieTrackingReconstruction *reconstruction, int framenr, int nearest)
2289 {
2290         MovieReconstructedCamera *cameras = reconstruction->cameras;
2291         int a = 0, d = 1;
2292
2293         if (!reconstruction->camnr)
2294                 return -1;
2295
2296         if (framenr < cameras[0].framenr) {
2297                 if (nearest)
2298                         return 0;
2299                 else
2300                         return -1;
2301         }
2302
2303         if (framenr > cameras[reconstruction->camnr - 1].framenr) {
2304                 if (nearest)
2305                         return reconstruction->camnr - 1;
2306                 else
2307                         return -1;
2308         }
2309
2310         if (reconstruction->last_camera < reconstruction->camnr)
2311                 a = reconstruction->last_camera;
2312
2313         if (cameras[a].framenr >= framenr)
2314                 d = -1;
2315
2316         while (a >= 0 && a < reconstruction->camnr) {
2317                 int cfra = cameras[a].framenr;
2318
2319                 /* check if needed framenr was "skipped" -- no data for requested frame */
2320
2321                 if (d > 0 && cfra > framenr) {
2322                         /* interpolate with previous position */
2323                         if (nearest)
2324                                 return a - 1;
2325                         else
2326                                 break;
2327                 }
2328
2329                 if (d < 0 && cfra < framenr) {
2330                         /* interpolate with next position */
2331                         if (nearest)
2332                                 return a;
2333                         else
2334                                 break;
2335                 }
2336
2337                 if (cfra == framenr) {
2338                         reconstruction->last_camera = a;
2339
2340                         return a;
2341                 }
2342
2343                 a += d;
2344         }
2345
2346         return -1;
2347 }
2348
2349 static void scale_reconstructed_camera(MovieTrackingObject *object, float mat[4][4])
2350 {
2351         if ((object->flag & TRACKING_OBJECT_CAMERA) == 0) {
2352                 float smat[4][4];
2353
2354                 scale_m4_fl(smat, 1.0f / object->scale);
2355                 mult_m4_m4m4(mat, mat, smat);
2356         }
2357 }
2358
2359 MovieReconstructedCamera *BKE_tracking_get_reconstructed_camera(MovieTracking *tracking,
2360                                                                 MovieTrackingObject *object, int framenr)
2361 {
2362         MovieTrackingReconstruction *reconstruction;
2363         int a;
2364
2365         reconstruction = BKE_tracking_object_reconstruction(tracking, object);
2366         a = reconstruction_camera_index(reconstruction, framenr, FALSE);
2367
2368         if (a == -1)
2369                 return NULL;
2370
2371         return &reconstruction->cameras[a];
2372 }
2373
2374 void BKE_tracking_get_interpolated_camera(MovieTracking *tracking, MovieTrackingObject *object,
2375                                           int framenr, float mat[4][4])
2376 {
2377         MovieTrackingReconstruction *reconstruction;
2378         MovieReconstructedCamera *cameras;
2379         int a;
2380
2381         reconstruction = BKE_tracking_object_reconstruction(tracking, object);
2382         cameras = reconstruction->cameras;
2383         a = reconstruction_camera_index(reconstruction, framenr, 1);
2384
2385         if (a == -1) {
2386                 unit_m4(mat);
2387
2388                 return;
2389         }
2390
2391         if (cameras[a].framenr != framenr && a > 0 && a < reconstruction->camnr - 1) {
2392                 float t = ((float)framenr - cameras[a].framenr) / (cameras[a + 1].framenr - cameras[a].framenr);
2393
2394                 blend_m4_m4m4(mat, cameras[a].mat, cameras[a + 1].mat, t);
2395         }
2396         else {
2397                 copy_m4_m4(mat, cameras[a].mat);
2398         }
2399
2400         scale_reconstructed_camera(object, mat);
2401 }
2402
2403 void BKE_get_tracking_mat(Scene *scene, Object *ob, float mat[4][4])
2404 {
2405         if (!ob) {
2406                 if (scene->camera)
2407                         ob = scene->camera;
2408                 else
2409                         ob = BKE_scene_camera_find(scene);
2410         }
2411
2412         if (ob)
2413                 BKE_object_where_is_calc_mat4(scene, ob, mat);
2414         else
2415                 unit_m4(mat);
2416 }
2417
2418 void BKE_tracking_camera_shift(MovieTracking *tracking, int winx, int winy, float *shiftx, float *shifty)
2419 {
2420         /* indeed in both of cases it should be winx -- it's just how camera shift works for blender's camera */
2421         *shiftx = (0.5f * winx - tracking->camera.principal[0]) / winx;
2422         *shifty = (0.5f * winy - tracking->camera.principal[1]) / winx;
2423 }
2424
2425 void BKE_tracking_camera_to_blender(MovieTracking *tracking, Scene *scene, Camera *camera, int width, int height)
2426 {
2427         float focal = tracking->camera.focal;
2428
2429         camera->sensor_x = tracking->camera.sensor_width;
2430         camera->sensor_fit = CAMERA_SENSOR_FIT_AUTO;
2431         camera->lens = focal * camera->sensor_x / width;
2432
2433         scene->r.xsch = width * tracking->camera.pixel_aspect;
2434         scene->r.ysch = height;
2435
2436         scene->r.xasp = 1.0f;
2437         scene->r.yasp = 1.0f;
2438
2439         BKE_tracking_camera_shift(tracking, width, height, &camera->shiftx, &camera->shifty);
2440 }
2441
2442 void BKE_tracking_projection_matrix(MovieTracking *tracking, MovieTrackingObject *object,
2443                                     int framenr, int winx, int winy, float mat[4][4])
2444 {
2445         MovieReconstructedCamera *camera;
2446         float lens = tracking->camera.focal * tracking->camera.sensor_width / (float)winx;
2447         float viewfac, pixsize, left, right, bottom, top, clipsta, clipend;
2448         float winmat[4][4];
2449         float ycor =  1.0f / tracking->camera.pixel_aspect;
2450         float shiftx, shifty, winside = MAX2(winx, winy);
2451
2452         BKE_tracking_camera_shift(tracking, winx, winy, &shiftx, &shifty);
2453
2454         clipsta = 0.1f;
2455         clipend = 1000.0f;
2456
2457         if (winx >= winy)
2458                 viewfac = (lens * winx) / tracking->camera.sensor_width;
2459         else
2460                 viewfac = (ycor * lens * winy) / tracking->camera.sensor_width;
2461
2462         pixsize = clipsta / viewfac;
2463
2464         left = -0.5f * (float)winx + shiftx * winside;
2465         bottom = -0.5f * (ycor) * (float)winy + shifty * winside;
2466         right =  0.5f * (float)winx + shiftx * winside;
2467         top =  0.5f * (ycor) * (float)winy + shifty * winside;
2468
2469         left *= pixsize;
2470         right *= pixsize;
2471         bottom *= pixsize;
2472         top *= pixsize;
2473
2474         perspective_m4(winmat, left, right, bottom, top, clipsta, clipend);
2475
2476         camera = BKE_tracking_get_reconstructed_camera(tracking, object, framenr);
2477
2478         if (camera) {
2479                 float imat[4][4];
2480
2481                 invert_m4_m4(imat, camera->mat);
2482                 mult_m4_m4m4(mat, winmat, imat);
2483         }
2484         else copy_m4_m4(mat, winmat);
2485 }
2486
2487 ListBase *BKE_tracking_get_tracks(MovieTracking *tracking)
2488 {
2489         MovieTrackingObject *object = BKE_tracking_active_object(tracking);
2490
2491         if (object && (object->flag & TRACKING_OBJECT_CAMERA) == 0) {
2492                 return &object->tracks;
2493         }
2494
2495         return &tracking->tracks;
2496 }
2497
2498 MovieTrackingTrack *BKE_tracking_active_track(MovieTracking *tracking)
2499 {
2500         ListBase *tracksbase;
2501
2502         if (!tracking->act_track)
2503                 return NULL;
2504
2505         tracksbase = BKE_tracking_get_tracks(tracking);
2506
2507         /* check that active track is in current tracks list */
2508         if (BLI_findindex(tracksbase, tracking->act_track) >= 0)
2509                 return tracking->act_track;
2510
2511         return NULL;
2512 }
2513
2514 MovieTrackingObject *BKE_tracking_active_object(MovieTracking *tracking)
2515 {
2516         return BLI_findlink(&tracking->objects, tracking->objectnr);
2517 }
2518
2519 MovieTrackingObject *BKE_tracking_get_camera_object(MovieTracking *tracking)
2520 {
2521         MovieTrackingObject *object = tracking->objects.first;
2522
2523         while (object) {
2524                 if (object->flag & TRACKING_OBJECT_CAMERA)
2525                         return object;
2526
2527                 object = object->next;
2528         }
2529
2530         return NULL;
2531 }
2532
2533 ListBase *BKE_tracking_object_tracks(MovieTracking *tracking, MovieTrackingObject *object)
2534 {
2535         if (object->flag & TRACKING_OBJECT_CAMERA) {
2536                 return &tracking->tracks;
2537         }
2538
2539         return &object->tracks;
2540 }
2541
2542 MovieTrackingReconstruction *BKE_tracking_object_reconstruction(MovieTracking *tracking, MovieTrackingObject *object)
2543 {
2544         if (object->flag & TRACKING_OBJECT_CAMERA) {
2545                 return &tracking->reconstruction;
2546         }
2547
2548         return &object->reconstruction;
2549 }
2550
2551 MovieTrackingReconstruction *BKE_tracking_get_reconstruction(MovieTracking *tracking)
2552 {
2553         MovieTrackingObject *object = BKE_tracking_active_object(tracking);
2554
2555         return BKE_tracking_object_reconstruction(tracking, object);
2556 }
2557
2558 void BKE_tracking_apply_intrinsics(MovieTracking *tracking, float co[2], float nco[2])
2559 {
2560         MovieTrackingCamera *camera = &tracking->camera;
2561
2562 #ifdef WITH_LIBMV
2563         double x, y;
2564         float aspy = 1.0f / tracking->camera.pixel_aspect;
2565
2566         /* normalize coords */
2567         x = (co[0] - camera->principal[0]) / camera->focal;
2568         y = (co[1] - camera->principal[1] * aspy) / camera->focal;
2569
2570         libmv_applyCameraIntrinsics(camera->focal, camera->principal[0], camera->principal[1] * aspy,
2571                                     camera->k1, camera->k2, camera->k3, x, y, &x, &y);
2572
2573         /* result is in image coords already */
2574         nco[0] = x;
2575         nco[1] = y;
2576 #else
2577         (void) camera;
2578         (void) co;
2579         (void) nco;
2580 #endif
2581 }
2582
2583 void BKE_tracking_invert_intrinsics(MovieTracking *tracking, float co[2], float nco[2])
2584 {
2585         MovieTrackingCamera *camera = &tracking->camera;
2586
2587 #ifdef WITH_LIBMV
2588         double x = co[0], y = co[1];
2589         float aspy = 1.0f / tracking->camera.pixel_aspect;
2590
2591         libmv_InvertIntrinsics(camera->focal, camera->principal[0], camera->principal[1] * aspy,
2592                                camera->k1, camera->k2, camera->k3, x, y, &x, &y);
2593
2594         nco[0] = x * camera->focal + camera->principal[0];
2595         nco[1] = y * camera->focal + camera->principal[1] * aspy;
2596 #else
2597         (void) camera;
2598         (void) co;
2599         (void) nco;
2600 #endif
2601 }
2602
2603 #ifdef WITH_LIBMV
2604 static int point_in_stroke(bGPDstroke *stroke, float x, float y)
2605 {
2606         int i, prev;
2607         int count = 0;
2608         bGPDspoint *points = stroke->points;
2609
2610         prev = stroke->totpoints - 1;
2611
2612         for (i = 0; i < stroke->totpoints; i++) {
2613                 if ((points[i].y < y && points[prev].y >= y) || (points[prev].y < y && points[i].y >= y)) {
2614                         float fac = (y - points[i].y) / (points[prev].y - points[i].y);
2615
2616                         if (points[i].x + fac * (points[prev].x - points[i].x) < x)
2617                                 count++;
2618                 }
2619
2620                 prev = i;
2621         }
2622
2623         return count % 2;
2624 }
2625
2626 static int point_in_layer(bGPDlayer *layer, float x, float y)
2627 {
2628         bGPDframe *frame = layer->frames.first;
2629
2630         while (frame) {
2631                 bGPDstroke *stroke = frame->strokes.first;
2632
2633                 while (stroke) {
2634                         if (point_in_stroke(stroke, x, y))
2635                                 return TRUE;
2636
2637                         stroke = stroke->next;
2638                 }
2639                 frame = frame->next;
2640         }
2641
2642         return FALSE;
2643 }
2644
2645 static void retrieve_libmv_features(MovieTracking *tracking, ListBase *tracksbase,
2646                                     struct libmv_Features *features, int framenr, int width, int height,
2647                                     bGPDlayer *layer, int place_outside_layer)
2648 {
2649         int a;
2650
2651         a = libmv_countFeatures(features);
2652         while (a--) {
2653                 MovieTrackingTrack *track;
2654                 double x, y, size, score;
2655                 int ok = TRUE;
2656                 float xu, yu;
2657
2658                 libmv_getFeature(features, a, &x, &y, &score, &size);
2659
2660                 xu = x / width;
2661                 yu = y / height;
2662
2663                 if (layer)
2664                         ok = point_in_layer(layer, xu, yu) != place_outside_layer;
2665
2666                 if (ok) {
2667                         track = BKE_tracking_add_track(tracking, tracksbase, xu, yu, framenr, width, height);
2668                         track->flag |= SELECT;
2669                         track->pat_flag |= SELECT;
2670                         track->search_flag |= SELECT;
2671                 }
2672         }
2673 }
2674 #endif
2675
2676 void BKE_tracking_detect_fast(MovieTracking *tracking, ListBase *tracksbase, ImBuf *ibuf,
2677                               int framenr, int margin, int min_trackness, int min_distance, bGPDlayer *layer,
2678                               int place_outside_layer)
2679 {
2680 #ifdef WITH_LIBMV
2681         struct libmv_Features *features;
2682         unsigned char *pixels = get_ucharbuf(ibuf);
2683
2684         features = libmv_detectFeaturesFAST(pixels, ibuf->x, ibuf->y, ibuf->x,
2685                                             margin, min_trackness, min_distance);
2686
2687         MEM_freeN(pixels);
2688
2689         retrieve_libmv_features(tracking, tracksbase, features, framenr,
2690                                 ibuf->x, ibuf->y, layer, place_outside_layer);
2691
2692         libmv_destroyFeatures(features);
2693 #else
2694         (void) tracking;
2695         (void) tracksbase;
2696         (void) ibuf;
2697         (void) framenr;
2698         (void) margin;
2699         (void) min_trackness;
2700         (void) min_distance;
2701         (void) layer;
2702         (void) place_outside_layer;
2703 #endif
2704 }
2705
2706 MovieTrackingTrack *BKE_tracking_indexed_track(MovieTracking *tracking, int tracknr, ListBase **tracksbase_r)
2707 {
2708         MovieTrackingObject *object;
2709         int cur = 1;
2710
2711         object = tracking->objects.first;
2712         while (object) {
2713                 ListBase *tracksbase = BKE_tracking_object_tracks(tracking, object);
2714                 MovieTrackingTrack *track = tracksbase->first;
2715
2716                 while (track) {
2717                         if (track->flag & TRACK_HAS_BUNDLE) {
2718                                 if (cur == tracknr) {
2719                                         *tracksbase_r = tracksbase;
2720                                         return track;
2721                                 }
2722
2723                                 cur++;
2724                         }
2725
2726                         track = track->next;
2727                 }
2728
2729                 object = object->next;
2730         }
2731
2732         *tracksbase_r = NULL;
2733
2734         return NULL;
2735 }
2736
2737 static int stabilization_median_point(MovieTracking *tracking, int framenr, float median[2])
2738 {
2739         int ok = FALSE;
2740         float min[2], max[2];
2741         MovieTrackingTrack *track;
2742
2743         INIT_MINMAX2(min, max);
2744
2745         track = tracking->tracks.first;
2746         while (track) {
2747                 if (track->flag & TRACK_USE_2D_STAB) {
2748                         MovieTrackingMarker *marker = BKE_tracking_get_marker(track, framenr);
2749
2750                         DO_MINMAX2(marker->pos, min, max);
2751
2752                         ok = TRUE;
2753                 }
2754
2755                 track = track->next;
2756         }
2757
2758         median[0] = (max[0] + min[0]) / 2.0f;
2759         median[1] = (max[1] + min[1]) / 2.0f;
2760
2761         return ok;
2762 }
2763
2764 static void calculate_stabdata(MovieTracking *tracking, int framenr, float width, float height,
2765                                float firstmedian[2], float median[2], float loc[2], float *scale, float *angle)
2766 {
2767         MovieTrackingStabilization *stab = &tracking->stabilization;
2768
2769         *scale = (stab->scale - 1.0f) * stab->scaleinf + 1.0f;
2770         *angle = 0.0f;
2771
2772         loc[0] = (firstmedian[0] - median[0]) * width * (*scale);
2773         loc[1] = (firstmedian[1] - median[1]) * height * (*scale);
2774
2775         mul_v2_fl(loc, stab->locinf);
2776
2777         if ((stab->flag & TRACKING_STABILIZE_ROTATION) && stab->rot_track && stab->rotinf) {
2778                 MovieTrackingMarker *marker;
2779                 float a[2], b[2];
2780                 float x0 = (float)width / 2.0f, y0 = (float)height / 2.0f;
2781                 float x = median[0] * width, y = median[1] * height;
2782
2783                 marker = BKE_tracking_get_marker(stab->rot_track, 1);
2784                 sub_v2_v2v2(a, marker->pos, firstmedian);
2785                 a[0] *= width;
2786                 a[1] *= height;
2787
2788                 marker = BKE_tracking_get_marker(stab->rot_track, framenr);
2789                 sub_v2_v2v2(b, marker->pos, median);
2790                 b[0] *= width;
2791                 b[1] *= height;
2792
2793                 *angle = -atan2(a[0] * b[1] - a[1] * b[0], a[0] * b[0] + a[1] * b[1]);
2794                 *angle *= stab->rotinf;
2795
2796                 /* convert to rotation around image center */
2797                 loc[0] -= (x0 + (x - x0) * cosf(*angle) - (y - y0) * sinf(*angle) - x) * (*scale);
2798                 loc[1] -= (y0 + (x - x0) * sinf(*angle) + (y - y0) * cosf(*angle) - y) * (*scale);
2799         }
2800 }
2801
2802 static float stabilization_auto_scale_factor(MovieTracking *tracking, int width, int height)
2803 {
2804         float firstmedian[2];
2805         MovieTrackingStabilization *stab = &tracking->stabilization;
2806         float aspect = tracking->camera.pixel_aspect;
2807
2808         if (stab->ok)
2809                 return stab->scale;
2810
2811         if (stabilization_median_point(tracking, 1, firstmedian)) {
2812                 int sfra = INT_MAX, efra = INT_MIN, cfra;
2813                 float scale = 1.0f;
2814                 MovieTrackingTrack *track;
2815
2816                 stab->scale = 1.0f;
2817
2818                 track = tracking->tracks.first;
2819                 while (track) {
2820                         if (track->flag & TRACK_USE_2D_STAB ||
2821                             ((stab->flag & TRACKING_STABILIZE_ROTATION) && track == stab->rot_track))
2822                         {
2823                                 sfra = MIN2(sfra, track->markers[0].framenr);
2824                                 efra = MAX2(efra, track->markers[track->markersnr - 1].framenr);
2825                         }
2826
2827                         track = track->next;
2828                 }
2829
2830                 for (cfra = sfra; cfra <= efra; cfra++) {
2831                         float median[2];
2832                         float loc[2], angle, tmp_scale;
2833                         int i;
2834                         float mat[4][4];
2835                         float points[4][2] = {{0.0f, 0.0f}, {0.0f, height}, {width, height}, {width, 0.0f}};
2836                         float si, co;
2837
2838                         stabilization_median_point(tracking, cfra, median);
2839
2840                         calculate_stabdata(tracking, cfra, width, height, firstmedian, median, loc, &tmp_scale, &angle);
2841
2842                         BKE_tracking_stabdata_to_mat4(width, height, aspect, loc, 1.0f, angle, mat);
2843
2844                         si = sin(angle);
2845                         co = cos(angle);
2846
2847                         for (i = 0; i < 4; i++) {
2848                                 int j;
2849                                 float a[3] = {0.0f, 0.0f, 0.0f}, b[3] = {0.0f, 0.0f, 0.0f};
2850
2851                                 copy_v3_v3(a, points[i]);
2852                                 copy_v3_v3(b, points[(i + 1) % 4]);
2853
2854                                 mul_m4_v3(mat, a);
2855                                 mul_m4_v3(mat, b);
2856
2857                                 for (j = 0; j < 4; j++) {
2858                                         float point[3] = {points[j][0], points[j][1], 0.0f};
2859                                         float v1[3], v2[3];
2860
2861                                         sub_v3_v3v3(v1, b, a);
2862                                         sub_v3_v3v3(v2, point, a);
2863
2864                                         if (cross_v2v2(v1, v2) >= 0.0f) {
2865                                                 const float rotDx[4][2] = {{1.0f, 0.0f}, {0.0f, -1.0f}, {-1.0f, 0.0f}, {0.0f, 1.0f}};
2866                                                 const float rotDy[4][2] = {{0.0f, 1.0f}, {1.0f, 0.0f}, {0.0f, -1.0f}, {-1.0f, 0.0f}};
2867
2868                                                 float dx = loc[0] * rotDx[j][0] + loc[1] * rotDx[j][1],
2869                                                       dy = loc[0] * rotDy[j][0] + loc[1] * rotDy[j][1];
2870
2871                                                 float w, h, E, F, G, H, I, J, K, S;
2872
2873                                                 if (j % 2) {
2874                                                         w = (float)height / 2.0f;
2875                                                         h = (float)width / 2.0f;
2876                                                 }
2877                                                 else {
2878                                                         w = (float)width / 2.0f;
2879                                                         h = (float)height / 2.0f;
2880                                                 }
2881
2882                                                 E = -w * co + h * si;
2883                                                 F = -h * co - w * si;
2884
2885                                                 if ((i % 2) == (j % 2)) {
2886                                                         G = -w * co - h * si;
2887                                                         H = h * co - w * si;
2888                                                 }
2889                                                 else {
2890                                                         G = w * co + h * si;
2891                                                         H = -h * co + w * si;
2892                                                 }
2893
2894                                                 I = F - H;
2895                                                 J = G - E;
2896                                                 K = G * F - E * H;
2897
2898                                                 S = (-w * I - h * J) / (dx * I + dy * J + K);
2899
2900                                                 scale = MAX2(scale, S);
2901                                         }
2902                                 }
2903                         }
2904                 }
2905
2906                 stab->scale = scale;
2907
2908                 if (stab->maxscale > 0.0f)
2909                         stab->scale = MIN2(stab->scale, stab->maxscale);
2910         }
2911         else {
2912                 stab->scale = 1.0f;
2913         }
2914
2915         stab->ok = TRUE;
2916
2917         return stab->scale;
2918 }
2919
2920 static ImBuf *stabilize_alloc_ibuf(ImBuf *cacheibuf, ImBuf *srcibuf, int fill)
2921 {
2922         int flags;
2923
2924         if (cacheibuf && (cacheibuf->x != srcibuf->x || cacheibuf->y != srcibuf->y)) {
2925                 IMB_freeImBuf(cacheibuf);
2926                 cacheibuf = NULL;
2927         }
2928
2929         flags = IB_rect;
2930
2931         if (srcibuf->rect_float)
2932                 flags |= IB_rectfloat;
2933
2934         if (cacheibuf) {
2935                 if (fill) {
2936                         float col[4] = {0.0f, 0.0f, 0.0f, 0.0f};
2937
2938                         IMB_rectfill(cacheibuf, col);
2939                 }
2940         }
2941         else {
2942                 cacheibuf = IMB_allocImBuf(srcibuf->x, srcibuf->y, srcibuf->planes, flags);
2943                 cacheibuf->profile = srcibuf->profile;
2944         }
2945
2946         return cacheibuf;
2947 }
2948
2949 void BKE_tracking_stabilization_data(MovieTracking *tracking, int framenr, int width, int height,
2950                                      float loc[2], float *scale, float *angle)
2951 {
2952         float firstmedian[2], median[2];
2953         MovieTrackingStabilization *stab = &tracking->stabilization;
2954
2955         if ((stab->flag & TRACKING_2D_STABILIZATION) == 0) {
2956                 zero_v2(loc);
2957                 *scale = 1.0f;
2958                 *angle = 0.0f;
2959
2960                 return;
2961         }
2962
2963         if (stabilization_median_point(tracking, 1, firstmedian)) {
2964                 stabilization_median_point(tracking, framenr, median);
2965
2966                 if ((stab->flag & TRACKING_AUTOSCALE) == 0)
2967                         stab->scale = 1.0f;
2968
2969                 if (!stab->ok) {
2970                         if (stab->flag & TRACKING_AUTOSCALE)
2971                                 stabilization_auto_scale_factor(tracking, width, height);
2972
2973                         calculate_stabdata(tracking, framenr, width, height, firstmedian, median, loc, scale, angle);
2974
2975                         stab->ok = TRUE;
2976                 }
2977                 else {
2978                         calculate_stabdata(tracking, framenr, width, height, firstmedian, median, loc, scale, angle);
2979                 }
2980         }
2981         else {
2982                 zero_v2(loc);
2983                 *scale = 1.0f;
2984                 *angle = 0.0f;
2985         }
2986 }
2987
2988 ImBuf *BKE_tracking_stabilize(MovieTracking *tracking, int framenr, ImBuf *ibuf,
2989                               float loc[2], float *scale, float *angle)
2990 {
2991         float tloc[2], tscale, tangle;
2992         MovieTrackingStabilization *stab = &tracking->stabilization;
2993         ImBuf *tmpibuf;
2994         float width = ibuf->x, height = ibuf->y;
2995         float aspect = tracking->camera.pixel_aspect;
2996
2997         if (loc)
2998                 copy_v2_v2(tloc, loc);
2999
3000         if (scale)
3001                 tscale = *scale;
3002
3003         if ((stab->flag & TRACKING_2D_STABILIZATION) == 0) {
3004                 if (loc)
3005                         zero_v2(loc);
3006
3007                 if (scale)
3008                         *scale = 1.0f;
3009
3010                 return ibuf;
3011         }
3012
3013         BKE_tracking_stabilization_data(tracking, framenr, width, height, tloc, &tscale, &tangle);
3014
3015         tmpibuf = stabilize_alloc_ibuf(NULL, ibuf, TRUE);
3016
3017         /* scale would be handled by matrix transformation when angle is non-zero */
3018         if (tscale != 1.0f && tangle == 0.0f) {
3019                 ImBuf *scaleibuf;
3020
3021                 stabilization_auto_scale_factor(tracking, width, height);
3022
3023                 scaleibuf = stabilize_alloc_ibuf(stab->scaleibuf, ibuf, 0);
3024                 stab->scaleibuf = scaleibuf;
3025
3026                 IMB_rectcpy(scaleibuf, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
3027                 IMB_scalefastImBuf(scaleibuf, ibuf->x * tscale, ibuf->y * tscale);
3028
3029                 ibuf = scaleibuf;
3030         }
3031
3032         if (tangle == 0.0f) {
3033                 /* if angle is zero, then it's much faster to use rect copy
3034                  * but could be issues with subpixel precisions
3035                  */
3036                 IMB_rectcpy(tmpibuf, ibuf,
3037                             tloc[0] - (tscale - 1.0f) * width / 2.0f,
3038                             tloc[1] - (tscale - 1.0f) * height / 2.0f,
3039                             0, 0, ibuf->x, ibuf->y);
3040         }
3041         else {
3042                 float mat[4][4];
3043                 int i, j, filter = tracking->stabilization.filter;
3044                 void (*interpolation)(struct ImBuf *, struct ImBuf *, float, float, int, int) = NULL;
3045
3046                 BKE_tracking_stabdata_to_mat4(ibuf->x, ibuf->y, aspect, tloc, tscale, tangle, mat);
3047                 invert_m4(mat);
3048
3049                 if (filter == TRACKING_FILTER_NEAREAST)
3050                         interpolation = neareast_interpolation;
3051                 else if (filter == TRACKING_FILTER_BILINEAR)
3052                         interpolation = bilinear_interpolation;
3053                 else if (filter == TRACKING_FILTER_BICUBIC)
3054                         interpolation = bicubic_interpolation;
3055                 else
3056                         /* fallback to default interpolation method */
3057                         interpolation = neareast_interpolation;
3058
3059                 for (j = 0; j < tmpibuf->y; j++) {
3060                         for (i = 0; i < tmpibuf->x; i++) {
3061                                 float vec[3] = {i, j, 0};
3062
3063                                 mul_v3_m4v3(vec, mat, vec);
3064
3065                                 interpolation(ibuf, tmpibuf, vec[0], vec[1], i, j);
3066                         }
3067                 }
3068         }
3069
3070         tmpibuf->userflags |= IB_MIPMAP_INVALID;
3071
3072         if (tmpibuf->rect_float)
3073                 tmpibuf->userflags |= IB_RECT_INVALID;
3074
3075         if (loc)
3076                 copy_v2_v2(loc, tloc);
3077
3078         if (scale)
3079                 *scale = tscale;
3080
3081         if (angle)
3082                 *angle = tangle;
3083
3084         return tmpibuf;
3085 }
3086
3087 void BKE_tracking_stabdata_to_mat4(int width, int height, float aspect,
3088                                    float loc[2], float scale, float angle, float mat[4][4])
3089 {
3090         float lmat[4][4], rmat[4][4], smat[4][4], cmat[4][4], icmat[4][4], amat[4][4], iamat[4][4];
3091         float svec[3] = {scale, scale, scale};
3092
3093         unit_m4(rmat);
3094         unit_m4(lmat);
3095         unit_m4(smat);
3096         unit_m4(cmat);
3097         unit_m4(amat);
3098
3099         /* aspect ratio correction matrix */
3100         amat[0][0] = 1.0f / aspect;
3101         invert_m4_m4(iamat, amat);
3102
3103         /* image center as rotation center */
3104         cmat[3][0] = (float)width / 2.0f;
3105         cmat[3][1] = (float)height / 2.0f;
3106         invert_m4_m4(icmat, cmat);
3107
3108         size_to_mat4(smat, svec);       /* scale matrix */
3109         add_v2_v2(lmat[3], loc);        /* translation matrix */
3110         rotate_m4(rmat, 'Z', angle);    /* rotation matrix */
3111
3112         /* compose transformation matrix */
3113         mul_serie_m4(mat, lmat, cmat, amat, rmat, iamat, smat, icmat, NULL);
3114 }
3115
3116 MovieDistortion *BKE_tracking_distortion_create(void)
3117 {
3118         MovieDistortion *distortion;
3119
3120         distortion = MEM_callocN(sizeof(MovieDistortion), "BKE_tracking_distortion_create");
3121
3122         return distortion;
3123 }
3124
3125 MovieDistortion *BKE_tracking_distortion_copy(MovieDistortion *distortion)
3126 {
3127         MovieDistortion *new_distortion;
3128
3129         new_distortion = MEM_callocN(sizeof(MovieDistortion), "BKE_tracking_distortion_create");
3130
3131 #ifdef WITH_LIBMV
3132         new_distortion->intrinsics = libmv_CameraIntrinsicsCopy(distortion->intrinsics);
3133 #else
3134         (void) distortion;
3135 #endif
3136
3137         return new_distortion;
3138 }
3139
3140 void BKE_tracking_distortion_update(MovieDistortion *distortion, MovieTracking *tracking, int width, int height)
3141 {
3142         MovieTrackingCamera *camera = &tracking->camera;
3143         float aspy = 1.0f / tracking->camera.pixel_aspect;
3144
3145 #ifdef WITH_LIBMV
3146         if (!distortion->intrinsics) {
3147                 distortion->intrinsics = libmv_CameraIntrinsicsNew(camera->focal,
3148                                                                    camera->principal[0], camera->principal[1] * aspy,
3149                                                                    camera->k1, camera->k2, camera->k3, width, height * aspy);
3150         }
3151         else {
3152                 libmv_CameraIntrinsicsUpdate(distortion->intrinsics, camera->focal,
3153                                              camera->principal[0], camera->principal[1] * aspy,
3154                                              camera->k1, camera->k2, camera->k3, width, height * aspy);
3155         }
3156 #else
3157         (void) distortion;
3158         (void) width;
3159         (void) height;
3160         (void) camera;
3161         (void) aspy;
3162 #endif
3163 }
3164
3165 ImBuf *BKE_tracking_distortion_exec(MovieDistortion *distortion, MovieTracking *tracking,
3166                                     ImBuf *ibuf, int width, int height, float overscan, int undistort)
3167 {
3168         ImBuf *resibuf;
3169
3170         BKE_tracking_distortion_update(distortion, tracking, width, height);
3171
3172         resibuf = IMB_dupImBuf(ibuf);
3173
3174         if (ibuf->rect_float) {
3175 #ifdef WITH_LIBMV
3176                 if (undistort) {
3177                         libmv_CameraIntrinsicsUndistortFloat(distortion->intrinsics,
3178                                                              ibuf->rect_float, resibuf->rect_float,
3179                                                              ibuf->x, ibuf->y, overscan, ibuf->channels);
3180                 }
3181                 else {
3182                         libmv_CameraIntrinsicsDistortFloat(distortion->intrinsics,
3183                                                            ibuf->rect_float, resibuf->rect_float,
3184                                                            ibuf->x, ibuf->y, overscan, ibuf->channels);
3185                 }
3186 #endif
3187
3188                 resibuf->userflags |= IB_RECT_INVALID;
3189         }
3190         else {
3191 #ifdef WITH_LIBMV
3192                 if (undistort) {
3193                         libmv_CameraIntrinsicsUndistortByte(distortion->intrinsics,
3194                                                             (unsigned char *)ibuf->rect, (unsigned char *)resibuf->rect,
3195                                                             ibuf->x, ibuf->y, overscan, ibuf->channels);
3196                 }
3197                 else {
3198                         libmv_CameraIntrinsicsDistortByte(distortion->intrinsics,
3199                                                           (unsigned char *)ibuf->rect, (unsigned char *)resibuf->rect,
3200                                                           ibuf->x, ibuf->y, overscan, ibuf->channels);
3201                 }
3202 #endif
3203         }
3204
3205 #ifndef WITH_LIBMV
3206         (void) overscan;
3207         (void) undistort;
3208 #endif
3209
3210         return resibuf;
3211 }
3212
3213 void BKE_tracking_distortion_destroy(MovieDistortion *distortion)
3214 {
3215 #ifdef WITH_LIBMV
3216         libmv_CameraIntrinsicsDestroy(distortion->intrinsics);
3217 #endif
3218
3219         MEM_freeN(distortion);
3220 }
3221
3222 ImBuf *BKE_tracking_undistort(MovieTracking *tracking, ImBuf *ibuf, int width, int height, float overscan)
3223 {
3224         MovieTrackingCamera *camera = &tracking->camera;
3225
3226         if (camera->intrinsics == NULL)
3227                 camera->intrinsics = BKE_tracking_distortion_create();
3228
3229         return BKE_tracking_distortion_exec(camera->intrinsics, tracking, ibuf, width, height, overscan, 1);
3230 }
3231
3232 ImBuf *BKE_tracking_distort(MovieTracking *tracking, ImBuf *ibuf, int width, int height, float overscan)
3233 {
3234         MovieTrackingCamera *camera = &tracking->camera;
3235
3236         if (camera->intrinsics == NULL)
3237                 camera->intrinsics = BKE_tracking_distortion_create();
3238
3239         return BKE_tracking_distortion_exec(camera->intrinsics, tracking, ibuf, width, height, overscan, 0);
3240 }
3241
3242 /* area - which part of marker should be selected. see TRACK_AREA_* constants */
3243 void BKE_tracking_select_track(ListBase *tracksbase, MovieTrackingTrack *track, int area, int extend)
3244 {
3245         if (extend) {
3246                 BKE_tracking_track_flag(track, area, SELECT, 0);
3247         }
3248         else {
3249                 MovieTrackingTrack *cur = tracksbase->first;
3250
3251                 while (cur) {
3252                         if ((cur->flag & TRACK_HIDDEN) == 0) {
3253                                 if (cur == track) {
3254                                         BKE_tracking_track_flag(cur, TRACK_AREA_ALL, SELECT, 1);
3255                                         BKE_tracking_track_flag(cur, area, SELECT, 0);
3256                                 }
3257                                 else {