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