You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

523 lines
18KB

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