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. av_expr_parse_and_eval(&res, (expr = s->w_expr),
  157. var_names, s->var_values,
  158. NULL, NULL, NULL, NULL, NULL, 0, ctx);
  159. s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = res;
  160. if ((ret = av_expr_parse_and_eval(&res, (expr = s->h_expr),
  161. var_names, s->var_values,
  162. NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  163. goto fail_expr;
  164. s->var_values[VAR_OUT_H] = s->var_values[VAR_OH] = res;
  165. /* evaluate again ow as it may depend on oh */
  166. if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
  167. var_names, s->var_values,
  168. NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  169. goto fail_expr;
  170. s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = res;
  171. if (normalize_double(&s->w, s->var_values[VAR_OUT_W]) < 0 ||
  172. normalize_double(&s->h, s->var_values[VAR_OUT_H]) < 0) {
  173. av_log(ctx, AV_LOG_ERROR,
  174. "Too big value or invalid expression for out_w/ow or out_h/oh. "
  175. "Maybe the expression for out_w:'%s' or for out_h:'%s' is self-referencing.\n",
  176. s->w_expr, s->h_expr);
  177. return AVERROR(EINVAL);
  178. }
  179. if (!s->exact) {
  180. s->w &= ~((1 << s->hsub) - 1);
  181. s->h &= ~((1 << s->vsub) - 1);
  182. }
  183. av_expr_free(s->x_pexpr);
  184. av_expr_free(s->y_pexpr);
  185. s->x_pexpr = s->y_pexpr = NULL;
  186. if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
  187. NULL, NULL, NULL, NULL, 0, ctx)) < 0 ||
  188. (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
  189. NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  190. return AVERROR(EINVAL);
  191. if (s->keep_aspect) {
  192. AVRational dar = av_mul_q(link->sample_aspect_ratio,
  193. (AVRational){ link->w, link->h });
  194. av_reduce(&s->out_sar.num, &s->out_sar.den,
  195. dar.num * s->h, dar.den * s->w, INT_MAX);
  196. } else
  197. s->out_sar = link->sample_aspect_ratio;
  198. av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d sar:%d/%d -> w:%d h:%d sar:%d/%d\n",
  199. link->w, link->h, link->sample_aspect_ratio.num, link->sample_aspect_ratio.den,
  200. s->w, s->h, s->out_sar.num, s->out_sar.den);
  201. if (s->w <= 0 || s->h <= 0 ||
  202. s->w > link->w || s->h > link->h) {
  203. av_log(ctx, AV_LOG_ERROR,
  204. "Invalid too big or non positive size for width '%d' or height '%d'\n",
  205. s->w, s->h);
  206. return AVERROR(EINVAL);
  207. }
  208. /* set default, required in the case the first computed value for x/y is NAN */
  209. s->x = (link->w - s->w) / 2;
  210. s->y = (link->h - s->h) / 2;
  211. if (!s->exact) {
  212. s->x &= ~((1 << s->hsub) - 1);
  213. s->y &= ~((1 << s->vsub) - 1);
  214. }
  215. return 0;
  216. fail_expr:
  217. av_log(ctx, AV_LOG_ERROR, "Error when evaluating the expression '%s'\n", expr);
  218. return ret;
  219. }
  220. static int config_output(AVFilterLink *link)
  221. {
  222. CropContext *s = link->src->priv;
  223. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
  224. if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
  225. // Hardware frames adjust the cropping regions rather than
  226. // changing the frame size.
  227. } else {
  228. link->w = s->w;
  229. link->h = s->h;
  230. }
  231. link->sample_aspect_ratio = s->out_sar;
  232. return 0;
  233. }
  234. static int filter_frame(AVFilterLink *link, AVFrame *frame)
  235. {
  236. AVFilterContext *ctx = link->dst;
  237. CropContext *s = ctx->priv;
  238. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
  239. int i;
  240. s->var_values[VAR_N] = link->frame_count_out;
  241. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  242. NAN : frame->pts * av_q2d(link->time_base);
  243. s->var_values[VAR_POS] = frame->pkt_pos == -1 ?
  244. NAN : frame->pkt_pos;
  245. s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, NULL);
  246. s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, NULL);
  247. /* It is necessary if x is expressed from y */
  248. s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, NULL);
  249. normalize_double(&s->x, s->var_values[VAR_X]);
  250. normalize_double(&s->y, s->var_values[VAR_Y]);
  251. if (s->x < 0)
  252. s->x = 0;
  253. if (s->y < 0)
  254. s->y = 0;
  255. if ((unsigned)s->x + (unsigned)s->w > link->w)
  256. s->x = link->w - s->w;
  257. if ((unsigned)s->y + (unsigned)s->h > link->h)
  258. s->y = link->h - s->h;
  259. if (!s->exact) {
  260. s->x &= ~((1 << s->hsub) - 1);
  261. s->y &= ~((1 << s->vsub) - 1);
  262. }
  263. av_log(ctx, AV_LOG_TRACE, "n:%d t:%f pos:%f x:%d y:%d x+w:%d y+h:%d\n",
  264. (int)s->var_values[VAR_N], s->var_values[VAR_T], s->var_values[VAR_POS],
  265. s->x, s->y, s->x+s->w, s->y+s->h);
  266. if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
  267. frame->crop_top += s->y;
  268. frame->crop_left += s->x;
  269. frame->crop_bottom = frame->height - frame->crop_top - frame->crop_bottom - s->h;
  270. frame->crop_right = frame->width - frame->crop_left - frame->crop_right - s->w;
  271. } else {
  272. frame->width = s->w;
  273. frame->height = s->h;
  274. frame->data[0] += s->y * frame->linesize[0];
  275. frame->data[0] += s->x * s->max_step[0];
  276. if (!(desc->flags & AV_PIX_FMT_FLAG_PAL || desc->flags & FF_PSEUDOPAL)) {
  277. for (i = 1; i < 3; i ++) {
  278. if (frame->data[i]) {
  279. frame->data[i] += (s->y >> s->vsub) * frame->linesize[i];
  280. frame->data[i] += (s->x * s->max_step[i]) >> s->hsub;
  281. }
  282. }
  283. }
  284. /* alpha plane */
  285. if (frame->data[3]) {
  286. frame->data[3] += s->y * frame->linesize[3];
  287. frame->data[3] += s->x * s->max_step[3];
  288. }
  289. }
  290. return ff_filter_frame(link->dst->outputs[0], frame);
  291. }
  292. static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
  293. char *res, int res_len, int flags)
  294. {
  295. CropContext *s = ctx->priv;
  296. int ret;
  297. if ( !strcmp(cmd, "out_w") || !strcmp(cmd, "w")
  298. || !strcmp(cmd, "out_h") || !strcmp(cmd, "h")
  299. || !strcmp(cmd, "x") || !strcmp(cmd, "y")) {
  300. int old_x = s->x;
  301. int old_y = s->y;
  302. int old_w = s->w;
  303. int old_h = s->h;
  304. AVFilterLink *outlink = ctx->outputs[0];
  305. AVFilterLink *inlink = ctx->inputs[0];
  306. av_opt_set(s, cmd, args, 0);
  307. if ((ret = config_input(inlink)) < 0) {
  308. s->x = old_x;
  309. s->y = old_y;
  310. s->w = old_w;
  311. s->h = old_h;
  312. return ret;
  313. }
  314. ret = config_output(outlink);
  315. } else
  316. ret = AVERROR(ENOSYS);
  317. return ret;
  318. }
  319. #define OFFSET(x) offsetof(CropContext, x)
  320. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  321. #define TFLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_RUNTIME_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, TFLAGS },
  324. { "w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, TFLAGS },
  325. { "out_h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, TFLAGS },
  326. { "h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, TFLAGS },
  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, TFLAGS },
  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, TFLAGS },
  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. };