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