]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_deshake.c
Merge commit '9f0b6e6827e21e3477abe1199dc2728e30b8c061'
[ffmpeg] / libavfilter / vf_deshake.c
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 #include "libavutil/qsort.h"
61
62 #include "deshake.h"
63 #include "deshake_opencl.h"
64
65 #define CHROMA_WIDTH(link)  (-((-(link)->w) >> av_pix_fmt_desc_get((link)->format)->log2_chroma_w))
66 #define CHROMA_HEIGHT(link) (-((-(link)->h) >> av_pix_fmt_desc_get((link)->format)->log2_chroma_h))
67
68 #define OFFSET(x) offsetof(DeshakeContext, x)
69 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
70
71 static const AVOption deshake_options[] = {
72     { "x", "set x for the rectangular search area",      OFFSET(cx), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS },
73     { "y", "set y for the rectangular search area",      OFFSET(cy), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS },
74     { "w", "set width for the rectangular search area",  OFFSET(cw), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS },
75     { "h", "set height for the rectangular search area", OFFSET(ch), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS },
76     { "rx", "set x for the rectangular search area",     OFFSET(rx), AV_OPT_TYPE_INT, {.i64=16}, 0, MAX_R, .flags = FLAGS },
77     { "ry", "set y for the rectangular search area",     OFFSET(ry), AV_OPT_TYPE_INT, {.i64=16}, 0, MAX_R, .flags = FLAGS },
78     { "edge", "set edge mode", OFFSET(edge), AV_OPT_TYPE_INT, {.i64=FILL_MIRROR}, FILL_BLANK, FILL_COUNT-1, FLAGS, "edge"},
79         { "blank",    "fill zeroes at blank locations",         0, AV_OPT_TYPE_CONST, {.i64=FILL_BLANK},    INT_MIN, INT_MAX, FLAGS, "edge" },
80         { "original", "original image at blank locations",      0, AV_OPT_TYPE_CONST, {.i64=FILL_ORIGINAL}, INT_MIN, INT_MAX, FLAGS, "edge" },
81         { "clamp",    "extruded edge value at blank locations", 0, AV_OPT_TYPE_CONST, {.i64=FILL_CLAMP},    INT_MIN, INT_MAX, FLAGS, "edge" },
82         { "mirror",   "mirrored edge at blank locations",       0, AV_OPT_TYPE_CONST, {.i64=FILL_MIRROR},   INT_MIN, INT_MAX, FLAGS, "edge" },
83     { "blocksize", "set motion search blocksize",       OFFSET(blocksize), AV_OPT_TYPE_INT, {.i64=8},   4, 128, .flags = FLAGS },
84     { "contrast",  "set contrast threshold for blocks", OFFSET(contrast),  AV_OPT_TYPE_INT, {.i64=125}, 1, 255, .flags = FLAGS },
85     { "search",  "set search strategy", OFFSET(search), AV_OPT_TYPE_INT, {.i64=EXHAUSTIVE}, EXHAUSTIVE, SEARCH_COUNT-1, FLAGS, "smode" },
86         { "exhaustive", "exhaustive search",      0, AV_OPT_TYPE_CONST, {.i64=EXHAUSTIVE},       INT_MIN, INT_MAX, FLAGS, "smode" },
87         { "less",       "less exhaustive search", 0, AV_OPT_TYPE_CONST, {.i64=SMART_EXHAUSTIVE}, INT_MIN, INT_MAX, FLAGS, "smode" },
88     { "filename", "set motion search detailed log file name", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
89     { "opencl", "use OpenCL filtering capabilities", OFFSET(opencl), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, .flags = FLAGS },
90     { NULL }
91 };
92
93 AVFILTER_DEFINE_CLASS(deshake);
94
95 static int cmp(const void *a, const void *b)
96 {
97     return FFDIFFSIGN(*(const double *)a, *(const double *)b);
98 }
99
100 /**
101  * Cleaned mean (cuts off 20% of values to remove outliers and then averages)
102  */
103 static double clean_mean(double *values, int count)
104 {
105     double mean = 0;
106     int cut = count / 5;
107     int x;
108
109     AV_QSORT(values, count, double, cmp);
110
111     for (x = cut; x < count - cut; x++) {
112         mean += values[x];
113     }
114
115     return mean / (count - cut * 2);
116 }
117
118 /**
119  * Find the most likely shift in motion between two frames for a given
120  * macroblock. Test each block against several shifts given by the rx
121  * and ry attributes. Searches using a simple matrix of those shifts and
122  * chooses the most likely shift by the smallest difference in blocks.
123  */
124 static void find_block_motion(DeshakeContext *deshake, uint8_t *src1,
125                               uint8_t *src2, int cx, int cy, int stride,
126                               IntMotionVector *mv)
127 {
128     int x, y;
129     int diff;
130     int smallest = INT_MAX;
131     int tmp, tmp2;
132
133     #define CMP(i, j) deshake->sad(src1 + cy  * stride + cx,  stride,\
134                                    src2 + (j) * stride + (i), stride)
135
136     if (deshake->search == EXHAUSTIVE) {
137         // Compare every possible position - this is sloooow!
138         for (y = -deshake->ry; y <= deshake->ry; y++) {
139             for (x = -deshake->rx; x <= deshake->rx; x++) {
140                 diff = CMP(cx - x, cy - y);
141                 if (diff < smallest) {
142                     smallest = diff;
143                     mv->x = x;
144                     mv->y = y;
145                 }
146             }
147         }
148     } else if (deshake->search == SMART_EXHAUSTIVE) {
149         // Compare every other possible position and find the best match
150         for (y = -deshake->ry + 1; y < deshake->ry; y += 2) {
151             for (x = -deshake->rx + 1; x < deshake->rx; x += 2) {
152                 diff = CMP(cx - x, cy - y);
153                 if (diff < smallest) {
154                     smallest = diff;
155                     mv->x = x;
156                     mv->y = y;
157                 }
158             }
159         }
160
161         // Hone in on the specific best match around the match we found above
162         tmp = mv->x;
163         tmp2 = mv->y;
164
165         for (y = tmp2 - 1; y <= tmp2 + 1; y++) {
166             for (x = tmp - 1; x <= tmp + 1; x++) {
167                 if (x == tmp && y == tmp2)
168                     continue;
169
170                 diff = CMP(cx - x, cy - y);
171                 if (diff < smallest) {
172                     smallest = diff;
173                     mv->x = x;
174                     mv->y = y;
175                 }
176             }
177         }
178     }
179
180     if (smallest > 512) {
181         mv->x = -1;
182         mv->y = -1;
183     }
184     emms_c();
185     //av_log(NULL, AV_LOG_ERROR, "%d\n", smallest);
186     //av_log(NULL, AV_LOG_ERROR, "Final: (%d, %d) = %d x %d\n", cx, cy, mv->x, mv->y);
187 }
188
189 /**
190  * Find the contrast of a given block. When searching for global motion we
191  * really only care about the high contrast blocks, so using this method we
192  * can actually skip blocks we don't care much about.
193  */
194 static int block_contrast(uint8_t *src, int x, int y, int stride, int blocksize)
195 {
196     int highest = 0;
197     int lowest = 255;
198     int i, j, pos;
199
200     for (i = 0; i <= blocksize * 2; i++) {
201         // We use a width of 16 here to match the sad function
202         for (j = 0; j <= 15; j++) {
203             pos = (y - i) * stride + (x - j);
204             if (src[pos] < lowest)
205                 lowest = src[pos];
206             else if (src[pos] > highest) {
207                 highest = src[pos];
208             }
209         }
210     }
211
212     return highest - lowest;
213 }
214
215 /**
216  * Find the rotation for a given block.
217  */
218 static double block_angle(int x, int y, int cx, int cy, IntMotionVector *shift)
219 {
220     double a1, a2, diff;
221
222     a1 = atan2(y - cy, x - cx);
223     a2 = atan2(y - cy + shift->y, x - cx + shift->x);
224
225     diff = a2 - a1;
226
227     return (diff > M_PI)  ? diff - 2 * M_PI :
228            (diff < -M_PI) ? diff + 2 * M_PI :
229            diff;
230 }
231
232 /**
233  * Find the estimated global motion for a scene given the most likely shift
234  * for each block in the frame. The global motion is estimated to be the
235  * same as the motion from most blocks in the frame, so if most blocks
236  * move one pixel to the right and two pixels down, this would yield a
237  * motion vector (1, -2).
238  */
239 static void find_motion(DeshakeContext *deshake, uint8_t *src1, uint8_t *src2,
240                         int width, int height, int stride, Transform *t)
241 {
242     int x, y;
243     IntMotionVector mv = {0, 0};
244     int count_max_value = 0;
245     int contrast;
246
247     int pos;
248     int center_x = 0, center_y = 0;
249     double p_x, p_y;
250
251     av_fast_malloc(&deshake->angles, &deshake->angles_size, width * height / (16 * deshake->blocksize) * sizeof(*deshake->angles));
252
253     // Reset counts to zero
254     for (x = 0; x < deshake->rx * 2 + 1; x++) {
255         for (y = 0; y < deshake->ry * 2 + 1; y++) {
256             deshake->counts[x][y] = 0;
257         }
258     }
259
260     pos = 0;
261     // Find motion for every block and store the motion vector in the counts
262     for (y = deshake->ry; y < height - deshake->ry - (deshake->blocksize * 2); y += deshake->blocksize * 2) {
263         // We use a width of 16 here to match the sad function
264         for (x = deshake->rx; x < width - deshake->rx - 16; x += 16) {
265             // If the contrast is too low, just skip this block as it probably
266             // won't be very useful to us.
267             contrast = block_contrast(src2, x, y, stride, deshake->blocksize);
268             if (contrast > deshake->contrast) {
269                 //av_log(NULL, AV_LOG_ERROR, "%d\n", contrast);
270                 find_block_motion(deshake, src1, src2, x, y, stride, &mv);
271                 if (mv.x != -1 && mv.y != -1) {
272                     deshake->counts[mv.x + deshake->rx][mv.y + deshake->ry] += 1;
273                     if (x > deshake->rx && y > deshake->ry)
274                         deshake->angles[pos++] = block_angle(x, y, 0, 0, &mv);
275
276                     center_x += mv.x;
277                     center_y += mv.y;
278                 }
279             }
280         }
281     }
282
283     if (pos) {
284          center_x /= pos;
285          center_y /= pos;
286          t->angle = clean_mean(deshake->angles, pos);
287          if (t->angle < 0.001)
288               t->angle = 0;
289     } else {
290          t->angle = 0;
291     }
292
293     // Find the most common motion vector in the frame and use it as the gmv
294     for (y = deshake->ry * 2; y >= 0; y--) {
295         for (x = 0; x < deshake->rx * 2 + 1; x++) {
296             //av_log(NULL, AV_LOG_ERROR, "%5d ", deshake->counts[x][y]);
297             if (deshake->counts[x][y] > count_max_value) {
298                 t->vec.x = x - deshake->rx;
299                 t->vec.y = y - deshake->ry;
300                 count_max_value = deshake->counts[x][y];
301             }
302         }
303         //av_log(NULL, AV_LOG_ERROR, "\n");
304     }
305
306     p_x = (center_x - width / 2.0);
307     p_y = (center_y - height / 2.0);
308     t->vec.x += (cos(t->angle)-1)*p_x  - sin(t->angle)*p_y;
309     t->vec.y += sin(t->angle)*p_x  + (cos(t->angle)-1)*p_y;
310
311     // Clamp max shift & rotation?
312     t->vec.x = av_clipf(t->vec.x, -deshake->rx * 2, deshake->rx * 2);
313     t->vec.y = av_clipf(t->vec.y, -deshake->ry * 2, deshake->ry * 2);
314     t->angle = av_clipf(t->angle, -0.1, 0.1);
315
316     //av_log(NULL, AV_LOG_ERROR, "%d x %d\n", avg->x, avg->y);
317 }
318
319 static int deshake_transform_c(AVFilterContext *ctx,
320                                     int width, int height, int cw, int ch,
321                                     const float *matrix_y, const float *matrix_uv,
322                                     enum InterpolateMethod interpolate,
323                                     enum FillMethod fill, AVFrame *in, AVFrame *out)
324 {
325     int i = 0, ret = 0;
326     const float *matrixs[3];
327     int plane_w[3], plane_h[3];
328     matrixs[0] = matrix_y;
329     matrixs[1] =  matrixs[2] = matrix_uv;
330     plane_w[0] = width;
331     plane_w[1] = plane_w[2] = cw;
332     plane_h[0] = height;
333     plane_h[1] = plane_h[2] = ch;
334
335     for (i = 0; i < 3; i++) {
336         // Transform the luma and chroma planes
337         ret = avfilter_transform(in->data[i], out->data[i], in->linesize[i], out->linesize[i],
338                                  plane_w[i], plane_h[i], matrixs[i], interpolate, fill);
339         if (ret < 0)
340             return ret;
341     }
342     return ret;
343 }
344
345 static av_cold int init(AVFilterContext *ctx)
346 {
347     int ret;
348     DeshakeContext *deshake = ctx->priv;
349
350     deshake->sad = av_pixelutils_get_sad_fn(4, 4, 1, deshake); // 16x16, 2nd source unaligned
351     if (!deshake->sad)
352         return AVERROR(EINVAL);
353
354     deshake->refcount = 20; // XXX: add to options?
355     deshake->blocksize /= 2;
356     deshake->blocksize = av_clip(deshake->blocksize, 4, 128);
357
358     if (deshake->rx % 16) {
359         av_log(ctx, AV_LOG_ERROR, "rx must be a multiple of 16\n");
360         return AVERROR_PATCHWELCOME;
361     }
362
363     if (deshake->filename)
364         deshake->fp = fopen(deshake->filename, "w");
365     if (deshake->fp)
366         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);
367
368     // Quadword align left edge of box for MMX code, adjust width if necessary
369     // to keep right margin
370     if (deshake->cx > 0) {
371         deshake->cw += deshake->cx - (deshake->cx & ~15);
372         deshake->cx &= ~15;
373     }
374     deshake->transform = deshake_transform_c;
375     if (!CONFIG_OPENCL && deshake->opencl) {
376         av_log(ctx, AV_LOG_ERROR, "OpenCL support was not enabled in this build, cannot be selected\n");
377         return AVERROR(EINVAL);
378     }
379
380     if (CONFIG_OPENCL && deshake->opencl) {
381         deshake->transform = ff_opencl_transform;
382         ret = ff_opencl_deshake_init(ctx);
383         if (ret < 0)
384             return ret;
385     }
386     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",
387            deshake->cx, deshake->cy, deshake->cw, deshake->ch,
388            deshake->rx, deshake->ry, deshake->edge, deshake->blocksize * 2, deshake->contrast, deshake->search);
389
390     return 0;
391 }
392
393 static int query_formats(AVFilterContext *ctx)
394 {
395     static const enum AVPixelFormat pix_fmts[] = {
396         AV_PIX_FMT_YUV420P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV410P,
397         AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV440P,  AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
398         AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_NONE
399     };
400     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
401     if (!fmts_list)
402         return AVERROR(ENOMEM);
403     return ff_set_common_formats(ctx, fmts_list);
404 }
405
406 static int config_props(AVFilterLink *link)
407 {
408     DeshakeContext *deshake = link->dst->priv;
409
410     deshake->ref = NULL;
411     deshake->last.vec.x = 0;
412     deshake->last.vec.y = 0;
413     deshake->last.angle = 0;
414     deshake->last.zoom = 0;
415
416     return 0;
417 }
418
419 static av_cold void uninit(AVFilterContext *ctx)
420 {
421     DeshakeContext *deshake = ctx->priv;
422     if (CONFIG_OPENCL && deshake->opencl) {
423         ff_opencl_deshake_uninit(ctx);
424     }
425     av_frame_free(&deshake->ref);
426     av_freep(&deshake->angles);
427     deshake->angles_size = 0;
428     if (deshake->fp)
429         fclose(deshake->fp);
430 }
431
432 static int filter_frame(AVFilterLink *link, AVFrame *in)
433 {
434     DeshakeContext *deshake = link->dst->priv;
435     AVFilterLink *outlink = link->dst->outputs[0];
436     AVFrame *out;
437     Transform t = {{0},0}, orig = {{0},0};
438     float matrix_y[9], matrix_uv[9];
439     float alpha = 2.0 / deshake->refcount;
440     char tmp[256];
441     int ret = 0;
442
443     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
444     if (!out) {
445         av_frame_free(&in);
446         return AVERROR(ENOMEM);
447     }
448     av_frame_copy_props(out, in);
449
450     if (CONFIG_OPENCL && deshake->opencl) {
451         ret = ff_opencl_deshake_process_inout_buf(link->dst,in, out);
452         if (ret < 0)
453             return ret;
454     }
455
456     if (deshake->cx < 0 || deshake->cy < 0 || deshake->cw < 0 || deshake->ch < 0) {
457         // Find the most likely global motion for the current frame
458         find_motion(deshake, (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0], in->data[0], link->w, link->h, in->linesize[0], &t);
459     } else {
460         uint8_t *src1 = (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0];
461         uint8_t *src2 = in->data[0];
462
463         deshake->cx = FFMIN(deshake->cx, link->w);
464         deshake->cy = FFMIN(deshake->cy, link->h);
465
466         if ((unsigned)deshake->cx + (unsigned)deshake->cw > link->w) deshake->cw = link->w - deshake->cx;
467         if ((unsigned)deshake->cy + (unsigned)deshake->ch > link->h) deshake->ch = link->h - deshake->cy;
468
469         // Quadword align right margin
470         deshake->cw &= ~15;
471
472         src1 += deshake->cy * in->linesize[0] + deshake->cx;
473         src2 += deshake->cy * in->linesize[0] + deshake->cx;
474
475         find_motion(deshake, src1, src2, deshake->cw, deshake->ch, in->linesize[0], &t);
476     }
477
478
479     // Copy transform so we can output it later to compare to the smoothed value
480     orig.vec.x = t.vec.x;
481     orig.vec.y = t.vec.y;
482     orig.angle = t.angle;
483     orig.zoom = t.zoom;
484
485     // Generate a one-sided moving exponential average
486     deshake->avg.vec.x = alpha * t.vec.x + (1.0 - alpha) * deshake->avg.vec.x;
487     deshake->avg.vec.y = alpha * t.vec.y + (1.0 - alpha) * deshake->avg.vec.y;
488     deshake->avg.angle = alpha * t.angle + (1.0 - alpha) * deshake->avg.angle;
489     deshake->avg.zoom = alpha * t.zoom + (1.0 - alpha) * deshake->avg.zoom;
490
491     // Remove the average from the current motion to detect the motion that
492     // is not on purpose, just as jitter from bumping the camera
493     t.vec.x -= deshake->avg.vec.x;
494     t.vec.y -= deshake->avg.vec.y;
495     t.angle -= deshake->avg.angle;
496     t.zoom -= deshake->avg.zoom;
497
498     // Invert the motion to undo it
499     t.vec.x *= -1;
500     t.vec.y *= -1;
501     t.angle *= -1;
502
503     // Write statistics to file
504     if (deshake->fp) {
505         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);
506         fwrite(tmp, sizeof(char), strlen(tmp), deshake->fp);
507     }
508
509     // Turn relative current frame motion into absolute by adding it to the
510     // last absolute motion
511     t.vec.x += deshake->last.vec.x;
512     t.vec.y += deshake->last.vec.y;
513     t.angle += deshake->last.angle;
514     t.zoom += deshake->last.zoom;
515
516     // Shrink motion by 10% to keep things centered in the camera frame
517     t.vec.x *= 0.9;
518     t.vec.y *= 0.9;
519     t.angle *= 0.9;
520
521     // Store the last absolute motion information
522     deshake->last.vec.x = t.vec.x;
523     deshake->last.vec.y = t.vec.y;
524     deshake->last.angle = t.angle;
525     deshake->last.zoom = t.zoom;
526
527     // Generate a luma transformation matrix
528     avfilter_get_matrix(t.vec.x, t.vec.y, t.angle, 1.0 + t.zoom / 100.0, matrix_y);
529     // Generate a chroma transformation matrix
530     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);
531     // Transform the luma and chroma planes
532     ret = deshake->transform(link->dst, link->w, link->h, CHROMA_WIDTH(link), CHROMA_HEIGHT(link),
533                              matrix_y, matrix_uv, INTERPOLATE_BILINEAR, deshake->edge, in, out);
534
535     // Cleanup the old reference frame
536     av_frame_free(&deshake->ref);
537
538     if (ret < 0)
539         return ret;
540
541     // Store the current frame as the reference frame for calculating the
542     // motion of the next frame
543     deshake->ref = in;
544
545     return ff_filter_frame(outlink, out);
546 }
547
548 static const AVFilterPad deshake_inputs[] = {
549     {
550         .name         = "default",
551         .type         = AVMEDIA_TYPE_VIDEO,
552         .filter_frame = filter_frame,
553         .config_props = config_props,
554     },
555     { NULL }
556 };
557
558 static const AVFilterPad deshake_outputs[] = {
559     {
560         .name = "default",
561         .type = AVMEDIA_TYPE_VIDEO,
562     },
563     { NULL }
564 };
565
566 AVFilter ff_vf_deshake = {
567     .name          = "deshake",
568     .description   = NULL_IF_CONFIG_SMALL("Stabilize shaky video."),
569     .priv_size     = sizeof(DeshakeContext),
570     .init          = init,
571     .uninit        = uninit,
572     .query_formats = query_formats,
573     .inputs        = deshake_inputs,
574     .outputs       = deshake_outputs,
575     .priv_class    = &deshake_class,
576 };