2cd13a90048a3aab6dcace0cd36914dee52b4a04
[blender.git] / source / blender / blenkernel / intern / tracking_auto.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_auto.c
29  *  \ingroup bke
30  */
31
32 #include <stdlib.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_movieclip_types.h"
37 #include "DNA_object_types.h"   /* SELECT */
38
39 #include "BLI_threads.h"
40 #include "BLI_utildefines.h"
41 #include "BLI_math.h"
42
43 #include "BKE_movieclip.h"
44 #include "BKE_tracking.h"
45
46 #include "libmv-capi.h"
47 #include "tracking_private.h"
48
49 typedef struct AutoTrackOptions {
50         int clip_index;  /** Index of the clip this track belogs to. */
51         int track_index;  /* Index of the track in AutoTrack tracks structure. */
52         MovieTrackingTrack *track;  /* Pointer to an original track/ */
53         libmv_TrackRegionOptions track_region_options;  /* Options for the region
54                                                            tracker. */
55         bool use_keyframe_match;  /* Keyframe pattern matching. */
56
57         /* TODO(sergey): A bit awkward to keep it in here, only used to
58          * place a disabled marker once the trackign fails,
59          * Wither find a more clear way to do it or call it track context
60          * or state, not options.
61          */
62         bool is_failed;
63         int failed_frame;
64 } AutoTrackOptions;
65
66 typedef struct AutoTrackContext {
67         MovieClip *clips[MAX_ACCESSOR_CLIP];
68         int num_clips;
69
70         MovieClipUser user;
71         int frame_width, frame_height;
72
73         struct libmv_AutoTrack *autotrack;
74         TrackingImageAccessor *image_accessor;
75
76         int num_tracks;  /* Number of tracks being tracked. */
77         AutoTrackOptions *options;  /* Per-tracking track options. */
78
79         bool backwards;
80         bool sequence;
81         int first_frame;
82         int sync_frame;
83         bool first_sync;
84         SpinLock spin_lock;
85 } AutoTrackContext;
86
87 static void normalized_to_libmv_frame(const float normalized[2],
88                                       const int frame_dimensions[2],
89                                       float result[2])
90 {
91         result[0] = normalized[0] * frame_dimensions[0] - 0.5f;
92         result[1] = normalized[1] * frame_dimensions[1] - 0.5f;
93 }
94
95 static void normalized_relative_to_libmv_frame(const float normalized[2],
96                                                const float origin[2],
97                                                const int frame_dimensions[2],
98                                                float result[2])
99 {
100         result[0] = (normalized[0] + origin[0]) * frame_dimensions[0] - 0.5f;
101         result[1] = (normalized[1] + origin[1]) * frame_dimensions[1] - 0.5f;
102 }
103
104 static void libmv_frame_to_normalized(const float frame_coord[2],
105                                       const int frame_dimensions[2],
106                                       float result[2])
107 {
108         result[0] = (frame_coord[0] + 0.5f) / frame_dimensions[0];
109         result[1] = (frame_coord[1] + 0.5f) / frame_dimensions[1];
110 }
111
112 static void libmv_frame_to_normalized_relative(const float frame_coord[2],
113                                                const float origin[2],
114                                                const int frame_dimensions[2],
115                                                float result[2])
116 {
117         result[0] = (frame_coord[0] - origin[0]) / frame_dimensions[0];
118         result[1] = (frame_coord[1] - origin[1]) / frame_dimensions[1];
119 }
120
121 static void dna_marker_to_libmv_marker(/*const*/ MovieTrackingTrack *track,
122                                        /*const*/ MovieTrackingMarker *marker,
123                                        int clip,
124                                        int track_index,
125                                        int frame_width,
126                                        int frame_height,
127                                        bool backwards,
128                                        libmv_Marker *libmv_marker)
129 {
130         const int frame_dimensions[2] = {frame_width, frame_height};
131         int i;
132         libmv_marker->clip = clip;
133         libmv_marker->frame = marker->framenr;
134         libmv_marker->track = track_index;
135
136         normalized_to_libmv_frame(marker->pos,
137                                   frame_dimensions,
138                                   libmv_marker->center);
139         for (i = 0; i < 4; ++i) {
140                 normalized_relative_to_libmv_frame(marker->pattern_corners[i],
141                                                    marker->pos,
142                                                    frame_dimensions,
143                                                    libmv_marker->patch[i]);
144         }
145
146         normalized_relative_to_libmv_frame(marker->search_min,
147                                            marker->pos,
148                                            frame_dimensions,
149                                            libmv_marker->search_region_min);
150
151         normalized_relative_to_libmv_frame(marker->search_max,
152                                            marker->pos,
153                                            frame_dimensions,
154                                            libmv_marker->search_region_max);
155
156         /* TODO(sergey): All the markers does have 1.0 weight. */
157         libmv_marker->weight = 1.0f;
158
159         if (marker->flag & MARKER_TRACKED) {
160                 libmv_marker->source = LIBMV_MARKER_SOURCE_TRACKED;
161         }
162         else {
163                 libmv_marker->source = LIBMV_MARKER_SOURCE_MANUAL;
164         }
165         libmv_marker->status = LIBMV_MARKER_STATUS_UNKNOWN;
166         libmv_marker->model_type = LIBMV_MARKER_MODEL_TYPE_POINT;
167         libmv_marker->model_id = 0;
168
169         /* TODO(sergey): We currently don't support reference marker from
170          * different clip.
171          */
172         libmv_marker->reference_clip = clip;
173
174         if (track->pattern_match == TRACK_MATCH_KEYFRAME) {
175                 MovieTrackingMarker *keyframe_marker =
176                         tracking_get_keyframed_marker(track,
177                                                       marker->framenr,
178                                                       backwards);
179                 libmv_marker->reference_frame = keyframe_marker->framenr;
180         }
181         else {
182                 libmv_marker->reference_frame = backwards ?
183                                                 marker->framenr - 1 :
184                                                 marker->framenr;
185         }
186 }
187
188 static void libmv_marker_to_dna_marker(libmv_Marker *libmv_marker,
189                                        int frame_width,
190                                        int frame_height,
191                                        MovieTrackingMarker *marker)
192 {
193         const int frame_dimensions[2] = {frame_width, frame_height};
194         int i;
195         marker->framenr = libmv_marker->frame;
196
197         libmv_frame_to_normalized(libmv_marker->center,
198                                   frame_dimensions,
199                                   marker->pos);
200         for (i = 0; i < 4; ++i) {
201                 libmv_frame_to_normalized_relative(libmv_marker->patch[i],
202                                                    libmv_marker->center,
203                                                    frame_dimensions,
204                                                    marker->pattern_corners[i]);
205         }
206
207         libmv_frame_to_normalized_relative(libmv_marker->search_region_min,
208                                            libmv_marker->center,
209                                            frame_dimensions,
210                                            marker->search_min);
211
212         libmv_frame_to_normalized_relative(libmv_marker->search_region_max,
213                                            libmv_marker->center,
214                                            frame_dimensions,
215                                            marker->search_max);
216
217         marker->flag = 0;
218         if (libmv_marker->source == LIBMV_MARKER_SOURCE_TRACKED) {
219                 marker->flag |= MARKER_TRACKED;
220         }
221         else {
222                 marker->flag &= ~MARKER_TRACKED;
223         }
224 }
225
226 static bool check_track_trackable(MovieClip *clip,
227                                   MovieTrackingTrack *track,
228                                   MovieClipUser *user)
229 {
230         if (TRACK_SELECTED(track) &&
231             (track->flag & (TRACK_LOCKED | TRACK_HIDDEN)) == 0)
232         {
233                 MovieTrackingMarker *marker;
234                 int frame;
235                 frame = BKE_movieclip_remap_scene_to_clip_frame(clip, user->framenr);
236                 marker = BKE_tracking_marker_get(track, frame);
237                 return (marker->flag & MARKER_DISABLED) == 0;
238         }
239         return false;
240 }
241
242 /* Returns false if marker crossed margin area from frame bounds. */
243 static bool tracking_check_marker_margin(libmv_Marker *libmv_marker,
244                                          int margin,
245                                          int frame_width,
246                                          int frame_height)
247 {
248         float patch_min[2], patch_max[2];
249         float margin_left, margin_top, margin_right, margin_bottom;
250
251         INIT_MINMAX2(patch_min, patch_max);
252         minmax_v2v2_v2(patch_min, patch_max, libmv_marker->patch[0]);
253         minmax_v2v2_v2(patch_min, patch_max, libmv_marker->patch[1]);
254         minmax_v2v2_v2(patch_min, patch_max, libmv_marker->patch[2]);
255         minmax_v2v2_v2(patch_min, patch_max, libmv_marker->patch[3]);
256
257         margin_left   = max_ff(libmv_marker->center[0] - patch_min[0], margin);
258         margin_top    = max_ff(patch_max[1] - libmv_marker->center[1], margin);
259         margin_right  = max_ff(patch_max[0] - libmv_marker->center[0], margin);
260         margin_bottom = max_ff(libmv_marker->center[1] - patch_min[1], margin);
261
262         if (libmv_marker->center[0] < margin_left ||
263             libmv_marker->center[0] > frame_width - margin_right ||
264             libmv_marker->center[1] < margin_bottom ||
265             libmv_marker->center[1] > frame_height - margin_top)
266         {
267                 return false;
268         }
269
270         return true;
271 }
272
273 AutoTrackContext *BKE_autotrack_context_new(MovieClip *clip,
274                                             MovieClipUser *user,
275                                             const bool backwards,
276                                             const bool sequence)
277 {
278         AutoTrackContext *context = MEM_callocN(sizeof(AutoTrackContext),
279                                                 "autotrack context");
280         MovieTracking *tracking = &clip->tracking;
281         MovieTrackingTrack *track;
282         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
283         int i, track_index, frame_width, frame_height;
284
285         BKE_movieclip_get_size(clip, user, &frame_width, &frame_height);
286
287         /* TODO(sergey): Currently using only a single clip. */
288         context->clips[0] = clip;
289         context->num_clips = 1;
290
291         context->user = *user;
292         context->user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL;
293         context->user.render_flag = 0;
294         context->frame_width = frame_width;
295         context->frame_height = frame_height;
296         context->backwards = backwards;
297         context->sequence = sequence;
298         context->first_frame = user->framenr;
299         context->sync_frame = user->framenr;
300         context->first_sync = true;
301
302         BLI_spin_init(&context->spin_lock);
303
304         context->image_accessor =
305                 tracking_image_accessor_new(context->clips, 1, user->framenr);
306         context->autotrack =
307                 libmv_autoTrackNew(context->image_accessor->libmv_accessor);
308
309         /* Fill in Autotrack with all markers we know. */
310         track_index = 0;
311         for (track = tracksbase->first;
312              track;
313              track = track->next)
314         {
315                 if (check_track_trackable(clip, track, user)) {
316                         context->num_tracks++;
317                 }
318
319                 for (i = 0; i < track->markersnr; ++i) {
320                         MovieTrackingMarker *marker = marker = track->markers + i;
321                         if ((marker->flag & MARKER_DISABLED) == 0) {
322                                 libmv_Marker libmv_marker;
323                                 dna_marker_to_libmv_marker(track,
324                                                            marker,
325                                                            0,
326                                                            track_index,
327                                                            frame_width,
328                                                            frame_height,
329                                                            backwards,
330                                                            &libmv_marker);
331                                 libmv_autoTrackAddMarker(context->autotrack,
332                                                          &libmv_marker);
333                         }
334                 }
335                 track_index++;
336         }
337
338         /* Create per-track tracking options. */
339         context->options =
340                 MEM_callocN(sizeof(AutoTrackOptions) * context->num_tracks,
341                             "auto track options");
342         i = track_index = 0;
343         for (track = tracksbase->first;
344              track;
345              track = track->next)
346         {
347                 if (check_track_trackable(clip, track, user)) {
348                         AutoTrackOptions *options = &context->options[i++];
349                         /* TODO(sergey): Single clip only for now. */
350                         options->clip_index = 0;
351                         options->track_index = track_index;
352                         options->track = track;
353                         tracking_configure_tracker(track,
354                                                    NULL,
355                                                    &options->track_region_options);
356                         options->use_keyframe_match =
357                                 track->pattern_match == TRACK_MATCH_KEYFRAME;
358                 }
359                 ++track_index;
360         }
361
362         return context;
363 }
364
365 bool BKE_autotrack_context_step(AutoTrackContext *context)
366 {
367         int frame_delta = context->backwards ? -1 : 1;
368         bool ok = false;
369         int track;
370
371 #pragma omp parallel for if(context->num_tracks > 1)
372         for (track = 0; track < context->num_tracks; ++track) {
373                 AutoTrackOptions *options = &context->options[track];
374                 libmv_Marker libmv_current_marker,
375                              libmv_reference_marker,
376                              libmv_tracked_marker;
377                 libmv_TrackRegionResult libmv_result;
378                 int frame = BKE_movieclip_remap_scene_to_clip_frame(
379                         context->clips[options->clip_index],
380                         context->user.framenr);
381
382                 if (libmv_autoTrackGetMarker(context->autotrack,
383                                              options->clip_index,
384                                              frame,
385                                              options->track_index,
386                                              &libmv_current_marker))
387                 {
388                         if (!tracking_check_marker_margin(&libmv_current_marker,
389                                                           options->track->margin,
390                                                           context->frame_width,
391                                                           context->frame_height))
392                         {
393                                 continue;
394                         }
395
396                         libmv_tracked_marker = libmv_current_marker;
397                         libmv_tracked_marker.frame = frame + frame_delta;
398
399                         if (options->use_keyframe_match) {
400                                 libmv_tracked_marker.reference_frame =
401                                         libmv_current_marker.reference_frame;
402                                 libmv_autoTrackGetMarker(context->autotrack,
403                                                      options->clip_index,
404                                                      libmv_tracked_marker.reference_frame,
405                                                      options->track_index,
406                                                      &libmv_reference_marker);
407                         }
408                         else {
409                                 libmv_tracked_marker.reference_frame = frame;
410                                 libmv_reference_marker = libmv_current_marker;
411                         }
412
413                         if (libmv_autoTrackMarker(context->autotrack,
414                                                   &options->track_region_options,
415                                                   &libmv_tracked_marker,
416                                                   &libmv_result))
417                         {
418                                 BLI_spin_lock(&context->spin_lock);
419                                 libmv_autoTrackAddMarker(context->autotrack,
420                                                          &libmv_tracked_marker);
421                                 BLI_spin_unlock(&context->spin_lock);
422                         }
423                         else {
424                                 options->is_failed = true;
425                                 options->failed_frame = frame;
426                         }
427                         ok = true;
428                 }
429         }
430
431         BLI_spin_lock(&context->spin_lock);
432         context->user.framenr += frame_delta;
433         BLI_spin_unlock(&context->spin_lock);
434
435         return ok;
436 }
437
438 void BKE_autotrack_context_sync(AutoTrackContext *context)
439 {
440         int newframe = context->user.framenr,
441             frame_delta = context->backwards ? -1 : 1;
442         int clip, frame;
443
444         BLI_spin_lock(&context->spin_lock);
445         for (frame = context->sync_frame;
446              frame != (context->backwards ? newframe - 1 : newframe + 1);
447              frame += frame_delta)
448         {
449                 MovieTrackingMarker marker;
450                 libmv_Marker libmv_marker;
451                 int clip = 0;
452                 int track;
453                 for (track = 0; track < context->num_tracks; ++track) {
454                         AutoTrackOptions *options = &context->options[track];
455                         int track_frame = BKE_movieclip_remap_scene_to_clip_frame(
456                                 context->clips[options->clip_index], frame);
457                         if (options->is_failed) {
458                                 if (options->failed_frame == track_frame) {
459                                         MovieTrackingMarker *prev_marker =
460                                                 BKE_tracking_marker_get_exact(
461                                                           options->track,
462                                                           frame);
463                                         if (prev_marker) {
464                                                 marker = *prev_marker;
465                                                 marker.framenr = context->backwards ?
466                                                                  track_frame - 1 :
467                                                                  track_frame + 1;
468                                                 marker.flag |= MARKER_DISABLED;
469                                                 BKE_tracking_marker_insert(options->track, &marker);
470                                         }
471                                 }
472                                 continue;
473                         }
474                         if (libmv_autoTrackGetMarker(context->autotrack,
475                                                      clip,
476                                                      track_frame,
477                                                      options->track_index,
478                                                      &libmv_marker))
479                         {
480                                 libmv_marker_to_dna_marker(&libmv_marker,
481                                                            context->frame_width,
482                                                            context->frame_height,
483                                                            &marker);
484                                 if (context->first_sync && frame == context->sync_frame) {
485                                         tracking_marker_insert_disabled(options->track,
486                                                                         &marker,
487                                                                         !context->backwards,
488                                                                         false);
489                                 }
490                                 BKE_tracking_marker_insert(options->track, &marker);
491                                 tracking_marker_insert_disabled(options->track,
492                                                                 &marker,
493                                                                 context->backwards,
494                                                                 false);
495                         }
496                 }
497         }
498         BLI_spin_unlock(&context->spin_lock);
499
500         for (clip = 0; clip < context->num_clips; ++clip) {
501                 MovieTracking *tracking = &context->clips[clip]->tracking;
502                 BKE_tracking_dopesheet_tag_update(tracking);
503         }
504
505         context->sync_frame = newframe;
506         context->first_sync = false;
507 }
508
509 void BKE_autotrack_context_sync_user(AutoTrackContext *context,
510                                      MovieClipUser *user)
511 {
512         user->framenr = context->sync_frame;
513 }
514
515 void BKE_autotrack_context_finish(AutoTrackContext *context)
516 {
517         int clip_index;
518
519         for (clip_index = 0; clip_index < context->num_clips; ++clip_index) {
520                 MovieClip *clip = context->clips[clip_index];
521                 ListBase *plane_tracks_base =
522                         BKE_tracking_get_active_plane_tracks(&clip->tracking);
523                 MovieTrackingPlaneTrack *plane_track;
524
525                 for (plane_track = plane_tracks_base->first;
526                      plane_track;
527                      plane_track = plane_track->next)
528                 {
529                         if ((plane_track->flag & PLANE_TRACK_AUTOKEY) == 0) {
530                                 int track;
531                                 for (track = 0; track < context->num_tracks; ++track) {
532                                         MovieTrackingTrack *old_track;
533                                         bool do_update = false;
534                                         int j;
535
536                                         old_track = context->options[track].track;
537                                         for (j = 0; j < plane_track->point_tracksnr; j++) {
538                                                 if (plane_track->point_tracks[j] == old_track) {
539                                                         do_update = true;
540                                                         break;
541                                                 }
542                                         }
543
544                                         if (do_update) {
545                                                 BKE_tracking_track_plane_from_existing_motion(
546                                                         plane_track,
547                                                         context->first_frame);
548                                                 break;
549                                         }
550                                 }
551                         }
552                 }
553         }
554 }
555
556 void BKE_autotrack_context_free(AutoTrackContext *context)
557 {
558         libmv_autoTrackDestroy(context->autotrack);
559         tracking_image_accessor_destroy(context->image_accessor);
560         MEM_freeN(context->options);
561         BLI_spin_end(&context->spin_lock);
562         MEM_freeN(context);
563 }