vf_deshake.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. * @file
  23. * fast deshake / depan video filter
  24. *
  25. * SAD block-matching motion compensation to fix small changes in
  26. * horizontal and/or vertical shift. This filter helps remove camera shake
  27. * from hand-holding a camera, bumping a tripod, moving on a vehicle, etc.
  28. *
  29. * Algorithm:
  30. * - For each frame with one previous reference frame
  31. * - For each block in the frame
  32. * - If contrast > threshold then find likely motion vector
  33. * - For all found motion vectors
  34. * - Find most common, store as global motion vector
  35. * - Find most likely rotation angle
  36. * - Transform image along global motion
  37. *
  38. * TODO:
  39. * - Fill frame edges based on previous/next reference frames
  40. * - Fill frame edges by stretching image near the edges?
  41. * - Can this be done quickly and look decent?
  42. *
  43. * Dark Shikari links to http://wiki.videolan.org/SoC_x264_2010#GPU_Motion_Estimation_2
  44. * for an algorithm similar to what could be used here to get the gmv
  45. * It requires only a couple diamond searches + fast downscaling
  46. *
  47. * Special thanks to Jason Kotenko for his help with the algorithm and my
  48. * inability to see simple errors in C code.
  49. */
  50. #include "avfilter.h"
  51. #include "libavutil/common.h"
  52. #include "libavutil/mem.h"
  53. #include "libavutil/pixdesc.h"
  54. #include "libavcodec/dsputil.h"
  55. #include "transform.h"
  56. #define CHROMA_WIDTH(link) -((-link->w) >> av_pix_fmt_descriptors[link->format].log2_chroma_w)
  57. #define CHROMA_HEIGHT(link) -((-link->h) >> av_pix_fmt_descriptors[link->format].log2_chroma_h)
  58. enum SearchMethod {
  59. EXHAUSTIVE, ///< Search all possible positions
  60. SMART_EXHAUSTIVE, ///< Search most possible positions (faster)
  61. SEARCH_COUNT
  62. };
  63. typedef struct {
  64. int x; ///< Horizontal shift
  65. int y; ///< Vertical shift
  66. } IntMotionVector;
  67. typedef struct {
  68. double x; ///< Horizontal shift
  69. double y; ///< Vertical shift
  70. } MotionVector;
  71. typedef struct {
  72. MotionVector vector; ///< Motion vector
  73. double angle; ///< Angle of rotation
  74. double zoom; ///< Zoom percentage
  75. } Transform;
  76. typedef struct {
  77. AVClass av_class;
  78. AVFilterBufferRef *ref; ///< Previous frame
  79. int rx; ///< Maximum horizontal shift
  80. int ry; ///< Maximum vertical shift
  81. enum FillMethod edge; ///< Edge fill method
  82. int blocksize; ///< Size of blocks to compare
  83. int contrast; ///< Contrast threshold
  84. enum SearchMethod search; ///< Motion search method
  85. AVCodecContext *avctx;
  86. DSPContext c; ///< Context providing optimized SAD methods
  87. Transform last; ///< Transform from last frame
  88. int refcount; ///< Number of reference frames (defines averaging window)
  89. FILE *fp;
  90. Transform avg;
  91. int cw; ///< Crop motion search to this box
  92. int ch;
  93. int cx;
  94. int cy;
  95. } DeshakeContext;
  96. static int cmp(const double *a, const double *b)
  97. {
  98. return *a < *b ? -1 : ( *a > *b ? 1 : 0 );
  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. qsort(values, count, sizeof(double), (void*)cmp);
  109. for (x = cut; x < count - cut; x++) {
  110. mean += values[x];
  111. }
  112. return mean / (count - cut * 2);
  113. }
  114. /**
  115. * Find the most likely shift in motion between two frames for a given
  116. * macroblock. Test each block against several shifts given by the rx
  117. * and ry attributes. Searches using a simple matrix of those shifts and
  118. * chooses the most likely shift by the smallest difference in blocks.
  119. */
  120. static void find_block_motion(DeshakeContext *deshake, uint8_t *src1,
  121. uint8_t *src2, int cx, int cy, int stride,
  122. IntMotionVector *mv)
  123. {
  124. int x, y;
  125. int diff;
  126. int smallest = INT_MAX;
  127. int tmp, tmp2;
  128. #define CMP(i, j) deshake->c.sad[0](deshake, src1 + cy * stride + cx, \
  129. src2 + (j) * stride + (i), stride, \
  130. deshake->blocksize)
  131. if (deshake->search == EXHAUSTIVE) {
  132. // Compare every possible position - this is sloooow!
  133. for (y = -deshake->ry; y <= deshake->ry; y++) {
  134. for (x = -deshake->rx; x <= deshake->rx; x++) {
  135. diff = CMP(cx - x, cy - y);
  136. if (diff < smallest) {
  137. smallest = diff;
  138. mv->x = x;
  139. mv->y = y;
  140. }
  141. }
  142. }
  143. } else if (deshake->search == SMART_EXHAUSTIVE) {
  144. // Compare every other possible position and find the best match
  145. for (y = -deshake->ry + 1; y < deshake->ry - 2; y += 2) {
  146. for (x = -deshake->rx + 1; x < deshake->rx - 2; x += 2) {
  147. diff = CMP(cx - x, cy - y);
  148. if (diff < smallest) {
  149. smallest = diff;
  150. mv->x = x;
  151. mv->y = y;
  152. }
  153. }
  154. }
  155. // Hone in on the specific best match around the match we found above
  156. tmp = mv->x;
  157. tmp2 = mv->y;
  158. for (y = tmp2 - 1; y <= tmp2 + 1; y++) {
  159. for (x = tmp - 1; x <= tmp + 1; x++) {
  160. if (x == tmp && y == tmp2)
  161. continue;
  162. diff = CMP(cx - x, cy - y);
  163. if (diff < smallest) {
  164. smallest = diff;
  165. mv->x = x;
  166. mv->y = y;
  167. }
  168. }
  169. }
  170. }
  171. if (smallest > 512) {
  172. mv->x = -1;
  173. mv->y = -1;
  174. }
  175. emms_c();
  176. //av_log(NULL, AV_LOG_ERROR, "%d\n", smallest);
  177. //av_log(NULL, AV_LOG_ERROR, "Final: (%d, %d) = %d x %d\n", cx, cy, mv->x, mv->y);
  178. }
  179. /**
  180. * Find the contrast of a given block. When searching for global motion we
  181. * really only care about the high contrast blocks, so using this method we
  182. * can actually skip blocks we don't care much about.
  183. */
  184. static int block_contrast(uint8_t *src, int x, int y, int stride, int blocksize)
  185. {
  186. int highest = 0;
  187. int lowest = 0;
  188. int i, j, pos;
  189. for (i = 0; i <= blocksize * 2; i++) {
  190. // We use a width of 16 here to match the libavcodec sad functions
  191. for (j = 0; i <= 15; i++) {
  192. pos = (y - i) * stride + (x - j);
  193. if (src[pos] < lowest)
  194. lowest = src[pos];
  195. else if (src[pos] > highest) {
  196. highest = src[pos];
  197. }
  198. }
  199. }
  200. return highest - lowest;
  201. }
  202. /**
  203. * Find the rotation for a given block.
  204. */
  205. static double block_angle(int x, int y, int cx, int cy, IntMotionVector *shift)
  206. {
  207. double a1, a2, diff;
  208. a1 = atan2(y - cy, x - cx);
  209. a2 = atan2(y - cy + shift->y, x - cx + shift->x);
  210. diff = a2 - a1;
  211. return (diff > M_PI) ? diff - 2 * M_PI :
  212. (diff < -M_PI) ? diff + 2 * M_PI :
  213. diff;
  214. }
  215. /**
  216. * Find the estimated global motion for a scene given the most likely shift
  217. * for each block in the frame. The global motion is estimated to be the
  218. * same as the motion from most blocks in the frame, so if most blocks
  219. * move one pixel to the right and two pixels down, this would yield a
  220. * motion vector (1, -2).
  221. */
  222. static void find_motion(DeshakeContext *deshake, uint8_t *src1, uint8_t *src2,
  223. int width, int height, int stride, Transform *t)
  224. {
  225. int x, y;
  226. IntMotionVector mv = {0, 0};
  227. int counts[128][128];
  228. int count_max_value = 0;
  229. int contrast;
  230. int pos;
  231. double *angles = av_malloc(sizeof(*angles) * width * height / (16 * deshake->blocksize));
  232. int center_x = 0, center_y = 0;
  233. double p_x, p_y;
  234. // Reset counts to zero
  235. for (x = 0; x < deshake->rx * 2 + 1; x++) {
  236. for (y = 0; y < deshake->ry * 2 + 1; y++) {
  237. counts[x][y] = 0;
  238. }
  239. }
  240. pos = 0;
  241. // Find motion for every block and store the motion vector in the counts
  242. for (y = deshake->ry; y < height - deshake->ry - (deshake->blocksize * 2); y += deshake->blocksize * 2) {
  243. // We use a width of 16 here to match the libavcodec sad functions
  244. for (x = deshake->rx; x < width - deshake->rx - 16; x += 16) {
  245. // If the contrast is too low, just skip this block as it probably
  246. // won't be very useful to us.
  247. contrast = block_contrast(src2, x, y, stride, deshake->blocksize);
  248. if (contrast > deshake->contrast) {
  249. //av_log(NULL, AV_LOG_ERROR, "%d\n", contrast);
  250. find_block_motion(deshake, src1, src2, x, y, stride, &mv);
  251. if (mv.x != -1 && mv.y != -1) {
  252. counts[mv.x + deshake->rx][mv.y + deshake->ry] += 1;
  253. if (x > deshake->rx && y > deshake->ry)
  254. angles[pos++] = block_angle(x, y, 0, 0, &mv);
  255. center_x += mv.x;
  256. center_y += mv.y;
  257. }
  258. }
  259. }
  260. }
  261. if (pos) {
  262. center_x /= pos;
  263. center_y /= pos;
  264. t->angle = clean_mean(angles, pos);
  265. if (t->angle < 0.001)
  266. t->angle = 0;
  267. } else {
  268. t->angle = 0;
  269. }
  270. // Find the most common motion vector in the frame and use it as the gmv
  271. for (y = deshake->ry * 2; y >= 0; y--) {
  272. for (x = 0; x < deshake->rx * 2 + 1; x++) {
  273. //av_log(NULL, AV_LOG_ERROR, "%5d ", counts[x][y]);
  274. if (counts[x][y] > count_max_value) {
  275. t->vector.x = x - deshake->rx;
  276. t->vector.y = y - deshake->ry;
  277. count_max_value = counts[x][y];
  278. }
  279. }
  280. //av_log(NULL, AV_LOG_ERROR, "\n");
  281. }
  282. p_x = (center_x - width / 2.0);
  283. p_y = (center_y - height / 2.0);
  284. t->vector.x += (cos(t->angle)-1)*p_x - sin(t->angle)*p_y;
  285. t->vector.y += sin(t->angle)*p_x + (cos(t->angle)-1)*p_y;
  286. // Clamp max shift & rotation?
  287. t->vector.x = av_clipf(t->vector.x, -deshake->rx * 2, deshake->rx * 2);
  288. t->vector.y = av_clipf(t->vector.y, -deshake->ry * 2, deshake->ry * 2);
  289. t->angle = av_clipf(t->angle, -0.1, 0.1);
  290. //av_log(NULL, AV_LOG_ERROR, "%d x %d\n", avg->x, avg->y);
  291. av_free(angles);
  292. }
  293. static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
  294. {
  295. DeshakeContext *deshake = ctx->priv;
  296. char filename[256] = {0};
  297. deshake->rx = 16;
  298. deshake->ry = 16;
  299. deshake->edge = FILL_MIRROR;
  300. deshake->blocksize = 8;
  301. deshake->contrast = 125;
  302. deshake->search = EXHAUSTIVE;
  303. deshake->refcount = 20;
  304. deshake->cw = -1;
  305. deshake->ch = -1;
  306. deshake->cx = -1;
  307. deshake->cy = -1;
  308. if (args) {
  309. sscanf(args, "%d:%d:%d:%d:%d:%d:%d:%d:%d:%d:%255s",
  310. &deshake->cx, &deshake->cy, &deshake->cw, &deshake->ch,
  311. &deshake->rx, &deshake->ry, (int *)&deshake->edge,
  312. &deshake->blocksize, &deshake->contrast, (int *)&deshake->search, filename);
  313. deshake->blocksize /= 2;
  314. deshake->rx = av_clip(deshake->rx, 0, 64);
  315. deshake->ry = av_clip(deshake->ry, 0, 64);
  316. deshake->edge = av_clip(deshake->edge, FILL_BLANK, FILL_COUNT - 1);
  317. deshake->blocksize = av_clip(deshake->blocksize, 4, 128);
  318. deshake->contrast = av_clip(deshake->contrast, 1, 255);
  319. deshake->search = av_clip(deshake->search, EXHAUSTIVE, SEARCH_COUNT - 1);
  320. }
  321. if (*filename)
  322. deshake->fp = fopen(filename, "w");
  323. if (deshake->fp)
  324. 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);
  325. // Quadword align left edge of box for MMX code, adjust width if necessary
  326. // to keep right margin
  327. if (deshake->cx > 0) {
  328. deshake->cw += deshake->cx - (deshake->cx & ~15);
  329. deshake->cx &= ~15;
  330. }
  331. 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",
  332. deshake->cx, deshake->cy, deshake->cw, deshake->ch,
  333. deshake->rx, deshake->ry, deshake->edge, deshake->blocksize * 2, deshake->contrast, deshake->search);
  334. return 0;
  335. }
  336. static int query_formats(AVFilterContext *ctx)
  337. {
  338. enum PixelFormat pix_fmts[] = {
  339. PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_YUV410P,
  340. PIX_FMT_YUV411P, PIX_FMT_YUV440P, PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P,
  341. PIX_FMT_YUVJ444P, PIX_FMT_YUVJ440P, PIX_FMT_NONE
  342. };
  343. avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
  344. return 0;
  345. }
  346. static int config_props(AVFilterLink *link)
  347. {
  348. DeshakeContext *deshake = link->dst->priv;
  349. deshake->ref = NULL;
  350. deshake->last.vector.x = 0;
  351. deshake->last.vector.y = 0;
  352. deshake->last.angle = 0;
  353. deshake->last.zoom = 0;
  354. deshake->avctx = avcodec_alloc_context3(NULL);
  355. dsputil_init(&deshake->c, deshake->avctx);
  356. return 0;
  357. }
  358. static av_cold void uninit(AVFilterContext *ctx)
  359. {
  360. DeshakeContext *deshake = ctx->priv;
  361. avfilter_unref_buffer(deshake->ref);
  362. if (deshake->fp)
  363. fclose(deshake->fp);
  364. }
  365. static void end_frame(AVFilterLink *link)
  366. {
  367. DeshakeContext *deshake = link->dst->priv;
  368. AVFilterBufferRef *in = link->cur_buf;
  369. AVFilterBufferRef *out = link->dst->outputs[0]->out_buf;
  370. Transform t = {{0},0}, orig = {{0},0};
  371. float matrix[9];
  372. float alpha = 2.0 / deshake->refcount;
  373. char tmp[256];
  374. if (deshake->cx < 0 || deshake->cy < 0 || deshake->cw < 0 || deshake->ch < 0) {
  375. // Find the most likely global motion for the current frame
  376. find_motion(deshake, (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0], in->data[0], link->w, link->h, in->linesize[0], &t);
  377. } else {
  378. uint8_t *src1 = (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0];
  379. uint8_t *src2 = in->data[0];
  380. deshake->cx = FFMIN(deshake->cx, link->w);
  381. deshake->cy = FFMIN(deshake->cy, link->h);
  382. if ((unsigned)deshake->cx + (unsigned)deshake->cw > link->w) deshake->cw = link->w - deshake->cx;
  383. if ((unsigned)deshake->cy + (unsigned)deshake->ch > link->h) deshake->ch = link->h - deshake->cy;
  384. // Quadword align right margin
  385. deshake->cw &= ~15;
  386. src1 += deshake->cy * in->linesize[0] + deshake->cx;
  387. src2 += deshake->cy * in->linesize[0] + deshake->cx;
  388. find_motion(deshake, src1, src2, deshake->cw, deshake->ch, in->linesize[0], &t);
  389. }
  390. // Copy transform so we can output it later to compare to the smoothed value
  391. orig.vector.x = t.vector.x;
  392. orig.vector.y = t.vector.y;
  393. orig.angle = t.angle;
  394. orig.zoom = t.zoom;
  395. // Generate a one-sided moving exponential average
  396. deshake->avg.vector.x = alpha * t.vector.x + (1.0 - alpha) * deshake->avg.vector.x;
  397. deshake->avg.vector.y = alpha * t.vector.y + (1.0 - alpha) * deshake->avg.vector.y;
  398. deshake->avg.angle = alpha * t.angle + (1.0 - alpha) * deshake->avg.angle;
  399. deshake->avg.zoom = alpha * t.zoom + (1.0 - alpha) * deshake->avg.zoom;
  400. // Remove the average from the current motion to detect the motion that
  401. // is not on purpose, just as jitter from bumping the camera
  402. t.vector.x -= deshake->avg.vector.x;
  403. t.vector.y -= deshake->avg.vector.y;
  404. t.angle -= deshake->avg.angle;
  405. t.zoom -= deshake->avg.zoom;
  406. // Invert the motion to undo it
  407. t.vector.x *= -1;
  408. t.vector.y *= -1;
  409. t.angle *= -1;
  410. // Write statistics to file
  411. if (deshake->fp) {
  412. 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);
  413. fwrite(tmp, sizeof(char), strlen(tmp), deshake->fp);
  414. }
  415. // Turn relative current frame motion into absolute by adding it to the
  416. // last absolute motion
  417. t.vector.x += deshake->last.vector.x;
  418. t.vector.y += deshake->last.vector.y;
  419. t.angle += deshake->last.angle;
  420. t.zoom += deshake->last.zoom;
  421. // Shrink motion by 10% to keep things centered in the camera frame
  422. t.vector.x *= 0.9;
  423. t.vector.y *= 0.9;
  424. t.angle *= 0.9;
  425. // Store the last absolute motion information
  426. deshake->last.vector.x = t.vector.x;
  427. deshake->last.vector.y = t.vector.y;
  428. deshake->last.angle = t.angle;
  429. deshake->last.zoom = t.zoom;
  430. // Generate a luma transformation matrix
  431. avfilter_get_matrix(t.vector.x, t.vector.y, t.angle, 1.0 + t.zoom / 100.0, matrix);
  432. // Transform the luma plane
  433. avfilter_transform(in->data[0], out->data[0], in->linesize[0], out->linesize[0], link->w, link->h, matrix, INTERPOLATE_BILINEAR, deshake->edge);
  434. // Generate a chroma transformation matrix
  435. 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);
  436. // Transform the chroma planes
  437. 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);
  438. 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);
  439. // Store the current frame as the reference frame for calculating the
  440. // motion of the next frame
  441. if (deshake->ref != NULL)
  442. avfilter_unref_buffer(deshake->ref);
  443. // Cleanup the old reference frame
  444. deshake->ref = in;
  445. // Draw the transformed frame information
  446. avfilter_draw_slice(link->dst->outputs[0], 0, link->h, 1);
  447. avfilter_end_frame(link->dst->outputs[0]);
  448. avfilter_unref_buffer(out);
  449. }
  450. static void draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
  451. {
  452. }
  453. AVFilter avfilter_vf_deshake = {
  454. .name = "deshake",
  455. .description = NULL_IF_CONFIG_SMALL("Stabilize shaky video."),
  456. .priv_size = sizeof(DeshakeContext),
  457. .init = init,
  458. .uninit = uninit,
  459. .query_formats = query_formats,
  460. .inputs = (const AVFilterPad[]) {{ .name = "default",
  461. .type = AVMEDIA_TYPE_VIDEO,
  462. .draw_slice = draw_slice,
  463. .end_frame = end_frame,
  464. .config_props = config_props,
  465. .min_perms = AV_PERM_READ, },
  466. { .name = NULL}},
  467. .outputs = (const AVFilterPad[]) {{ .name = "default",
  468. .type = AVMEDIA_TYPE_VIDEO, },
  469. { .name = NULL}},
  470. };