• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • File List
  • Globals

libavfilter/vf_deshake.c

Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2010 Georg Martius <georg.martius@web.de>
00003  * Copyright (C) 2010 Daniel G. Taylor <dan@programmer-art.org>
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00052 #include "avfilter.h"
00053 #include "libavutil/common.h"
00054 #include "libavutil/mem.h"
00055 #include "libavutil/pixdesc.h"
00056 #include "libavcodec/dsputil.h"
00057 
00058 #include "transform.h"
00059 
00060 #define CHROMA_WIDTH(link)  -((-link->w) >> av_pix_fmt_descriptors[link->format].log2_chroma_w)
00061 #define CHROMA_HEIGHT(link) -((-link->h) >> av_pix_fmt_descriptors[link->format].log2_chroma_h)
00062 
00063 enum SearchMethod {
00064     EXHAUSTIVE,        
00065     SMART_EXHAUSTIVE,  
00066     SEARCH_COUNT
00067 };
00068 
00069 typedef struct {
00070     int x;             
00071     int y;             
00072 } IntMotionVector;
00073 
00074 typedef struct {
00075     double x;             
00076     double y;             
00077 } MotionVector;
00078 
00079 typedef struct {
00080     MotionVector vector;  
00081     double angle;         
00082     double zoom;          
00083 } Transform;
00084 
00085 typedef struct {
00086     AVClass av_class;
00087     AVFilterBufferRef *ref;    
00088     int rx;                    
00089     int ry;                    
00090     enum FillMethod edge;      
00091     int blocksize;             
00092     int contrast;              
00093     enum SearchMethod search;  
00094     AVCodecContext *avctx;
00095     DSPContext c;              
00096     Transform last;            
00097     int refcount;              
00098     FILE *fp;
00099     Transform avg;
00100     int cw;                    
00101     int ch;
00102     int cx;
00103     int cy;
00104 } DeshakeContext;
00105 
00106 static int cmp(const double *a, const double *b)
00107 {
00108     return *a < *b ? -1 : ( *a > *b ? 1 : 0 );
00109 }
00110 
00114 static double clean_mean(double *values, int count)
00115 {
00116     double mean = 0;
00117     int cut = count / 5;
00118     int x;
00119 
00120     qsort(values, count, sizeof(double), (void*)cmp);
00121 
00122     for (x = cut; x < count - cut; x++) {
00123         mean += values[x];
00124     }
00125 
00126     return mean / (count - cut * 2);
00127 }
00128 
00135 static void find_block_motion(DeshakeContext *deshake, uint8_t *src1,
00136                               uint8_t *src2, int cx, int cy, int stride,
00137                               IntMotionVector *mv)
00138 {
00139     int x, y;
00140     int diff;
00141     int smallest = INT_MAX;
00142     int tmp, tmp2;
00143 
00144     #define CMP(i, j) deshake->c.sad[0](deshake, src1 + cy * stride + cx, \
00145                                         src2 + (j) * stride + (i), stride, \
00146                                         deshake->blocksize)
00147 
00148     if (deshake->search == EXHAUSTIVE) {
00149         // Compare every possible position - this is sloooow!
00150         for (y = -deshake->ry; y <= deshake->ry; y++) {
00151             for (x = -deshake->rx; x <= deshake->rx; x++) {
00152                 diff = CMP(cx - x, cy - y);
00153                 if (diff < smallest) {
00154                     smallest = diff;
00155                     mv->x = x;
00156                     mv->y = y;
00157                 }
00158             }
00159         }
00160     } else if (deshake->search == SMART_EXHAUSTIVE) {
00161         // Compare every other possible position and find the best match
00162         for (y = -deshake->ry + 1; y < deshake->ry - 2; y += 2) {
00163             for (x = -deshake->rx + 1; x < deshake->rx - 2; x += 2) {
00164                 diff = CMP(cx - x, cy - y);
00165                 if (diff < smallest) {
00166                     smallest = diff;
00167                     mv->x = x;
00168                     mv->y = y;
00169                 }
00170             }
00171         }
00172 
00173         // Hone in on the specific best match around the match we found above
00174         tmp = mv->x;
00175         tmp2 = mv->y;
00176 
00177         for (y = tmp2 - 1; y <= tmp2 + 1; y++) {
00178             for (x = tmp - 1; x <= tmp + 1; x++) {
00179                 if (x == tmp && y == tmp2)
00180                     continue;
00181 
00182                 diff = CMP(cx - x, cy - y);
00183                 if (diff < smallest) {
00184                     smallest = diff;
00185                     mv->x = x;
00186                     mv->y = y;
00187                 }
00188             }
00189         }
00190     }
00191 
00192     if (smallest > 512) {
00193         mv->x = -1;
00194         mv->y = -1;
00195     }
00196     emms_c();
00197     //av_log(NULL, AV_LOG_ERROR, "%d\n", smallest);
00198     //av_log(NULL, AV_LOG_ERROR, "Final: (%d, %d) = %d x %d\n", cx, cy, mv->x, mv->y);
00199 }
00200 
00206 static int block_contrast(uint8_t *src, int x, int y, int stride, int blocksize)
00207 {
00208     int highest = 0;
00209     int lowest = 0;
00210     int i, j, pos;
00211 
00212     for (i = 0; i <= blocksize * 2; i++) {
00213         // We use a width of 16 here to match the libavcodec sad functions
00214         for (j = 0; i <= 15; i++) {
00215             pos = (y - i) * stride + (x - j);
00216             if (src[pos] < lowest)
00217                 lowest = src[pos];
00218             else if (src[pos] > highest) {
00219                 highest = src[pos];
00220             }
00221         }
00222     }
00223 
00224     return highest - lowest;
00225 }
00226 
00230 static double block_angle(int x, int y, int cx, int cy, IntMotionVector *shift)
00231 {
00232     double a1, a2, diff;
00233 
00234     a1 = atan2(y - cy, x - cx);
00235     a2 = atan2(y - cy + shift->y, x - cx + shift->x);
00236 
00237     diff = a2 - a1;
00238 
00239     return (diff > M_PI)  ? diff - 2 * M_PI :
00240            (diff < -M_PI) ? diff + 2 * M_PI :
00241            diff;
00242 }
00243 
00251 static void find_motion(DeshakeContext *deshake, uint8_t *src1, uint8_t *src2,
00252                         int width, int height, int stride, Transform *t)
00253 {
00254     int x, y;
00255     IntMotionVector mv = {0, 0};
00256     int counts[128][128];
00257     int count_max_value = 0;
00258     int contrast;
00259 
00260     int pos;
00261     double *angles = av_malloc(sizeof(*angles) * width * height / (16 * deshake->blocksize));
00262     int center_x = 0, center_y = 0;
00263     double p_x, p_y;
00264 
00265     // Reset counts to zero
00266     for (x = 0; x < deshake->rx * 2 + 1; x++) {
00267         for (y = 0; y < deshake->ry * 2 + 1; y++) {
00268             counts[x][y] = 0;
00269         }
00270     }
00271 
00272     pos = 0;
00273     // Find motion for every block and store the motion vector in the counts
00274     for (y = deshake->ry; y < height - deshake->ry - (deshake->blocksize * 2); y += deshake->blocksize * 2) {
00275         // We use a width of 16 here to match the libavcodec sad functions
00276         for (x = deshake->rx; x < width - deshake->rx - 16; x += 16) {
00277             // If the contrast is too low, just skip this block as it probably
00278             // won't be very useful to us.
00279             contrast = block_contrast(src2, x, y, stride, deshake->blocksize);
00280             if (contrast > deshake->contrast) {
00281                 //av_log(NULL, AV_LOG_ERROR, "%d\n", contrast);
00282                 find_block_motion(deshake, src1, src2, x, y, stride, &mv);
00283                 if (mv.x != -1 && mv.y != -1) {
00284                     counts[mv.x + deshake->rx][mv.y + deshake->ry] += 1;
00285                     if (x > deshake->rx && y > deshake->ry)
00286                         angles[pos++] = block_angle(x, y, 0, 0, &mv);
00287 
00288                     center_x += mv.x;
00289                     center_y += mv.y;
00290                 }
00291             }
00292         }
00293     }
00294 
00295     if (pos) {
00296          center_x /= pos;
00297          center_y /= pos;
00298          t->angle = clean_mean(angles, pos);
00299          if (t->angle < 0.001)
00300               t->angle = 0;
00301     } else {
00302          t->angle = 0;
00303     }
00304 
00305     // Find the most common motion vector in the frame and use it as the gmv
00306     for (y = deshake->ry * 2; y >= 0; y--) {
00307         for (x = 0; x < deshake->rx * 2 + 1; x++) {
00308             //av_log(NULL, AV_LOG_ERROR, "%5d ", counts[x][y]);
00309             if (counts[x][y] > count_max_value) {
00310                 t->vector.x = x - deshake->rx;
00311                 t->vector.y = y - deshake->ry;
00312                 count_max_value = counts[x][y];
00313             }
00314         }
00315         //av_log(NULL, AV_LOG_ERROR, "\n");
00316     }
00317 
00318     p_x = (center_x - width / 2);
00319     p_y = (center_y - height / 2);
00320     t->vector.x += (cos(t->angle)-1)*p_x  - sin(t->angle)*p_y;
00321     t->vector.y += sin(t->angle)*p_x  + (cos(t->angle)-1)*p_y;
00322 
00323     // Clamp max shift & rotation?
00324     t->vector.x = av_clipf(t->vector.x, -deshake->rx * 2, deshake->rx * 2);
00325     t->vector.y = av_clipf(t->vector.y, -deshake->ry * 2, deshake->ry * 2);
00326     t->angle = av_clipf(t->angle, -0.1, 0.1);
00327 
00328     //av_log(NULL, AV_LOG_ERROR, "%d x %d\n", avg->x, avg->y);
00329     av_free(angles);
00330 }
00331 
00332 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
00333 {
00334     DeshakeContext *deshake = ctx->priv;
00335     char filename[256] = {0};
00336 
00337     deshake->rx = 16;
00338     deshake->ry = 16;
00339     deshake->edge = FILL_MIRROR;
00340     deshake->blocksize = 8;
00341     deshake->contrast = 125;
00342     deshake->search = EXHAUSTIVE;
00343     deshake->refcount = 20;
00344 
00345     deshake->cw = -1;
00346     deshake->ch = -1;
00347     deshake->cx = -1;
00348     deshake->cy = -1;
00349 
00350     if (args) {
00351         sscanf(args, "%d:%d:%d:%d:%d:%d:%d:%d:%d:%d:%255s",
00352                &deshake->cx, &deshake->cy, &deshake->cw, &deshake->ch,
00353                &deshake->rx, &deshake->ry, (int *)&deshake->edge,
00354                &deshake->blocksize, &deshake->contrast, (int *)&deshake->search, filename);
00355 
00356         deshake->blocksize /= 2;
00357 
00358         deshake->rx = av_clip(deshake->rx, 0, 64);
00359         deshake->ry = av_clip(deshake->ry, 0, 64);
00360         deshake->edge = av_clip(deshake->edge, FILL_BLANK, FILL_COUNT - 1);
00361         deshake->blocksize = av_clip(deshake->blocksize, 4, 128);
00362         deshake->contrast = av_clip(deshake->contrast, 1, 255);
00363         deshake->search = av_clip(deshake->search, EXHAUSTIVE, SEARCH_COUNT - 1);
00364 
00365     }
00366     if (*filename)
00367         deshake->fp = fopen(filename, "w");
00368     if (deshake->fp)
00369         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);
00370 
00371     // Quadword align left edge of box for MMX code, adjust width if necessary
00372     // to keep right margin
00373     if (deshake->cx > 0) {
00374         deshake->cw += deshake->cx - (deshake->cx & ~15);
00375         deshake->cx &= ~15;
00376     }
00377 
00378     av_log(ctx, AV_LOG_INFO, "cx: %d, cy: %d, cw: %d, ch: %d, rx: %d, ry: %d, edge: %d blocksize: %d contrast: %d search: %d\n",
00379            deshake->cx, deshake->cy, deshake->cw, deshake->ch,
00380            deshake->rx, deshake->ry, deshake->edge, deshake->blocksize * 2, deshake->contrast, deshake->search);
00381 
00382     return 0;
00383 }
00384 
00385 static int query_formats(AVFilterContext *ctx)
00386 {
00387     enum PixelFormat pix_fmts[] = {
00388         PIX_FMT_YUV420P,  PIX_FMT_YUV422P,  PIX_FMT_YUV444P,  PIX_FMT_YUV410P,
00389         PIX_FMT_YUV411P,  PIX_FMT_YUV440P,  PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P,
00390         PIX_FMT_YUVJ444P, PIX_FMT_YUVJ440P, PIX_FMT_NONE
00391     };
00392 
00393     avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
00394 
00395     return 0;
00396 }
00397 
00398 static int config_props(AVFilterLink *link)
00399 {
00400     DeshakeContext *deshake = link->dst->priv;
00401 
00402     deshake->ref = NULL;
00403     deshake->last.vector.x = 0;
00404     deshake->last.vector.y = 0;
00405     deshake->last.angle = 0;
00406     deshake->last.zoom = 0;
00407 
00408     deshake->avctx = avcodec_alloc_context3(NULL);
00409     dsputil_init(&deshake->c, deshake->avctx);
00410 
00411     return 0;
00412 }
00413 
00414 static av_cold void uninit(AVFilterContext *ctx)
00415 {
00416     DeshakeContext *deshake = ctx->priv;
00417 
00418     avfilter_unref_buffer(deshake->ref);
00419     if (deshake->fp)
00420         fclose(deshake->fp);
00421 }
00422 
00423 static void end_frame(AVFilterLink *link)
00424 {
00425     DeshakeContext *deshake = link->dst->priv;
00426     AVFilterBufferRef *in  = link->cur_buf;
00427     AVFilterBufferRef *out = link->dst->outputs[0]->out_buf;
00428     Transform t = {{0},0}, orig = {{0},0};
00429     float matrix[9];
00430     float alpha = 2.0 / deshake->refcount;
00431     char tmp[256];
00432 
00433     if (deshake->cx < 0 || deshake->cy < 0 || deshake->cw < 0 || deshake->ch < 0) {
00434         // Find the most likely global motion for the current frame
00435         find_motion(deshake, (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0], in->data[0], link->w, link->h, in->linesize[0], &t);
00436     } else {
00437         uint8_t *src1 = (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0];
00438         uint8_t *src2 = in->data[0];
00439 
00440         deshake->cx = FFMIN(deshake->cx, link->w);
00441         deshake->cy = FFMIN(deshake->cy, link->h);
00442 
00443         if ((unsigned)deshake->cx + (unsigned)deshake->cw > link->w) deshake->cw = link->w - deshake->cx;
00444         if ((unsigned)deshake->cy + (unsigned)deshake->ch > link->h) deshake->ch = link->h - deshake->cy;
00445 
00446         // Quadword align right margin
00447         deshake->cw &= ~15;
00448 
00449         src1 += deshake->cy * in->linesize[0] + deshake->cx;
00450         src2 += deshake->cy * in->linesize[0] + deshake->cx;
00451 
00452         find_motion(deshake, src1, src2, deshake->cw, deshake->ch, in->linesize[0], &t);
00453     }
00454 
00455 
00456     // Copy transform so we can output it later to compare to the smoothed value
00457     orig.vector.x = t.vector.x;
00458     orig.vector.y = t.vector.y;
00459     orig.angle = t.angle;
00460     orig.zoom = t.zoom;
00461 
00462     // Generate a one-sided moving exponential average
00463     deshake->avg.vector.x = alpha * t.vector.x + (1.0 - alpha) * deshake->avg.vector.x;
00464     deshake->avg.vector.y = alpha * t.vector.y + (1.0 - alpha) * deshake->avg.vector.y;
00465     deshake->avg.angle = alpha * t.angle + (1.0 - alpha) * deshake->avg.angle;
00466     deshake->avg.zoom = alpha * t.zoom + (1.0 - alpha) * deshake->avg.zoom;
00467 
00468     // Remove the average from the current motion to detect the motion that
00469     // is not on purpose, just as jitter from bumping the camera
00470     t.vector.x -= deshake->avg.vector.x;
00471     t.vector.y -= deshake->avg.vector.y;
00472     t.angle -= deshake->avg.angle;
00473     t.zoom -= deshake->avg.zoom;
00474 
00475     // Invert the motion to undo it
00476     t.vector.x *= -1;
00477     t.vector.y *= -1;
00478     t.angle *= -1;
00479 
00480     // Write statistics to file
00481     if (deshake->fp) {
00482         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);
00483         fwrite(tmp, sizeof(char), strlen(tmp), deshake->fp);
00484     }
00485 
00486     // Turn relative current frame motion into absolute by adding it to the
00487     // last absolute motion
00488     t.vector.x += deshake->last.vector.x;
00489     t.vector.y += deshake->last.vector.y;
00490     t.angle += deshake->last.angle;
00491     t.zoom += deshake->last.zoom;
00492 
00493     // Shrink motion by 10% to keep things centered in the camera frame
00494     t.vector.x *= 0.9;
00495     t.vector.y *= 0.9;
00496     t.angle *= 0.9;
00497 
00498     // Store the last absolute motion information
00499     deshake->last.vector.x = t.vector.x;
00500     deshake->last.vector.y = t.vector.y;
00501     deshake->last.angle = t.angle;
00502     deshake->last.zoom = t.zoom;
00503 
00504     // Generate a luma transformation matrix
00505     avfilter_get_matrix(t.vector.x, t.vector.y, t.angle, 1.0 + t.zoom / 100.0, matrix);
00506 
00507     // Transform the luma plane
00508     avfilter_transform(in->data[0], out->data[0], in->linesize[0], out->linesize[0], link->w, link->h, matrix, INTERPOLATE_BILINEAR, deshake->edge);
00509 
00510     // Generate a chroma transformation matrix
00511     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);
00512 
00513     // Transform the chroma planes
00514     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);
00515     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);
00516 
00517     // Store the current frame as the reference frame for calculating the
00518     // motion of the next frame
00519     if (deshake->ref != NULL)
00520         avfilter_unref_buffer(deshake->ref);
00521 
00522     // Cleanup the old reference frame
00523     deshake->ref = in;
00524 
00525     // Draw the transformed frame information
00526     avfilter_draw_slice(link->dst->outputs[0], 0, link->h, 1);
00527     avfilter_end_frame(link->dst->outputs[0]);
00528     avfilter_unref_buffer(out);
00529 }
00530 
00531 static void draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
00532 {
00533 }
00534 
00535 AVFilter avfilter_vf_deshake = {
00536     .name      = "deshake",
00537     .description = NULL_IF_CONFIG_SMALL("Stabilize shaky video."),
00538 
00539     .priv_size = sizeof(DeshakeContext),
00540 
00541     .init = init,
00542     .uninit = uninit,
00543     .query_formats = query_formats,
00544 
00545     .inputs    = (const AVFilterPad[]) {{ .name       = "default",
00546                                     .type             = AVMEDIA_TYPE_VIDEO,
00547                                     .draw_slice       = draw_slice,
00548                                     .end_frame        = end_frame,
00549                                     .config_props     = config_props,
00550                                     .min_perms        = AV_PERM_READ, },
00551                                   { .name = NULL}},
00552 
00553     .outputs   = (const AVFilterPad[]) {{ .name       = "default",
00554                                     .type             = AVMEDIA_TYPE_VIDEO, },
00555                                   { .name = NULL}},
00556 };
Generated on Fri Feb 1 2013 14:34:49 for FFmpeg by doxygen 1.7.1