vf_crop.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /*
  2. * Copyright (c) 2007 Bobby Bingham
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (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 GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * video crop filter
  23. */
  24. #include <stdio.h>
  25. #include "avfilter.h"
  26. #include "formats.h"
  27. #include "internal.h"
  28. #include "video.h"
  29. #include "libavutil/eval.h"
  30. #include "libavutil/avstring.h"
  31. #include "libavutil/internal.h"
  32. #include "libavutil/libm.h"
  33. #include "libavutil/imgutils.h"
  34. #include "libavutil/mathematics.h"
  35. #include "libavutil/opt.h"
  36. static const char *const var_names[] = {
  37. "in_w", "iw", ///< width of the input video
  38. "in_h", "ih", ///< height of the input video
  39. "out_w", "ow", ///< width of the cropped video
  40. "out_h", "oh", ///< height of the cropped video
  41. "a",
  42. "sar",
  43. "dar",
  44. "hsub",
  45. "vsub",
  46. "x",
  47. "y",
  48. "n", ///< number of frame
  49. "pos", ///< position in the file
  50. "t", ///< timestamp expressed in seconds
  51. NULL
  52. };
  53. enum var_name {
  54. VAR_IN_W, VAR_IW,
  55. VAR_IN_H, VAR_IH,
  56. VAR_OUT_W, VAR_OW,
  57. VAR_OUT_H, VAR_OH,
  58. VAR_A,
  59. VAR_SAR,
  60. VAR_DAR,
  61. VAR_HSUB,
  62. VAR_VSUB,
  63. VAR_X,
  64. VAR_Y,
  65. VAR_N,
  66. VAR_POS,
  67. VAR_T,
  68. VAR_VARS_NB
  69. };
  70. typedef struct CropContext {
  71. const AVClass *class;
  72. int x; ///< x offset of the non-cropped area with respect to the input area
  73. int y; ///< y offset of the non-cropped area with respect to the input area
  74. int w; ///< width of the cropped area
  75. int h; ///< height of the cropped area
  76. AVRational out_sar; ///< output sample aspect ratio
  77. int keep_aspect; ///< keep display aspect ratio when cropping
  78. int max_step[4]; ///< max pixel step for each plane, expressed as a number of bytes
  79. int hsub, vsub; ///< chroma subsampling
  80. char *x_expr, *y_expr, *w_expr, *h_expr;
  81. AVExpr *x_pexpr, *y_pexpr; /* parsed expressions for x and y */
  82. double var_values[VAR_VARS_NB];
  83. } CropContext;
  84. static int query_formats(AVFilterContext *ctx)
  85. {
  86. AVFilterFormats *formats = NULL;
  87. int fmt, ret;
  88. for (fmt = 0; av_pix_fmt_desc_get(fmt); fmt++) {
  89. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt);
  90. if (!(desc->flags & (AV_PIX_FMT_FLAG_HWACCEL | AV_PIX_FMT_FLAG_BITSTREAM)) &&
  91. !((desc->log2_chroma_w || desc->log2_chroma_h) && !(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) &&
  92. (ret = ff_add_format(&formats, fmt)) < 0)
  93. return ret;
  94. }
  95. return ff_set_common_formats(ctx, formats);
  96. }
  97. static av_cold void uninit(AVFilterContext *ctx)
  98. {
  99. CropContext *s = ctx->priv;
  100. av_expr_free(s->x_pexpr);
  101. s->x_pexpr = NULL;
  102. av_expr_free(s->y_pexpr);
  103. s->y_pexpr = NULL;
  104. }
  105. static inline int normalize_double(int *n, double d)
  106. {
  107. int ret = 0;
  108. if (isnan(d)) {
  109. ret = AVERROR(EINVAL);
  110. } else if (d > INT_MAX || d < INT_MIN) {
  111. *n = d > INT_MAX ? INT_MAX : INT_MIN;
  112. ret = AVERROR(EINVAL);
  113. } else
  114. *n = lrint(d);
  115. return ret;
  116. }
  117. static int config_input(AVFilterLink *link)
  118. {
  119. AVFilterContext *ctx = link->dst;
  120. CropContext *s = ctx->priv;
  121. const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(link->format);
  122. int ret;
  123. const char *expr;
  124. double res;
  125. s->var_values[VAR_IN_W] = s->var_values[VAR_IW] = ctx->inputs[0]->w;
  126. s->var_values[VAR_IN_H] = s->var_values[VAR_IH] = ctx->inputs[0]->h;
  127. s->var_values[VAR_A] = (float) link->w / link->h;
  128. s->var_values[VAR_SAR] = link->sample_aspect_ratio.num ? av_q2d(link->sample_aspect_ratio) : 1;
  129. s->var_values[VAR_DAR] = s->var_values[VAR_A] * s->var_values[VAR_SAR];
  130. s->var_values[VAR_HSUB] = 1<<pix_desc->log2_chroma_w;
  131. s->var_values[VAR_VSUB] = 1<<pix_desc->log2_chroma_h;
  132. s->var_values[VAR_X] = NAN;
  133. s->var_values[VAR_Y] = NAN;
  134. s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = NAN;
  135. s->var_values[VAR_OUT_H] = s->var_values[VAR_OH] = NAN;
  136. s->var_values[VAR_N] = 0;
  137. s->var_values[VAR_T] = NAN;
  138. s->var_values[VAR_POS] = NAN;
  139. av_image_fill_max_pixsteps(s->max_step, NULL, pix_desc);
  140. s->hsub = pix_desc->log2_chroma_w;
  141. s->vsub = pix_desc->log2_chroma_h;
  142. if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
  143. var_names, s->var_values,
  144. NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  145. goto fail_expr;
  146. s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = res;
  147. if ((ret = av_expr_parse_and_eval(&res, (expr = s->h_expr),
  148. var_names, s->var_values,
  149. NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  150. goto fail_expr;
  151. s->var_values[VAR_OUT_H] = s->var_values[VAR_OH] = res;
  152. /* evaluate again ow as it may depend on oh */
  153. if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
  154. var_names, s->var_values,
  155. NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  156. goto fail_expr;
  157. s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = res;
  158. if (normalize_double(&s->w, s->var_values[VAR_OUT_W]) < 0 ||
  159. normalize_double(&s->h, s->var_values[VAR_OUT_H]) < 0) {
  160. av_log(ctx, AV_LOG_ERROR,
  161. "Too big value or invalid expression for out_w/ow or out_h/oh. "
  162. "Maybe the expression for out_w:'%s' or for out_h:'%s' is self-referencing.\n",
  163. s->w_expr, s->h_expr);
  164. return AVERROR(EINVAL);
  165. }
  166. s->w &= ~((1 << s->hsub) - 1);
  167. s->h &= ~((1 << s->vsub) - 1);
  168. av_expr_free(s->x_pexpr);
  169. av_expr_free(s->y_pexpr);
  170. s->x_pexpr = s->y_pexpr = NULL;
  171. if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
  172. NULL, NULL, NULL, NULL, 0, ctx)) < 0 ||
  173. (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
  174. NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  175. return AVERROR(EINVAL);
  176. if (s->keep_aspect) {
  177. AVRational dar = av_mul_q(link->sample_aspect_ratio,
  178. (AVRational){ link->w, link->h });
  179. av_reduce(&s->out_sar.num, &s->out_sar.den,
  180. dar.num * s->h, dar.den * s->w, INT_MAX);
  181. } else
  182. s->out_sar = link->sample_aspect_ratio;
  183. av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d sar:%d/%d -> w:%d h:%d sar:%d/%d\n",
  184. link->w, link->h, link->sample_aspect_ratio.num, link->sample_aspect_ratio.den,
  185. s->w, s->h, s->out_sar.num, s->out_sar.den);
  186. if (s->w <= 0 || s->h <= 0 ||
  187. s->w > link->w || s->h > link->h) {
  188. av_log(ctx, AV_LOG_ERROR,
  189. "Invalid too big or non positive size for width '%d' or height '%d'\n",
  190. s->w, s->h);
  191. return AVERROR(EINVAL);
  192. }
  193. /* set default, required in the case the first computed value for x/y is NAN */
  194. s->x = (link->w - s->w) / 2;
  195. s->y = (link->h - s->h) / 2;
  196. s->x &= ~((1 << s->hsub) - 1);
  197. s->y &= ~((1 << s->vsub) - 1);
  198. return 0;
  199. fail_expr:
  200. av_log(NULL, AV_LOG_ERROR, "Error when evaluating the expression '%s'\n", expr);
  201. return ret;
  202. }
  203. static int config_output(AVFilterLink *link)
  204. {
  205. CropContext *s = link->src->priv;
  206. link->w = s->w;
  207. link->h = s->h;
  208. link->sample_aspect_ratio = s->out_sar;
  209. return 0;
  210. }
  211. static int filter_frame(AVFilterLink *link, AVFrame *frame)
  212. {
  213. AVFilterContext *ctx = link->dst;
  214. CropContext *s = ctx->priv;
  215. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
  216. int i;
  217. frame->width = s->w;
  218. frame->height = s->h;
  219. s->var_values[VAR_N] = link->frame_count;
  220. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  221. NAN : frame->pts * av_q2d(link->time_base);
  222. s->var_values[VAR_POS] = av_frame_get_pkt_pos(frame) == -1 ?
  223. NAN : av_frame_get_pkt_pos(frame);
  224. s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, NULL);
  225. s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, NULL);
  226. s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, NULL);
  227. normalize_double(&s->x, s->var_values[VAR_X]);
  228. normalize_double(&s->y, s->var_values[VAR_Y]);
  229. if (s->x < 0)
  230. s->x = 0;
  231. if (s->y < 0)
  232. s->y = 0;
  233. if ((unsigned)s->x + (unsigned)s->w > link->w)
  234. s->x = link->w - s->w;
  235. if ((unsigned)s->y + (unsigned)s->h > link->h)
  236. s->y = link->h - s->h;
  237. s->x &= ~((1 << s->hsub) - 1);
  238. s->y &= ~((1 << s->vsub) - 1);
  239. av_log(ctx, AV_LOG_TRACE, "n:%d t:%f pos:%f x:%d y:%d x+w:%d y+h:%d\n",
  240. (int)s->var_values[VAR_N], s->var_values[VAR_T], s->var_values[VAR_POS],
  241. s->x, s->y, s->x+s->w, s->y+s->h);
  242. frame->data[0] += s->y * frame->linesize[0];
  243. frame->data[0] += s->x * s->max_step[0];
  244. if (!(desc->flags & AV_PIX_FMT_FLAG_PAL || desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)) {
  245. for (i = 1; i < 3; i ++) {
  246. if (frame->data[i]) {
  247. frame->data[i] += (s->y >> s->vsub) * frame->linesize[i];
  248. frame->data[i] += (s->x * s->max_step[i]) >> s->hsub;
  249. }
  250. }
  251. }
  252. /* alpha plane */
  253. if (frame->data[3]) {
  254. frame->data[3] += s->y * frame->linesize[3];
  255. frame->data[3] += s->x * s->max_step[3];
  256. }
  257. return ff_filter_frame(link->dst->outputs[0], frame);
  258. }
  259. static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
  260. char *res, int res_len, int flags)
  261. {
  262. CropContext *s = ctx->priv;
  263. int ret;
  264. if ( !strcmp(cmd, "out_w") || !strcmp(cmd, "w")
  265. || !strcmp(cmd, "out_h") || !strcmp(cmd, "h")
  266. || !strcmp(cmd, "x") || !strcmp(cmd, "y")) {
  267. int old_x = s->x;
  268. int old_y = s->y;
  269. int old_w = s->w;
  270. int old_h = s->h;
  271. AVFilterLink *outlink = ctx->outputs[0];
  272. AVFilterLink *inlink = ctx->inputs[0];
  273. av_opt_set(s, cmd, args, 0);
  274. if ((ret = config_input(inlink)) < 0) {
  275. s->x = old_x;
  276. s->y = old_y;
  277. s->w = old_w;
  278. s->h = old_h;
  279. return ret;
  280. }
  281. ret = config_output(outlink);
  282. } else
  283. ret = AVERROR(ENOSYS);
  284. return ret;
  285. }
  286. #define OFFSET(x) offsetof(CropContext, x)
  287. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  288. static const AVOption crop_options[] = {
  289. { "out_w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, FLAGS },
  290. { "w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, FLAGS },
  291. { "out_h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, FLAGS },
  292. { "h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, FLAGS },
  293. { "x", "set the x crop area expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "(in_w-out_w)/2"}, CHAR_MIN, CHAR_MAX, FLAGS },
  294. { "y", "set the y crop area expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "(in_h-out_h)/2"}, CHAR_MIN, CHAR_MAX, FLAGS },
  295. { "keep_aspect", "keep aspect ratio", OFFSET(keep_aspect), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
  296. { NULL }
  297. };
  298. AVFILTER_DEFINE_CLASS(crop);
  299. static const AVFilterPad avfilter_vf_crop_inputs[] = {
  300. {
  301. .name = "default",
  302. .type = AVMEDIA_TYPE_VIDEO,
  303. .filter_frame = filter_frame,
  304. .config_props = config_input,
  305. },
  306. { NULL }
  307. };
  308. static const AVFilterPad avfilter_vf_crop_outputs[] = {
  309. {
  310. .name = "default",
  311. .type = AVMEDIA_TYPE_VIDEO,
  312. .config_props = config_output,
  313. },
  314. { NULL }
  315. };
  316. AVFilter ff_vf_crop = {
  317. .name = "crop",
  318. .description = NULL_IF_CONFIG_SMALL("Crop the input video."),
  319. .priv_size = sizeof(CropContext),
  320. .priv_class = &crop_class,
  321. .query_formats = query_formats,
  322. .uninit = uninit,
  323. .inputs = avfilter_vf_crop_inputs,
  324. .outputs = avfilter_vf_crop_outputs,
  325. .process_command = process_command,
  326. };