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.

419 lines
14KB

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