vf_mcdeint.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /*
  2. * Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with FFmpeg; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. */
  20. /**
  21. * @file
  22. * Motion Compensation Deinterlacer
  23. * Ported from MPlayer libmpcodecs/vf_mcdeint.c.
  24. *
  25. * Known Issues:
  26. *
  27. * The motion estimation is somewhat at the mercy of the input, if the
  28. * input frames are created purely based on spatial interpolation then
  29. * for example a thin black line or another random and not
  30. * interpolateable pattern will cause problems.
  31. * Note: completely ignoring the "unavailable" lines during motion
  32. * estimation did not look any better, so the most obvious solution
  33. * would be to improve tfields or penalize problematic motion vectors.
  34. *
  35. * If non iterative ME is used then snow currently ignores the OBMC
  36. * window and as a result sometimes creates artifacts.
  37. *
  38. * Only past frames are used, we should ideally use future frames too,
  39. * something like filtering the whole movie in forward and then
  40. * backward direction seems like an interesting idea but the current
  41. * filter framework is FAR from supporting such things.
  42. *
  43. * Combining the motion compensated image with the input image also is
  44. * not as trivial as it seems, simple blindly taking even lines from
  45. * one and odd ones from the other does not work at all as ME/MC
  46. * sometimes has nothing in the previous frames which matches the
  47. * current. The current algorithm has been found by trial and error
  48. * and almost certainly can be improved...
  49. */
  50. #include "libavutil/opt.h"
  51. #include "libavutil/pixdesc.h"
  52. #include "libavcodec/avcodec.h"
  53. #include "avfilter.h"
  54. #include "formats.h"
  55. #include "internal.h"
  56. enum MCDeintMode {
  57. MODE_FAST = 0,
  58. MODE_MEDIUM,
  59. MODE_SLOW,
  60. MODE_EXTRA_SLOW,
  61. MODE_NB,
  62. };
  63. enum MCDeintParity {
  64. PARITY_TFF = 0, ///< top field first
  65. PARITY_BFF = 1, ///< bottom field first
  66. };
  67. typedef struct MCDeintContext {
  68. const AVClass *class;
  69. int mode; ///< MCDeintMode
  70. int parity; ///< MCDeintParity
  71. int qp;
  72. AVCodecContext *enc_ctx;
  73. } MCDeintContext;
  74. #define OFFSET(x) offsetof(MCDeintContext, x)
  75. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  76. #define CONST(name, help, val, unit) { name, help, 0, AV_OPT_TYPE_CONST, {.i64=val}, INT_MIN, INT_MAX, FLAGS, unit }
  77. static const AVOption mcdeint_options[] = {
  78. { "mode", "set mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=MODE_FAST}, 0, MODE_NB-1, FLAGS, .unit="mode" },
  79. CONST("fast", NULL, MODE_FAST, "mode"),
  80. CONST("medium", NULL, MODE_MEDIUM, "mode"),
  81. CONST("slow", NULL, MODE_SLOW, "mode"),
  82. CONST("extra_slow", NULL, MODE_EXTRA_SLOW, "mode"),
  83. { "parity", "set the assumed picture field parity", OFFSET(parity), AV_OPT_TYPE_INT, {.i64=PARITY_BFF}, -1, 1, FLAGS, "parity" },
  84. CONST("tff", "assume top field first", PARITY_TFF, "parity"),
  85. CONST("bff", "assume bottom field first", PARITY_BFF, "parity"),
  86. { "qp", "set qp", OFFSET(qp), AV_OPT_TYPE_INT, {.i64=1}, INT_MIN, INT_MAX, FLAGS },
  87. { NULL }
  88. };
  89. AVFILTER_DEFINE_CLASS(mcdeint);
  90. static int config_props(AVFilterLink *inlink)
  91. {
  92. AVFilterContext *ctx = inlink->dst;
  93. MCDeintContext *mcdeint = ctx->priv;
  94. AVCodec *enc;
  95. AVCodecContext *enc_ctx;
  96. AVDictionary *opts = NULL;
  97. int ret;
  98. if (!(enc = avcodec_find_encoder(AV_CODEC_ID_SNOW))) {
  99. av_log(ctx, AV_LOG_ERROR, "Snow encoder is not enabled in libavcodec\n");
  100. return AVERROR(EINVAL);
  101. }
  102. mcdeint->enc_ctx = avcodec_alloc_context3(enc);
  103. if (!mcdeint->enc_ctx)
  104. return AVERROR(ENOMEM);
  105. enc_ctx = mcdeint->enc_ctx;
  106. enc_ctx->width = inlink->w;
  107. enc_ctx->height = inlink->h;
  108. enc_ctx->time_base = (AVRational){1,25}; // meaningless
  109. enc_ctx->gop_size = INT_MAX;
  110. enc_ctx->max_b_frames = 0;
  111. enc_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
  112. enc_ctx->flags = AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_LOW_DELAY;
  113. enc_ctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
  114. enc_ctx->global_quality = 1;
  115. enc_ctx->me_cmp = enc_ctx->me_sub_cmp = FF_CMP_SAD;
  116. enc_ctx->mb_cmp = FF_CMP_SSE;
  117. av_dict_set(&opts, "memc_only", "1", 0);
  118. av_dict_set(&opts, "no_bitstream", "1", 0);
  119. switch (mcdeint->mode) {
  120. case MODE_EXTRA_SLOW:
  121. enc_ctx->refs = 3;
  122. case MODE_SLOW:
  123. av_dict_set(&opts, "motion_est", "iter", 0);
  124. case MODE_MEDIUM:
  125. enc_ctx->flags |= AV_CODEC_FLAG_4MV;
  126. enc_ctx->dia_size = 2;
  127. case MODE_FAST:
  128. enc_ctx->flags |= AV_CODEC_FLAG_QPEL;
  129. }
  130. ret = avcodec_open2(enc_ctx, enc, &opts);
  131. av_dict_free(&opts);
  132. if (ret < 0)
  133. return ret;
  134. return 0;
  135. }
  136. static av_cold void uninit(AVFilterContext *ctx)
  137. {
  138. MCDeintContext *mcdeint = ctx->priv;
  139. avcodec_free_context(&mcdeint->enc_ctx);
  140. }
  141. static int query_formats(AVFilterContext *ctx)
  142. {
  143. static const enum AVPixelFormat pix_fmts[] = {
  144. AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE
  145. };
  146. AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
  147. if (!fmts_list)
  148. return AVERROR(ENOMEM);
  149. return ff_set_common_formats(ctx, fmts_list);
  150. }
  151. static int filter_frame(AVFilterLink *inlink, AVFrame *inpic)
  152. {
  153. MCDeintContext *mcdeint = inlink->dst->priv;
  154. AVFilterLink *outlink = inlink->dst->outputs[0];
  155. AVFrame *outpic, *frame_dec;
  156. AVPacket pkt = {0};
  157. int x, y, i, ret, got_frame = 0;
  158. outpic = ff_get_video_buffer(outlink, outlink->w, outlink->h);
  159. if (!outpic) {
  160. av_frame_free(&inpic);
  161. return AVERROR(ENOMEM);
  162. }
  163. av_frame_copy_props(outpic, inpic);
  164. inpic->quality = mcdeint->qp * FF_QP2LAMBDA;
  165. av_init_packet(&pkt);
  166. ret = avcodec_encode_video2(mcdeint->enc_ctx, &pkt, inpic, &got_frame);
  167. if (ret < 0)
  168. goto end;
  169. frame_dec = mcdeint->enc_ctx->coded_frame;
  170. for (i = 0; i < 3; i++) {
  171. int is_chroma = !!i;
  172. int w = AV_CEIL_RSHIFT(inlink->w, is_chroma);
  173. int h = AV_CEIL_RSHIFT(inlink->h, is_chroma);
  174. int fils = frame_dec->linesize[i];
  175. int srcs = inpic ->linesize[i];
  176. int dsts = outpic ->linesize[i];
  177. for (y = 0; y < h; y++) {
  178. if ((y ^ mcdeint->parity) & 1) {
  179. for (x = 0; x < w; x++) {
  180. uint8_t *filp = &frame_dec->data[i][x + y*fils];
  181. uint8_t *srcp = &inpic ->data[i][x + y*srcs];
  182. uint8_t *dstp = &outpic ->data[i][x + y*dsts];
  183. if (y > 0 && y < h-1){
  184. int is_edge = x < 3 || x > w-4;
  185. int diff0 = filp[-fils] - srcp[-srcs];
  186. int diff1 = filp[+fils] - srcp[+srcs];
  187. int temp = filp[0];
  188. #define DELTA(j) av_clip(j, -x, w-1-x)
  189. #define GET_SCORE_EDGE(j)\
  190. FFABS(srcp[-srcs+DELTA(-1+(j))] - srcp[+srcs+DELTA(-1-(j))])+\
  191. FFABS(srcp[-srcs+DELTA(j) ] - srcp[+srcs+DELTA( -(j))])+\
  192. FFABS(srcp[-srcs+DELTA(1+(j)) ] - srcp[+srcs+DELTA( 1-(j))])
  193. #define GET_SCORE(j)\
  194. FFABS(srcp[-srcs-1+(j)] - srcp[+srcs-1-(j)])+\
  195. FFABS(srcp[-srcs +(j)] - srcp[+srcs -(j)])+\
  196. FFABS(srcp[-srcs+1+(j)] - srcp[+srcs+1-(j)])
  197. #define CHECK_EDGE(j)\
  198. { int score = GET_SCORE_EDGE(j);\
  199. if (score < spatial_score){\
  200. spatial_score = score;\
  201. diff0 = filp[-fils+DELTA(j)] - srcp[-srcs+DELTA(j)];\
  202. diff1 = filp[+fils+DELTA(-(j))] - srcp[+srcs+DELTA(-(j))];\
  203. #define CHECK(j)\
  204. { int score = GET_SCORE(j);\
  205. if (score < spatial_score){\
  206. spatial_score= score;\
  207. diff0 = filp[-fils+(j)] - srcp[-srcs+(j)];\
  208. diff1 = filp[+fils-(j)] - srcp[+srcs-(j)];\
  209. if (is_edge) {
  210. int spatial_score = GET_SCORE_EDGE(0) - 1;
  211. CHECK_EDGE(-1) CHECK_EDGE(-2) }} }}
  212. CHECK_EDGE( 1) CHECK_EDGE( 2) }} }}
  213. } else {
  214. int spatial_score = GET_SCORE(0) - 1;
  215. CHECK(-1) CHECK(-2) }} }}
  216. CHECK( 1) CHECK( 2) }} }}
  217. }
  218. if (diff0 + diff1 > 0)
  219. temp -= (diff0 + diff1 - FFABS(FFABS(diff0) - FFABS(diff1)) / 2) / 2;
  220. else
  221. temp -= (diff0 + diff1 + FFABS(FFABS(diff0) - FFABS(diff1)) / 2) / 2;
  222. *filp = *dstp = temp > 255U ? ~(temp>>31) : temp;
  223. } else {
  224. *dstp = *filp;
  225. }
  226. }
  227. }
  228. }
  229. for (y = 0; y < h; y++) {
  230. if (!((y ^ mcdeint->parity) & 1)) {
  231. for (x = 0; x < w; x++) {
  232. frame_dec->data[i][x + y*fils] =
  233. outpic ->data[i][x + y*dsts] = inpic->data[i][x + y*srcs];
  234. }
  235. }
  236. }
  237. }
  238. mcdeint->parity ^= 1;
  239. end:
  240. av_packet_unref(&pkt);
  241. av_frame_free(&inpic);
  242. if (ret < 0) {
  243. av_frame_free(&outpic);
  244. return ret;
  245. }
  246. return ff_filter_frame(outlink, outpic);
  247. }
  248. static const AVFilterPad mcdeint_inputs[] = {
  249. {
  250. .name = "default",
  251. .type = AVMEDIA_TYPE_VIDEO,
  252. .filter_frame = filter_frame,
  253. .config_props = config_props,
  254. },
  255. { NULL }
  256. };
  257. static const AVFilterPad mcdeint_outputs[] = {
  258. {
  259. .name = "default",
  260. .type = AVMEDIA_TYPE_VIDEO,
  261. },
  262. { NULL }
  263. };
  264. AVFilter ff_vf_mcdeint = {
  265. .name = "mcdeint",
  266. .description = NULL_IF_CONFIG_SMALL("Apply motion compensating deinterlacing."),
  267. .priv_size = sizeof(MCDeintContext),
  268. .uninit = uninit,
  269. .query_formats = query_formats,
  270. .inputs = mcdeint_inputs,
  271. .outputs = mcdeint_outputs,
  272. .priv_class = &mcdeint_class,
  273. };