FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
vf_deshake.c
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2010 Georg Martius <georg.martius@web.de>
3  * Copyright (C) 2010 Daniel G. Taylor <dan@programmer-art.org>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 /**
23  * @file
24  * fast deshake / depan video filter
25  *
26  * SAD block-matching motion compensation to fix small changes in
27  * horizontal and/or vertical shift. This filter helps remove camera shake
28  * from hand-holding a camera, bumping a tripod, moving on a vehicle, etc.
29  *
30  * Algorithm:
31  * - For each frame with one previous reference frame
32  * - For each block in the frame
33  * - If contrast > threshold then find likely motion vector
34  * - For all found motion vectors
35  * - Find most common, store as global motion vector
36  * - Find most likely rotation angle
37  * - Transform image along global motion
38  *
39  * TODO:
40  * - Fill frame edges based on previous/next reference frames
41  * - Fill frame edges by stretching image near the edges?
42  * - Can this be done quickly and look decent?
43  *
44  * Dark Shikari links to http://wiki.videolan.org/SoC_x264_2010#GPU_Motion_Estimation_2
45  * for an algorithm similar to what could be used here to get the gmv
46  * It requires only a couple diamond searches + fast downscaling
47  *
48  * Special thanks to Jason Kotenko for his help with the algorithm and my
49  * inability to see simple errors in C code.
50  */
51 
52 #include "avfilter.h"
53 #include "formats.h"
54 #include "internal.h"
55 #include "video.h"
56 #include "libavutil/common.h"
57 #include "libavutil/mem.h"
58 #include "libavutil/pixdesc.h"
59 #include "libavcodec/dsputil.h"
60 
61 #include "transform.h"
62 
63 #define CHROMA_WIDTH(link) -((-link->w) >> av_pix_fmt_desc_get(link->format)->log2_chroma_w)
64 #define CHROMA_HEIGHT(link) -((-link->h) >> av_pix_fmt_desc_get(link->format)->log2_chroma_h)
65 
67  EXHAUSTIVE, ///< Search all possible positions
68  SMART_EXHAUSTIVE, ///< Search most possible positions (faster)
70 };
71 
72 typedef struct {
73  int x; ///< Horizontal shift
74  int y; ///< Vertical shift
76 
77 typedef struct {
78  double x; ///< Horizontal shift
79  double y; ///< Vertical shift
80 } MotionVector;
81 
82 typedef struct {
83  MotionVector vector; ///< Motion vector
84  double angle; ///< Angle of rotation
85  double zoom; ///< Zoom percentage
86 } Transform;
87 
88 typedef struct {
90  AVFilterBufferRef *ref; ///< Previous frame
91  int rx; ///< Maximum horizontal shift
92  int ry; ///< Maximum vertical shift
93  int edge; ///< Edge fill method
94  int blocksize; ///< Size of blocks to compare
95  int contrast; ///< Contrast threshold
96  int search; ///< Motion search method
98  DSPContext c; ///< Context providing optimized SAD methods
99  Transform last; ///< Transform from last frame
100  int refcount; ///< Number of reference frames (defines averaging window)
101  FILE *fp;
103  int cw; ///< Crop motion search to this box
104  int ch;
105  int cx;
106  int cy;
108 
109 static int cmp(const double *a, const double *b)
110 {
111  return *a < *b ? -1 : ( *a > *b ? 1 : 0 );
112 }
113 
114 /**
115  * Cleaned mean (cuts off 20% of values to remove outliers and then averages)
116  */
117 static double clean_mean(double *values, int count)
118 {
119  double mean = 0;
120  int cut = count / 5;
121  int x;
122 
123  qsort(values, count, sizeof(double), (void*)cmp);
124 
125  for (x = cut; x < count - cut; x++) {
126  mean += values[x];
127  }
128 
129  return mean / (count - cut * 2);
130 }
131 
132 /**
133  * Find the most likely shift in motion between two frames for a given
134  * macroblock. Test each block against several shifts given by the rx
135  * and ry attributes. Searches using a simple matrix of those shifts and
136  * chooses the most likely shift by the smallest difference in blocks.
137  */
138 static void find_block_motion(DeshakeContext *deshake, uint8_t *src1,
139  uint8_t *src2, int cx, int cy, int stride,
141 {
142  int x, y;
143  int diff;
144  int smallest = INT_MAX;
145  int tmp, tmp2;
146 
147  #define CMP(i, j) deshake->c.sad[0](deshake, src1 + cy * stride + cx, \
148  src2 + (j) * stride + (i), stride, \
149  deshake->blocksize)
150 
151  if (deshake->search == EXHAUSTIVE) {
152  // Compare every possible position - this is sloooow!
153  for (y = -deshake->ry; y <= deshake->ry; y++) {
154  for (x = -deshake->rx; x <= deshake->rx; x++) {
155  diff = CMP(cx - x, cy - y);
156  if (diff < smallest) {
157  smallest = diff;
158  mv->x = x;
159  mv->y = y;
160  }
161  }
162  }
163  } else if (deshake->search == SMART_EXHAUSTIVE) {
164  // Compare every other possible position and find the best match
165  for (y = -deshake->ry + 1; y < deshake->ry - 2; y += 2) {
166  for (x = -deshake->rx + 1; x < deshake->rx - 2; x += 2) {
167  diff = CMP(cx - x, cy - y);
168  if (diff < smallest) {
169  smallest = diff;
170  mv->x = x;
171  mv->y = y;
172  }
173  }
174  }
175 
176  // Hone in on the specific best match around the match we found above
177  tmp = mv->x;
178  tmp2 = mv->y;
179 
180  for (y = tmp2 - 1; y <= tmp2 + 1; y++) {
181  for (x = tmp - 1; x <= tmp + 1; x++) {
182  if (x == tmp && y == tmp2)
183  continue;
184 
185  diff = CMP(cx - x, cy - y);
186  if (diff < smallest) {
187  smallest = diff;
188  mv->x = x;
189  mv->y = y;
190  }
191  }
192  }
193  }
194 
195  if (smallest > 512) {
196  mv->x = -1;
197  mv->y = -1;
198  }
199  emms_c();
200  //av_log(NULL, AV_LOG_ERROR, "%d\n", smallest);
201  //av_log(NULL, AV_LOG_ERROR, "Final: (%d, %d) = %d x %d\n", cx, cy, mv->x, mv->y);
202 }
203 
204 /**
205  * Find the contrast of a given block. When searching for global motion we
206  * really only care about the high contrast blocks, so using this method we
207  * can actually skip blocks we don't care much about.
208  */
209 static int block_contrast(uint8_t *src, int x, int y, int stride, int blocksize)
210 {
211  int highest = 0;
212  int lowest = 0;
213  int i, j, pos;
214 
215  for (i = 0; i <= blocksize * 2; i++) {
216  // We use a width of 16 here to match the libavcodec sad functions
217  for (j = 0; i <= 15; i++) {
218  pos = (y - i) * stride + (x - j);
219  if (src[pos] < lowest)
220  lowest = src[pos];
221  else if (src[pos] > highest) {
222  highest = src[pos];
223  }
224  }
225  }
226 
227  return highest - lowest;
228 }
229 
230 /**
231  * Find the rotation for a given block.
232  */
233 static double block_angle(int x, int y, int cx, int cy, IntMotionVector *shift)
234 {
235  double a1, a2, diff;
236 
237  a1 = atan2(y - cy, x - cx);
238  a2 = atan2(y - cy + shift->y, x - cx + shift->x);
239 
240  diff = a2 - a1;
241 
242  return (diff > M_PI) ? diff - 2 * M_PI :
243  (diff < -M_PI) ? diff + 2 * M_PI :
244  diff;
245 }
246 
247 /**
248  * Find the estimated global motion for a scene given the most likely shift
249  * for each block in the frame. The global motion is estimated to be the
250  * same as the motion from most blocks in the frame, so if most blocks
251  * move one pixel to the right and two pixels down, this would yield a
252  * motion vector (1, -2).
253  */
254 static void find_motion(DeshakeContext *deshake, uint8_t *src1, uint8_t *src2,
255  int width, int height, int stride, Transform *t)
256 {
257  int x, y;
258  IntMotionVector mv = {0, 0};
259  int counts[128][128];
260  int count_max_value = 0;
261  int contrast;
262 
263  int pos;
264  double *angles = av_malloc(sizeof(*angles) * width * height / (16 * deshake->blocksize));
265  int center_x = 0, center_y = 0;
266  double p_x, p_y;
267 
268  // Reset counts to zero
269  for (x = 0; x < deshake->rx * 2 + 1; x++) {
270  for (y = 0; y < deshake->ry * 2 + 1; y++) {
271  counts[x][y] = 0;
272  }
273  }
274 
275  pos = 0;
276  // Find motion for every block and store the motion vector in the counts
277  for (y = deshake->ry; y < height - deshake->ry - (deshake->blocksize * 2); y += deshake->blocksize * 2) {
278  // We use a width of 16 here to match the libavcodec sad functions
279  for (x = deshake->rx; x < width - deshake->rx - 16; x += 16) {
280  // If the contrast is too low, just skip this block as it probably
281  // won't be very useful to us.
282  contrast = block_contrast(src2, x, y, stride, deshake->blocksize);
283  if (contrast > deshake->contrast) {
284  //av_log(NULL, AV_LOG_ERROR, "%d\n", contrast);
285  find_block_motion(deshake, src1, src2, x, y, stride, &mv);
286  if (mv.x != -1 && mv.y != -1) {
287  counts[mv.x + deshake->rx][mv.y + deshake->ry] += 1;
288  if (x > deshake->rx && y > deshake->ry)
289  angles[pos++] = block_angle(x, y, 0, 0, &mv);
290 
291  center_x += mv.x;
292  center_y += mv.y;
293  }
294  }
295  }
296  }
297 
298  if (pos) {
299  center_x /= pos;
300  center_y /= pos;
301  t->angle = clean_mean(angles, pos);
302  if (t->angle < 0.001)
303  t->angle = 0;
304  } else {
305  t->angle = 0;
306  }
307 
308  // Find the most common motion vector in the frame and use it as the gmv
309  for (y = deshake->ry * 2; y >= 0; y--) {
310  for (x = 0; x < deshake->rx * 2 + 1; x++) {
311  //av_log(NULL, AV_LOG_ERROR, "%5d ", counts[x][y]);
312  if (counts[x][y] > count_max_value) {
313  t->vector.x = x - deshake->rx;
314  t->vector.y = y - deshake->ry;
315  count_max_value = counts[x][y];
316  }
317  }
318  //av_log(NULL, AV_LOG_ERROR, "\n");
319  }
320 
321  p_x = (center_x - width / 2);
322  p_y = (center_y - height / 2);
323  t->vector.x += (cos(t->angle)-1)*p_x - sin(t->angle)*p_y;
324  t->vector.y += sin(t->angle)*p_x + (cos(t->angle)-1)*p_y;
325 
326  // Clamp max shift & rotation?
327  t->vector.x = av_clipf(t->vector.x, -deshake->rx * 2, deshake->rx * 2);
328  t->vector.y = av_clipf(t->vector.y, -deshake->ry * 2, deshake->ry * 2);
329  t->angle = av_clipf(t->angle, -0.1, 0.1);
330 
331  //av_log(NULL, AV_LOG_ERROR, "%d x %d\n", avg->x, avg->y);
332  av_free(angles);
333 }
334 
335 static av_cold int init(AVFilterContext *ctx, const char *args)
336 {
337  DeshakeContext *deshake = ctx->priv;
338  char filename[256] = {0};
339 
340  deshake->rx = 16;
341  deshake->ry = 16;
342  deshake->edge = FILL_MIRROR;
343  deshake->blocksize = 8;
344  deshake->contrast = 125;
345  deshake->search = EXHAUSTIVE;
346  deshake->refcount = 20;
347 
348  deshake->cw = -1;
349  deshake->ch = -1;
350  deshake->cx = -1;
351  deshake->cy = -1;
352 
353  if (args) {
354  sscanf(args, "%d:%d:%d:%d:%d:%d:%d:%d:%d:%d:%255s",
355  &deshake->cx, &deshake->cy, &deshake->cw, &deshake->ch,
356  &deshake->rx, &deshake->ry, &deshake->edge,
357  &deshake->blocksize, &deshake->contrast, &deshake->search, filename);
358 
359  deshake->blocksize /= 2;
360 
361  deshake->rx = av_clip(deshake->rx, 0, 64);
362  deshake->ry = av_clip(deshake->ry, 0, 64);
363  deshake->edge = av_clip(deshake->edge, FILL_BLANK, FILL_COUNT - 1);
364  deshake->blocksize = av_clip(deshake->blocksize, 4, 128);
365  deshake->contrast = av_clip(deshake->contrast, 1, 255);
366  deshake->search = av_clip(deshake->search, EXHAUSTIVE, SEARCH_COUNT - 1);
367 
368  }
369  if (*filename)
370  deshake->fp = fopen(filename, "w");
371  if (deshake->fp)
372  fwrite("Ori x, Avg x, Fin x, Ori y, Avg y, Fin y, Ori angle, Avg angle, Fin angle, Ori zoom, Avg zoom, Fin zoom\n", sizeof(char), 104, deshake->fp);
373 
374  // Quadword align left edge of box for MMX code, adjust width if necessary
375  // to keep right margin
376  if (deshake->cx > 0) {
377  deshake->cw += deshake->cx - (deshake->cx & ~15);
378  deshake->cx &= ~15;
379  }
380 
381  av_log(ctx, AV_LOG_VERBOSE, "cx: %d, cy: %d, cw: %d, ch: %d, rx: %d, ry: %d, edge: %d blocksize: %d contrast: %d search: %d\n",
382  deshake->cx, deshake->cy, deshake->cw, deshake->ch,
383  deshake->rx, deshake->ry, deshake->edge, deshake->blocksize * 2, deshake->contrast, deshake->search);
384 
385  return 0;
386 }
387 
389 {
390  static const enum AVPixelFormat pix_fmts[] = {
394  };
395 
397 
398  return 0;
399 }
400 
401 static int config_props(AVFilterLink *link)
402 {
403  DeshakeContext *deshake = link->dst->priv;
404 
405  deshake->ref = NULL;
406  deshake->last.vector.x = 0;
407  deshake->last.vector.y = 0;
408  deshake->last.angle = 0;
409  deshake->last.zoom = 0;
410 
411  deshake->avctx = avcodec_alloc_context3(NULL);
412  dsputil_init(&deshake->c, deshake->avctx);
413 
414  return 0;
415 }
416 
417 static av_cold void uninit(AVFilterContext *ctx)
418 {
419  DeshakeContext *deshake = ctx->priv;
420 
421  avfilter_unref_buffer(deshake->ref);
422  if (deshake->fp)
423  fclose(deshake->fp);
424  if (deshake->avctx)
425  avcodec_close(deshake->avctx);
426  av_freep(&deshake->avctx);
427 }
428 
430 {
431  DeshakeContext *deshake = link->dst->priv;
432  AVFilterLink *outlink = link->dst->outputs[0];
433  AVFilterBufferRef *out;
434  Transform t = {{0},0}, orig = {{0},0};
435  float matrix[9];
436  float alpha = 2.0 / deshake->refcount;
437  char tmp[256];
438 
439  out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
440  if (!out) {
442  return AVERROR(ENOMEM);
443  }
445 
446  if (deshake->cx < 0 || deshake->cy < 0 || deshake->cw < 0 || deshake->ch < 0) {
447  // Find the most likely global motion for the current frame
448  find_motion(deshake, (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0], in->data[0], link->w, link->h, in->linesize[0], &t);
449  } else {
450  uint8_t *src1 = (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0];
451  uint8_t *src2 = in->data[0];
452 
453  deshake->cx = FFMIN(deshake->cx, link->w);
454  deshake->cy = FFMIN(deshake->cy, link->h);
455 
456  if ((unsigned)deshake->cx + (unsigned)deshake->cw > link->w) deshake->cw = link->w - deshake->cx;
457  if ((unsigned)deshake->cy + (unsigned)deshake->ch > link->h) deshake->ch = link->h - deshake->cy;
458 
459  // Quadword align right margin
460  deshake->cw &= ~15;
461 
462  src1 += deshake->cy * in->linesize[0] + deshake->cx;
463  src2 += deshake->cy * in->linesize[0] + deshake->cx;
464 
465  find_motion(deshake, src1, src2, deshake->cw, deshake->ch, in->linesize[0], &t);
466  }
467 
468 
469  // Copy transform so we can output it later to compare to the smoothed value
470  orig.vector.x = t.vector.x;
471  orig.vector.y = t.vector.y;
472  orig.angle = t.angle;
473  orig.zoom = t.zoom;
474 
475  // Generate a one-sided moving exponential average
476  deshake->avg.vector.x = alpha * t.vector.x + (1.0 - alpha) * deshake->avg.vector.x;
477  deshake->avg.vector.y = alpha * t.vector.y + (1.0 - alpha) * deshake->avg.vector.y;
478  deshake->avg.angle = alpha * t.angle + (1.0 - alpha) * deshake->avg.angle;
479  deshake->avg.zoom = alpha * t.zoom + (1.0 - alpha) * deshake->avg.zoom;
480 
481  // Remove the average from the current motion to detect the motion that
482  // is not on purpose, just as jitter from bumping the camera
483  t.vector.x -= deshake->avg.vector.x;
484  t.vector.y -= deshake->avg.vector.y;
485  t.angle -= deshake->avg.angle;
486  t.zoom -= deshake->avg.zoom;
487 
488  // Invert the motion to undo it
489  t.vector.x *= -1;
490  t.vector.y *= -1;
491  t.angle *= -1;
492 
493  // Write statistics to file
494  if (deshake->fp) {
495  snprintf(tmp, 256, "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f\n", orig.vector.x, deshake->avg.vector.x, t.vector.x, orig.vector.y, deshake->avg.vector.y, t.vector.y, orig.angle, deshake->avg.angle, t.angle, orig.zoom, deshake->avg.zoom, t.zoom);
496  fwrite(tmp, sizeof(char), strlen(tmp), deshake->fp);
497  }
498 
499  // Turn relative current frame motion into absolute by adding it to the
500  // last absolute motion
501  t.vector.x += deshake->last.vector.x;
502  t.vector.y += deshake->last.vector.y;
503  t.angle += deshake->last.angle;
504  t.zoom += deshake->last.zoom;
505 
506  // Shrink motion by 10% to keep things centered in the camera frame
507  t.vector.x *= 0.9;
508  t.vector.y *= 0.9;
509  t.angle *= 0.9;
510 
511  // Store the last absolute motion information
512  deshake->last.vector.x = t.vector.x;
513  deshake->last.vector.y = t.vector.y;
514  deshake->last.angle = t.angle;
515  deshake->last.zoom = t.zoom;
516 
517  // Generate a luma transformation matrix
518  avfilter_get_matrix(t.vector.x, t.vector.y, t.angle, 1.0 + t.zoom / 100.0, matrix);
519 
520  // Transform the luma plane
521  avfilter_transform(in->data[0], out->data[0], in->linesize[0], out->linesize[0], link->w, link->h, matrix, INTERPOLATE_BILINEAR, deshake->edge);
522 
523  // Generate a chroma transformation matrix
524  avfilter_get_matrix(t.vector.x / (link->w / CHROMA_WIDTH(link)), t.vector.y / (link->h / CHROMA_HEIGHT(link)), t.angle, 1.0 + t.zoom / 100.0, matrix);
525 
526  // Transform the chroma planes
527  avfilter_transform(in->data[1], out->data[1], in->linesize[1], out->linesize[1], CHROMA_WIDTH(link), CHROMA_HEIGHT(link), matrix, INTERPOLATE_BILINEAR, deshake->edge);
528  avfilter_transform(in->data[2], out->data[2], in->linesize[2], out->linesize[2], CHROMA_WIDTH(link), CHROMA_HEIGHT(link), matrix, INTERPOLATE_BILINEAR, deshake->edge);
529 
530  // Cleanup the old reference frame
531  avfilter_unref_buffer(deshake->ref);
532 
533  // Store the current frame as the reference frame for calculating the
534  // motion of the next frame
535  deshake->ref = in;
536 
537  return ff_filter_frame(outlink, out);
538 }
539 
540 static const AVFilterPad deshake_inputs[] = {
541  {
542  .name = "default",
543  .type = AVMEDIA_TYPE_VIDEO,
544  .filter_frame = filter_frame,
545  .config_props = config_props,
546  .min_perms = AV_PERM_READ | AV_PERM_PRESERVE,
547  },
548  { NULL }
549 };
550 
551 static const AVFilterPad deshake_outputs[] = {
552  {
553  .name = "default",
554  .type = AVMEDIA_TYPE_VIDEO,
555  },
556  { NULL }
557 };
558 
560  .name = "deshake",
561  .description = NULL_IF_CONFIG_SMALL("Stabilize shaky video."),
562  .priv_size = sizeof(DeshakeContext),
563  .init = init,
564  .uninit = uninit,
566  .inputs = deshake_inputs,
567  .outputs = deshake_outputs,
568 };