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