vf_deshake.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 libavfilter/vf_deshake.c
  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. double x; //< Horizontal shift
  65. double y; //< Vertical shift
  66. } MotionVector;
  67. typedef struct {
  68. MotionVector vector; //< Motion vector
  69. double angle; //< Angle of rotation
  70. double zoom; //< Zoom percentage
  71. } Transform;
  72. typedef struct {
  73. AVFilterBufferRef *ref; //< Previous frame
  74. int rx; //< Maximum horizontal shift
  75. int ry; //< Maximum vertical shift
  76. enum FillMethod edge; //< Edge fill method
  77. int blocksize; //< Size of blocks to compare
  78. int contrast; //< Contrast threshold
  79. enum SearchMethod search; //< Motion search method
  80. AVCodecContext *avctx;
  81. DSPContext c; //< Context providing optimized SAD methods
  82. Transform last; //< Transform from last frame
  83. int refcount; //< Number of reference frames (defines averaging window)
  84. FILE *fp;
  85. } DeshakeContext;
  86. static int cmp(void const *ca, void const *cb)
  87. {
  88. double *a = (double *) ca;
  89. double *b = (double *) cb;
  90. return *a < *b ? -1 : ( *a > *b ? 1 : 0 );
  91. }
  92. /**
  93. * Cleaned mean (cuts off 20% of values to remove outliers and then averages)
  94. */
  95. static double clean_mean(double *values, int count)
  96. {
  97. double mean = 0;
  98. int cut = count / 5;
  99. int x;
  100. qsort(values, count, sizeof(double), cmp);
  101. for (x = cut; x < count - cut; x++) {
  102. mean += values[x];
  103. }
  104. return mean / (count - cut * 2);
  105. }
  106. /**
  107. * Find the most likely shift in motion between two frames for a given
  108. * macroblock. Test each block against several shifts given by the rx
  109. * and ry attributes. Searches using a simple matrix of those shifts and
  110. * chooses the most likely shift by the smallest difference in blocks.
  111. */
  112. static void find_block_motion(DeshakeContext *deshake, uint8_t *src1,
  113. uint8_t *src2, int cx, int cy, int stride,
  114. MotionVector *mv)
  115. {
  116. int x, y;
  117. int diff;
  118. int smallest = INT_MAX;
  119. int tmp, tmp2;
  120. #define CMP(i, j) deshake->c.sad[0](deshake, src1 + cy * stride + cx, \
  121. src2 + (j) * stride + (i), stride, \
  122. deshake->blocksize)
  123. if (deshake->search == EXHAUSTIVE) {
  124. // Compare every possible position - this is sloooow!
  125. for (y = -deshake->ry; y <= deshake->ry; y++) {
  126. for (x = -deshake->rx; x <= deshake->rx; x++) {
  127. diff = CMP(cx - x, cy - y);
  128. if (diff < smallest) {
  129. smallest = diff;
  130. mv->x = x;
  131. mv->y = y;
  132. }
  133. }
  134. }
  135. } else if (deshake->search == SMART_EXHAUSTIVE) {
  136. // Compare every other possible position and find the best match
  137. for (y = -deshake->ry + 1; y < deshake->ry - 2; y += 2) {
  138. for (x = -deshake->rx + 1; x < deshake->rx - 2; x += 2) {
  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. // Hone in on the specific best match around the match we found above
  148. tmp = mv->x;
  149. tmp2 = mv->y;
  150. for (y = tmp2 - 1; y <= tmp2 + 1; y++) {
  151. for (x = tmp - 1; x <= tmp + 1; x++) {
  152. if (x == tmp && y == tmp2)
  153. continue;
  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. }
  163. if (smallest > 512) {
  164. mv->x = -1;
  165. mv->y = -1;
  166. }
  167. emms_c();
  168. //av_log(NULL, AV_LOG_ERROR, "%d\n", smallest);
  169. //av_log(NULL, AV_LOG_ERROR, "Final: (%d, %d) = %d x %d\n", cx, cy, mv->x, mv->y);
  170. }
  171. /**
  172. * Find the contrast of a given block. When searching for global motion we
  173. * really only care about the high contrast blocks, so using this method we
  174. * can actually skip blocks we don't care much about.
  175. */
  176. static int block_contrast(uint8_t *src, int x, int y, int stride, int blocksize)
  177. {
  178. int highest = 0;
  179. int lowest = 0;
  180. int i, j, pos;
  181. for (i = 0; i <= blocksize * 2; i++) {
  182. // We use a width of 16 here to match the libavcodec sad functions
  183. for (j = 0; i <= 15; i++) {
  184. pos = (y - i) * stride + (x - j);
  185. if (src[pos] < lowest)
  186. lowest = src[pos];
  187. else if (src[pos] > highest) {
  188. highest = src[pos];
  189. }
  190. }
  191. }
  192. return highest - lowest;
  193. }
  194. /**
  195. * Find the rotation for a given block.
  196. */
  197. static double block_angle(int x, int y, int cx, int cy, MotionVector *shift)
  198. {
  199. double a1, a2, diff;
  200. a1 = atan2(y - cy, x - cx);
  201. a2 = atan2(y - cy + shift->y, x - cx + shift->x);
  202. diff = a2 - a1;
  203. return (diff > M_PI) ? diff - 2 * M_PI :
  204. (diff < -M_PI) ? diff + 2 * M_PI :
  205. diff;
  206. }
  207. /**
  208. * Find the estimated global motion for a scene given the most likely shift
  209. * for each block in the frame. The global motion is estimated to be the
  210. * same as the motion from most blocks in the frame, so if most blocks
  211. * move one pixel to the right and two pixels down, this would yield a
  212. * motion vector (1, -2).
  213. */
  214. static void find_motion(DeshakeContext *deshake, uint8_t *src1, uint8_t *src2,
  215. int width, int height, int stride, Transform *t)
  216. {
  217. int x, y;
  218. MotionVector mv = {0, 0};
  219. int counts[128][128];
  220. int count_max_value = 0;
  221. int contrast;
  222. int pos;
  223. double angles[1200];
  224. double totalangles = 0;
  225. int center_x = 0, center_y = 0;
  226. double p_x, p_y;
  227. // Reset counts to zero
  228. for (x = 0; x < deshake->rx * 2 + 1; x++) {
  229. for (y = 0; y < deshake->ry * 2 + 1; y++) {
  230. counts[x][y] = 0;
  231. }
  232. }
  233. pos = 0;
  234. // Find motion for every block and store the motion vector in the counts
  235. for (y = deshake->ry; y < height - deshake->ry - (deshake->blocksize * 2); y += deshake->blocksize * 2) {
  236. // We use a width of 16 here to match the libavcodec sad functions
  237. for (x = deshake->rx; x < width - deshake->rx - 16; x += 16) {
  238. // If the contrast is too low, just skip this block as it probably
  239. // won't be very useful to us.
  240. contrast = block_contrast(src2, x, y, stride, deshake->blocksize);
  241. if (contrast > deshake->contrast) {
  242. //av_log(NULL, AV_LOG_ERROR, "%d\n", contrast);
  243. find_block_motion(deshake, src1, src2, x, y, stride, &mv);
  244. if (mv.x != -1 && mv.y != -1) {
  245. counts[(int)(mv.x + deshake->rx)][(int)(mv.y + deshake->ry)] += 1;
  246. if (x > deshake->rx && y > deshake->ry)
  247. angles[pos++] = block_angle(x, y, 0, 0, &mv);
  248. center_x += mv.x;
  249. center_y += mv.y;
  250. }
  251. }
  252. }
  253. }
  254. pos = FFMAX(1, pos);
  255. center_x /= pos;
  256. center_y /= pos;
  257. for (x = 0; x < pos; x++) {
  258. totalangles += angles[x];
  259. }
  260. //av_log(NULL, AV_LOG_ERROR, "Angle: %lf\n", totalangles / (pos - 1));
  261. t->angle = totalangles / (pos - 1);
  262. t->angle = clean_mean(angles, pos);
  263. if (t->angle < 0.001)
  264. t->angle = 0;
  265. // Find the most common motion vector in the frame and use it as the gmv
  266. for (y = deshake->ry * 2; y >= 0; y--) {
  267. for (x = 0; x < deshake->rx * 2 + 1; x++) {
  268. //av_log(NULL, AV_LOG_ERROR, "%5d ", counts[x][y]);
  269. if (counts[x][y] > count_max_value) {
  270. t->vector.x = x - deshake->rx;
  271. t->vector.y = y - deshake->ry;
  272. count_max_value = counts[x][y];
  273. }
  274. }
  275. //av_log(NULL, AV_LOG_ERROR, "\n");
  276. }
  277. p_x = (center_x - width / 2);
  278. p_y = (center_y - height / 2);
  279. t->vector.x += (cos(t->angle)-1)*p_x - sin(t->angle)*p_y;
  280. t->vector.y += sin(t->angle)*p_x + (cos(t->angle)-1)*p_y;
  281. // Clamp max shift & rotation?
  282. t->vector.x = av_clipf(t->vector.x, -deshake->rx * 2, deshake->rx * 2);
  283. t->vector.y = av_clipf(t->vector.y, -deshake->ry * 2, deshake->ry * 2);
  284. t->angle = av_clipf(t->angle, -0.1, 0.1);
  285. //av_log(NULL, AV_LOG_ERROR, "%d x %d\n", avg->x, avg->y);
  286. }
  287. static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
  288. {
  289. DeshakeContext *deshake = ctx->priv;
  290. deshake->rx = 16;
  291. deshake->ry = 16;
  292. deshake->edge = FILL_BLANK;
  293. deshake->blocksize = 8;
  294. deshake->contrast = 125;
  295. deshake->search = EXHAUSTIVE;
  296. deshake->refcount = 20;
  297. deshake->fp = fopen("stats.txt", "w");
  298. 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);
  299. if (args) {
  300. sscanf(args, "%d:%d:%d:%d:%d:%d", &deshake->rx, &deshake->ry, (int *)&deshake->edge,
  301. &deshake->blocksize, &deshake->contrast, (int *)&deshake->search);
  302. deshake->blocksize /= 2;
  303. deshake->rx = av_clip(deshake->rx, 0, 64);
  304. deshake->ry = av_clip(deshake->ry, 0, 64);
  305. deshake->edge = av_clip(deshake->edge, FILL_BLANK, FILL_COUNT - 1);
  306. deshake->blocksize = av_clip(deshake->blocksize, 4, 128);
  307. deshake->contrast = av_clip(deshake->contrast, 1, 255);
  308. deshake->search = av_clip(deshake->search, EXHAUSTIVE, SEARCH_COUNT - 1);
  309. }
  310. av_log(ctx, AV_LOG_INFO, "rx: %d, ry: %d, edge: %d blocksize: %d contrast: %d search: %d\n",
  311. deshake->rx, deshake->ry, deshake->edge, deshake->blocksize * 2, deshake->contrast, deshake->search);
  312. return 0;
  313. }
  314. static int query_formats(AVFilterContext *ctx)
  315. {
  316. enum PixelFormat pix_fmts[] = {
  317. PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_YUV410P,
  318. PIX_FMT_YUV411P, PIX_FMT_YUV440P, PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P,
  319. PIX_FMT_YUVJ444P, PIX_FMT_YUVJ440P, PIX_FMT_NONE
  320. };
  321. avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
  322. return 0;
  323. }
  324. static int config_props(AVFilterLink *link)
  325. {
  326. DeshakeContext *deshake = link->dst->priv;
  327. deshake->ref = NULL;
  328. deshake->last.vector.x = 0;
  329. deshake->last.vector.y = 0;
  330. deshake->last.angle = 0;
  331. deshake->last.zoom = 0;
  332. deshake->avctx= avcodec_alloc_context3(NULL);
  333. dsputil_init(&deshake->c, deshake->avctx);
  334. return 0;
  335. }
  336. static av_cold void uninit(AVFilterContext *ctx)
  337. {
  338. DeshakeContext *deshake = ctx->priv;
  339. avfilter_unref_buffer(deshake->ref);
  340. fclose(deshake->fp);
  341. }
  342. static void end_frame(AVFilterLink *link)
  343. {
  344. DeshakeContext *deshake = link->dst->priv;
  345. AVFilterBufferRef *in = link->cur_buf;
  346. AVFilterBufferRef *out = link->dst->outputs[0]->out_buf;
  347. Transform t;
  348. static float matrix[9];
  349. static Transform avg = {
  350. .vector = {
  351. .x = 0,
  352. .y = 0
  353. },
  354. .angle = 0,
  355. .zoom = 0.0f
  356. };
  357. float alpha = 2.0 / deshake->refcount;
  358. char tmp[256];
  359. Transform orig;
  360. // Find the most likely global motion for the current frame
  361. find_motion(deshake, (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0], in->data[0], link->w, link->h, in->linesize[0], &t);
  362. // Copy transform so we can output it later to compare to the smoothed value
  363. orig.vector.x = t.vector.x;
  364. orig.vector.y = t.vector.y;
  365. orig.angle = t.angle;
  366. orig.zoom = t.zoom;
  367. // Generate a one-sided moving exponential average
  368. avg.vector.x = alpha * t.vector.x + (1.0 - alpha) * avg.vector.x;
  369. avg.vector.y = alpha * t.vector.y + (1.0 - alpha) * avg.vector.y;
  370. avg.angle = alpha * t.angle + (1.0 - alpha) * avg.angle;
  371. avg.zoom = alpha * t.zoom + (1.0 - alpha) * avg.zoom;
  372. // Remove the average from the current motion to detect the motion that
  373. // is not on purpose, just as jitter from bumping the camera
  374. t.vector.x -= avg.vector.x;
  375. t.vector.y -= avg.vector.y;
  376. t.angle -= avg.angle;
  377. t.zoom -= avg.zoom;
  378. // Invert the motion to undo it
  379. t.vector.x *= -1;
  380. t.vector.y *= -1;
  381. t.angle *= -1;
  382. // Write statistics to file
  383. snprintf(tmp, 256, "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f\n", orig.vector.x, avg.vector.x, t.vector.x, orig.vector.y, avg.vector.y, t.vector.y, orig.angle, avg.angle, t.angle, orig.zoom, avg.zoom, t.zoom);
  384. fwrite(tmp, sizeof(char), strlen(tmp), deshake->fp);
  385. // Turn relative current frame motion into absolute by adding it to the
  386. // last absolute motion
  387. t.vector.x += deshake->last.vector.x;
  388. t.vector.y += deshake->last.vector.y;
  389. t.angle += deshake->last.angle;
  390. t.zoom += deshake->last.zoom;
  391. // Shrink motion by 10% to keep things centered in the camera frame
  392. t.vector.x *= 0.9;
  393. t.vector.y *= 0.9;
  394. t.angle *= 0.9;
  395. // Store the last absolute motion information
  396. deshake->last.vector.x = t.vector.x;
  397. deshake->last.vector.y = t.vector.y;
  398. deshake->last.angle = t.angle;
  399. deshake->last.zoom = t.zoom;
  400. // Generate a luma transformation matrix
  401. avfilter_get_matrix(t.vector.x, t.vector.y, t.angle, 1.0 + t.zoom / 100.0, matrix);
  402. // Transform the luma plane
  403. avfilter_transform(in->data[0], out->data[0], in->linesize[0], out->linesize[0], link->w, link->h, matrix, INTERPOLATE_BILINEAR, deshake->edge);
  404. // Generate a chroma transformation matrix
  405. 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);
  406. // Transform the chroma planes
  407. 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);
  408. 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);
  409. // Store the current frame as the reference frame for calculating the
  410. // motion of the next frame
  411. if (deshake->ref != NULL)
  412. avfilter_unref_buffer(deshake->ref);
  413. // Cleanup the old reference frame
  414. deshake->ref = in;
  415. // Draw the transformed frame information
  416. avfilter_draw_slice(link->dst->outputs[0], 0, link->h, 1);
  417. avfilter_end_frame(link->dst->outputs[0]);
  418. avfilter_unref_buffer(out);
  419. }
  420. static void draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
  421. {
  422. }
  423. AVFilter avfilter_vf_deshake = {
  424. .name = "deshake",
  425. .description = NULL_IF_CONFIG_SMALL("Stabilize shaky video."),
  426. .priv_size = sizeof(DeshakeContext),
  427. .init = init,
  428. .uninit = uninit,
  429. .query_formats = query_formats,
  430. .inputs = (AVFilterPad[]) {{ .name = "default",
  431. .type = AVMEDIA_TYPE_VIDEO,
  432. .draw_slice = draw_slice,
  433. .end_frame = end_frame,
  434. .config_props = config_props,
  435. .min_perms = AV_PERM_READ, },
  436. { .name = NULL}},
  437. .outputs = (AVFilterPad[]) {{ .name = "default",
  438. .type = AVMEDIA_TYPE_VIDEO, },
  439. { .name = NULL}},
  440. };