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