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.

406 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 ret;
  89. ret = ff_formats_pixdesc_filter(&formats, 0, AV_PIX_FMT_FLAG_BITSTREAM | FF_PIX_FMT_FLAG_SW_FLAT_SUB);
  90. if (ret < 0)
  91. return ret;
  92. return ff_set_common_formats(ctx, formats);
  93. }
  94. static av_cold void uninit(AVFilterContext *ctx)
  95. {
  96. CropContext *s = ctx->priv;
  97. av_expr_free(s->x_pexpr);
  98. s->x_pexpr = NULL;
  99. av_expr_free(s->y_pexpr);
  100. s->y_pexpr = NULL;
  101. }
  102. static inline int normalize_double(int *n, double d)
  103. {
  104. int ret = 0;
  105. if (isnan(d)) {
  106. ret = AVERROR(EINVAL);
  107. } else if (d > INT_MAX || d < INT_MIN) {
  108. *n = d > INT_MAX ? INT_MAX : INT_MIN;
  109. ret = AVERROR(EINVAL);
  110. } else
  111. *n = lrint(d);
  112. return ret;
  113. }
  114. static int config_input(AVFilterLink *link)
  115. {
  116. AVFilterContext *ctx = link->dst;
  117. CropContext *s = ctx->priv;
  118. const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(link->format);
  119. int ret;
  120. const char *expr;
  121. double res;
  122. s->var_values[VAR_IN_W] = s->var_values[VAR_IW] = ctx->inputs[0]->w;
  123. s->var_values[VAR_IN_H] = s->var_values[VAR_IH] = ctx->inputs[0]->h;
  124. s->var_values[VAR_A] = (float) link->w / link->h;
  125. s->var_values[VAR_SAR] = link->sample_aspect_ratio.num ? av_q2d(link->sample_aspect_ratio) : 1;
  126. s->var_values[VAR_DAR] = s->var_values[VAR_A] * s->var_values[VAR_SAR];
  127. s->var_values[VAR_HSUB] = 1<<pix_desc->log2_chroma_w;
  128. s->var_values[VAR_VSUB] = 1<<pix_desc->log2_chroma_h;
  129. s->var_values[VAR_X] = NAN;
  130. s->var_values[VAR_Y] = NAN;
  131. s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = NAN;
  132. s->var_values[VAR_OUT_H] = s->var_values[VAR_OH] = NAN;
  133. s->var_values[VAR_N] = 0;
  134. s->var_values[VAR_T] = NAN;
  135. s->var_values[VAR_POS] = NAN;
  136. av_image_fill_max_pixsteps(s->max_step, NULL, pix_desc);
  137. if (pix_desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
  138. s->hsub = 1;
  139. s->vsub = 1;
  140. } else {
  141. s->hsub = pix_desc->log2_chroma_w;
  142. s->vsub = pix_desc->log2_chroma_h;
  143. }
  144. av_expr_parse_and_eval(&res, (expr = s->w_expr),
  145. var_names, s->var_values,
  146. NULL, NULL, NULL, NULL, NULL, 0, ctx);
  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(ctx, 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. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
  212. if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
  213. // Hardware frames adjust the cropping regions rather than
  214. // changing the frame size.
  215. } else {
  216. link->w = s->w;
  217. link->h = s->h;
  218. }
  219. link->sample_aspect_ratio = s->out_sar;
  220. return 0;
  221. }
  222. static int filter_frame(AVFilterLink *link, AVFrame *frame)
  223. {
  224. AVFilterContext *ctx = link->dst;
  225. CropContext *s = ctx->priv;
  226. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
  227. int i;
  228. s->var_values[VAR_N] = link->frame_count_out;
  229. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  230. NAN : frame->pts * av_q2d(link->time_base);
  231. s->var_values[VAR_POS] = frame->pkt_pos == -1 ?
  232. NAN : frame->pkt_pos;
  233. s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, NULL);
  234. s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, NULL);
  235. /* It is necessary if x is expressed from y */
  236. s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, NULL);
  237. normalize_double(&s->x, s->var_values[VAR_X]);
  238. normalize_double(&s->y, s->var_values[VAR_Y]);
  239. if (s->x < 0)
  240. s->x = 0;
  241. if (s->y < 0)
  242. s->y = 0;
  243. if ((unsigned)s->x + (unsigned)s->w > link->w)
  244. s->x = link->w - s->w;
  245. if ((unsigned)s->y + (unsigned)s->h > link->h)
  246. s->y = link->h - s->h;
  247. if (!s->exact) {
  248. s->x &= ~((1 << s->hsub) - 1);
  249. s->y &= ~((1 << s->vsub) - 1);
  250. }
  251. av_log(ctx, AV_LOG_TRACE, "n:%d t:%f pos:%f x:%d y:%d x+w:%d y+h:%d\n",
  252. (int)s->var_values[VAR_N], s->var_values[VAR_T], s->var_values[VAR_POS],
  253. s->x, s->y, s->x+s->w, s->y+s->h);
  254. if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
  255. frame->crop_top += s->y;
  256. frame->crop_left += s->x;
  257. frame->crop_bottom = frame->height - frame->crop_top - frame->crop_bottom - s->h;
  258. frame->crop_right = frame->width - frame->crop_left - frame->crop_right - s->w;
  259. } else {
  260. frame->width = s->w;
  261. frame->height = s->h;
  262. frame->data[0] += s->y * frame->linesize[0];
  263. frame->data[0] += s->x * s->max_step[0];
  264. if (!(desc->flags & AV_PIX_FMT_FLAG_PAL || desc->flags & FF_PSEUDOPAL)) {
  265. for (i = 1; i < 3; i ++) {
  266. if (frame->data[i]) {
  267. frame->data[i] += (s->y >> s->vsub) * frame->linesize[i];
  268. frame->data[i] += (s->x * s->max_step[i]) >> s->hsub;
  269. }
  270. }
  271. }
  272. /* alpha plane */
  273. if (frame->data[3]) {
  274. frame->data[3] += s->y * frame->linesize[3];
  275. frame->data[3] += s->x * s->max_step[3];
  276. }
  277. }
  278. return ff_filter_frame(link->dst->outputs[0], frame);
  279. }
  280. static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
  281. char *res, int res_len, int flags)
  282. {
  283. CropContext *s = ctx->priv;
  284. int ret;
  285. if ( !strcmp(cmd, "out_w") || !strcmp(cmd, "w")
  286. || !strcmp(cmd, "out_h") || !strcmp(cmd, "h")
  287. || !strcmp(cmd, "x") || !strcmp(cmd, "y")) {
  288. int old_x = s->x;
  289. int old_y = s->y;
  290. int old_w = s->w;
  291. int old_h = s->h;
  292. AVFilterLink *outlink = ctx->outputs[0];
  293. AVFilterLink *inlink = ctx->inputs[0];
  294. av_opt_set(s, cmd, args, 0);
  295. if ((ret = config_input(inlink)) < 0) {
  296. s->x = old_x;
  297. s->y = old_y;
  298. s->w = old_w;
  299. s->h = old_h;
  300. return ret;
  301. }
  302. ret = config_output(outlink);
  303. } else
  304. ret = AVERROR(ENOSYS);
  305. return ret;
  306. }
  307. #define OFFSET(x) offsetof(CropContext, x)
  308. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  309. #define TFLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_RUNTIME_PARAM
  310. static const AVOption crop_options[] = {
  311. { "out_w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, 0, 0, TFLAGS },
  312. { "w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, 0, 0, TFLAGS },
  313. { "out_h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, 0, 0, TFLAGS },
  314. { "h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, 0, 0, TFLAGS },
  315. { "x", "set the x crop area expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "(in_w-out_w)/2"}, 0, 0, TFLAGS },
  316. { "y", "set the y crop area expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "(in_h-out_h)/2"}, 0, 0, TFLAGS },
  317. { "keep_aspect", "keep aspect ratio", OFFSET(keep_aspect), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
  318. { "exact", "do exact cropping", OFFSET(exact), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
  319. { NULL }
  320. };
  321. AVFILTER_DEFINE_CLASS(crop);
  322. static const AVFilterPad avfilter_vf_crop_inputs[] = {
  323. {
  324. .name = "default",
  325. .type = AVMEDIA_TYPE_VIDEO,
  326. .filter_frame = filter_frame,
  327. .config_props = config_input,
  328. },
  329. { NULL }
  330. };
  331. static const AVFilterPad avfilter_vf_crop_outputs[] = {
  332. {
  333. .name = "default",
  334. .type = AVMEDIA_TYPE_VIDEO,
  335. .config_props = config_output,
  336. },
  337. { NULL }
  338. };
  339. AVFilter ff_vf_crop = {
  340. .name = "crop",
  341. .description = NULL_IF_CONFIG_SMALL("Crop the input video."),
  342. .priv_size = sizeof(CropContext),
  343. .priv_class = &crop_class,
  344. .query_formats = query_formats,
  345. .uninit = uninit,
  346. .inputs = avfilter_vf_crop_inputs,
  347. .outputs = avfilter_vf_crop_outputs,
  348. .process_command = process_command,
  349. };