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