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