Cleanup: naming
[blender.git] / source / blender / blenkernel / intern / tracking_stabilize.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  *                 Ichthyostega
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file blender/blenkernel/intern/tracking_stabilize.c
30  *  \ingroup bke
31  *
32  * This file contains implementation of 2D image stabilization.
33  */
34
35 #include <limits.h>
36
37 #include "DNA_movieclip_types.h"
38 #include "DNA_scene_types.h"
39 #include "DNA_anim_types.h"
40 #include "RNA_access.h"
41
42 #include "BLI_utildefines.h"
43 #include "BLI_sort_utils.h"
44 #include "BLI_math_vector.h"
45 #include "BLI_math.h"
46
47 #include "BKE_tracking.h"
48 #include "BKE_movieclip.h"
49 #include "BKE_fcurve.h"
50 #include "BLI_ghash.h"
51
52 #include "MEM_guardedalloc.h"
53 #include "IMB_imbuf_types.h"
54 #include "IMB_imbuf.h"
55
56
57 /* == Parameterization constants == */
58
59 /* When measuring the scale changes relative to the rotation pivot point, it
60  * might happen accidentally that a probe point (tracking point), which doesn't
61  * actually move on a circular path, gets very close to the pivot point, causing
62  * the measured scale contribution to go toward infinity. We damp this undesired
63  * effect by adding a bias (floor) to the measured distances, which will
64  * dominate very small distances and thus cause the corresponding track's
65  * contribution to diminish.
66  * Measurements happen in normalized (0...1) coordinates within a frame.
67  */
68 static float SCALE_ERROR_LIMIT_BIAS = 0.01f;
69
70 /* When to consider a track as completely faded out.
71  * This is used in conjunction with the "disabled" flag of the track
72  * to determine start positions, end positions and gaps
73  */
74 static float EPSILON_WEIGHT = 0.005f;
75
76
77
78 /* == private working data == */
79
80 /* Per track baseline for stabilization, defined at reference frame.
81  * A track's reference frame is chosen as close as possible to the (global)
82  * anchor_frame. Baseline holds the constant part of each track's contribution
83  * to the observed movement; it is calculated at initialization pass, using the
84  * measurement value at reference frame plus the average contribution to fill
85  * the gap between global anchor_frame and the reference frame for this track.
86  * This struct with private working data is associated to the local call context
87  * via `StabContext::private_track_data`
88  */
89 typedef struct TrackStabilizationBase {
90         float stabilization_offset_base[2];
91
92         /* measured relative to translated pivot */
93         float stabilization_rotation_base[2][2];
94
95         /* measured relative to translated pivot */
96         float stabilization_scale_base;
97
98         bool is_init_for_stabilization;
99         FCurve *track_weight_curve;
100 } TrackStabilizationBase;
101
102 /* Tracks are reordered for initialization, starting as close as possible to
103  * anchor_frame
104  */
105 typedef struct TrackInitOrder {
106         int sort_value;
107         int reference_frame;
108         MovieTrackingTrack *data;
109 } TrackInitOrder;
110
111 /* Per frame private working data, for accessing possibly animated values. */
112 typedef struct StabContext {
113         MovieClip *clip;
114         MovieTracking *tracking;
115         MovieTrackingStabilization *stab;
116         GHash *private_track_data;
117         FCurve *locinf;
118         FCurve *rotinf;
119         FCurve *scaleinf;
120         FCurve *target_pos[2];
121         FCurve *target_rot;
122         FCurve *target_scale;
123         bool use_animation;
124 } StabContext;
125
126
127 static TrackStabilizationBase *access_stabilization_baseline_data(
128         StabContext *ctx,
129         MovieTrackingTrack *track)
130 {
131         return BLI_ghash_lookup(ctx->private_track_data, track);
132 }
133
134 static void attach_stabilization_baseline_data(
135         StabContext *ctx,
136         MovieTrackingTrack *track,
137         TrackStabilizationBase *private_data)
138 {
139         BLI_ghash_insert(ctx->private_track_data, track, private_data);
140 }
141
142 static void discard_stabilization_baseline_data(void *val)
143 {
144         if (val != NULL) {
145                 MEM_freeN(val);
146         }
147 }
148
149
150 /* == access animated values for given frame == */
151
152 static FCurve *retrieve_stab_animation(MovieClip *clip,
153                                        const char *data_path,
154                                        int idx)
155 {
156         return id_data_find_fcurve(&clip->id,
157                                    &clip->tracking.stabilization,
158                                    &RNA_MovieTrackingStabilization,
159                                    data_path,
160                                    idx,
161                                    NULL);
162 }
163
164 static FCurve *retrieve_track_weight_animation(MovieClip *clip,
165                                                MovieTrackingTrack *track)
166 {
167         return id_data_find_fcurve(&clip->id,
168                                    track,
169                                    &RNA_MovieTrackingTrack,
170                                    "weight_stab",
171                                    0,
172                                    NULL);
173 }
174
175 static float fetch_from_fcurve(FCurve *animationCurve,
176                                int framenr,
177                                StabContext *ctx,
178                                float default_value)
179 {
180         if (ctx && ctx->use_animation && animationCurve) {
181                 int scene_framenr = BKE_movieclip_remap_clip_to_scene_frame(ctx->clip,
182                                                                             framenr);
183                 return evaluate_fcurve(animationCurve, scene_framenr);
184         }
185         return default_value;
186 }
187
188
189 static float get_animated_locinf(StabContext *ctx, int framenr)
190 {
191         return fetch_from_fcurve(ctx->locinf, framenr, ctx, ctx->stab->locinf);
192 }
193
194 static float get_animated_rotinf(StabContext *ctx, int framenr)
195 {
196         return fetch_from_fcurve(ctx->rotinf, framenr, ctx, ctx->stab->rotinf);
197 }
198
199 static float get_animated_scaleinf(StabContext *ctx, int framenr)
200 {
201         return fetch_from_fcurve(ctx->scaleinf, framenr, ctx, ctx->stab->scaleinf);
202 }
203
204 static void get_animated_target_pos(StabContext *ctx,
205                                     int framenr,
206                                     float target_pos[2])
207 {
208         target_pos[0] = fetch_from_fcurve(ctx->target_pos[0],
209                                           framenr,
210                                           ctx,
211                                           ctx->stab->target_pos[0]);
212         target_pos[1] = fetch_from_fcurve(ctx->target_pos[1],
213                                           framenr,
214                                           ctx,
215                                           ctx->stab->target_pos[1]);
216 }
217
218 static float get_animated_target_rot(StabContext *ctx, int framenr)
219 {
220         return fetch_from_fcurve(ctx->target_rot,
221                                  framenr,
222                                  ctx,
223                                  ctx->stab->target_rot);
224 }
225
226 static float get_animated_target_scale(StabContext *ctx, int framenr)
227 {
228         return fetch_from_fcurve(ctx->target_scale, framenr, ctx, ctx->stab->scale);
229 }
230
231 static float get_animated_weight(StabContext *ctx,
232                                  MovieTrackingTrack *track,
233                                  int framenr)
234 {
235         TrackStabilizationBase *working_data =
236                 access_stabilization_baseline_data(ctx, track);
237         if (working_data && working_data->track_weight_curve) {
238                 int scene_framenr = BKE_movieclip_remap_clip_to_scene_frame(ctx->clip,
239                                                                             framenr);
240                 return evaluate_fcurve(working_data->track_weight_curve, scene_framenr);
241         }
242         /* Use weight at global 'current frame' as fallback default. */
243         return track->weight_stab;
244 }
245
246 static void use_values_from_fcurves(StabContext *ctx, bool toggle)
247 {
248         if (ctx != NULL) {
249                 ctx->use_animation = toggle;
250         }
251 }
252
253
254 /* Prepare per call private working area.
255  * Used for access to possibly animated values: retrieve available F-curves.
256  */
257 static StabContext *initialize_stabilization_working_context(MovieClip *clip)
258 {
259         StabContext *ctx = MEM_callocN(sizeof(StabContext),
260                                        "2D stabilization animation runtime data");
261         ctx->clip = clip;
262         ctx->tracking = &clip->tracking;
263         ctx->stab = &clip->tracking.stabilization;
264         ctx->private_track_data = BLI_ghash_ptr_new(
265                  "2D stabilization per track private working data");
266         ctx->locinf        = retrieve_stab_animation(clip, "influence_location", 0);
267         ctx->rotinf        = retrieve_stab_animation(clip, "influence_rotation", 0);
268         ctx->scaleinf      = retrieve_stab_animation(clip, "influence_scale", 0);
269         ctx->target_pos[0] = retrieve_stab_animation(clip, "target_pos", 0);
270         ctx->target_pos[1] = retrieve_stab_animation(clip, "target_pos", 1);
271         ctx->target_rot    = retrieve_stab_animation(clip, "target_rot", 0);
272         ctx->target_scale  = retrieve_stab_animation(clip, "target_zoom", 0);
273         ctx->use_animation = true;
274         return ctx;
275 }
276
277 /* Discard all private working data attached to this call context.
278  * NOTE: We allocate the record for the per track baseline contribution
279  *       locally for each call context (i.e. call to
280  *       BKE_tracking_stabilization_data_get()
281  *       Thus it is correct to discard all allocations found within the
282  *       corresponding _local_ GHash
283  */
284 static void discard_stabilization_working_context(StabContext *ctx)
285 {
286         if (ctx != NULL) {
287                 BLI_ghash_free(ctx->private_track_data,
288                                NULL,
289                                discard_stabilization_baseline_data);
290                 MEM_freeN(ctx);
291         }
292 }
293
294 static bool is_init_for_stabilization(StabContext *ctx,
295                                       MovieTrackingTrack *track)
296 {
297         TrackStabilizationBase *working_data =
298                 access_stabilization_baseline_data(ctx, track);
299         return (working_data != NULL && working_data->is_init_for_stabilization);
300 }
301
302 static bool is_usable_for_stabilization(StabContext *ctx,
303                                         MovieTrackingTrack *track)
304 {
305         return (track->flag & TRACK_USE_2D_STAB) &&
306                is_init_for_stabilization(ctx, track);
307 }
308
309 static bool is_effectively_disabled(StabContext *ctx,
310                                     MovieTrackingTrack *track,
311                                     MovieTrackingMarker *marker)
312 {
313         return (marker->flag & MARKER_DISABLED) ||
314                (EPSILON_WEIGHT > get_animated_weight(ctx, track, marker->framenr));
315 }
316
317
318 static int search_closest_marker_index(MovieTrackingTrack *track,
319                                        int ref_frame)
320 {
321         MovieTrackingMarker *markers = track->markers;
322         int end = track->markersnr;
323         int i = track->last_marker;
324
325         i = MAX2(0, i);
326         i = MIN2(i, end - 1);
327         for ( ; i < end - 1 && markers[i].framenr <= ref_frame; ++i);
328         for ( ; 0 < i && markers[i].framenr > ref_frame; --i);
329
330         track->last_marker = i;
331         return i;
332 }
333
334 static void retrieve_next_higher_usable_frame(StabContext *ctx,
335                                               MovieTrackingTrack *track,
336                                               int i,
337                                               int ref_frame,
338                                               int *next_higher)
339 {
340         MovieTrackingMarker *markers = track->markers;
341         int end = track->markersnr;
342         BLI_assert(0 <= i && i < end);
343
344         while (i < end &&
345                (markers[i].framenr < ref_frame ||
346                 is_effectively_disabled(ctx, track, &markers[i])))
347         {
348                 ++i;
349         }
350         if (i < end && markers[i].framenr < *next_higher) {
351                 BLI_assert(markers[i].framenr >= ref_frame);
352                 *next_higher = markers[i].framenr;
353         }
354 }
355
356 static void retrieve_next_lower_usable_frame(StabContext *ctx,
357                                              MovieTrackingTrack *track,
358                                              int i,
359                                              int ref_frame,
360                                              int *next_lower)
361 {
362         MovieTrackingMarker *markers = track->markers;
363         BLI_assert(0 <= i && i < track->markersnr);
364         while (i >= 0 &&
365                (markers[i].framenr > ref_frame ||
366                 is_effectively_disabled(ctx, track, &markers[i])))
367         {
368                 --i;
369         }
370         if (0 <= i && markers[i].framenr > *next_lower) {
371                 BLI_assert(markers[i].framenr <= ref_frame);
372                 *next_lower = markers[i].framenr;
373         }
374 }
375
376 /* Find closest frames with usable stabilization data.
377  * A frame counts as _usable_ when there is at least one track marked for
378  * translation stabilization, which has an enabled tracking marker at this very
379  * frame. We search both for the next lower and next higher position, to allow
380  * the caller to interpolate gaps and to extrapolate at the ends of the
381  * definition range.
382  *
383  * NOTE: Regarding performance note that the individual tracks will cache the
384  *       last search position.
385  */
386 static void find_next_working_frames(StabContext *ctx,
387                                      int framenr,
388                                      int *next_lower,
389                                      int *next_higher)
390 {
391         for (MovieTrackingTrack *track = ctx->tracking->tracks.first;
392              track != NULL;
393              track = track->next)
394         {
395                 if (is_usable_for_stabilization(ctx, track)) {
396                         int startpoint = search_closest_marker_index(track, framenr);
397                         retrieve_next_higher_usable_frame(ctx,
398                                                           track,
399                                                           startpoint,
400                                                           framenr,
401                                                           next_higher);
402                         retrieve_next_lower_usable_frame(ctx,
403                                                          track,
404                                                          startpoint,
405                                                          framenr,
406                                                          next_lower);
407                 }
408         }
409 }
410
411
412 /* Find active (enabled) marker closest to the reference frame. */
413 static MovieTrackingMarker *get_closest_marker(StabContext *ctx,
414                                                MovieTrackingTrack *track,
415                                                int ref_frame)
416 {
417         int next_lower = MINAFRAME;
418         int next_higher = MAXFRAME;
419         int i = search_closest_marker_index(track, ref_frame);
420         retrieve_next_higher_usable_frame(ctx, track, i, ref_frame, &next_higher);
421         retrieve_next_lower_usable_frame(ctx, track, i, ref_frame, &next_lower);
422
423         if ((next_higher - ref_frame) < (ref_frame - next_lower)) {
424                 return BKE_tracking_marker_get_exact(track, next_higher);
425         }
426         else {
427                 return BKE_tracking_marker_get_exact(track, next_lower);
428         }
429 }
430
431
432 /* Retrieve tracking data, if available and applicable for this frame.
433  * The returned weight value signals the validity; data recorded for this
434  * tracking marker on the exact requested frame is output with the full weight
435  * of this track, while gaps in the data sequence cause the weight to go to zero.
436  */
437 static MovieTrackingMarker *get_tracking_data_point(
438         StabContext *ctx,
439         MovieTrackingTrack *track,
440         int framenr,
441         float *r_weight)
442 {
443         MovieTrackingMarker *marker = BKE_tracking_marker_get_exact(track, framenr);
444         if (marker != NULL && !(marker->flag & MARKER_DISABLED)) {
445                 *r_weight = get_animated_weight(ctx, track, framenr);
446                 return marker;
447         }
448         else {
449                 /* No marker at this frame (=gap) or marker disabled. */
450                 *r_weight = 0.0f;
451                 return NULL;
452         }
453 }
454
455
456 /* Define the reference point for rotation/scale measurement and compensation.
457  * The stabilizator works by assuming the image was distorted by a affine linear
458  * transform, i.e. it was rotated and stretched around this reference point
459  * (pivot point) and then shifted laterally. Any scale and orientation changes
460  * will be picked up relative to this point. And later the image will be
461  * stabilized by rotating around this point. The result can only be as
462  * accurate as this pivot point actually matches the real rotation center
463  * of the actual movements. Thus any scheme to define a pivot point is
464  * always guesswork.
465  *
466  * As a simple default, we use the weighted average of the location markers
467  * of the current frame as pivot point. TODO It is planned to add further
468  * options,  like e.g. anchoring the pivot point at the canvas. Moreover,
469  * it is planned to allow for a user controllable offset.
470  */
471 static void setup_pivot(const float ref_pos[2], float r_pivot[2])
472 {
473         zero_v2(r_pivot);  /* TODO: add an animated offset position here. */
474         add_v2_v2(r_pivot, ref_pos);
475 }
476
477
478 /* Calculate the contribution of a single track at the time position (frame) of
479  * the given marker. Each track has a local reference frame, which is as close
480  * as possible to the global anchor_frame. Thus the translation contribution is
481  * comprised of the offset relative to the image position at that reference
482  * frame, plus a guess of the contribution for the time span between the
483  * anchor_frame and the local reference frame of this track. The constant part
484  * of this contribution is precomputed initially. At the anchor_frame, by
485  * definition the contribution of all tracks is zero, keeping the frame in place.
486  *
487  * track_ref is per track baseline contribution at reference frame; filled in at
488  *           initialization
489  * marker is tracking data to use as contribution for current frame.
490  * result_offset is a total cumulated contribution of this track,
491  *               relative to the stabilization anchor_frame,
492  *               in normalized (0...1) coordinates.
493  */
494 static void translation_contribution(TrackStabilizationBase *track_ref,
495                                      MovieTrackingMarker *marker,
496                                      float result_offset[2])
497 {
498         add_v2_v2v2(result_offset,
499                     track_ref->stabilization_offset_base,
500                     marker->pos);
501 }
502
503 /* Similar to the ::translation_contribution(), the rotation contribution is
504  * comprised of the contribution by this individual track, and the averaged
505  * contribution from anchor_frame to the ref point of this track.
506  * - Contribution is in terms of angles, -pi < angle < +pi, and all averaging
507  *   happens in this domain.
508  * - Yet the actual measurement happens as vector between pivot and the current
509  *   tracking point
510  * - Currently we use the center of frame as approximation for the rotation pivot
511  *   point.
512  * - Moreover, the pivot point has to be compensated for the already determined
513  *   shift offset, in order to get the pure rotation around the pivot.
514  *   To turn this into a _contribution_, the likewise corrected angle at the
515  *   reference frame has to be subtracted, to get only the pure angle difference
516  *   this tracking point has captured.
517  * - To get from vectors to angles, we have to go through an arcus tangens,
518  *   which involves the issue of the definition range: the resulting angles will
519  *   flip by 360deg when the measured vector passes from the 2nd to the third
520  *   quadrant, thus messing up the average calculation. Since _any_ tracking
521  *   point might be used, these problems are quite common in practice.
522  * - Thus we perform the subtraction of the reference and the addition of the
523  *   baseline contribution in polar coordinates as simple addition of angles;
524  *   since these parts are fixed, we can bake them into a rotation matrix.
525  *   With this approach, the border of the arcus tangens definition range will
526  *   be reached only, when the _whole_ contribution approaches +- 180deg,
527  *   meaning we've already tilted the frame upside down. This situation is way
528  *   less common and can be tolerated.
529  * - As an additional feature, when activated, also changes in image scale
530  *   relative to the rotation center can be picked up. To handle those values
531  *   in the same framework, we average the scales as logarithms.
532  *
533  * aspect is a total aspect ratio of the undistorted image (includes fame and
534  * pixel aspect). The function returns a quality factor, which can be used
535  * to damp the contributions of points in close proximity to the pivot point,
536  * since such contributions might be dominated by rounding errors and thus
537  * poison the calculated average. When the quality factor goes towards zero,
538  * the weight of this contribution should be reduced accordingly.
539  */
540 static float rotation_contribution(TrackStabilizationBase *track_ref,
541                                    MovieTrackingMarker *marker,
542                                    const float aspect,
543                                    const float pivot[2],
544                                    float *result_angle,
545                                    float *result_scale)
546 {
547         float len, quality;
548         float pos[2];
549         sub_v2_v2v2(pos, marker->pos, pivot);
550
551         pos[0] *= aspect;
552         mul_m2v2(track_ref->stabilization_rotation_base, pos);
553
554         *result_angle = atan2f(pos[1],pos[0]);
555
556         len = len_v2(pos);
557
558         /* prevent points very close to the pivot point from poisoning the result */
559         quality = 1 - expf(-len*len / SCALE_ERROR_LIMIT_BIAS*SCALE_ERROR_LIMIT_BIAS);
560         len += SCALE_ERROR_LIMIT_BIAS;
561
562         *result_scale = len * track_ref->stabilization_scale_base;
563         BLI_assert(0.0 < *result_scale);
564
565         return quality;
566 }
567
568
569 /* Workaround to allow for rotation around an arbitrary pivot point.
570  * Currently, the public API functions do not support this flexibility.
571  * Rather, rotation will always be applied around a fixed origin.
572  * As a workaround, we shift the image after rotation to match the
573  * desired rotation centre. And since this offset needs to be applied
574  * after the rotation and scaling, we can collapse it with the
575  * translation compensation, which is also a lateral shift (offset).
576  * The offset to apply is intended_pivot - rotated_pivot
577  */
578 static void compensate_rotation_center(const int size, float aspect,
579                                        const float angle,
580                                        const float scale,
581                                        const float pivot[2],
582                                        float result_translation[2])
583 {
584         const float origin[2]  = {0.5f*aspect*size, 0.5f*size};
585         float intended_pivot[2], rotated_pivot[2];
586         float rotation_mat[2][2];
587
588         copy_v2_v2(intended_pivot, pivot);
589         copy_v2_v2(rotated_pivot, pivot);
590         angle_to_mat2(rotation_mat, +angle);
591         sub_v2_v2(rotated_pivot, origin);
592         mul_m2v2(rotation_mat, rotated_pivot);
593         mul_v2_fl(rotated_pivot, scale);
594         add_v2_v2(rotated_pivot, origin);
595         add_v2_v2(result_translation, intended_pivot);
596         sub_v2_v2(result_translation, rotated_pivot);
597 }
598
599
600 /* Weighted average of the per track cumulated contributions at given frame.
601  * Returns truth if all desired calculations could be done and all averages are
602  * available.
603  *
604  * NOTE: Even if the result is not `true`, the returned translation and angle
605  *       are always sensible and as good as can be. Especially in the
606  *       initialization phase we might not be able to get any average (yet) or
607  *       get only a translation value. Since initialization visits tracks in a
608  *       specific order, starting from anchor_frame, the result is logically
609  *       correct non the less. But under normal operation conditions,
610  *       a result of `false` should disable the stabilization function
611  */
612 static bool average_track_contributions(StabContext *ctx,
613                                         int framenr,
614                                         float aspect,
615                                         float r_translation[2],
616                                         float r_pivot[2],
617                                         float *r_angle,
618                                         float *r_scale_step)
619 {
620         bool ok;
621         float weight_sum;
622         MovieTrackingTrack *track;
623         MovieTracking *tracking = ctx->tracking;
624         MovieTrackingStabilization *stab = &tracking->stabilization;
625         float ref_pos[2];
626         BLI_assert(stab->flag & TRACKING_2D_STABILIZATION);
627
628         zero_v2(r_translation);
629         *r_scale_step = 0.0f;  /* logarithm */
630         *r_angle = 0.0f;
631
632         zero_v2(ref_pos);
633
634         ok = false;
635         weight_sum = 0.0f;
636         for (track = tracking->tracks.first; track; track = track->next) {
637                 if (!is_init_for_stabilization(ctx, track)) {
638                         continue;
639                 }
640                 if (track->flag & TRACK_USE_2D_STAB) {
641                         float weight = 0.0f;
642                         MovieTrackingMarker *marker = get_tracking_data_point(ctx,
643                                                                               track,
644                                                                               framenr,
645                                                                               &weight);
646                         if (marker) {
647                                 TrackStabilizationBase *stabilization_base =
648                                        access_stabilization_baseline_data(ctx, track);
649                                 BLI_assert(stabilization_base != NULL);
650                                 float offset[2];
651                                 weight_sum += weight;
652                                 translation_contribution(stabilization_base, marker, offset);
653                                 r_translation[0] += weight * offset[0];
654                                 r_translation[1] += weight * offset[1];
655                                 ref_pos[0] += weight * marker->pos[0];
656                                 ref_pos[1] += weight * marker->pos[1];
657                                 ok |= (weight_sum > EPSILON_WEIGHT);
658                         }
659                 }
660         }
661         if (!ok) {
662                 return false;
663         }
664
665         ref_pos[0] /= weight_sum;
666         ref_pos[1] /= weight_sum;
667         r_translation[0] /= weight_sum;
668         r_translation[1] /= weight_sum;
669         setup_pivot(ref_pos, r_pivot);
670
671         if (!(stab->flag & TRACKING_STABILIZE_ROTATION)) {
672                 return ok;
673         }
674
675         ok = false;
676         weight_sum = 0.0f;
677         for (track = tracking->tracks.first; track; track = track->next) {
678                 if (!is_init_for_stabilization(ctx, track)) {
679                         continue;
680                 }
681                 if (track->flag & TRACK_USE_2D_STAB_ROT) {
682                         float weight = 0.0f;
683                         MovieTrackingMarker *marker = get_tracking_data_point(ctx,
684                                                                               track,
685                                                                               framenr,
686                                                                               &weight);
687                         if (marker) {
688                                 TrackStabilizationBase *stabilization_base =
689                                         access_stabilization_baseline_data(ctx, track);
690                                 BLI_assert(stabilization_base != NULL);
691                                 float rotation, scale, quality;
692                                 quality = rotation_contribution(stabilization_base,
693                                                                 marker,
694                                                                 aspect,
695                                                                 r_pivot,
696                                                                 &rotation,
697                                                                 &scale);
698                                 weight *= quality;
699                                 weight_sum += weight;
700                                 *r_angle += rotation * weight;
701                                 if (stab->flag & TRACKING_STABILIZE_SCALE) {
702                                         *r_scale_step += logf(scale) * weight;
703                                 }
704                                 else {
705                                         *r_scale_step = 0;
706                                 }
707                                 ok |= (weight_sum > EPSILON_WEIGHT);
708                         }
709                 }
710         }
711         if (ok) {
712                 *r_scale_step /= weight_sum;
713                 *r_angle /= weight_sum;
714         }
715         else {
716                 /* We reach this point because translation could be calculated,
717                  * but rotation/scale found no data to work on.
718                  */
719                 *r_scale_step = 0.0f;
720                 *r_angle = 0.0f;
721         }
722         return true;
723 }
724
725
726 /* Calculate weight center of location tracks for given frame.
727  * This function performs similar calculations as average_track_contributions(),
728  * but does not require the tracks to be initialized for stabilisation. Moreover,
729  * when there is no usable tracking data for the given frame number, data from
730  * a neighbouring frame is used. Thus this function can be used to calculate
731  * a starting point on initialization.
732  */
733 static void average_marker_positions(StabContext *ctx, int framenr, float r_ref_pos[2])
734 {
735         bool ok = false;
736         float weight_sum;
737         MovieTrackingTrack *track;
738         MovieTracking *tracking = ctx->tracking;
739
740         zero_v2(r_ref_pos);
741         weight_sum = 0.0f;
742         for (track = tracking->tracks.first; track; track = track->next) {
743                 if (track->flag & TRACK_USE_2D_STAB) {
744                         float weight = 0.0f;
745                         MovieTrackingMarker *marker =
746                                 get_tracking_data_point(ctx, track, framenr, &weight);
747                         if (marker) {
748                                 weight_sum += weight;
749                                 r_ref_pos[0] += weight * marker->pos[0];
750                                 r_ref_pos[1] += weight * marker->pos[1];
751                                 ok |= (weight_sum > EPSILON_WEIGHT);
752                         }
753                 }
754         }
755         if (ok) {
756                 r_ref_pos[0] /= weight_sum;
757                 r_ref_pos[1] /= weight_sum;
758         }
759         else {
760                 /* No usable tracking data on any track on this frame.
761                  * Use data from neighbouring frames to extrapolate...
762                  */
763                 int next_lower = MINAFRAME;
764                 int next_higher = MAXFRAME;
765                 use_values_from_fcurves(ctx, true);
766                 for (track = tracking->tracks.first; track; track = track->next) {
767                         /* Note: we deliberately do not care if this track
768                          *       is already initialized for stabilisation */
769                         if (track->flag & TRACK_USE_2D_STAB) {
770                                 int startpoint = search_closest_marker_index(track, framenr);
771                                 retrieve_next_higher_usable_frame(ctx,
772                                                                   track,
773                                                                   startpoint,
774                                                                   framenr,
775                                                                   &next_higher);
776                                 retrieve_next_lower_usable_frame(ctx,
777                                                                  track,
778                                                                  startpoint,
779                                                                  framenr,
780                                                                  &next_lower);
781                         }
782                 }
783                 if (next_lower >= MINFRAME) {
784                         /* use next usable frame to the left.
785                          * Also default to this frame when we're in a gap */
786                         average_marker_positions(ctx, next_lower, r_ref_pos);
787
788                 }
789                 else if (next_higher < MAXFRAME) {
790                         average_marker_positions(ctx, next_higher, r_ref_pos);
791                 }
792                 use_values_from_fcurves(ctx, false);
793         }
794 }
795
796
797 /* Linear interpolation of data retrieved at two measurement points.
798  * This function is used to fill gaps in the middle of the covered area,
799  * at frames without any usable tracks for stabilization.
800  *
801  * framenr is a position to interpolate for.
802  * frame_a is a valid measurement point below framenr
803  * frame_b is a valid measurement point above framenr
804  * Returns truth if both measurements could actually be retrieved.
805  * Otherwise output parameters remain unaltered
806  */
807 static bool interpolate_averaged_track_contributions(StabContext *ctx,
808                                                      int framenr,
809                                                      int frame_a,
810                                                      int frame_b,
811                                                      const float aspect,
812                                                      float r_translation[2],
813                                                      float r_pivot[2],
814                                                      float *r_angle,
815                                                      float *r_scale_step)
816 {
817         float t, s;
818         float trans_a[2], trans_b[2];
819         float angle_a, angle_b;
820         float scale_a, scale_b;
821         float pivot_a[2], pivot_b[2];
822         bool success = false;
823
824         BLI_assert(frame_a <= frame_b);
825         BLI_assert(frame_a <= framenr);
826         BLI_assert(framenr <= frame_b);
827
828         t = ((float)framenr - frame_a) / (frame_b - frame_a);
829         s = 1.0f - t;
830
831         success = average_track_contributions(ctx, frame_a, aspect, trans_a, pivot_a, &angle_a, &scale_a);
832         if (!success) {
833                 return false;
834         }
835         success = average_track_contributions(ctx, frame_b, aspect, trans_b, pivot_b, &angle_b, &scale_b);
836         if (!success) {
837                 return false;
838         }
839
840         interp_v2_v2v2(r_translation, trans_a, trans_b, t);
841         interp_v2_v2v2(r_pivot, pivot_a, pivot_b, t);
842         *r_scale_step = s * scale_a + t * scale_b;
843         *r_angle = s * angle_a + t * angle_b;
844         return true;
845 }
846
847
848 /* Reorder tracks starting with those providing a tracking data frame
849  * closest to the global anchor_frame. Tracks with a gap at anchor_frame or
850  * starting farer away from anchor_frame altogether will be visited later.
851  * This allows to build up baseline contributions incrementally.
852  *
853  * order is an array for sorting the tracks. Must be of suitable size to hold
854  * all tracks.
855  * Returns number of actually usable tracks, can be less than the overall number
856  * of tracks.
857  *
858  * NOTE: After returning, the order array holds entries up to the number of
859  *       usable tracks, appropriately sorted starting with the closest tracks.
860  *       Initialization includes disabled tracks, since they might be enabled
861  *       through automation later.
862  */
863 static int establish_track_initialization_order(StabContext *ctx,
864                                                 TrackInitOrder *order)
865 {
866         size_t tracknr = 0;
867         MovieTrackingTrack *track;
868         MovieTracking *tracking = ctx->tracking;
869         int anchor_frame = tracking->stabilization.anchor_frame;
870
871         for (track = tracking->tracks.first; track != NULL; track = track->next) {
872                 MovieTrackingMarker *marker;
873                 order[tracknr].data = track;
874                 marker = get_closest_marker(ctx, track, anchor_frame);
875                 if (marker != NULL &&
876                         (track->flag & (TRACK_USE_2D_STAB | TRACK_USE_2D_STAB_ROT)))
877                 {
878                         order[tracknr].sort_value = abs(marker->framenr - anchor_frame);
879                         order[tracknr].reference_frame = marker->framenr;
880                         ++tracknr;
881                 }
882         }
883         if (tracknr) {
884                 qsort(order, tracknr, sizeof(TrackInitOrder), BLI_sortutil_cmp_int);
885         }
886         return tracknr;
887 }
888
889
890 /* Setup the constant part of this track's contribution to the determined frame
891  * movement. Tracks usually don't provide tracking data for every frame. Thus,
892  * for determining data at a given frame, we split up the contribution into a
893  * part covered by actual measurements on this track, and the initial gap
894  * between this track's reference frame and the global anchor_frame.
895  * The (missing) data for the gap can be substituted by the average offset
896  * observed by the other tracks covering the gap. This approximation doesn't
897  * introduce wrong data, but it records data with incorrect weight. A totally
898  * correct solution would require us to average the contribution per frame, and
899  * then integrate stepwise over all frames -- which of course would be way more
900  * expensive, especially for longer clips. To the contrary, our solution
901  * cumulates the total contribution per track and averages afterwards over all
902  * tracks; it can thus be calculated just based on the data of a single frame,
903  * plus the "baseline" for the reference frame, which is what we are computing
904  * here.
905  *
906  * Since we're averaging _contributions_, we have to calculate the _difference_
907  * of the measured position at current frame and the position at the reference
908  * frame. But the "reference" part of this difference is constant and can thus
909  * be packed together with the baseline contribution into a single precomputed
910  * vector per track.
911  *
912  * In case of the rotation contribution, the principle is the same, but we have
913  * to compensate for the already determined translation and measure the pure
914  * rotation, simply because this is how we model the offset: shift plus rotation
915  * around the shifted rotation center. To circumvent problems with the
916  * definition range of the arcus tangens function, we perform this baseline
917  * addition and reference angle subtraction in polar coordinates and bake this
918  * operation into a precomputed rotation matrix.
919  *
920  * track is a track to be initialized to initialize
921  * reference_frame is a local frame for this track, the closest pick to the
922  *                 global anchor_frame.
923  * aspect is a total aspect ratio of the undistorted image (includes fame and
924  *        pixel aspect).
925  * target_pos is a possibly animated target position as set by the user for
926  *            the reference_frame
927  * average_translation is a value observed by the _other_ tracks for the gap
928  *                     between reference_frame and anchor_frame. This
929  *                     average must not contain contributions of frames
930  *                     not yet initialized
931  * average_angle in a similar way, the rotation value observed by the
932  *               _other_ tracks.
933  * average_scale_step is an image scale factor observed on average by the other
934  *                    tracks for this frame. This value is recorded and
935  *                    averaged as logarithm. The recorded scale changes
936  *                    are damped for very small contributions, to limit
937  *                    the effect of probe points approaching the pivot
938  *                    too closely.
939  *
940  * NOTE: when done, this track is marked as initialized
941  */
942 static void initialize_track_for_stabilization(StabContext *ctx,
943                                                MovieTrackingTrack *track,
944                                                int reference_frame,
945                                                float aspect,
946                                                const float average_translation[2],
947                                                const float pivot[2],
948                                                const float average_angle,
949                                                const float average_scale_step)
950 {
951         float pos[2], angle, len;
952         TrackStabilizationBase *local_data =
953                 access_stabilization_baseline_data(ctx, track);
954         MovieTrackingMarker *marker =
955                 BKE_tracking_marker_get_exact(track, reference_frame);
956         /* Logic for initialization order ensures there *is* a marker on that
957          * very frame.
958          */
959         BLI_assert(marker != NULL);
960         BLI_assert(local_data != NULL);
961
962         /* Per track baseline value for translation. */
963         sub_v2_v2v2(local_data->stabilization_offset_base,
964                     average_translation,
965                     marker->pos);
966
967         /* Per track baseline value for rotation. */
968         sub_v2_v2v2(pos, marker->pos, pivot);
969
970         pos[0] *= aspect;
971         angle = average_angle - atan2f(pos[1],pos[0]);
972         angle_to_mat2(local_data->stabilization_rotation_base, angle);
973
974         /* Per track baseline value for zoom. */
975         len = len_v2(pos) + SCALE_ERROR_LIMIT_BIAS;
976         local_data->stabilization_scale_base = expf(average_scale_step) / len;
977
978         local_data->is_init_for_stabilization = true;
979 }
980
981
982 static void initialize_all_tracks(StabContext *ctx, float aspect)
983 {
984         size_t i, track_cnt = 0;
985         MovieClip *clip = ctx->clip;
986         MovieTracking *tracking = ctx->tracking;
987         MovieTrackingTrack *track;
988         TrackInitOrder *order;
989
990         /* Attempt to start initialization at anchor_frame.
991          * By definition, offset contribution is zero there.
992          */
993         int reference_frame = tracking->stabilization.anchor_frame;
994         float average_angle=0, average_scale_step=0;
995         float average_translation[2], average_pos[2], pivot[2];
996         zero_v2(average_translation);
997         zero_v2(pivot);
998
999         /* Initialize private working data. */
1000         for (track = tracking->tracks.first; track != NULL; track = track->next) {
1001                 TrackStabilizationBase *local_data =
1002                         access_stabilization_baseline_data(ctx, track);
1003                 if (!local_data) {
1004                         local_data = MEM_callocN(sizeof(TrackStabilizationBase),
1005                                                  "2D stabilization per track baseline data");
1006                         attach_stabilization_baseline_data(ctx, track, local_data);
1007                 }
1008                 BLI_assert(local_data != NULL);
1009                 local_data->track_weight_curve = retrieve_track_weight_animation(clip,
1010                                                                                  track);
1011                 local_data->is_init_for_stabilization = false;
1012
1013                 ++track_cnt;
1014         }
1015         if (!track_cnt) {
1016                 return;
1017         }
1018
1019         order = MEM_mallocN(track_cnt * sizeof(TrackInitOrder),
1020                             "stabilization track order");
1021         if (!order) {
1022                 return;
1023         }
1024
1025         track_cnt = establish_track_initialization_order(ctx, order);
1026         if (track_cnt == 0) {
1027                 goto cleanup;
1028         }
1029
1030         /* starting point for pivot, before having initialized any track */
1031         average_marker_positions(ctx, reference_frame, average_pos);
1032         setup_pivot(average_pos, pivot);
1033
1034         for (i = 0; i < track_cnt; ++i) {
1035                 track = order[i].data;
1036                 if (reference_frame != order[i].reference_frame) {
1037                         reference_frame = order[i].reference_frame;
1038                         average_track_contributions(ctx,
1039                                                     reference_frame,
1040                                                     aspect,
1041                                                     average_translation,
1042                                                     pivot,
1043                                                     &average_angle,
1044                                                     &average_scale_step);
1045                 }
1046                 initialize_track_for_stabilization(ctx,
1047                                                    track,
1048                                                    reference_frame,
1049                                                    aspect,
1050                                                    average_translation,
1051                                                    pivot,
1052                                                    average_angle,
1053                                                    average_scale_step);
1054         }
1055
1056 cleanup:
1057         MEM_freeN(order);
1058 }
1059
1060
1061 /* Retrieve the measurement of frame movement by averaging contributions of
1062  * active tracks.
1063  *
1064  * translation is a measurement in normalized 0..1 coordinates.
1065  * angle is a measurement in radians -pi..+pi counter clockwise relative to
1066  *       translation compensated frame center
1067  * scale_step is a measurement of image scale changes, in logarithmic scale
1068  *            (zero means scale == 1)
1069  * Returns calculation enabled and all data retrieved as expected for this frame.
1070  *
1071  * NOTE: when returning `false`, output parameters are reset to neutral values.
1072  */
1073 static bool stabilization_determine_offset_for_frame(StabContext *ctx,
1074                                                      int framenr,
1075                                                      float aspect,
1076                                                      float r_translation[2],
1077                                                      float r_pivot[2],
1078                                                      float *r_angle,
1079                                                      float *r_scale_step)
1080 {
1081         bool success = false;
1082
1083         /* Early output if stabilization is disabled. */
1084         if ((ctx->stab->flag & TRACKING_2D_STABILIZATION) == 0) {
1085                 zero_v2(r_translation);
1086                 *r_scale_step = 0.0f;
1087                 *r_angle = 0.0f;
1088                 return false;
1089         }
1090
1091         success = average_track_contributions(ctx,
1092                                               framenr,
1093                                               aspect,
1094                                               r_translation,
1095                                               r_pivot,
1096                                               r_angle,
1097                                               r_scale_step);
1098         if (!success) {
1099                 /* Try to hold extrapolated settings beyond the definition range
1100                  * and to interpolate in gaps without any usable tracking data
1101                  * to prevent sudden jump to image zero position.
1102                  */
1103                 int next_lower = MINAFRAME;
1104                 int next_higher = MAXFRAME;
1105                 use_values_from_fcurves(ctx, true);
1106                 find_next_working_frames(ctx, framenr, &next_lower, &next_higher);
1107                 if (next_lower >= MINFRAME && next_higher < MAXFRAME) {
1108                         success = interpolate_averaged_track_contributions(ctx,
1109                                                                            framenr,
1110                                                                            next_lower,
1111                                                                            next_higher,
1112                                                                            aspect,
1113                                                                            r_translation,
1114                                                                            r_pivot,
1115                                                                            r_angle,
1116                                                                            r_scale_step);
1117                 }
1118                 else if (next_higher < MAXFRAME) {
1119                         /* Before start of stabilized range: extrapolate start point
1120                          * settings.
1121                          */
1122                         success = average_track_contributions(ctx,
1123                                                               next_higher,
1124                                                               aspect,
1125                                                               r_translation,
1126                                                               r_pivot,
1127                                                               r_angle,
1128                                                               r_scale_step);
1129                 }
1130                 else if (next_lower >= MINFRAME) {
1131                         /* After end of stabilized range: extrapolate end point settings. */
1132                         success = average_track_contributions(ctx,
1133                                                               next_lower,
1134                                                               aspect,
1135                                                               r_translation,
1136                                                               r_pivot,
1137                                                               r_angle,
1138                                                               r_scale_step);
1139                 }
1140                 use_values_from_fcurves(ctx, false);
1141         }
1142         return success;
1143 }
1144
1145 /* Calculate stabilization data (translation, scale and rotation) from given raw
1146  * measurements. Result is in absolute image dimensions (expanded image, square
1147  * pixels), includes automatic or manual scaling and compensates for a target
1148  * frame position, if given.
1149  *
1150  * size is a size of the expanded image, the width in pixels is size * aspect.
1151  * aspect is a ratio (width / height) of the effective canvas (square pixels).
1152  * do_compensate denotes whether to actually output values necessary to
1153  *               _compensate_ the determined frame movement.
1154  *               Otherwise, the effective target movement is returned.
1155  */
1156 static void stabilization_calculate_data(StabContext *ctx,
1157                                          int framenr,
1158                                          int size,
1159                                          float aspect,
1160                                          bool do_compensate,
1161                                          float scale_step,
1162                                          float r_translation[2],
1163                                          float r_pivot[2],
1164                                          float *r_scale,
1165                                          float *r_angle)
1166 {
1167         float target_pos[2], target_scale;
1168         float scaleinf = get_animated_scaleinf(ctx, framenr);
1169
1170         if (ctx->stab->flag & TRACKING_STABILIZE_SCALE) {
1171                 *r_scale = expf(scale_step * scaleinf);  /* Averaged in log scale */
1172         }
1173         else {
1174                 *r_scale = 1.0f;
1175         }
1176
1177         mul_v2_fl(r_translation, get_animated_locinf(ctx, framenr));
1178         *r_angle *= get_animated_rotinf(ctx, framenr);
1179
1180         /* Compensate for a target frame position.
1181          * This allows to follow tracking / panning shots in a semi manual fashion,
1182          * when animating the settings for the target frame position.
1183          */
1184         get_animated_target_pos(ctx, framenr, target_pos);
1185         sub_v2_v2(r_translation, target_pos);
1186         *r_angle -= get_animated_target_rot(ctx, framenr);
1187         target_scale = get_animated_target_scale(ctx, framenr);
1188         if (target_scale != 0.0f) {
1189                 *r_scale /= target_scale;
1190                 /* target_scale is an expected/intended reference zoom value */
1191         }
1192
1193         /* Convert from relative to absolute coordinates, square pixels. */
1194         r_translation[0] *= (float)size * aspect;
1195         r_translation[1] *= (float)size;
1196         r_pivot[0] *= (float)size * aspect;
1197         r_pivot[1] *= (float)size;
1198
1199         /* Output measured data, or inverse of the measured values for
1200          * compensation?
1201          */
1202         if (do_compensate) {
1203                 mul_v2_fl(r_translation, -1.0f);
1204                 *r_angle *= -1.0f;
1205                 if (*r_scale != 0.0f) {
1206                         *r_scale = 1.0f / *r_scale;
1207                 }
1208         }
1209 }
1210
1211 static void stabilization_data_to_mat4(float pixel_aspect,
1212                                        const float pivot[2],
1213                                        const float translation[2],
1214                                        float scale,
1215                                        float angle,
1216                                        float r_mat[4][4])
1217 {
1218         float translation_mat[4][4], rotation_mat[4][4], scale_mat[4][4],
1219               pivot_mat[4][4], inv_pivot_mat[4][4],
1220               aspect_mat[4][4], inv_aspect_mat[4][4];
1221         float scale_vector[3] = {scale, scale, 1.0f};
1222
1223         unit_m4(translation_mat);
1224         unit_m4(rotation_mat);
1225         unit_m4(scale_mat);
1226         unit_m4(aspect_mat);
1227         unit_m4(pivot_mat);
1228         unit_m4(inv_pivot_mat);
1229
1230         /* aspect ratio correction matrix */
1231         aspect_mat[0][0] /= pixel_aspect;
1232         invert_m4_m4(inv_aspect_mat, aspect_mat);
1233
1234         add_v2_v2(pivot_mat[3],     pivot);
1235         sub_v2_v2(inv_pivot_mat[3], pivot);
1236
1237         size_to_mat4(scale_mat, scale_vector);       /* scale matrix */
1238         add_v2_v2(translation_mat[3], translation);  /* translation matrix */
1239         rotate_m4(rotation_mat, 'Z', angle);         /* rotation matrix */
1240
1241         /* Compose transformation matrix. */
1242         mul_m4_series(r_mat, aspect_mat, translation_mat,
1243                              pivot_mat, scale_mat, rotation_mat, inv_pivot_mat,
1244                              inv_aspect_mat);
1245 }
1246
1247 /* Calculate scale factor necessary to eliminate black image areas
1248  * caused by the compensating movements of the stabilizator.
1249  * This function visits every frame where stabilisation data is
1250  * available and determines the factor for this frame. The overall
1251  * largest factor found is returned as result.
1252  *
1253  * NOTE: all tracks need to be initialized before calling this function.
1254  */
1255 static float calculate_autoscale_factor(StabContext *ctx,
1256                                         int size,
1257                                         float aspect)
1258 {
1259         MovieTrackingStabilization *stab = ctx->stab;
1260         float pixel_aspect = ctx->tracking->camera.pixel_aspect;
1261         int height = size, width = aspect*size;
1262
1263         int sfra = INT_MAX, efra = INT_MIN, cfra;
1264         float scale = 1.0f, scale_step = 0.0f;
1265         MovieTrackingTrack *track;
1266
1267         /* Calculate maximal frame range of tracks where stabilization is active. */
1268         for (track = ctx->tracking->tracks.first; track; track = track->next) {
1269                 if ((track->flag & TRACK_USE_2D_STAB) ||
1270                         ((stab->flag & TRACKING_STABILIZE_ROTATION) &&
1271                          (track->flag & TRACK_USE_2D_STAB_ROT)))
1272                 {
1273                         int first_frame = track->markers[0].framenr;
1274                         int last_frame  = track->markers[track->markersnr - 1].framenr;
1275                         sfra = min_ii(sfra, first_frame);
1276                         efra = max_ii(efra, last_frame);
1277                 }
1278         }
1279
1280         use_values_from_fcurves(ctx, true);
1281         for (cfra = sfra; cfra <= efra; cfra++) {
1282                 float translation[2], pivot[2], angle, tmp_scale;
1283                 float mat[4][4];
1284                 const float points[4][2] = {{0.0f, 0.0f},
1285                                             {0.0f, height},
1286                                             {width, height},
1287                                             {width, 0.0f}};
1288                 const bool do_compensate = true;
1289                 /* Calculate stabilization parameters for the current frame. */
1290                 stabilization_determine_offset_for_frame(ctx,
1291                                                          cfra,
1292                                                          aspect,
1293                                                          translation,
1294                                                          pivot,
1295                                                          &angle,
1296                                                          &scale_step);
1297                 stabilization_calculate_data(ctx,
1298                                              cfra,
1299                                              size,
1300                                              aspect,
1301                                              do_compensate,
1302                                              scale_step,
1303                                              translation,
1304                                              pivot,
1305                                              &tmp_scale,
1306                                              &angle);
1307                 /* Compose transformation matrix. */
1308                 /* NOTE: Here we operate in NON-COMPENSATED coordinates, meaning we have
1309                  * to construct transformation matrix using proper pivot point.
1310                  * Compensation for that will happen later on.
1311                  */
1312                 stabilization_data_to_mat4(pixel_aspect,
1313                                            pivot,
1314                                            translation,
1315                                            tmp_scale,
1316                                            angle,
1317                                            mat);
1318                 /* Investigate the transformed border lines for this frame;
1319                  * find out, where it cuts the original frame.
1320                  */
1321                 for (int edge_index = 0; edge_index < 4; edge_index++) {
1322                         /* Calculate coordinates of stabilized frame edge points.
1323                          * Use matrix multiplication here so we operate in homogeneous
1324                          * coordinates.
1325                          */
1326                         float stable_edge_p1[3], stable_edge_p2[3];
1327                         copy_v2_v2(stable_edge_p1, points[edge_index]);
1328                         copy_v2_v2(stable_edge_p2, points[(edge_index + 1) % 4]);
1329                         stable_edge_p1[2] = stable_edge_p2[2] = 0.0f;
1330                         mul_m4_v3(mat, stable_edge_p1);
1331                         mul_m4_v3(mat, stable_edge_p2);
1332                         /* Now we iterate over all original frame corners (we call them
1333                          * 'point' here) to see if there's black area between stabilized
1334                          * frame edge and original point.
1335                          */
1336                         for (int point_index = 0; point_index < 4; point_index++) {
1337                                 const float point[3] = {points[point_index][0],
1338                                                         points[point_index][1],
1339                                                         0.0f};
1340                                 /* Calculate vector which goes from first edge point to
1341                                  * second one.
1342                                  */
1343                                 float stable_edge_vec[3];
1344                                 sub_v3_v3v3(stable_edge_vec, stable_edge_p2, stable_edge_p1);
1345                                 /* Calculate vector which connects current frame point to
1346                                  * first edge point.
1347                                  */
1348                                 float point_to_edge_start_vec[3];
1349                                 sub_v3_v3v3(point_to_edge_start_vec, point, stable_edge_p1);
1350                                 /* Use this two vectors to check whether frame point is inside
1351                                  * of the stabilized frame or not.
1352                                  * If the point is inside, there is no black area happening
1353                                  * and no scaling required for it.
1354                                  */
1355                                 if (cross_v2v2(stable_edge_vec, point_to_edge_start_vec) >= 0.0f) {
1356                                         /* We are scaling around motion-compensated pivot point. */
1357                                         float scale_pivot[2];
1358                                         add_v2_v2v2(scale_pivot, pivot, translation);
1359                                         /* Calculate line which goes via `point` and parallel to
1360                                          * the stabilized frame edge. This line is coming via
1361                                          * `point` and `point2` at the end.
1362                                          */
1363                                         float point2[2];
1364                                         add_v2_v2v2(point2, point, stable_edge_vec);
1365                                         /* Calculate actual distance between pivot point and
1366                                          * the stabilized frame edge. Then calculate distance
1367                                          * between pivot point and line which goes via actual
1368                                          * corner and is parallel to the edge.
1369                                          *
1370                                          * Dividing one by another will give us required scale
1371                                          * factor to get rid of black areas.
1372                                          */
1373                                         float real_dist = dist_to_line_v2(scale_pivot,
1374                                                                           stable_edge_p1,
1375                                                                           stable_edge_p2);
1376                                         float required_dist = dist_to_line_v2(scale_pivot,
1377                                                                               point,
1378                                                                               point2);
1379                                         const float S = required_dist / real_dist;
1380                                         scale = max_ff(scale, S);
1381                                 }
1382                         }
1383                 }
1384         }
1385         if (stab->maxscale > 0.0f) {
1386                 scale = min_ff(scale, stab->maxscale);
1387         }
1388         use_values_from_fcurves(ctx, false);
1389
1390         return scale;
1391 }
1392
1393
1394 /* Prepare working data and determine reference point for each track.
1395  *
1396  * NOTE: These calculations _could_ be cached and reused for all frames of the
1397  *       same clip. However, since proper initialization depends on (weight)
1398  *       animation and setup of tracks, ensuring consistency of cached init data
1399  *       turns out to be tricky, hard to maintain and generally not worth the
1400  *       effort. Thus we'll re-initialize on every frame.
1401  */
1402 static StabContext *init_stabilizer(MovieClip *clip, int size, float aspect)
1403 {
1404         StabContext *ctx = initialize_stabilization_working_context(clip);
1405         BLI_assert(ctx != NULL);
1406         initialize_all_tracks(ctx, aspect);
1407         if (ctx->stab->flag & TRACKING_AUTOSCALE) {
1408                 ctx->stab->scale = 1.0;
1409                 ctx->stab->scale = calculate_autoscale_factor(ctx, size, aspect);
1410         }
1411         /* By default, just use values for the global current frame. */
1412         use_values_from_fcurves(ctx, false);
1413         return ctx;
1414 }
1415
1416
1417 /* === public interface functions === */
1418
1419 /* Get stabilization data (translation, scaling and angle) for a given frame.
1420  * Returned data describes how to compensate the detected movement, but with any
1421  * chosen scale factor already applied and any target frame position already
1422  * compensated. In case stabilization fails or is disabled, neutral values are
1423  * returned.
1424  *
1425  * framenr is a frame number, relative to the clip (not relative to the scene
1426  *         timeline)
1427  * width is an effective width of the canvas (square pixels), used to scale the
1428  *       determined translation
1429  *
1430  * Outputs:
1431  * - translation of the lateral shift, absolute canvas coordinates
1432  *   (square pixels).
1433  * - scale of the scaling to apply
1434  * - angle of the rotation angle, relative to the frame center
1435  */
1436 /* TODO(sergey): Use r_ prefix for output parameters here. */
1437 void BKE_tracking_stabilization_data_get(MovieClip *clip,
1438                                          int framenr,
1439                                          int width,
1440                                          int height,
1441                                          float translation[2],
1442                                          float *scale,
1443                                          float *angle)
1444 {
1445         StabContext *ctx = NULL;
1446         MovieTracking *tracking = &clip->tracking;
1447         bool enabled = (tracking->stabilization.flag & TRACKING_2D_STABILIZATION);
1448         /* Might become a parameter of a stabilization compositor node. */
1449         bool do_compensate = true;
1450         float scale_step = 0.0f;
1451         float pixel_aspect = tracking->camera.pixel_aspect;
1452         float aspect = (float)width * pixel_aspect / height;
1453         int size = height;
1454         float pivot[2];
1455
1456         if (enabled) {
1457                 ctx = init_stabilizer(clip, size, aspect);
1458         }
1459
1460         if (enabled &&
1461                 stabilization_determine_offset_for_frame(ctx,
1462                                                          framenr,
1463                                                          aspect,
1464                                                          translation,
1465                                                          pivot,
1466                                                          angle,
1467                                                          &scale_step))
1468         {
1469                 stabilization_calculate_data(ctx,
1470                                              framenr,
1471                                              size,
1472                                              aspect,
1473                                              do_compensate,
1474                                              scale_step,
1475                                              translation,
1476                                              pivot,
1477                                              scale,
1478                                              angle);
1479                 compensate_rotation_center(size,
1480                                            aspect,
1481                                            *angle,
1482                                            *scale,
1483                                            pivot,
1484                                            translation);
1485         }
1486         else {
1487                 zero_v2(translation);
1488                 *scale = 1.0f;
1489                 *angle = 0.0f;
1490         }
1491         discard_stabilization_working_context(ctx);
1492 }
1493
1494 /* Stabilize given image buffer using stabilization data for a specified
1495  * frame number.
1496  *
1497  * NOTE: frame number should be in clip space, not scene space.
1498  */
1499 /* TODO(sergey): Use r_ prefix for output parameters here. */
1500 ImBuf *BKE_tracking_stabilize_frame(MovieClip *clip,
1501                                     int framenr,
1502                                     ImBuf *ibuf,
1503                                     float translation[2],
1504                                     float *scale,
1505                                     float *angle)
1506 {
1507         float tloc[2], tscale, tangle;
1508         MovieTracking *tracking = &clip->tracking;
1509         MovieTrackingStabilization *stab = &tracking->stabilization;
1510         ImBuf *tmpibuf;
1511         int width = ibuf->x, height = ibuf->y;
1512         float pixel_aspect = tracking->camera.pixel_aspect;
1513         float mat[4][4];
1514         int j, filter = tracking->stabilization.filter;
1515         void (*interpolation)(struct ImBuf *, struct ImBuf *, float, float, int, int) = NULL;
1516         int ibuf_flags;
1517
1518         if (translation)
1519                 copy_v2_v2(tloc, translation);
1520
1521         if (scale)
1522                 tscale = *scale;
1523
1524         /* Perform early output if no stabilization is used. */
1525         if ((stab->flag & TRACKING_2D_STABILIZATION) == 0) {
1526                 if (translation)
1527                         zero_v2(translation);
1528
1529                 if (scale)
1530                         *scale = 1.0f;
1531
1532                 if (angle)
1533                         *angle = 0.0f;
1534
1535                 return ibuf;
1536         }
1537
1538         /* Allocate frame for stabilization result. */
1539         ibuf_flags = 0;
1540         if (ibuf->rect)
1541                 ibuf_flags |= IB_rect;
1542         if (ibuf->rect_float)
1543                 ibuf_flags |= IB_rectfloat;
1544
1545         tmpibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, ibuf_flags);
1546
1547         /* Calculate stabilization matrix. */
1548         BKE_tracking_stabilization_data_get(clip, framenr, width, height, tloc, &tscale, &tangle);
1549         BKE_tracking_stabilization_data_to_mat4(ibuf->x, ibuf->y, pixel_aspect, tloc, tscale, tangle, mat);
1550
1551         /* The following code visits each nominal target grid position
1552          * and picks interpolated data "backwards" from source.
1553          * thus we need the inverse of the transformation to apply. */
1554         invert_m4(mat);
1555
1556         if (filter == TRACKING_FILTER_NEAREST)
1557                 interpolation = nearest_interpolation;
1558         else if (filter == TRACKING_FILTER_BILINEAR)
1559                 interpolation = bilinear_interpolation;
1560         else if (filter == TRACKING_FILTER_BICUBIC)
1561                 interpolation = bicubic_interpolation;
1562         else
1563                 /* fallback to default interpolation method */
1564                 interpolation = nearest_interpolation;
1565
1566         /* This function is only used for display in clip editor and
1567          * sequencer only, which would only benefit of using threads
1568          * here.
1569          *
1570          * But need to keep an eye on this if the function will be
1571          * used in other cases.
1572          */
1573 #pragma omp parallel for if (tmpibuf->y > 128)
1574         for (j = 0; j < tmpibuf->y; j++) {
1575                 int i;
1576                 for (i = 0; i < tmpibuf->x; i++) {
1577                         float vec[3] = {i, j, 0.0f};
1578
1579                         mul_v3_m4v3(vec, mat, vec);
1580
1581                         interpolation(ibuf, tmpibuf, vec[0], vec[1], i, j);
1582                 }
1583         }
1584
1585         if (tmpibuf->rect_float)
1586                 tmpibuf->userflags |= IB_RECT_INVALID;
1587
1588         if (translation)
1589                 copy_v2_v2(translation, tloc);
1590
1591         if (scale)
1592                 *scale = tscale;
1593
1594         if (angle)
1595                 *angle = tangle;
1596
1597         return tmpibuf;
1598 }
1599
1600
1601 /* Build a 4x4 transformation matrix based on the given 2D stabilization data.
1602  * mat is a 4x4 matrix in homogeneous coordinates, adapted to the
1603  *     final image buffer size and compensated for pixel aspect ratio,
1604  *     ready for direct OpenGL drawing.
1605  *
1606  * TODO(sergey): The signature of this function should be changed. we actually
1607  *               don't need the dimensions of the image buffer. Instead we
1608  *               should consider to provide the pivot point of the rotation as a
1609  *               further stabilization data parameter.
1610  */
1611 void BKE_tracking_stabilization_data_to_mat4(int buffer_width,
1612                                              int buffer_height,
1613                                              float pixel_aspect,
1614                                              float translation[2],
1615                                              float scale,
1616                                              float angle,
1617                                              float r_mat[4][4])
1618 {
1619         /* Since we cannot receive the real pivot point coordinates (API limitation),
1620          * we perform the rotation/scale around the center of frame.
1621          * Then we correct by an additional shift, which was calculated in
1622          * compensate_rotation_center() and "sneaked in" as additional offset
1623          * in the translation parameter. This works, since translation needs to be
1624          * applied after rotation/scale anyway. Thus effectively the image gets
1625          * rotated around the desired pivot point
1626          */
1627         /* TODO(sergey) pivot shouldn't be calculated here, rather received
1628          * as a parameter.
1629          */
1630         float pivot[2];
1631         pivot[0] = 0.5f * pixel_aspect * buffer_width;
1632         pivot[1] = 0.5f * buffer_height;
1633         /* Compose transformation matrix. */
1634         stabilization_data_to_mat4(pixel_aspect,
1635                                    pivot,
1636                                    translation,
1637                                    scale,
1638                                    angle,
1639                                    r_mat);
1640 }