FFmpeg
 All Data Structures Namespaces 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/opt.h"
59 #include "libavutil/pixdesc.h"
60 
61 #include "deshake.h"
62 #include "deshake_opencl.h"
63 
64 #define CHROMA_WIDTH(link) (-((-(link)->w) >> av_pix_fmt_desc_get((link)->format)->log2_chroma_w))
65 #define CHROMA_HEIGHT(link) (-((-(link)->h) >> av_pix_fmt_desc_get((link)->format)->log2_chroma_h))
66 
67 #define OFFSET(x) offsetof(DeshakeContext, x)
68 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
69 
70 static const AVOption deshake_options[] = {
71  { "x", "set x for the rectangular search area", OFFSET(cx), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS },
72  { "y", "set y for the rectangular search area", OFFSET(cy), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS },
73  { "w", "set width for the rectangular search area", OFFSET(cw), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS },
74  { "h", "set height for the rectangular search area", OFFSET(ch), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS },
75  { "rx", "set x for the rectangular search area", OFFSET(rx), AV_OPT_TYPE_INT, {.i64=16}, 0, MAX_R, .flags = FLAGS },
76  { "ry", "set y for the rectangular search area", OFFSET(ry), AV_OPT_TYPE_INT, {.i64=16}, 0, MAX_R, .flags = FLAGS },
77  { "edge", "set edge mode", OFFSET(edge), AV_OPT_TYPE_INT, {.i64=FILL_MIRROR}, FILL_BLANK, FILL_COUNT-1, FLAGS, "edge"},
78  { "blank", "fill zeroes at blank locations", 0, AV_OPT_TYPE_CONST, {.i64=FILL_BLANK}, INT_MIN, INT_MAX, FLAGS, "edge" },
79  { "original", "original image at blank locations", 0, AV_OPT_TYPE_CONST, {.i64=FILL_ORIGINAL}, INT_MIN, INT_MAX, FLAGS, "edge" },
80  { "clamp", "extruded edge value at blank locations", 0, AV_OPT_TYPE_CONST, {.i64=FILL_CLAMP}, INT_MIN, INT_MAX, FLAGS, "edge" },
81  { "mirror", "mirrored edge at blank locations", 0, AV_OPT_TYPE_CONST, {.i64=FILL_MIRROR}, INT_MIN, INT_MAX, FLAGS, "edge" },
82  { "blocksize", "set motion search blocksize", OFFSET(blocksize), AV_OPT_TYPE_INT, {.i64=8}, 4, 128, .flags = FLAGS },
83  { "contrast", "set contrast threshold for blocks", OFFSET(contrast), AV_OPT_TYPE_INT, {.i64=125}, 1, 255, .flags = FLAGS },
84  { "search", "set search strategy", OFFSET(search), AV_OPT_TYPE_INT, {.i64=EXHAUSTIVE}, EXHAUSTIVE, SEARCH_COUNT-1, FLAGS, "smode" },
85  { "exhaustive", "exhaustive search", 0, AV_OPT_TYPE_CONST, {.i64=EXHAUSTIVE}, INT_MIN, INT_MAX, FLAGS, "smode" },
86  { "less", "less exhaustive search", 0, AV_OPT_TYPE_CONST, {.i64=SMART_EXHAUSTIVE}, INT_MIN, INT_MAX, FLAGS, "smode" },
87  { "filename", "set motion search detailed log file name", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
88  { "opencl", "use OpenCL filtering capabilities", OFFSET(opencl), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, .flags = FLAGS },
89  { NULL }
90 };
91 
92 AVFILTER_DEFINE_CLASS(deshake);
93 
94 static int cmp(const double *a, const double *b)
95 {
96  return *a < *b ? -1 : ( *a > *b ? 1 : 0 );
97 }
98 
99 /**
100  * Cleaned mean (cuts off 20% of values to remove outliers and then averages)
101  */
102 static double clean_mean(double *values, int count)
103 {
104  double mean = 0;
105  int cut = count / 5;
106  int x;
107 
108  qsort(values, count, sizeof(double), (void*)cmp);
109 
110  for (x = cut; x < count - cut; x++) {
111  mean += values[x];
112  }
113 
114  return mean / (count - cut * 2);
115 }
116 
117 /**
118  * Find the most likely shift in motion between two frames for a given
119  * macroblock. Test each block against several shifts given by the rx
120  * and ry attributes. Searches using a simple matrix of those shifts and
121  * chooses the most likely shift by the smallest difference in blocks.
122  */
124  uint8_t *src2, int cx, int cy, int stride,
126 {
127  int x, y;
128  int diff;
129  int smallest = INT_MAX;
130  int tmp, tmp2;
131 
132  #define CMP(i, j) deshake->sad(src1 + cy * stride + cx, stride,\
133  src2 + (j) * stride + (i), stride)
134 
135  if (deshake->search == EXHAUSTIVE) {
136  // Compare every possible position - this is sloooow!
137  for (y = -deshake->ry; y <= deshake->ry; y++) {
138  for (x = -deshake->rx; x <= deshake->rx; x++) {
139  diff = CMP(cx - x, cy - y);
140  if (diff < smallest) {
141  smallest = diff;
142  mv->x = x;
143  mv->y = y;
144  }
145  }
146  }
147  } else if (deshake->search == SMART_EXHAUSTIVE) {
148  // Compare every other possible position and find the best match
149  for (y = -deshake->ry + 1; y < deshake->ry; y += 2) {
150  for (x = -deshake->rx + 1; x < deshake->rx; x += 2) {
151  diff = CMP(cx - x, cy - y);
152  if (diff < smallest) {
153  smallest = diff;
154  mv->x = x;
155  mv->y = y;
156  }
157  }
158  }
159 
160  // Hone in on the specific best match around the match we found above
161  tmp = mv->x;
162  tmp2 = mv->y;
163 
164  for (y = tmp2 - 1; y <= tmp2 + 1; y++) {
165  for (x = tmp - 1; x <= tmp + 1; x++) {
166  if (x == tmp && y == tmp2)
167  continue;
168 
169  diff = CMP(cx - x, cy - y);
170  if (diff < smallest) {
171  smallest = diff;
172  mv->x = x;
173  mv->y = y;
174  }
175  }
176  }
177  }
178 
179  if (smallest > 512) {
180  mv->x = -1;
181  mv->y = -1;
182  }
183  emms_c();
184  //av_log(NULL, AV_LOG_ERROR, "%d\n", smallest);
185  //av_log(NULL, AV_LOG_ERROR, "Final: (%d, %d) = %d x %d\n", cx, cy, mv->x, mv->y);
186 }
187 
188 /**
189  * Find the contrast of a given block. When searching for global motion we
190  * really only care about the high contrast blocks, so using this method we
191  * can actually skip blocks we don't care much about.
192  */
193 static int block_contrast(uint8_t *src, int x, int y, int stride, int blocksize)
194 {
195  int highest = 0;
196  int lowest = 255;
197  int i, j, pos;
198 
199  for (i = 0; i <= blocksize * 2; i++) {
200  // We use a width of 16 here to match the sad function
201  for (j = 0; j <= 15; j++) {
202  pos = (y - i) * stride + (x - j);
203  if (src[pos] < lowest)
204  lowest = src[pos];
205  else if (src[pos] > highest) {
206  highest = src[pos];
207  }
208  }
209  }
210 
211  return highest - lowest;
212 }
213 
214 /**
215  * Find the rotation for a given block.
216  */
217 static double block_angle(int x, int y, int cx, int cy, IntMotionVector *shift)
218 {
219  double a1, a2, diff;
220 
221  a1 = atan2(y - cy, x - cx);
222  a2 = atan2(y - cy + shift->y, x - cx + shift->x);
223 
224  diff = a2 - a1;
225 
226  return (diff > M_PI) ? diff - 2 * M_PI :
227  (diff < -M_PI) ? diff + 2 * M_PI :
228  diff;
229 }
230 
231 /**
232  * Find the estimated global motion for a scene given the most likely shift
233  * for each block in the frame. The global motion is estimated to be the
234  * same as the motion from most blocks in the frame, so if most blocks
235  * move one pixel to the right and two pixels down, this would yield a
236  * motion vector (1, -2).
237  */
238 static void find_motion(DeshakeContext *deshake, uint8_t *src1, uint8_t *src2,
239  int width, int height, int stride, Transform *t)
240 {
241  int x, y;
242  IntMotionVector mv = {0, 0};
243  int count_max_value = 0;
244  int contrast;
245 
246  int pos;
247  int center_x = 0, center_y = 0;
248  double p_x, p_y;
249 
250  av_fast_malloc(&deshake->angles, &deshake->angles_size, width * height / (16 * deshake->blocksize) * sizeof(*deshake->angles));
251 
252  // Reset counts to zero
253  for (x = 0; x < deshake->rx * 2 + 1; x++) {
254  for (y = 0; y < deshake->ry * 2 + 1; y++) {
255  deshake->counts[x][y] = 0;
256  }
257  }
258 
259  pos = 0;
260  // Find motion for every block and store the motion vector in the counts
261  for (y = deshake->ry; y < height - deshake->ry - (deshake->blocksize * 2); y += deshake->blocksize * 2) {
262  // We use a width of 16 here to match the sad function
263  for (x = deshake->rx; x < width - deshake->rx - 16; x += 16) {
264  // If the contrast is too low, just skip this block as it probably
265  // won't be very useful to us.
266  contrast = block_contrast(src2, x, y, stride, deshake->blocksize);
267  if (contrast > deshake->contrast) {
268  //av_log(NULL, AV_LOG_ERROR, "%d\n", contrast);
269  find_block_motion(deshake, src1, src2, x, y, stride, &mv);
270  if (mv.x != -1 && mv.y != -1) {
271  deshake->counts[mv.x + deshake->rx][mv.y + deshake->ry] += 1;
272  if (x > deshake->rx && y > deshake->ry)
273  deshake->angles[pos++] = block_angle(x, y, 0, 0, &mv);
274 
275  center_x += mv.x;
276  center_y += mv.y;
277  }
278  }
279  }
280  }
281 
282  if (pos) {
283  center_x /= pos;
284  center_y /= pos;
285  t->angle = clean_mean(deshake->angles, pos);
286  if (t->angle < 0.001)
287  t->angle = 0;
288  } else {
289  t->angle = 0;
290  }
291 
292  // Find the most common motion vector in the frame and use it as the gmv
293  for (y = deshake->ry * 2; y >= 0; y--) {
294  for (x = 0; x < deshake->rx * 2 + 1; x++) {
295  //av_log(NULL, AV_LOG_ERROR, "%5d ", deshake->counts[x][y]);
296  if (deshake->counts[x][y] > count_max_value) {
297  t->vec.x = x - deshake->rx;
298  t->vec.y = y - deshake->ry;
299  count_max_value = deshake->counts[x][y];
300  }
301  }
302  //av_log(NULL, AV_LOG_ERROR, "\n");
303  }
304 
305  p_x = (center_x - width / 2.0);
306  p_y = (center_y - height / 2.0);
307  t->vec.x += (cos(t->angle)-1)*p_x - sin(t->angle)*p_y;
308  t->vec.y += sin(t->angle)*p_x + (cos(t->angle)-1)*p_y;
309 
310  // Clamp max shift & rotation?
311  t->vec.x = av_clipf(t->vec.x, -deshake->rx * 2, deshake->rx * 2);
312  t->vec.y = av_clipf(t->vec.y, -deshake->ry * 2, deshake->ry * 2);
313  t->angle = av_clipf(t->angle, -0.1, 0.1);
314 
315  //av_log(NULL, AV_LOG_ERROR, "%d x %d\n", avg->x, avg->y);
316 }
317 
319  int width, int height, int cw, int ch,
320  const float *matrix_y, const float *matrix_uv,
322  enum FillMethod fill, AVFrame *in, AVFrame *out)
323 {
324  int i = 0, ret = 0;
325  const float *matrixs[3];
326  int plane_w[3], plane_h[3];
327  matrixs[0] = matrix_y;
328  matrixs[1] = matrixs[2] = matrix_uv;
329  plane_w[0] = width;
330  plane_w[1] = plane_w[2] = cw;
331  plane_h[0] = height;
332  plane_h[1] = plane_h[2] = ch;
333 
334  for (i = 0; i < 3; i++) {
335  // Transform the luma and chroma planes
336  ret = avfilter_transform(in->data[i], out->data[i], in->linesize[i], out->linesize[i],
337  plane_w[i], plane_h[i], matrixs[i], interpolate, fill);
338  if (ret < 0)
339  return ret;
340  }
341  return ret;
342 }
343 
344 static av_cold int init(AVFilterContext *ctx)
345 {
346  int ret;
347  DeshakeContext *deshake = ctx->priv;
348 
349  deshake->sad = av_pixelutils_get_sad_fn(4, 4, 1, deshake); // 16x16, 2nd source unaligned
350  if (!deshake->sad)
351  return AVERROR(EINVAL);
352 
353  deshake->refcount = 20; // XXX: add to options?
354  deshake->blocksize /= 2;
355  deshake->blocksize = av_clip(deshake->blocksize, 4, 128);
356 
357  if (deshake->rx % 16) {
358  av_log(ctx, AV_LOG_ERROR, "rx must be a multiple of 16\n");
359  return AVERROR_PATCHWELCOME;
360  }
361 
362  if (deshake->filename)
363  deshake->fp = fopen(deshake->filename, "w");
364  if (deshake->fp)
365  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);
366 
367  // Quadword align left edge of box for MMX code, adjust width if necessary
368  // to keep right margin
369  if (deshake->cx > 0) {
370  deshake->cw += deshake->cx - (deshake->cx & ~15);
371  deshake->cx &= ~15;
372  }
373  deshake->transform = deshake_transform_c;
374  if (!CONFIG_OPENCL && deshake->opencl) {
375  av_log(ctx, AV_LOG_ERROR, "OpenCL support was not enabled in this build, cannot be selected\n");
376  return AVERROR(EINVAL);
377  }
378 
379  if (CONFIG_OPENCL && deshake->opencl) {
380  deshake->transform = ff_opencl_transform;
381  ret = ff_opencl_deshake_init(ctx);
382  if (ret < 0)
383  return ret;
384  }
385  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",
386  deshake->cx, deshake->cy, deshake->cw, deshake->ch,
387  deshake->rx, deshake->ry, deshake->edge, deshake->blocksize * 2, deshake->contrast, deshake->search);
388 
389  return 0;
390 }
391 
393 {
394  static const enum AVPixelFormat pix_fmts[] = {
398  };
399  AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
400  if (!fmts_list)
401  return AVERROR(ENOMEM);
402  return ff_set_common_formats(ctx, fmts_list);
403 }
404 
405 static int config_props(AVFilterLink *link)
406 {
407  DeshakeContext *deshake = link->dst->priv;
408 
409  deshake->ref = NULL;
410  deshake->last.vec.x = 0;
411  deshake->last.vec.y = 0;
412  deshake->last.angle = 0;
413  deshake->last.zoom = 0;
414 
415  return 0;
416 }
417 
418 static av_cold void uninit(AVFilterContext *ctx)
419 {
420  DeshakeContext *deshake = ctx->priv;
421  if (CONFIG_OPENCL && deshake->opencl) {
423  }
424  av_frame_free(&deshake->ref);
425  av_freep(&deshake->angles);
426  deshake->angles_size = 0;
427  if (deshake->fp)
428  fclose(deshake->fp);
429 }
430 
431 static int filter_frame(AVFilterLink *link, AVFrame *in)
432 {
433  DeshakeContext *deshake = link->dst->priv;
434  AVFilterLink *outlink = link->dst->outputs[0];
435  AVFrame *out;
436  Transform t = {{0},0}, orig = {{0},0};
437  float matrix_y[9], matrix_uv[9];
438  float alpha = 2.0 / deshake->refcount;
439  char tmp[256];
440  int ret = 0;
441 
442  out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
443  if (!out) {
444  av_frame_free(&in);
445  return AVERROR(ENOMEM);
446  }
447  av_frame_copy_props(out, in);
448 
449  if (CONFIG_OPENCL && deshake->opencl) {
450  ret = ff_opencl_deshake_process_inout_buf(link->dst,in, out);
451  if (ret < 0)
452  return ret;
453  }
454 
455  if (deshake->cx < 0 || deshake->cy < 0 || deshake->cw < 0 || deshake->ch < 0) {
456  // Find the most likely global motion for the current frame
457  find_motion(deshake, (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0], in->data[0], link->w, link->h, in->linesize[0], &t);
458  } else {
459  uint8_t *src1 = (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0];
460  uint8_t *src2 = in->data[0];
461 
462  deshake->cx = FFMIN(deshake->cx, link->w);
463  deshake->cy = FFMIN(deshake->cy, link->h);
464 
465  if ((unsigned)deshake->cx + (unsigned)deshake->cw > link->w) deshake->cw = link->w - deshake->cx;
466  if ((unsigned)deshake->cy + (unsigned)deshake->ch > link->h) deshake->ch = link->h - deshake->cy;
467 
468  // Quadword align right margin
469  deshake->cw &= ~15;
470 
471  src1 += deshake->cy * in->linesize[0] + deshake->cx;
472  src2 += deshake->cy * in->linesize[0] + deshake->cx;
473 
474  find_motion(deshake, src1, src2, deshake->cw, deshake->ch, in->linesize[0], &t);
475  }
476 
477 
478  // Copy transform so we can output it later to compare to the smoothed value
479  orig.vec.x = t.vec.x;
480  orig.vec.y = t.vec.y;
481  orig.angle = t.angle;
482  orig.zoom = t.zoom;
483 
484  // Generate a one-sided moving exponential average
485  deshake->avg.vec.x = alpha * t.vec.x + (1.0 - alpha) * deshake->avg.vec.x;
486  deshake->avg.vec.y = alpha * t.vec.y + (1.0 - alpha) * deshake->avg.vec.y;
487  deshake->avg.angle = alpha * t.angle + (1.0 - alpha) * deshake->avg.angle;
488  deshake->avg.zoom = alpha * t.zoom + (1.0 - alpha) * deshake->avg.zoom;
489 
490  // Remove the average from the current motion to detect the motion that
491  // is not on purpose, just as jitter from bumping the camera
492  t.vec.x -= deshake->avg.vec.x;
493  t.vec.y -= deshake->avg.vec.y;
494  t.angle -= deshake->avg.angle;
495  t.zoom -= deshake->avg.zoom;
496 
497  // Invert the motion to undo it
498  t.vec.x *= -1;
499  t.vec.y *= -1;
500  t.angle *= -1;
501 
502  // Write statistics to file
503  if (deshake->fp) {
504  snprintf(tmp, 256, "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f\n", orig.vec.x, deshake->avg.vec.x, t.vec.x, orig.vec.y, deshake->avg.vec.y, t.vec.y, orig.angle, deshake->avg.angle, t.angle, orig.zoom, deshake->avg.zoom, t.zoom);
505  fwrite(tmp, sizeof(char), strlen(tmp), deshake->fp);
506  }
507 
508  // Turn relative current frame motion into absolute by adding it to the
509  // last absolute motion
510  t.vec.x += deshake->last.vec.x;
511  t.vec.y += deshake->last.vec.y;
512  t.angle += deshake->last.angle;
513  t.zoom += deshake->last.zoom;
514 
515  // Shrink motion by 10% to keep things centered in the camera frame
516  t.vec.x *= 0.9;
517  t.vec.y *= 0.9;
518  t.angle *= 0.9;
519 
520  // Store the last absolute motion information
521  deshake->last.vec.x = t.vec.x;
522  deshake->last.vec.y = t.vec.y;
523  deshake->last.angle = t.angle;
524  deshake->last.zoom = t.zoom;
525 
526  // Generate a luma transformation matrix
527  avfilter_get_matrix(t.vec.x, t.vec.y, t.angle, 1.0 + t.zoom / 100.0, matrix_y);
528  // Generate a chroma transformation matrix
529  avfilter_get_matrix(t.vec.x / (link->w / CHROMA_WIDTH(link)), t.vec.y / (link->h / CHROMA_HEIGHT(link)), t.angle, 1.0 + t.zoom / 100.0, matrix_uv);
530  // Transform the luma and chroma planes
531  ret = deshake->transform(link->dst, link->w, link->h, CHROMA_WIDTH(link), CHROMA_HEIGHT(link),
532  matrix_y, matrix_uv, INTERPOLATE_BILINEAR, deshake->edge, in, out);
533 
534  // Cleanup the old reference frame
535  av_frame_free(&deshake->ref);
536 
537  if (ret < 0)
538  return ret;
539 
540  // Store the current frame as the reference frame for calculating the
541  // motion of the next frame
542  deshake->ref = in;
543 
544  return ff_filter_frame(outlink, out);
545 }
546 
547 static const AVFilterPad deshake_inputs[] = {
548  {
549  .name = "default",
550  .type = AVMEDIA_TYPE_VIDEO,
551  .filter_frame = filter_frame,
552  .config_props = config_props,
553  },
554  { NULL }
555 };
556 
557 static const AVFilterPad deshake_outputs[] = {
558  {
559  .name = "default",
560  .type = AVMEDIA_TYPE_VIDEO,
561  },
562  { NULL }
563 };
564 
566  .name = "deshake",
567  .description = NULL_IF_CONFIG_SMALL("Stabilize shaky video."),
568  .priv_size = sizeof(DeshakeContext),
569  .init = init,
570  .uninit = uninit,
572  .inputs = deshake_inputs,
573  .outputs = deshake_outputs,
574  .priv_class = &deshake_class,
575 };
#define NULL
Definition: coverity.c:32
static int shift(int a, int b)
Definition: sonic.c:82
This structure describes decoded (raw) audio or video data.
Definition: frame.h:171
#define OFFSET(x)
Definition: vf_deshake.c:67
AVOption.
Definition: opt.h:255
int ry
Maximum vertical shift.
Definition: deshake.h:83
planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
Definition: pixfmt.h:68
static const AVFilterPad outputs[]
Definition: af_ashowinfo.c:248
Main libavfilter public API header.
memory handling functions
#define FLAGS
Definition: vf_deshake.c:68
int y
Vertical shift.
Definition: deshake.h:42
const char * b
Definition: vf_curves.c:109
unsigned angles_size
Definition: deshake.h:80
#define a1
Definition: regdef.h:47
AVFrame * ff_get_video_buffer(AVFilterLink *link, int w, int h)
Request a picture buffer with a specific set of permissions.
Definition: video.c:109
double angle
Angle of rotation.
Definition: deshake.h:52
AVFilterFormats * ff_make_format_list(const int *fmts)
Create a list of supported formats.
Definition: formats.c:283
InterpolateMethod
Definition: transform.h:39
const char * name
Pad name.
Definition: internal.h:69
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:1158
double zoom
Zoom percentage.
Definition: deshake.h:53
uint8_t
#define av_cold
Definition: attributes.h:74
static float search(FOCContext *foc, int pass, int maxpass, int xmin, int xmax, int ymin, int ymax, int *best_x, int *best_y, float best_score)
Definition: vf_find_rect.c:156
AVOptions.
static void find_block_motion(DeshakeContext *deshake, uint8_t *src1, uint8_t *src2, int cx, int cy, int stride, IntMotionVector *mv)
Find the most likely shift in motion between two frames for a given macroblock.
Definition: vf_deshake.c:123
int avfilter_transform(const uint8_t *src, uint8_t *dst, int src_stride, int dst_stride, int width, int height, const float *matrix, enum InterpolateMethod interpolate, enum FillMethod fill)
Do an affine transformation with the given interpolation method.
Definition: transform.c:139
static double clean_mean(double *values, int count)
Cleaned mean (cuts off 20% of values to remove outliers and then averages)
Definition: vf_deshake.c:102
static void interpolate(float *out, float v1, float v2, int size)
Definition: twinvq.c:84
planar YUV 4:4:0 full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV440P and setting color_range...
Definition: pixfmt.h:102
int blocksize
Size of blocks to compare.
Definition: deshake.h:85
planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV422P and setting col...
Definition: pixfmt.h:76
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
FILE * fp
Definition: deshake.h:91
#define av_log(a,...)
A filter pad used for either input or output.
Definition: internal.h:63
int refcount
Number of reference frames (defines averaging window)
Definition: deshake.h:90
int rx
Maximum horizontal shift.
Definition: deshake.h:82
int ff_opencl_transform(AVFilterContext *ctx, int width, int height, int cw, int ch, const float *matrix_y, const float *matrix_uv, enum InterpolateMethod interpolate, enum FillMethod fill, AVFrame *in, AVFrame *out)
static double alpha(void *priv, double x, double y)
Definition: vf_geq.c:99
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
int ff_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats)
A helper for query_formats() which sets all links to the same list of formats.
Definition: formats.c:542
#define AVERROR(e)
Definition: error.h:43
AVFilter ff_vf_deshake
Definition: vf_deshake.c:565
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:148
AVFILTER_DEFINE_CLASS(deshake)
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:175
char * filename
Motion search detailed log filename.
Definition: deshake.h:97
void * priv
private data for use by the filter
Definition: avfilter.h:654
static int filter_frame(AVFilterLink *link, AVFrame *in)
Definition: vf_deshake.c:431
double x
Horizontal shift.
Definition: deshake.h:46
static int query_formats(AVFilterContext *ctx)
Definition: vf_deshake.c:392
av_pixelutils_sad_fn sad
Sum of the absolute difference function.
Definition: deshake.h:88
GLsizei count
Definition: opengl_enc.c:109
static const AVFilterPad deshake_inputs[]
Definition: vf_deshake.c:547
int contrast
Contrast threshold.
Definition: deshake.h:86
planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
Definition: pixfmt.h:67
static double block_angle(int x, int y, int cx, int cy, IntMotionVector *shift)
Find the rotation for a given block.
Definition: vf_deshake.c:217
static int deshake_transform_c(AVFilterContext *ctx, int width, int height, int cw, int ch, const float *matrix_y, const float *matrix_uv, enum InterpolateMethod interpolate, enum FillMethod fill, AVFrame *in, AVFrame *out)
Definition: vf_deshake.c:318
FillMethod
Definition: transform.h:51
#define FFMIN(a, b)
Definition: common.h:81
float y
planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV420P and setting col...
Definition: pixfmt.h:75
static void find_motion(DeshakeContext *deshake, uint8_t *src1, uint8_t *src2, int width, int height, int stride, Transform *t)
Find the estimated global motion for a scene given the most likely shift for each block in the frame...
Definition: vf_deshake.c:238
#define a2
Definition: regdef.h:48
int edge
Edge fill method.
Definition: deshake.h:84
int search
Motion search method.
Definition: deshake.h:87
#define CHROMA_HEIGHT(link)
Definition: vf_deshake.c:65
static const AVOption deshake_options[]
Definition: vf_deshake.c:70
double y
Vertical shift.
Definition: deshake.h:47
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
static const int8_t mv[256][2]
Definition: 4xm.c:77
Search all possible positions.
Definition: deshake.h:35
int ff_opencl_deshake_process_inout_buf(AVFilterContext *ctx, AVFrame *in, AVFrame *out)
#define src1
Definition: h264pred.c:139
AVS_Value src
Definition: avisynth_c.h:482
double * angles
< Scratch buffer for motion search
Definition: deshake.h:79
static int block_contrast(uint8_t *src, int x, int y, int stride, int blocksize)
Find the contrast of a given block.
Definition: vf_deshake.c:193
AVFrame * ref
Previous frame.
Definition: deshake.h:81
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:199
Transform avg
Definition: deshake.h:92
Search most possible positions (faster)
Definition: deshake.h:36
#define CHROMA_WIDTH(link)
Definition: vf_deshake.c:64
uint8_t pi<< 24) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0f/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16, int16_t,(*(constint16_t *) pi >>8)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32, int32_t,(*(constint32_t *) pi >>24)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, float, av_clip_uint8(lrintf(*(constfloat *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, float, av_clip_int16(lrintf(*(constfloat *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, float, av_clipl_int32(llrintf(*(constfloat *) pi *(1U<< 31)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, double, av_clip_uint8(lrint(*(constdouble *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, double, av_clip_int16(lrint(*(constdouble *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, double, av_clipl_int32(llrint(*(constdouble *) pi *(1U<< 31))))#defineSET_CONV_FUNC_GROUP(ofmt, ifmt) staticvoidset_generic_function(AudioConvert *ac){}voidff_audio_convert_free(AudioConvert **ac){if(!*ac) return;ff_dither_free(&(*ac) ->dc);av_freep(ac);}AudioConvert *ff_audio_convert_alloc(AVAudioResampleContext *avr, enumAVSampleFormatout_fmt, enumAVSampleFormatin_fmt, intchannels, intsample_rate, intapply_map){AudioConvert *ac;intin_planar, out_planar;ac=av_mallocz(sizeof(*ac));if(!ac) returnNULL;ac->avr=avr;ac->out_fmt=out_fmt;ac->in_fmt=in_fmt;ac->channels=channels;ac->apply_map=apply_map;if(avr->dither_method!=AV_RESAMPLE_DITHER_NONE &&av_get_packed_sample_fmt(out_fmt)==AV_SAMPLE_FMT_S16 &&av_get_bytes_per_sample(in_fmt)>2){ac->dc=ff_dither_alloc(avr, out_fmt, in_fmt, channels, sample_rate, apply_map);if(!ac->dc){av_free(ac);returnNULL;}returnac;}in_planar=ff_sample_fmt_is_planar(in_fmt, channels);out_planar=ff_sample_fmt_is_planar(out_fmt, channels);if(in_planar==out_planar){ac->func_type=CONV_FUNC_TYPE_FLAT;ac->planes=in_planar?ac->channels:1;}elseif(in_planar) ac->func_type=CONV_FUNC_TYPE_INTERLEAVE;elseac->func_type=CONV_FUNC_TYPE_DEINTERLEAVE;set_generic_function(ac);if(ARCH_AARCH64) ff_audio_convert_init_aarch64(ac);if(ARCH_ARM) ff_audio_convert_init_arm(ac);if(ARCH_X86) ff_audio_convert_init_x86(ac);returnac;}intff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in){intuse_generic=1;intlen=in->nb_samples;intp;if(ac->dc){av_log(ac->avr, AV_LOG_TRACE,"%dsamples-audio_convert:%sto%s(dithered)\n", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt));returnff_convert_dither(ac-> in
BYTE int const BYTE int int int height
Definition: avisynth_c.h:676
planar YUV 4:1:0, 9bpp, (1 Cr & Cb sample per 4x4 Y samples)
Definition: pixfmt.h:69
av_pixelutils_sad_fn av_pixelutils_get_sad_fn(int w_bits, int h_bits, int aligned, void *log_ctx)
Get a potentially optimized pointer to a Sum-of-absolute-differences function (see the av_pixelutils_...
Definition: pixelutils.c:64
Filter definition.
Definition: avfilter.h:470
static int config_props(AVFilterLink *link)
Definition: vf_deshake.c:405
static const AVFilterPad inputs[]
Definition: af_ashowinfo.c:239
static av_cold int init(AVFilterContext *ctx)
Definition: vf_deshake.c:344
const char * name
Filter name.
Definition: avfilter.h:474
int(* transform)(AVFilterContext *ctx, int width, int height, int cw, int ch, const float *matrix_y, const float *matrix_uv, enum InterpolateMethod interpolate, enum FillMethod fill, AVFrame *in, AVFrame *out)
Definition: deshake.h:102
#define snprintf
Definition: snprintf.h:34
AVFilterLink ** outputs
array of pointers to output links
Definition: avfilter.h:648
int counts[2 *MAX_R+1][2 *MAX_R+1]
Definition: deshake.h:78
static enum AVPixelFormat pix_fmts[]
Definition: libkvazaar.c:209
#define CMP(i, j)
static int cmp(const double *a, const double *b)
Definition: vf_deshake.c:94
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:182
int cw
Crop motion search to this box.
Definition: deshake.h:93
Transform last
Transform from last frame.
Definition: deshake.h:89
GLint GLenum GLboolean GLsizei stride
Definition: opengl_enc.c:105
int ff_opencl_deshake_init(AVFilterContext *ctx)
void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
Allocate a buffer, reusing the given one if large enough.
Definition: mem.c:499
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition: pixfmt.h:63
common internal and external API header
planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV444P and setting col...
Definition: pixfmt.h:77
planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples)
Definition: pixfmt.h:70
int x
Horizontal shift.
Definition: deshake.h:41
static av_always_inline int diff(const uint32_t a, const uint32_t b)
MotionVector vec
Motion vector.
Definition: deshake.h:51
#define MAX_R
Definition: deshake.h:74
static const AVFilterPad deshake_outputs[]
Definition: vf_deshake.c:557
void avfilter_get_matrix(float x_shift, float y_shift, float angle, float zoom, float *matrix)
Get an affine transformation matrix from a given translation, rotation, and zoom factor.
Definition: transform.c:106
A list of supported formats for one end of a filter link.
Definition: formats.h:64
uint8_t pi<< 24) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0f/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16, int16_t,(*(constint16_t *) pi >>8)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32, int32_t,(*(constint32_t *) pi >>24)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, float, av_clip_uint8(lrintf(*(constfloat *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, float, av_clip_int16(lrintf(*(constfloat *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, float, av_clipl_int32(llrintf(*(constfloat *) pi *(1U<< 31)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, double, av_clip_uint8(lrint(*(constdouble *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, double, av_clip_int16(lrint(*(constdouble *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, double, av_clipl_int32(llrint(*(constdouble *) pi *(1U<< 31))))#defineSET_CONV_FUNC_GROUP(ofmt, ifmt) staticvoidset_generic_function(AudioConvert *ac){}voidff_audio_convert_free(AudioConvert **ac){if(!*ac) return;ff_dither_free(&(*ac) ->dc);av_freep(ac);}AudioConvert *ff_audio_convert_alloc(AVAudioResampleContext *avr, enumAVSampleFormatout_fmt, enumAVSampleFormatin_fmt, intchannels, intsample_rate, intapply_map){AudioConvert *ac;intin_planar, out_planar;ac=av_mallocz(sizeof(*ac));if(!ac) returnNULL;ac->avr=avr;ac->out_fmt=out_fmt;ac->in_fmt=in_fmt;ac->channels=channels;ac->apply_map=apply_map;if(avr->dither_method!=AV_RESAMPLE_DITHER_NONE &&av_get_packed_sample_fmt(out_fmt)==AV_SAMPLE_FMT_S16 &&av_get_bytes_per_sample(in_fmt)>2){ac->dc=ff_dither_alloc(avr, out_fmt, in_fmt, channels, sample_rate, apply_map);if(!ac->dc){av_free(ac);returnNULL;}returnac;}in_planar=ff_sample_fmt_is_planar(in_fmt, channels);out_planar=ff_sample_fmt_is_planar(out_fmt, channels);if(in_planar==out_planar){ac->func_type=CONV_FUNC_TYPE_FLAT;ac->planes=in_planar?ac->channels:1;}elseif(in_planar) ac->func_type=CONV_FUNC_TYPE_INTERLEAVE;elseac->func_type=CONV_FUNC_TYPE_DEINTERLEAVE;set_generic_function(ac);if(ARCH_AARCH64) ff_audio_convert_init_aarch64(ac);if(ARCH_ARM) ff_audio_convert_init_arm(ac);if(ARCH_X86) ff_audio_convert_init_x86(ac);returnac;}intff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in){intuse_generic=1;intlen=in->nb_samples;intp;if(ac->dc){av_log(ac->avr, AV_LOG_TRACE,"%dsamples-audio_convert:%sto%s(dithered)\n", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt));returnff_convert_dither(ac-> out
An instance of a filter.
Definition: avfilter.h:633
#define av_freep(p)
planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples)
Definition: pixfmt.h:101
#define M_PI
Definition: mathematics.h:46
internal API functions
AVPixelFormat
Pixel format.
Definition: pixfmt.h:61
static av_cold void uninit(AVFilterContext *ctx)
Definition: vf_deshake.c:418
int av_frame_copy_props(AVFrame *dst, const AVFrame *src)
Copy only "metadata" fields from src to dst.
Definition: frame.c:553
void ff_opencl_deshake_uninit(AVFilterContext *ctx)
static int width