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.

391 lines
13KB

  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 exact; ///< exact cropping, for subsampled formats
  79. int max_step[4]; ///< max pixel step for each plane, expressed as a number of bytes
  80. int hsub, vsub; ///< chroma subsampling
  81. char *x_expr, *y_expr, *w_expr, *h_expr;
  82. AVExpr *x_pexpr, *y_pexpr; /* parsed expressions for x and y */
  83. double var_values[VAR_VARS_NB];
  84. } CropContext;
  85. static int query_formats(AVFilterContext *ctx)
  86. {
  87. AVFilterFormats *formats = NULL;
  88. int fmt, ret;
  89. for (fmt = 0; av_pix_fmt_desc_get(fmt); fmt++) {
  90. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt);
  91. if (!(desc->flags & (AV_PIX_FMT_FLAG_HWACCEL | AV_PIX_FMT_FLAG_BITSTREAM)) &&
  92. !((desc->log2_chroma_w || desc->log2_chroma_h) && !(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) &&
  93. (ret = ff_add_format(&formats, fmt)) < 0)
  94. return ret;
  95. }
  96. return ff_set_common_formats(ctx, formats);
  97. }
  98. static av_cold void uninit(AVFilterContext *ctx)
  99. {
  100. CropContext *s = ctx->priv;
  101. av_expr_free(s->x_pexpr);
  102. s->x_pexpr = NULL;
  103. av_expr_free(s->y_pexpr);
  104. s->y_pexpr = NULL;
  105. }
  106. static inline int normalize_double(int *n, double d)
  107. {
  108. int ret = 0;
  109. if (isnan(d)) {
  110. ret = AVERROR(EINVAL);
  111. } else if (d > INT_MAX || d < INT_MIN) {
  112. *n = d > INT_MAX ? INT_MAX : INT_MIN;
  113. ret = AVERROR(EINVAL);
  114. } else
  115. *n = lrint(d);
  116. return ret;
  117. }
  118. static int config_input(AVFilterLink *link)
  119. {
  120. AVFilterContext *ctx = link->dst;
  121. CropContext *s = ctx->priv;
  122. const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(link->format);
  123. int ret;
  124. const char *expr;
  125. double res;
  126. s->var_values[VAR_IN_W] = s->var_values[VAR_IW] = ctx->inputs[0]->w;
  127. s->var_values[VAR_IN_H] = s->var_values[VAR_IH] = ctx->inputs[0]->h;
  128. s->var_values[VAR_A] = (float) link->w / link->h;
  129. s->var_values[VAR_SAR] = link->sample_aspect_ratio.num ? av_q2d(link->sample_aspect_ratio) : 1;
  130. s->var_values[VAR_DAR] = s->var_values[VAR_A] * s->var_values[VAR_SAR];
  131. s->var_values[VAR_HSUB] = 1<<pix_desc->log2_chroma_w;
  132. s->var_values[VAR_VSUB] = 1<<pix_desc->log2_chroma_h;
  133. s->var_values[VAR_X] = NAN;
  134. s->var_values[VAR_Y] = NAN;
  135. s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = NAN;
  136. s->var_values[VAR_OUT_H] = s->var_values[VAR_OH] = NAN;
  137. s->var_values[VAR_N] = 0;
  138. s->var_values[VAR_T] = NAN;
  139. s->var_values[VAR_POS] = NAN;
  140. av_image_fill_max_pixsteps(s->max_step, NULL, pix_desc);
  141. s->hsub = pix_desc->log2_chroma_w;
  142. s->vsub = pix_desc->log2_chroma_h;
  143. if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
  144. var_names, s->var_values,
  145. NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  146. goto fail_expr;
  147. s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = res;
  148. if ((ret = av_expr_parse_and_eval(&res, (expr = s->h_expr),
  149. var_names, s->var_values,
  150. NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  151. goto fail_expr;
  152. s->var_values[VAR_OUT_H] = s->var_values[VAR_OH] = res;
  153. /* evaluate again ow as it may depend on oh */
  154. if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
  155. var_names, s->var_values,
  156. NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  157. goto fail_expr;
  158. s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = res;
  159. if (normalize_double(&s->w, s->var_values[VAR_OUT_W]) < 0 ||
  160. normalize_double(&s->h, s->var_values[VAR_OUT_H]) < 0) {
  161. av_log(ctx, AV_LOG_ERROR,
  162. "Too big value or invalid expression for out_w/ow or out_h/oh. "
  163. "Maybe the expression for out_w:'%s' or for out_h:'%s' is self-referencing.\n",
  164. s->w_expr, s->h_expr);
  165. return AVERROR(EINVAL);
  166. }
  167. if (!s->exact) {
  168. s->w &= ~((1 << s->hsub) - 1);
  169. s->h &= ~((1 << s->vsub) - 1);
  170. }
  171. av_expr_free(s->x_pexpr);
  172. av_expr_free(s->y_pexpr);
  173. s->x_pexpr = s->y_pexpr = NULL;
  174. if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
  175. NULL, NULL, NULL, NULL, 0, ctx)) < 0 ||
  176. (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
  177. NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  178. return AVERROR(EINVAL);
  179. if (s->keep_aspect) {
  180. AVRational dar = av_mul_q(link->sample_aspect_ratio,
  181. (AVRational){ link->w, link->h });
  182. av_reduce(&s->out_sar.num, &s->out_sar.den,
  183. dar.num * s->h, dar.den * s->w, INT_MAX);
  184. } else
  185. s->out_sar = link->sample_aspect_ratio;
  186. av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d sar:%d/%d -> w:%d h:%d sar:%d/%d\n",
  187. link->w, link->h, link->sample_aspect_ratio.num, link->sample_aspect_ratio.den,
  188. s->w, s->h, s->out_sar.num, s->out_sar.den);
  189. if (s->w <= 0 || s->h <= 0 ||
  190. s->w > link->w || s->h > link->h) {
  191. av_log(ctx, AV_LOG_ERROR,
  192. "Invalid too big or non positive size for width '%d' or height '%d'\n",
  193. s->w, s->h);
  194. return AVERROR(EINVAL);
  195. }
  196. /* set default, required in the case the first computed value for x/y is NAN */
  197. s->x = (link->w - s->w) / 2;
  198. s->y = (link->h - s->h) / 2;
  199. if (!s->exact) {
  200. s->x &= ~((1 << s->hsub) - 1);
  201. s->y &= ~((1 << s->vsub) - 1);
  202. }
  203. return 0;
  204. fail_expr:
  205. av_log(NULL, AV_LOG_ERROR, "Error when evaluating the expression '%s'\n", expr);
  206. return ret;
  207. }
  208. static int config_output(AVFilterLink *link)
  209. {
  210. CropContext *s = link->src->priv;
  211. link->w = s->w;
  212. link->h = s->h;
  213. link->sample_aspect_ratio = s->out_sar;
  214. return 0;
  215. }
  216. static int filter_frame(AVFilterLink *link, AVFrame *frame)
  217. {
  218. AVFilterContext *ctx = link->dst;
  219. CropContext *s = ctx->priv;
  220. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
  221. int i;
  222. frame->width = s->w;
  223. frame->height = s->h;
  224. s->var_values[VAR_N] = link->frame_count_out;
  225. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  226. NAN : frame->pts * av_q2d(link->time_base);
  227. s->var_values[VAR_POS] = frame->pkt_pos == -1 ?
  228. NAN : frame->pkt_pos;
  229. s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, NULL);
  230. s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, NULL);
  231. s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, NULL);
  232. normalize_double(&s->x, s->var_values[VAR_X]);
  233. normalize_double(&s->y, s->var_values[VAR_Y]);
  234. if (s->x < 0)
  235. s->x = 0;
  236. if (s->y < 0)
  237. s->y = 0;
  238. if ((unsigned)s->x + (unsigned)s->w > link->w)
  239. s->x = link->w - s->w;
  240. if ((unsigned)s->y + (unsigned)s->h > link->h)
  241. s->y = link->h - s->h;
  242. if (!s->exact) {
  243. s->x &= ~((1 << s->hsub) - 1);
  244. s->y &= ~((1 << s->vsub) - 1);
  245. }
  246. av_log(ctx, AV_LOG_TRACE, "n:%d t:%f pos:%f x:%d y:%d x+w:%d y+h:%d\n",
  247. (int)s->var_values[VAR_N], s->var_values[VAR_T], s->var_values[VAR_POS],
  248. s->x, s->y, s->x+s->w, s->y+s->h);
  249. frame->data[0] += s->y * frame->linesize[0];
  250. frame->data[0] += s->x * s->max_step[0];
  251. if (!(desc->flags & AV_PIX_FMT_FLAG_PAL || desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)) {
  252. for (i = 1; i < 3; i ++) {
  253. if (frame->data[i]) {
  254. frame->data[i] += (s->y >> s->vsub) * frame->linesize[i];
  255. frame->data[i] += (s->x * s->max_step[i]) >> s->hsub;
  256. }
  257. }
  258. }
  259. /* alpha plane */
  260. if (frame->data[3]) {
  261. frame->data[3] += s->y * frame->linesize[3];
  262. frame->data[3] += s->x * s->max_step[3];
  263. }
  264. return ff_filter_frame(link->dst->outputs[0], frame);
  265. }
  266. static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
  267. char *res, int res_len, int flags)
  268. {
  269. CropContext *s = ctx->priv;
  270. int ret;
  271. if ( !strcmp(cmd, "out_w") || !strcmp(cmd, "w")
  272. || !strcmp(cmd, "out_h") || !strcmp(cmd, "h")
  273. || !strcmp(cmd, "x") || !strcmp(cmd, "y")) {
  274. int old_x = s->x;
  275. int old_y = s->y;
  276. int old_w = s->w;
  277. int old_h = s->h;
  278. AVFilterLink *outlink = ctx->outputs[0];
  279. AVFilterLink *inlink = ctx->inputs[0];
  280. av_opt_set(s, cmd, args, 0);
  281. if ((ret = config_input(inlink)) < 0) {
  282. s->x = old_x;
  283. s->y = old_y;
  284. s->w = old_w;
  285. s->h = old_h;
  286. return ret;
  287. }
  288. ret = config_output(outlink);
  289. } else
  290. ret = AVERROR(ENOSYS);
  291. return ret;
  292. }
  293. #define OFFSET(x) offsetof(CropContext, x)
  294. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  295. static const AVOption crop_options[] = {
  296. { "out_w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, FLAGS },
  297. { "w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, FLAGS },
  298. { "out_h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, FLAGS },
  299. { "h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, FLAGS },
  300. { "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 },
  301. { "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 },
  302. { "keep_aspect", "keep aspect ratio", OFFSET(keep_aspect), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
  303. { "exact", "do exact cropping", OFFSET(exact), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
  304. { NULL }
  305. };
  306. AVFILTER_DEFINE_CLASS(crop);
  307. static const AVFilterPad avfilter_vf_crop_inputs[] = {
  308. {
  309. .name = "default",
  310. .type = AVMEDIA_TYPE_VIDEO,
  311. .filter_frame = filter_frame,
  312. .config_props = config_input,
  313. },
  314. { NULL }
  315. };
  316. static const AVFilterPad avfilter_vf_crop_outputs[] = {
  317. {
  318. .name = "default",
  319. .type = AVMEDIA_TYPE_VIDEO,
  320. .config_props = config_output,
  321. },
  322. { NULL }
  323. };
  324. AVFilter ff_vf_crop = {
  325. .name = "crop",
  326. .description = NULL_IF_CONFIG_SMALL("Crop the input video."),
  327. .priv_size = sizeof(CropContext),
  328. .priv_class = &crop_class,
  329. .query_formats = query_formats,
  330. .uninit = uninit,
  331. .inputs = avfilter_vf_crop_inputs,
  332. .outputs = avfilter_vf_crop_outputs,
  333. .process_command = process_command,
  334. };