2 * Copyright (c) 2007 Bobby Bingham
4 * This file is part of FFmpeg.
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.
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.
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
32 #include "libavutil/eval.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/internal.h"
35 #include "libavutil/libm.h"
36 #include "libavutil/imgutils.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/opt.h"
40 static const char *const var_names[] = {
41 "in_w", "iw", ///< width of the input video
42 "in_h", "ih", ///< height of the input video
43 "out_w", "ow", ///< width of the cropped video
44 "out_h", "oh", ///< height of the cropped video
52 "n", ///< number of frame
53 "pos", ///< position in the file
54 "t", ///< timestamp expressed in seconds
76 typedef struct CropContext {
78 int x; ///< x offset of the non-cropped area with respect to the input area
79 int y; ///< y offset of the non-cropped area with respect to the input area
80 int w; ///< width of the cropped area
81 int h; ///< height of the cropped area
83 AVRational out_sar; ///< output sample aspect ratio
84 int keep_aspect; ///< keep display aspect ratio when cropping
85 int exact; ///< exact cropping, for subsampled formats
87 int max_step[4]; ///< max pixel step for each plane, expressed as a number of bytes
88 int hsub, vsub; ///< chroma subsampling
89 char *x_expr, *y_expr, *w_expr, *h_expr;
90 AVExpr *x_pexpr, *y_pexpr; /* parsed expressions for x and y */
91 double var_values[VAR_VARS_NB];
94 static int query_formats(AVFilterContext *ctx)
96 AVFilterFormats *formats = NULL;
99 for (fmt = 0; av_pix_fmt_desc_get(fmt); fmt++) {
100 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt);
101 if (desc->flags & AV_PIX_FMT_FLAG_BITSTREAM)
103 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) {
104 // Not usable if there is any subsampling but the format is
105 // not planar (e.g. YUYV422).
106 if ((desc->log2_chroma_w || desc->log2_chroma_h) &&
107 !(desc->flags & AV_PIX_FMT_FLAG_PLANAR))
110 ret = ff_add_format(&formats, fmt);
115 return ff_set_common_formats(ctx, formats);
118 static av_cold void uninit(AVFilterContext *ctx)
120 CropContext *s = ctx->priv;
122 av_expr_free(s->x_pexpr);
124 av_expr_free(s->y_pexpr);
128 static inline int normalize_double(int *n, double d)
133 ret = AVERROR(EINVAL);
134 } else if (d > INT_MAX || d < INT_MIN) {
135 *n = d > INT_MAX ? INT_MAX : INT_MIN;
136 ret = AVERROR(EINVAL);
143 static int config_input(AVFilterLink *link)
145 AVFilterContext *ctx = link->dst;
146 CropContext *s = ctx->priv;
147 const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(link->format);
152 s->var_values[VAR_IN_W] = s->var_values[VAR_IW] = ctx->inputs[0]->w;
153 s->var_values[VAR_IN_H] = s->var_values[VAR_IH] = ctx->inputs[0]->h;
154 s->var_values[VAR_A] = (float) link->w / link->h;
155 s->var_values[VAR_SAR] = link->sample_aspect_ratio.num ? av_q2d(link->sample_aspect_ratio) : 1;
156 s->var_values[VAR_DAR] = s->var_values[VAR_A] * s->var_values[VAR_SAR];
157 s->var_values[VAR_HSUB] = 1<<pix_desc->log2_chroma_w;
158 s->var_values[VAR_VSUB] = 1<<pix_desc->log2_chroma_h;
159 s->var_values[VAR_X] = NAN;
160 s->var_values[VAR_Y] = NAN;
161 s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = NAN;
162 s->var_values[VAR_OUT_H] = s->var_values[VAR_OH] = NAN;
163 s->var_values[VAR_N] = 0;
164 s->var_values[VAR_T] = NAN;
165 s->var_values[VAR_POS] = NAN;
167 av_image_fill_max_pixsteps(s->max_step, NULL, pix_desc);
169 if (pix_desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
173 s->hsub = pix_desc->log2_chroma_w;
174 s->vsub = pix_desc->log2_chroma_h;
177 av_expr_parse_and_eval(&res, (expr = s->w_expr),
178 var_names, s->var_values,
179 NULL, NULL, NULL, NULL, NULL, 0, ctx);
180 s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = res;
181 if ((ret = av_expr_parse_and_eval(&res, (expr = s->h_expr),
182 var_names, s->var_values,
183 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
185 s->var_values[VAR_OUT_H] = s->var_values[VAR_OH] = res;
186 /* evaluate again ow as it may depend on oh */
187 if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
188 var_names, s->var_values,
189 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
192 s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = res;
193 if (normalize_double(&s->w, s->var_values[VAR_OUT_W]) < 0 ||
194 normalize_double(&s->h, s->var_values[VAR_OUT_H]) < 0) {
195 av_log(ctx, AV_LOG_ERROR,
196 "Too big value or invalid expression for out_w/ow or out_h/oh. "
197 "Maybe the expression for out_w:'%s' or for out_h:'%s' is self-referencing.\n",
198 s->w_expr, s->h_expr);
199 return AVERROR(EINVAL);
203 s->w &= ~((1 << s->hsub) - 1);
204 s->h &= ~((1 << s->vsub) - 1);
207 av_expr_free(s->x_pexpr);
208 av_expr_free(s->y_pexpr);
209 s->x_pexpr = s->y_pexpr = NULL;
210 if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
211 NULL, NULL, NULL, NULL, 0, ctx)) < 0 ||
212 (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
213 NULL, NULL, NULL, NULL, 0, ctx)) < 0)
214 return AVERROR(EINVAL);
216 if (s->keep_aspect) {
217 AVRational dar = av_mul_q(link->sample_aspect_ratio,
218 (AVRational){ link->w, link->h });
219 av_reduce(&s->out_sar.num, &s->out_sar.den,
220 dar.num * s->h, dar.den * s->w, INT_MAX);
222 s->out_sar = link->sample_aspect_ratio;
224 av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d sar:%d/%d -> w:%d h:%d sar:%d/%d\n",
225 link->w, link->h, link->sample_aspect_ratio.num, link->sample_aspect_ratio.den,
226 s->w, s->h, s->out_sar.num, s->out_sar.den);
228 if (s->w <= 0 || s->h <= 0 ||
229 s->w > link->w || s->h > link->h) {
230 av_log(ctx, AV_LOG_ERROR,
231 "Invalid too big or non positive size for width '%d' or height '%d'\n",
233 return AVERROR(EINVAL);
236 /* set default, required in the case the first computed value for x/y is NAN */
237 s->x = (link->w - s->w) / 2;
238 s->y = (link->h - s->h) / 2;
240 s->x &= ~((1 << s->hsub) - 1);
241 s->y &= ~((1 << s->vsub) - 1);
246 av_log(ctx, AV_LOG_ERROR, "Error when evaluating the expression '%s'\n", expr);
250 static int config_output(AVFilterLink *link)
252 CropContext *s = link->src->priv;
253 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
255 if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
256 // Hardware frames adjust the cropping regions rather than
257 // changing the frame size.
262 link->sample_aspect_ratio = s->out_sar;
267 static int filter_frame(AVFilterLink *link, AVFrame *frame)
269 AVFilterContext *ctx = link->dst;
270 CropContext *s = ctx->priv;
271 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
274 s->var_values[VAR_N] = link->frame_count_out;
275 s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
276 NAN : frame->pts * av_q2d(link->time_base);
277 s->var_values[VAR_POS] = frame->pkt_pos == -1 ?
278 NAN : frame->pkt_pos;
279 s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, NULL);
280 s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, NULL);
281 /* It is necessary if x is expressed from y */
282 s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, NULL);
284 normalize_double(&s->x, s->var_values[VAR_X]);
285 normalize_double(&s->y, s->var_values[VAR_Y]);
291 if ((unsigned)s->x + (unsigned)s->w > link->w)
292 s->x = link->w - s->w;
293 if ((unsigned)s->y + (unsigned)s->h > link->h)
294 s->y = link->h - s->h;
296 s->x &= ~((1 << s->hsub) - 1);
297 s->y &= ~((1 << s->vsub) - 1);
300 av_log(ctx, AV_LOG_TRACE, "n:%d t:%f pos:%f x:%d y:%d x+w:%d y+h:%d\n",
301 (int)s->var_values[VAR_N], s->var_values[VAR_T], s->var_values[VAR_POS],
302 s->x, s->y, s->x+s->w, s->y+s->h);
304 if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
305 frame->crop_top += s->y;
306 frame->crop_left += s->x;
307 frame->crop_bottom = frame->height - frame->crop_top - frame->crop_bottom - s->h;
308 frame->crop_right = frame->width - frame->crop_left - frame->crop_right - s->w;
311 frame->height = s->h;
313 frame->data[0] += s->y * frame->linesize[0];
314 frame->data[0] += s->x * s->max_step[0];
316 if (!(desc->flags & AV_PIX_FMT_FLAG_PAL || desc->flags & FF_PSEUDOPAL)) {
317 for (i = 1; i < 3; i ++) {
318 if (frame->data[i]) {
319 frame->data[i] += (s->y >> s->vsub) * frame->linesize[i];
320 frame->data[i] += (s->x * s->max_step[i]) >> s->hsub;
326 if (frame->data[3]) {
327 frame->data[3] += s->y * frame->linesize[3];
328 frame->data[3] += s->x * s->max_step[3];
332 return ff_filter_frame(link->dst->outputs[0], frame);
335 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
336 char *res, int res_len, int flags)
338 CropContext *s = ctx->priv;
341 if ( !strcmp(cmd, "out_w") || !strcmp(cmd, "w")
342 || !strcmp(cmd, "out_h") || !strcmp(cmd, "h")
343 || !strcmp(cmd, "x") || !strcmp(cmd, "y")) {
350 AVFilterLink *outlink = ctx->outputs[0];
351 AVFilterLink *inlink = ctx->inputs[0];
353 av_opt_set(s, cmd, args, 0);
355 if ((ret = config_input(inlink)) < 0) {
363 ret = config_output(outlink);
366 ret = AVERROR(ENOSYS);
371 #define OFFSET(x) offsetof(CropContext, x)
372 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
373 #define TFLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_RUNTIME_PARAM
375 static const AVOption crop_options[] = {
376 { "out_w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, 0, 0, TFLAGS },
377 { "w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, 0, 0, TFLAGS },
378 { "out_h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, 0, 0, TFLAGS },
379 { "h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, 0, 0, TFLAGS },
380 { "x", "set the x crop area expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "(in_w-out_w)/2"}, 0, 0, TFLAGS },
381 { "y", "set the y crop area expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "(in_h-out_h)/2"}, 0, 0, TFLAGS },
382 { "keep_aspect", "keep aspect ratio", OFFSET(keep_aspect), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
383 { "exact", "do exact cropping", OFFSET(exact), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
387 AVFILTER_DEFINE_CLASS(crop);
389 static const AVFilterPad avfilter_vf_crop_inputs[] = {
392 .type = AVMEDIA_TYPE_VIDEO,
393 .filter_frame = filter_frame,
394 .config_props = config_input,
399 static const AVFilterPad avfilter_vf_crop_outputs[] = {
402 .type = AVMEDIA_TYPE_VIDEO,
403 .config_props = config_output,
408 AVFilter ff_vf_crop = {
410 .description = NULL_IF_CONFIG_SMALL("Crop the input video."),
411 .priv_size = sizeof(CropContext),
412 .priv_class = &crop_class,
413 .query_formats = query_formats,
415 .inputs = avfilter_vf_crop_inputs,
416 .outputs = avfilter_vf_crop_outputs,
417 .process_command = process_command,