Cleanup: code-style, duplicate header
[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         } else {
759                 /* No usable tracking data on any track on this frame.
760                  * Use data from neighbouring frames to extrapolate...
761                  */
762                 int next_lower = MINAFRAME;
763                 int next_higher = MAXFRAME;
764                 use_values_from_fcurves(ctx, true);
765                 for (track = tracking->tracks.first; track; track = track->next) {
766                         /* Note: we deliberately do not care if this track
767                          *       is already initialized for stabilisation */
768                         if (track->flag & TRACK_USE_2D_STAB) {
769                                 int startpoint = search_closest_marker_index(track, framenr);
770                                 retrieve_next_higher_usable_frame(ctx,
771                                                                   track,
772                                                                   startpoint,
773                                                                   framenr,
774                                                                   &next_higher);
775                                 retrieve_next_lower_usable_frame(ctx,
776                                                                  track,
777                                                                  startpoint,
778                                                                  framenr,
779                                                                  &next_lower);
780                         }
781                 }
782                 if (next_lower >= MINFRAME) {
783                         /* use next usable frame to the left.
784                          * Also default to this frame when we're in a gap */
785                         average_marker_positions(ctx, next_lower, r_ref_pos);
786
787                 } else if (next_higher < MAXFRAME) {
788                         average_marker_positions(ctx, next_higher, r_ref_pos);
789                 }
790                 use_values_from_fcurves(ctx, false);
791         }
792 }
793
794
795 /* Linear interpolation of data retrieved at two measurement points.
796  * This function is used to fill gaps in the middle of the covered area,
797  * at frames without any usable tracks for stabilization.
798  *
799  * framenr is a position to interpolate for.
800  * frame_a is a valid measurement point below framenr
801  * frame_b is a valid measurement point above framenr
802  * Returns truth if both measurements could actually be retrieved.
803  * Otherwise output parameters remain unaltered
804  */
805 static bool interpolate_averaged_track_contributions(StabContext *ctx,
806                                                      int framenr,
807                                                      int frame_a,
808                                                      int frame_b,
809                                                      const float aspect,
810                                                      float r_translation[2],
811                                                      float r_pivot[2],
812                                                      float *r_angle,
813                                                      float *r_scale_step)
814 {
815         float t, s;
816         float trans_a[2], trans_b[2];
817         float angle_a, angle_b;
818         float scale_a, scale_b;
819         float pivot_a[2], pivot_b[2];
820         bool success = false;
821
822         BLI_assert(frame_a <= frame_b);
823         BLI_assert(frame_a <= framenr);
824         BLI_assert(framenr <= frame_b);
825
826         t = ((float)framenr - frame_a) / (frame_b - frame_a);
827         s = 1.0f - t;
828
829         success = average_track_contributions(ctx, frame_a, aspect, trans_a, pivot_a, &angle_a, &scale_a);
830         if (!success) {
831                 return false;
832         }
833         success = average_track_contributions(ctx, frame_b, aspect, trans_b, pivot_b, &angle_b, &scale_b);
834         if (!success) {
835                 return false;
836         }
837
838         interp_v2_v2v2(r_translation, trans_a, trans_b, t);
839         interp_v2_v2v2(r_pivot, pivot_a, pivot_b, t);
840         *r_scale_step = s * scale_a + t * scale_b;
841         *r_angle = s * angle_a + t * angle_b;
842         return true;
843 }
844
845
846 /* Reorder tracks starting with those providing a tracking data frame
847  * closest to the global anchor_frame. Tracks with a gap at anchor_frame or
848  * starting farer away from anchor_frame altogether will be visited later.
849  * This allows to build up baseline contributions incrementally.
850  *
851  * order is an array for sorting the tracks. Must be of suitable size to hold
852  * all tracks.
853  * Returns number of actually usable tracks, can be less than the overall number
854  * of tracks.
855  *
856  * NOTE: After returning, the order array holds entries up to the number of
857  *       usable tracks, appropriately sorted starting with the closest tracks.
858  *       Initialization includes disabled tracks, since they might be enabled
859  *       through automation later.
860  */
861 static int establish_track_initialization_order(StabContext *ctx,
862                                                 TrackInitOrder *order)
863 {
864         size_t tracknr = 0;
865         MovieTrackingTrack *track;
866         MovieTracking *tracking = ctx->tracking;
867         int anchor_frame = tracking->stabilization.anchor_frame;
868
869         for (track = tracking->tracks.first; track != NULL; track = track->next) {
870                 MovieTrackingMarker *marker;
871                 order[tracknr].data = track;
872                 marker = get_closest_marker(ctx, track, anchor_frame);
873                 if (marker != NULL &&
874                         (track->flag & (TRACK_USE_2D_STAB | TRACK_USE_2D_STAB_ROT)))
875                 {
876                         order[tracknr].sort_value = abs(marker->framenr - anchor_frame);
877                         order[tracknr].reference_frame = marker->framenr;
878                         ++tracknr;
879                 }
880         }
881         if (tracknr) {
882                 qsort(order, tracknr, sizeof(TrackInitOrder), BLI_sortutil_cmp_int);
883         }
884         return tracknr;
885 }
886
887
888 /* Setup the constant part of this track's contribution to the determined frame
889  * movement. Tracks usually don't provide tracking data for every frame. Thus,
890  * for determining data at a given frame, we split up the contribution into a
891  * part covered by actual measurements on this track, and the initial gap
892  * between this track's reference frame and the global anchor_frame.
893  * The (missing) data for the gap can be substituted by the average offset
894  * observed by the other tracks covering the gap. This approximation doesn't
895  * introduce wrong data, but it records data with incorrect weight. A totally
896  * correct solution would require us to average the contribution per frame, and
897  * then integrate stepwise over all frames -- which of course would be way more
898  * expensive, especially for longer clips. To the contrary, our solution
899  * cumulates the total contribution per track and averages afterwards over all
900  * tracks; it can thus be calculated just based on the data of a single frame,
901  * plus the "baseline" for the reference frame, which is what we are computing
902  * here.
903  *
904  * Since we're averaging _contributions_, we have to calculate the _difference_
905  * of the measured position at current frame and the position at the reference
906  * frame. But the "reference" part of this difference is constant and can thus
907  * be packed together with the baseline contribution into a single precomputed
908  * vector per track.
909  *
910  * In case of the rotation contribution, the principle is the same, but we have
911  * to compensate for the already determined translation and measure the pure
912  * rotation, simply because this is how we model the offset: shift plus rotation
913  * around the shifted rotation center. To circumvent problems with the
914  * definition range of the arcus tangens function, we perform this baseline
915  * addition and reference angle subtraction in polar coordinates and bake this
916  * operation into a precomputed rotation matrix.
917  *
918  * track is a track to be initialized to initialize
919  * reference_frame is a local frame for this track, the closest pick to the
920  *                 global anchor_frame.
921  * aspect is a total aspect ratio of the undistorted image (includes fame and
922  *        pixel aspect).
923  * target_pos is a possibly animated target position as set by the user for
924  *            the reference_frame
925  * average_translation is a value observed by the _other_ tracks for the gap
926  *                     between reference_frame and anchor_frame. This
927  *                     average must not contain contributions of frames
928  *                     not yet initialized
929  * average_angle in a similar way, the rotation value observed by the
930  *               _other_ tracks.
931  * average_scale_step is an image scale factor observed on average by the other
932  *                    tracks for this frame. This value is recorded and
933  *                    averaged as logarithm. The recorded scale changes
934  *                    are damped for very small contributions, to limit
935  *                    the effect of probe points approaching the pivot
936  *                    too closely.
937  *
938  * NOTE: when done, this track is marked as initialized
939  */
940 static void initialize_track_for_stabilization(StabContext *ctx,
941                                                MovieTrackingTrack *track,
942                                                int reference_frame,
943                                                float aspect,
944                                                const float average_translation[2],
945                                                const float pivot[2],
946                                                const float average_angle,
947                                                const float average_scale_step)
948 {
949         float pos[2], angle, len;
950         TrackStabilizationBase *local_data =
951                 access_stabilization_baseline_data(ctx, track);
952         MovieTrackingMarker *marker =
953                 BKE_tracking_marker_get_exact(track, reference_frame);
954         /* Logic for initialization order ensures there *is* a marker on that
955          * very frame.
956          */
957         BLI_assert(marker != NULL);
958         BLI_assert(local_data != NULL);
959
960         /* Per track baseline value for translation. */
961         sub_v2_v2v2(local_data->stabilization_offset_base,
962                     average_translation,
963                     marker->pos);
964
965         /* Per track baseline value for rotation. */
966         sub_v2_v2v2(pos, marker->pos, pivot);
967
968         pos[0] *= aspect;
969         angle = average_angle - atan2f(pos[1],pos[0]);
970         angle_to_mat2(local_data->stabilization_rotation_base, angle);
971
972         /* Per track baseline value for zoom. */
973         len = len_v2(pos) + SCALE_ERROR_LIMIT_BIAS;
974         local_data->stabilization_scale_base = expf(average_scale_step) / len;
975
976         local_data->is_init_for_stabilization = true;
977 }
978
979
980 static void initialize_all_tracks(StabContext *ctx, float aspect)
981 {
982         size_t i, track_cnt = 0;
983         MovieClip *clip = ctx->clip;
984         MovieTracking *tracking = ctx->tracking;
985         MovieTrackingTrack *track;
986         TrackInitOrder *order;
987
988         /* Attempt to start initialization at anchor_frame.
989          * By definition, offset contribution is zero there.
990          */
991         int reference_frame = tracking->stabilization.anchor_frame;
992         float average_angle=0, average_scale_step=0;
993         float average_translation[2], average_pos[2], pivot[2];
994         zero_v2(average_translation);
995         zero_v2(pivot);
996
997         /* Initialize private working data. */
998         for (track = tracking->tracks.first; track != NULL; track = track->next) {
999                 TrackStabilizationBase *local_data =
1000                         access_stabilization_baseline_data(ctx, track);
1001                 if (!local_data) {
1002                         local_data = MEM_callocN(sizeof(TrackStabilizationBase),
1003                                                  "2D stabilization per track baseline data");
1004                         attach_stabilization_baseline_data(ctx, track, local_data);
1005                 }
1006                 BLI_assert(local_data != NULL);
1007                 local_data->track_weight_curve = retrieve_track_weight_animation(clip,
1008                                                                                  track);
1009                 local_data->is_init_for_stabilization = false;
1010
1011                 ++track_cnt;
1012         }
1013         if (!track_cnt) {
1014                 return;
1015         }
1016
1017         order = MEM_mallocN(track_cnt * sizeof(TrackInitOrder),
1018                             "stabilization track order");
1019         if (!order) {
1020                 return;
1021         }
1022
1023         track_cnt = establish_track_initialization_order(ctx, order);
1024         if (track_cnt == 0) {
1025                 goto cleanup;
1026         }
1027
1028         /* starting point for pivot, before having initialized any track */
1029         average_marker_positions(ctx, reference_frame, average_pos);
1030         setup_pivot(average_pos, pivot);
1031
1032         for (i = 0; i < track_cnt; ++i) {
1033                 track = order[i].data;
1034                 if (reference_frame != order[i].reference_frame) {
1035                         reference_frame = order[i].reference_frame;
1036                         average_track_contributions(ctx,
1037                                                     reference_frame,
1038                                                     aspect,
1039                                                     average_translation,
1040                                                     pivot,
1041                                                     &average_angle,
1042                                                     &average_scale_step);
1043                 }
1044                 initialize_track_for_stabilization(ctx,
1045                                                    track,
1046                                                    reference_frame,
1047                                                    aspect,
1048                                                    average_translation,
1049                                                    pivot,
1050                                                    average_angle,
1051                                                    average_scale_step);
1052         }
1053
1054 cleanup:
1055         MEM_freeN(order);
1056 }
1057
1058
1059 /* Retrieve the measurement of frame movement by averaging contributions of
1060  * active tracks.
1061  *
1062  * translation is a measurement in normalized 0..1 coordinates.
1063  * angle is a measurement in radians -pi..+pi counter clockwise relative to
1064  *       translation compensated frame center
1065  * scale_step is a measurement of image scale changes, in logarithmic scale
1066  *            (zero means scale == 1)
1067  * Returns calculation enabled and all data retrieved as expected for this frame.
1068  *
1069  * NOTE: when returning `false`, output parameters are reset to neutral values.
1070  */
1071 static bool stabilization_determine_offset_for_frame(StabContext *ctx,
1072                                                      int framenr,
1073                                                      float aspect,
1074                                                      float r_translation[2],
1075                                                      float r_pivot[2],
1076                                                      float *r_angle,
1077                                                      float *r_scale_step)
1078 {
1079         bool success = false;
1080
1081         /* Early output if stabilization is disabled. */
1082         if ((ctx->stab->flag & TRACKING_2D_STABILIZATION) == 0) {
1083                 zero_v2(r_translation);
1084                 *r_scale_step = 0.0f;
1085                 *r_angle = 0.0f;
1086                 return false;
1087         }
1088
1089         success = average_track_contributions(ctx,
1090                                               framenr,
1091                                               aspect,
1092                                               r_translation,
1093                                               r_pivot,
1094                                               r_angle,
1095                                               r_scale_step);
1096         if (!success) {
1097                 /* Try to hold extrapolated settings beyond the definition range
1098                  * and to interpolate in gaps without any usable tracking data
1099                  * to prevent sudden jump to image zero position.
1100                  */
1101                 int next_lower = MINAFRAME;
1102                 int next_higher = MAXFRAME;
1103                 use_values_from_fcurves(ctx, true);
1104                 find_next_working_frames(ctx, framenr, &next_lower, &next_higher);
1105                 if (next_lower >= MINFRAME && next_higher < MAXFRAME) {
1106                         success = interpolate_averaged_track_contributions(ctx,
1107                                                                            framenr,
1108                                                                            next_lower,
1109                                                                            next_higher,
1110                                                                            aspect,
1111                                                                            r_translation,
1112                                                                            r_pivot,
1113                                                                            r_angle,
1114                                                                            r_scale_step);
1115                 }
1116                 else if (next_higher < MAXFRAME) {
1117                         /* Before start of stabilized range: extrapolate start point
1118                          * settings.
1119                          */
1120                         success = average_track_contributions(ctx,
1121                                                               next_higher,
1122                                                               aspect,
1123                                                               r_translation,
1124                                                               r_pivot,
1125                                                               r_angle,
1126                                                               r_scale_step);
1127                 }
1128                 else if (next_lower >= MINFRAME) {
1129                         /* After end of stabilized range: extrapolate end point settings. */
1130                         success = average_track_contributions(ctx,
1131                                                               next_lower,
1132                                                               aspect,
1133                                                               r_translation,
1134                                                               r_pivot,
1135                                                               r_angle,
1136                                                               r_scale_step);
1137                 }
1138                 use_values_from_fcurves(ctx, false);
1139         }
1140         return success;
1141 }
1142
1143 /* Calculate stabilization data (translation, scale and rotation) from given raw
1144  * measurements. Result is in absolute image dimensions (expanded image, square
1145  * pixels), includes automatic or manual scaling and compensates for a target
1146  * frame position, if given.
1147  *
1148  * size is a size of the expanded image, the width in pixels is size * aspect.
1149  * aspect is a ratio (width / height) of the effective canvas (square pixels).
1150  * do_compensate denotes whether to actually output values necessary to
1151  *               _compensate_ the determined frame movement.
1152  *               Otherwise, the effective target movement is returned.
1153  */
1154 static void stabilization_calculate_data(StabContext *ctx,
1155                                          int framenr,
1156                                          int size,
1157                                          float aspect,
1158                                          bool do_compensate,
1159                                          float scale_step,
1160                                          float r_translation[2],
1161                                          float r_pivot[2],
1162                                          float *r_scale,
1163                                          float *r_angle)
1164 {
1165         float target_pos[2], target_scale;
1166         float scaleinf = get_animated_scaleinf(ctx, framenr);
1167
1168         if (ctx->stab->flag & TRACKING_STABILIZE_SCALE) {
1169                 *r_scale = expf(scale_step * scaleinf);  /* Averaged in log scale */
1170         }
1171         else {
1172                 *r_scale = 1.0f;
1173         }
1174
1175         mul_v2_fl(r_translation, get_animated_locinf(ctx, framenr));
1176         *r_angle *= get_animated_rotinf(ctx, framenr);
1177
1178         /* Compensate for a target frame position.
1179          * This allows to follow tracking / panning shots in a semi manual fashion,
1180          * when animating the settings for the target frame position.
1181          */
1182         get_animated_target_pos(ctx, framenr, target_pos);
1183         sub_v2_v2(r_translation, target_pos);
1184         *r_angle -= get_animated_target_rot(ctx, framenr);
1185         target_scale = get_animated_target_scale(ctx, framenr);
1186         if (target_scale != 0.0f) {
1187                 *r_scale /= target_scale;
1188                 /* target_scale is an expected/intended reference zoom value */
1189         }
1190
1191         /* Convert from relative to absolute coordinates, square pixels. */
1192         r_translation[0] *= (float)size * aspect;
1193         r_translation[1] *= (float)size;
1194         r_pivot[0] *= (float)size * aspect;
1195         r_pivot[1] *= (float)size;
1196
1197         /* Output measured data, or inverse of the measured values for
1198          * compensation?
1199          */
1200         if (do_compensate) {
1201                 mul_v2_fl(r_translation, -1.0f);
1202                 *r_angle *= -1.0f;
1203                 if (*r_scale != 0.0f) {
1204                         *r_scale = 1.0f / *r_scale;
1205                 }
1206         }
1207 }
1208
1209 static void stabilization_data_to_mat4(float pixel_aspect,
1210                                        const float pivot[2],
1211                                        const float translation[2],
1212                                        float scale,
1213                                        float angle,
1214                                        float r_mat[4][4])
1215 {
1216         float translation_mat[4][4], rotation_mat[4][4], scale_mat[4][4],
1217               pivot_mat[4][4], inv_pivot_mat[4][4],
1218               aspect_mat[4][4], inv_aspect_mat[4][4];
1219         float scale_vector[3] = {scale, scale, 1.0f};
1220
1221         unit_m4(translation_mat);
1222         unit_m4(rotation_mat);
1223         unit_m4(scale_mat);
1224         unit_m4(aspect_mat);
1225         unit_m4(pivot_mat);
1226         unit_m4(inv_pivot_mat);
1227
1228         /* aspect ratio correction matrix */
1229         aspect_mat[0][0] /= pixel_aspect;
1230         invert_m4_m4(inv_aspect_mat, aspect_mat);
1231
1232         add_v2_v2(pivot_mat[3],     pivot);
1233         sub_v2_v2(inv_pivot_mat[3], pivot);
1234
1235         size_to_mat4(scale_mat, scale_vector);       /* scale matrix */
1236         add_v2_v2(translation_mat[3], translation);  /* translation matrix */
1237         rotate_m4(rotation_mat, 'Z', angle);         /* rotation matrix */
1238
1239         /* Compose transformation matrix. */
1240         mul_m4_series(r_mat, aspect_mat, translation_mat,
1241                              pivot_mat, scale_mat, rotation_mat, inv_pivot_mat,
1242                              inv_aspect_mat);
1243 }
1244
1245 /* Calculate scale factor necessary to eliminate black image areas
1246  * caused by the compensating movements of the stabilizator.
1247  * This function visits every frame where stabilisation data is
1248  * available and determines the factor for this frame. The overall
1249  * largest factor found is returned as result.
1250  *
1251  * NOTE: all tracks need to be initialized before calling this function.
1252  */
1253 static float calculate_autoscale_factor(StabContext *ctx,
1254                                         int size,
1255                                         float aspect)
1256 {
1257         MovieTrackingStabilization *stab = ctx->stab;
1258         float pixel_aspect = ctx->tracking->camera.pixel_aspect;
1259         int height = size, width = aspect*size;
1260
1261         int sfra = INT_MAX, efra = INT_MIN, cfra;
1262         float scale = 1.0f, scale_step = 0.0f;
1263         MovieTrackingTrack *track;
1264
1265         /* Calculate maximal frame range of tracks where stabilization is active. */
1266         for (track = ctx->tracking->tracks.first; track; track = track->next) {
1267                 if ((track->flag & TRACK_USE_2D_STAB) ||
1268                         ((stab->flag & TRACKING_STABILIZE_ROTATION) &&
1269                          (track->flag & TRACK_USE_2D_STAB_ROT)))
1270                 {
1271                         int first_frame = track->markers[0].framenr;
1272                         int last_frame  = track->markers[track->markersnr - 1].framenr;
1273                         sfra = min_ii(sfra, first_frame);
1274                         efra = max_ii(efra, last_frame);
1275                 }
1276         }
1277
1278         use_values_from_fcurves(ctx, true);
1279         for (cfra = sfra; cfra <= efra; cfra++) {
1280                 float translation[2], pivot[2], angle, tmp_scale;
1281                 float mat[4][4];
1282                 const float points[4][2] = {{0.0f, 0.0f},
1283                                             {0.0f, height},
1284                                             {width, height},
1285                                             {width, 0.0f}};
1286                 const bool do_compensate = true;
1287                 /* Calculate stabilization parameters for the current frame. */
1288                 stabilization_determine_offset_for_frame(ctx,
1289                                                          cfra,
1290                                                          aspect,
1291                                                          translation,
1292                                                          pivot,
1293                                                          &angle,
1294                                                          &scale_step);
1295                 stabilization_calculate_data(ctx,
1296                                              cfra,
1297                                              size,
1298                                              aspect,
1299                                              do_compensate,
1300                                              scale_step,
1301                                              translation,
1302                                              pivot,
1303                                              &tmp_scale,
1304                                              &angle);
1305                 /* Compose transformation matrix. */
1306                 /* NOTE: Here we operate in NON-COMPENSATED coordinates, meaning we have
1307                  * to construct transformation matrix using proper pivot point.
1308                  * Compensation for that will happen later on.
1309                  */
1310                 stabilization_data_to_mat4(pixel_aspect,
1311                                            pivot,
1312                                            translation,
1313                                            tmp_scale,
1314                                            angle,
1315                                            mat);
1316                 /* Investigate the transformed border lines for this frame;
1317                  * find out, where it cuts the original frame.
1318                  */
1319                 for (int edge_index = 0; edge_index < 4; edge_index++) {
1320                         /* Calculate coordinates of stabilized frame edge points.
1321                          * Use matrix multiplication here so we operate in homogeneous
1322                          * coordinates.
1323                          */
1324                         float stable_edge_p1[3], stable_edge_p2[3];
1325                         copy_v2_v2(stable_edge_p1, points[edge_index]);
1326                         copy_v2_v2(stable_edge_p2, points[(edge_index + 1) % 4]);
1327                         stable_edge_p1[2] = stable_edge_p2[2] = 0.0f;
1328                         mul_m4_v3(mat, stable_edge_p1);
1329                         mul_m4_v3(mat, stable_edge_p2);
1330                         /* Now we iterate over all original frame corners (we call them
1331                          * 'point' here) to see if there's black area between stabilized
1332                          * frame edge and original point.
1333                          */
1334                         for (int point_index = 0; point_index < 4; point_index++) {
1335                                 const float point[3] = {points[point_index][0],
1336                                                         points[point_index][1],
1337                                                         0.0f};
1338                                 /* Calculate vector which goes from first edge point to
1339                                  * second one.
1340                                  */
1341                                 float stable_edge_vec[3];
1342                                 sub_v3_v3v3(stable_edge_vec, stable_edge_p2, stable_edge_p1);
1343                                 /* Calculate vector which connects current frame point to
1344                                  * first edge point.
1345                                  */
1346                                 float point_to_edge_start_vec[3];
1347                                 sub_v3_v3v3(point_to_edge_start_vec, point, stable_edge_p1);
1348                                 /* Use this two vectors to check whether frame point is inside
1349                                  * of the stabilized frame or not.
1350                                  * If the point is inside, there is no black area happening
1351                                  * and no scaling required for it.
1352                                  */
1353                                 if (cross_v2v2(stable_edge_vec, point_to_edge_start_vec) >= 0.0f) {
1354                                         /* We are scaling around motion-compensated pivot point. */
1355                                         float scale_pivot[2];
1356                                         add_v2_v2v2(scale_pivot, pivot, translation);
1357                                         /* Calculate line which goes via `point` and parallel to
1358                                          * the stabilized frame edge. This line is coming via
1359                                          * `point` and `point2` at the end.
1360                                          */
1361                                         float point2[2];
1362                                         add_v2_v2v2(point2, point, stable_edge_vec);
1363                                         /* Calculate actual distance between pivot point and
1364                                          * the stabilized frame edge. Then calculate distance
1365                                          * between pivot point and line which goes via actual
1366                                          * corner and is parallel to the edge.
1367                                          *
1368                                          * Dividing one by another will give us required scale
1369                                          * factor to get rid of black areas.
1370                                          */
1371                                         float real_dist = dist_to_line_v2(scale_pivot,
1372                                                                           stable_edge_p1,
1373                                                                           stable_edge_p2);
1374                                         float required_dist = dist_to_line_v2(scale_pivot,
1375                                                                               point,
1376                                                                               point2);
1377                                         const float S = required_dist / real_dist;
1378                                         scale = max_ff(scale, S);
1379                                 }
1380                         }
1381                 }
1382         }
1383         if (stab->maxscale > 0.0f) {
1384                 scale = min_ff(scale, stab->maxscale);
1385         }
1386         use_values_from_fcurves(ctx, false);
1387
1388         return scale;
1389 }
1390
1391
1392 /* Prepare working data and determine reference point for each track.
1393  *
1394  * NOTE: These calculations _could_ be cached and reused for all frames of the
1395  *       same clip. However, since proper initialization depends on (weight)
1396  *       animation and setup of tracks, ensuring consistency of cached init data
1397  *       turns out to be tricky, hard to maintain and generally not worth the
1398  *       effort. Thus we'll re-initialize on every frame.
1399  */
1400 static StabContext *init_stabilizer(MovieClip *clip, int size, float aspect)
1401 {
1402         StabContext *ctx = initialize_stabilization_working_context(clip);
1403         BLI_assert(ctx != NULL);
1404         initialize_all_tracks(ctx, aspect);
1405         if (ctx->stab->flag & TRACKING_AUTOSCALE) {
1406                 ctx->stab->scale = 1.0;
1407                 ctx->stab->scale = calculate_autoscale_factor(ctx, size, aspect);
1408         }
1409         /* By default, just use values for the global current frame. */
1410         use_values_from_fcurves(ctx, false);
1411         return ctx;
1412 }
1413
1414
1415 /* === public interface functions === */
1416
1417 /* Get stabilization data (translation, scaling and angle) for a given frame.
1418  * Returned data describes how to compensate the detected movement, but with any
1419  * chosen scale factor already applied and any target frame position already
1420  * compensated. In case stabilization fails or is disabled, neutral values are
1421  * returned.
1422  *
1423  * framenr is a frame number, relative to the clip (not relative to the scene
1424  *         timeline)
1425  * width is an effective width of the canvas (square pixels), used to scale the
1426  *       determined translation
1427  *
1428  * Outputs:
1429  * - translation of the lateral shift, absolute canvas coordinates
1430  *   (square pixels).
1431  * - scale of the scaling to apply
1432  * - angle of the rotation angle, relative to the frame center
1433  */
1434 /* TODO(sergey): Use r_ prefix for output parameters here. */
1435 void BKE_tracking_stabilization_data_get(MovieClip *clip,
1436                                          int framenr,
1437                                          int width,
1438                                          int height,
1439                                          float translation[2],
1440                                          float *scale,
1441                                          float *angle)
1442 {
1443         StabContext *ctx = NULL;
1444         MovieTracking *tracking = &clip->tracking;
1445         bool enabled = (tracking->stabilization.flag & TRACKING_2D_STABILIZATION);
1446         /* Might become a parameter of a stabilization compositor node. */
1447         bool do_compensate = true;
1448         float scale_step = 0.0f;
1449         float pixel_aspect = tracking->camera.pixel_aspect;
1450         float aspect = (float)width * pixel_aspect / height;
1451         int size = height;
1452         float pivot[2];
1453
1454         if (enabled) {
1455                 ctx = init_stabilizer(clip, size, aspect);
1456         }
1457
1458         if (enabled &&
1459                 stabilization_determine_offset_for_frame(ctx,
1460                                                          framenr,
1461                                                          aspect,
1462                                                          translation,
1463                                                          pivot,
1464                                                          angle,
1465                                                          &scale_step))
1466         {
1467                 stabilization_calculate_data(ctx,
1468                                              framenr,
1469                                              size,
1470                                              aspect,
1471                                              do_compensate,
1472                                              scale_step,
1473                                              translation,
1474                                              pivot,
1475                                              scale,
1476                                              angle);
1477                 compensate_rotation_center(size,
1478                                            aspect,
1479                                            *angle,
1480                                            *scale,
1481                                            pivot,
1482                                            translation);
1483         }
1484         else {
1485                 zero_v2(translation);
1486                 *scale = 1.0f;
1487                 *angle = 0.0f;
1488         }
1489         discard_stabilization_working_context(ctx);
1490 }
1491
1492 /* Stabilize given image buffer using stabilization data for a specified
1493  * frame number.
1494  *
1495  * NOTE: frame number should be in clip space, not scene space.
1496  */
1497 /* TODO(sergey): Use r_ prefix for output parameters here. */
1498 ImBuf *BKE_tracking_stabilize_frame(MovieClip *clip,
1499                                     int framenr,
1500                                     ImBuf *ibuf,
1501                                     float translation[2],
1502                                     float *scale,
1503                                     float *angle)
1504 {
1505         float tloc[2], tscale, tangle;
1506         MovieTracking *tracking = &clip->tracking;
1507         MovieTrackingStabilization *stab = &tracking->stabilization;
1508         ImBuf *tmpibuf;
1509         int width = ibuf->x, height = ibuf->y;
1510         float pixel_aspect = tracking->camera.pixel_aspect;
1511         float mat[4][4];
1512         int j, filter = tracking->stabilization.filter;
1513         void (*interpolation)(struct ImBuf *, struct ImBuf *, float, float, int, int) = NULL;
1514         int ibuf_flags;
1515
1516         if (translation)
1517                 copy_v2_v2(tloc, translation);
1518
1519         if (scale)
1520                 tscale = *scale;
1521
1522         /* Perform early output if no stabilization is used. */
1523         if ((stab->flag & TRACKING_2D_STABILIZATION) == 0) {
1524                 if (translation)
1525                         zero_v2(translation);
1526
1527                 if (scale)
1528                         *scale = 1.0f;
1529
1530                 if (angle)
1531                         *angle = 0.0f;
1532
1533                 return ibuf;
1534         }
1535
1536         /* Allocate frame for stabilization result. */
1537         ibuf_flags = 0;
1538         if (ibuf->rect)
1539                 ibuf_flags |= IB_rect;
1540         if (ibuf->rect_float)
1541                 ibuf_flags |= IB_rectfloat;
1542
1543         tmpibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, ibuf_flags);
1544
1545         /* Calculate stabilization matrix. */
1546         BKE_tracking_stabilization_data_get(clip, framenr, width, height, tloc, &tscale, &tangle);
1547         BKE_tracking_stabilization_data_to_mat4(ibuf->x, ibuf->y, pixel_aspect, tloc, tscale, tangle, mat);
1548
1549         /* The following code visits each nominal target grid position
1550          * and picks interpolated data "backwards" from source.
1551          * thus we need the inverse of the transformation to apply. */
1552         invert_m4(mat);
1553
1554         if (filter == TRACKING_FILTER_NEAREST)
1555                 interpolation = nearest_interpolation;
1556         else if (filter == TRACKING_FILTER_BILINEAR)
1557                 interpolation = bilinear_interpolation;
1558         else if (filter == TRACKING_FILTER_BICUBIC)
1559                 interpolation = bicubic_interpolation;
1560         else
1561                 /* fallback to default interpolation method */
1562                 interpolation = nearest_interpolation;
1563
1564         /* This function is only used for display in clip editor and
1565          * sequencer only, which would only benefit of using threads
1566          * here.
1567          *
1568          * But need to keep an eye on this if the function will be
1569          * used in other cases.
1570          */
1571 #pragma omp parallel for if (tmpibuf->y > 128)
1572         for (j = 0; j < tmpibuf->y; j++) {
1573                 int i;
1574                 for (i = 0; i < tmpibuf->x; i++) {
1575                         float vec[3] = {i, j, 0.0f};
1576
1577                         mul_v3_m4v3(vec, mat, vec);
1578
1579                         interpolation(ibuf, tmpibuf, vec[0], vec[1], i, j);
1580                 }
1581         }
1582
1583         if (tmpibuf->rect_float)
1584                 tmpibuf->userflags |= IB_RECT_INVALID;
1585
1586         if (translation)
1587                 copy_v2_v2(translation, tloc);
1588
1589         if (scale)
1590                 *scale = tscale;
1591
1592         if (angle)
1593                 *angle = tangle;
1594
1595         return tmpibuf;
1596 }
1597
1598
1599 /* Build a 4x4 transformation matrix based on the given 2D stabilization data.
1600  * mat is a 4x4 matrix in homogeneous coordinates, adapted to the
1601  *     final image buffer size and compensated for pixel aspect ratio,
1602  *     ready for direct OpenGL drawing.
1603  *
1604  * TODO(sergey): The signature of this function should be changed. we actually
1605  *               don't need the dimensions of the image buffer. Instead we
1606  *               should consider to provide the pivot point of the rotation as a
1607  *               further stabilization data parameter.
1608  */
1609 void BKE_tracking_stabilization_data_to_mat4(int buffer_width,
1610                                              int buffer_height,
1611                                              float pixel_aspect,
1612                                              float translation[2],
1613                                              float scale,
1614                                              float angle,
1615                                              float r_mat[4][4])
1616 {
1617         /* Since we cannot receive the real pivot point coordinates (API limitation),
1618          * we perform the rotation/scale around the center of frame.
1619          * Then we correct by an additional shift, which was calculated in
1620          * compensate_rotation_center() and "sneaked in" as additional offset
1621          * in the translation parameter. This works, since translation needs to be
1622          * applied after rotation/scale anyway. Thus effectively the image gets
1623          * rotated around the desired pivot point
1624          */
1625         /* TODO(sergey) pivot shouldn't be calculated here, rather received
1626          * as a parameter.
1627          */
1628         float pivot[2];
1629         pivot[0] = 0.5f * pixel_aspect * buffer_width;
1630         pivot[1] = 0.5f * buffer_height;
1631         /* Compose transformation matrix. */
1632         stabilization_data_to_mat4(pixel_aspect,
1633                                    pivot,
1634                                    translation,
1635                                    scale,
1636                                    angle,
1637                                    r_mat);
1638 }