FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
vf_crop.c
Go to the documentation of this file.
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 /**
22  * @file
23  * video crop filter
24  */
25 
26 #include <stdio.h>
27 
28 #include "avfilter.h"
29 #include "formats.h"
30 #include "internal.h"
31 #include "video.h"
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"
39 
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
45  "a",
46  "sar",
47  "dar",
48  "hsub",
49  "vsub",
50  "x",
51  "y",
52  "n", ///< number of frame
53  "pos", ///< position in the file
54  "t", ///< timestamp expressed in seconds
55  NULL
56 };
57 
58 enum var_name {
74 };
75 
76 typedef struct CropContext {
77  const AVClass *class;
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
82 
83  AVRational out_sar; ///< output sample aspect ratio
84  int keep_aspect; ///< keep display aspect ratio when cropping
85 
86  int max_step[4]; ///< max pixel step for each plane, expressed as a number of bytes
87  int hsub, vsub; ///< chroma subsampling
88  char *x_expr, *y_expr, *w_expr, *h_expr;
89  AVExpr *x_pexpr, *y_pexpr; /* parsed expressions for x and y */
91 } CropContext;
92 
94 {
96  int fmt, ret;
97 
98  for (fmt = 0; av_pix_fmt_desc_get(fmt); fmt++) {
101  !((desc->log2_chroma_w || desc->log2_chroma_h) && !(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) &&
102  (ret = ff_add_format(&formats, fmt)) < 0)
103  return ret;
104  }
105 
106  return ff_set_common_formats(ctx, formats);
107 }
108 
110 {
111  CropContext *s = ctx->priv;
112 
113  av_expr_free(s->x_pexpr);
114  s->x_pexpr = NULL;
115  av_expr_free(s->y_pexpr);
116  s->y_pexpr = NULL;
117 }
118 
119 static inline int normalize_double(int *n, double d)
120 {
121  int ret = 0;
122 
123  if (isnan(d)) {
124  ret = AVERROR(EINVAL);
125  } else if (d > INT_MAX || d < INT_MIN) {
126  *n = d > INT_MAX ? INT_MAX : INT_MIN;
127  ret = AVERROR(EINVAL);
128  } else
129  *n = lrint(d);
130 
131  return ret;
132 }
133 
134 static int config_input(AVFilterLink *link)
135 {
136  AVFilterContext *ctx = link->dst;
137  CropContext *s = ctx->priv;
138  const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(link->format);
139  int ret;
140  const char *expr;
141  double res;
142 
143  s->var_values[VAR_IN_W] = s->var_values[VAR_IW] = ctx->inputs[0]->w;
144  s->var_values[VAR_IN_H] = s->var_values[VAR_IH] = ctx->inputs[0]->h;
145  s->var_values[VAR_A] = (float) link->w / link->h;
148  s->var_values[VAR_HSUB] = 1<<pix_desc->log2_chroma_w;
149  s->var_values[VAR_VSUB] = 1<<pix_desc->log2_chroma_h;
150  s->var_values[VAR_X] = NAN;
151  s->var_values[VAR_Y] = NAN;
154  s->var_values[VAR_N] = 0;
155  s->var_values[VAR_T] = NAN;
156  s->var_values[VAR_POS] = NAN;
157 
159  s->hsub = pix_desc->log2_chroma_w;
160  s->vsub = pix_desc->log2_chroma_h;
161 
162  if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
163  var_names, s->var_values,
164  NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
165  goto fail_expr;
166  s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = res;
167  if ((ret = av_expr_parse_and_eval(&res, (expr = s->h_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_H] = s->var_values[VAR_OH] = res;
172  /* evaluate again ow as it may depend on oh */
173  if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
174  var_names, s->var_values,
175  NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
176  goto fail_expr;
177 
178  s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = res;
179  if (normalize_double(&s->w, s->var_values[VAR_OUT_W]) < 0 ||
180  normalize_double(&s->h, s->var_values[VAR_OUT_H]) < 0) {
181  av_log(ctx, AV_LOG_ERROR,
182  "Too big value or invalid expression for out_w/ow or out_h/oh. "
183  "Maybe the expression for out_w:'%s' or for out_h:'%s' is self-referencing.\n",
184  s->w_expr, s->h_expr);
185  return AVERROR(EINVAL);
186  }
187  s->w &= ~((1 << s->hsub) - 1);
188  s->h &= ~((1 << s->vsub) - 1);
189 
190  av_expr_free(s->x_pexpr);
191  av_expr_free(s->y_pexpr);
192  s->x_pexpr = s->y_pexpr = NULL;
193  if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
194  NULL, NULL, NULL, NULL, 0, ctx)) < 0 ||
195  (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
196  NULL, NULL, NULL, NULL, 0, ctx)) < 0)
197  return AVERROR(EINVAL);
198 
199  if (s->keep_aspect) {
201  (AVRational){ link->w, link->h });
202  av_reduce(&s->out_sar.num, &s->out_sar.den,
203  dar.num * s->h, dar.den * s->w, INT_MAX);
204  } else
205  s->out_sar = link->sample_aspect_ratio;
206 
207  av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d sar:%d/%d -> w:%d h:%d sar:%d/%d\n",
208  link->w, link->h, link->sample_aspect_ratio.num, link->sample_aspect_ratio.den,
209  s->w, s->h, s->out_sar.num, s->out_sar.den);
210 
211  if (s->w <= 0 || s->h <= 0 ||
212  s->w > link->w || s->h > link->h) {
214  "Invalid too big or non positive size for width '%d' or height '%d'\n",
215  s->w, s->h);
216  return AVERROR(EINVAL);
217  }
218 
219  /* set default, required in the case the first computed value for x/y is NAN */
220  s->x = (link->w - s->w) / 2;
221  s->y = (link->h - s->h) / 2;
222  s->x &= ~((1 << s->hsub) - 1);
223  s->y &= ~((1 << s->vsub) - 1);
224  return 0;
225 
226 fail_expr:
227  av_log(NULL, AV_LOG_ERROR, "Error when evaluating the expression '%s'\n", expr);
228  return ret;
229 }
230 
231 static int config_output(AVFilterLink *link)
232 {
233  CropContext *s = link->src->priv;
234 
235  link->w = s->w;
236  link->h = s->h;
237  link->sample_aspect_ratio = s->out_sar;
238 
239  return 0;
240 }
241 
243 {
244  AVFilterContext *ctx = link->dst;
245  CropContext *s = ctx->priv;
247  int i;
248 
249  frame->width = s->w;
250  frame->height = s->h;
251 
252  s->var_values[VAR_N] = link->frame_count;
253  s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
254  NAN : frame->pts * av_q2d(link->time_base);
255  s->var_values[VAR_POS] = av_frame_get_pkt_pos(frame) == -1 ?
256  NAN : av_frame_get_pkt_pos(frame);
260 
263 
264  if (s->x < 0)
265  s->x = 0;
266  if (s->y < 0)
267  s->y = 0;
268  if ((unsigned)s->x + (unsigned)s->w > link->w)
269  s->x = link->w - s->w;
270  if ((unsigned)s->y + (unsigned)s->h > link->h)
271  s->y = link->h - s->h;
272  s->x &= ~((1 << s->hsub) - 1);
273  s->y &= ~((1 << s->vsub) - 1);
274 
275  av_log(ctx, AV_LOG_TRACE, "n:%d t:%f pos:%f x:%d y:%d x+w:%d y+h:%d\n",
276  (int)s->var_values[VAR_N], s->var_values[VAR_T], s->var_values[VAR_POS],
277  s->x, s->y, s->x+s->w, s->y+s->h);
278 
279  frame->data[0] += s->y * frame->linesize[0];
280  frame->data[0] += s->x * s->max_step[0];
281 
282  if (!(desc->flags & AV_PIX_FMT_FLAG_PAL || desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)) {
283  for (i = 1; i < 3; i ++) {
284  if (frame->data[i]) {
285  frame->data[i] += (s->y >> s->vsub) * frame->linesize[i];
286  frame->data[i] += (s->x * s->max_step[i]) >> s->hsub;
287  }
288  }
289  }
290 
291  /* alpha plane */
292  if (frame->data[3]) {
293  frame->data[3] += s->y * frame->linesize[3];
294  frame->data[3] += s->x * s->max_step[3];
295  }
296 
297  return ff_filter_frame(link->dst->outputs[0], frame);
298 }
299 
300 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
301  char *res, int res_len, int flags)
302 {
303  CropContext *s = ctx->priv;
304  int ret;
305 
306  if ( !strcmp(cmd, "out_w") || !strcmp(cmd, "w")
307  || !strcmp(cmd, "out_h") || !strcmp(cmd, "h")
308  || !strcmp(cmd, "x") || !strcmp(cmd, "y")) {
309 
310  int old_x = s->x;
311  int old_y = s->y;
312  int old_w = s->w;
313  int old_h = s->h;
314 
315  AVFilterLink *outlink = ctx->outputs[0];
316  AVFilterLink *inlink = ctx->inputs[0];
317 
318  av_opt_set(s, cmd, args, 0);
319 
320  if ((ret = config_input(inlink)) < 0) {
321  s->x = old_x;
322  s->y = old_y;
323  s->w = old_w;
324  s->h = old_h;
325  return ret;
326  }
327 
328  ret = config_output(outlink);
329 
330  } else
331  ret = AVERROR(ENOSYS);
332 
333  return ret;
334 }
335 
336 #define OFFSET(x) offsetof(CropContext, x)
337 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
338 
339 static const AVOption crop_options[] = {
340  { "out_w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, FLAGS },
341  { "w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, FLAGS },
342  { "out_h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, FLAGS },
343  { "h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, FLAGS },
344  { "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 },
345  { "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 },
346  { "keep_aspect", "keep aspect ratio", OFFSET(keep_aspect), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
347  { NULL }
348 };
349 
351 
353  {
354  .name = "default",
355  .type = AVMEDIA_TYPE_VIDEO,
356  .filter_frame = filter_frame,
357  .config_props = config_input,
358  },
359  { NULL }
360 };
361 
363  {
364  .name = "default",
365  .type = AVMEDIA_TYPE_VIDEO,
366  .config_props = config_output,
367  },
368  { NULL }
369 };
370 
372  .name = "crop",
373  .description = NULL_IF_CONFIG_SMALL("Crop the input video."),
374  .priv_size = sizeof(CropContext),
375  .priv_class = &crop_class,
377  .uninit = uninit,
378  .inputs = avfilter_vf_crop_inputs,
379  .outputs = avfilter_vf_crop_outputs,
381 };
#define AV_PIX_FMT_FLAG_PAL
Pixel format has a palette in data[1], values are indexes in this palette.
Definition: pixdesc.h:132
#define NULL
Definition: coverity.c:32
const char * s
Definition: avisynth_c.h:631
AVExpr * x_pexpr
Definition: vf_crop.c:89
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition: pixdesc.c:2222
This structure describes decoded (raw) audio or video data.
Definition: frame.h:184
#define FLAGS
Definition: vf_crop.c:337
AVOption.
Definition: opt.h:245
const char * fmt
Definition: avisynth_c.h:632
static int config_input(AVFilterLink *link)
Definition: vf_crop.c:134
misc image utilities
Main libavfilter public API header.
const char * desc
Definition: nvenc.c:89
int num
numerator
Definition: rational.h:44
static enum AVSampleFormat formats[]
Definition: avresample.c:163
int av_expr_parse(AVExpr **expr, const char *s, const char *const *const_names, const char *const *func1_names, double(*const *funcs1)(void *, double), const char *const *func2_names, double(*const *funcs2)(void *, double, double), int log_offset, void *log_ctx)
Parse an expression.
Definition: eval.c:658
uint8_t log2_chroma_w
Amount to shift the luma width right to find the chroma width.
Definition: pixdesc.h:92
AVFilter ff_vf_crop
Definition: vf_crop.c:371
Definition: vf_crop.c:61
void av_image_fill_max_pixsteps(int max_pixsteps[4], int max_pixstep_comps[4], const AVPixFmtDescriptor *pixdesc)
Compute the max pixel step for each plane of an image with a format described by pixdesc.
Definition: imgutils.c:34
const char * name
Pad name.
Definition: internal.h:59
AVFilterLink ** inputs
array of pointers to input links
Definition: avfilter.h:313
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:1180
#define av_cold
Definition: attributes.h:82
int x
x offset of the non-cropped area with respect to the input area
Definition: vf_crop.c:78
AVOptions.
int y
y offset of the non-cropped area with respect to the input area
Definition: vf_crop.c:79
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:202
int max_step[4]
max pixel step for each plane, expressed as a number of bytes
Definition: vf_crop.c:86
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:268
Definition: eval.c:149
static const AVFilterPad avfilter_vf_crop_outputs[]
Definition: vf_crop.c:362
static AVFrame * frame
static double av_q2d(AVRational a)
Convert rational to double.
Definition: rational.h:80
AVRational av_mul_q(AVRational b, AVRational c)
Multiply two rationals.
Definition: rational.c:80
Definition: vf_crop.c:60
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
char * w_expr
Definition: vf_crop.c:88
static const AVFilterPad avfilter_vf_crop_inputs[]
Definition: vf_crop.c:352
#define av_log(a,...)
A filter pad used for either input or output.
Definition: internal.h:53
int hsub
Definition: vf_crop.c:87
int av_expr_parse_and_eval(double *d, const char *s, const char *const *const_names, const double *const_values, const char *const *func1_names, double(*const *funcs1)(void *, double), const char *const *func2_names, double(*const *funcs2)(void *, double, double), void *opaque, int log_offset, void *log_ctx)
Parse and evaluate an expression.
Definition: eval.c:723
int width
width and height of the video frame
Definition: frame.h:236
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
int ff_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats)
A helper for query_formats() which sets all links to the same list of formats.
Definition: formats.c:568
uint8_t log2_chroma_h
Amount to shift the luma height right to find the chroma height.
Definition: pixdesc.h:101
Definition: vf_crop.c:70
double var_values[VAR_VARS_NB]
Definition: vf_crop.c:90
#define AVERROR(e)
Definition: error.h:43
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:176
void * priv
private data for use by the filter
Definition: avfilter.h:320
#define AV_PIX_FMT_FLAG_HWACCEL
Pixel format is an HW accelerated format.
Definition: pixdesc.h:140
int ff_add_format(AVFilterFormats **avff, int64_t fmt)
Add fmt to the list of media formats contained in *avff.
Definition: formats.c:337
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:35
var_name
Definition: aeval.c:46
common internal API header
uint64_t flags
Combination of AV_PIX_FMT_FLAG_...
Definition: pixdesc.h:106
char * x_expr
Definition: vf_crop.c:88
static int process_command(AVFilterContext *ctx, const char *cmd, const char *args, char *res, int res_len, int flags)
Definition: vf_crop.c:300
#define AV_PIX_FMT_FLAG_PSEUDOPAL
The pixel format is "pseudo-paletted".
Definition: pixdesc.h:158
AVRational out_sar
output sample aspect ratio
Definition: vf_crop.c:83
AVFormatContext * ctx
Definition: movenc.c:48
int n
Definition: avisynth_c.h:547
#define OFFSET(x)
Definition: vf_crop.c:336
AVExpr * y_pexpr
Definition: vf_crop.c:89
static const AVFilterPad outputs[]
Definition: af_afftfilt.c:386
static int query_formats(AVFilterContext *ctx)
Definition: vf_crop.c:93
char * h_expr
Definition: vf_crop.c:88
int h
height of the cropped area
Definition: vf_crop.c:81
int vsub
chroma subsampling
Definition: vf_crop.c:87
static const AVFilterPad inputs[]
Definition: af_afftfilt.c:376
Definition: vf_crop.c:68
void av_expr_free(AVExpr *e)
Free a parsed expression previously created with av_expr_parse().
Definition: eval.c:318
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:215
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Definition: pixdesc.h:81
static av_cold void uninit(AVFilterContext *ctx)
Definition: vf_crop.c:109
Definition: vf_crop.c:59
Replacements for frequently missing libm functions.
Describe the class of an AVClass context structure.
Definition: log.h:67
Filter definition.
Definition: avfilter.h:142
rational number numerator/denominator
Definition: rational.h:43
#define isnan(x)
Definition: libm.h:340
const char * name
Filter name.
Definition: avfilter.h:146
static const AVOption crop_options[]
Definition: vf_crop.c:339
#define AV_PIX_FMT_FLAG_BITSTREAM
All values of a component are bit-wise packed end to end.
Definition: pixdesc.h:136
AVFilterLink ** outputs
array of pointers to output links
Definition: avfilter.h:317
Definition: vf_crop.c:62
static const char *const var_names[]
Definition: vf_crop.c:40
static int flags
Definition: cpu.c:47
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:198
static int normalize_double(int *n, double d)
Definition: vf_crop.c:119
static int config_output(AVFilterLink *link)
Definition: vf_crop.c:231
Definition: vf_crop.c:69
AVFILTER_DEFINE_CLASS(crop)
int den
denominator
Definition: rational.h:45
Definition: vf_crop.c:72
Definition: vf_crop.c:63
#define NAN
Definition: math.h:28
double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
Evaluate a previously parsed expression.
Definition: eval.c:713
int64_t av_frame_get_pkt_pos(const AVFrame *frame)
int keep_aspect
keep display aspect ratio when cropping
Definition: vf_crop.c:84
A list of supported formats for one end of a filter link.
Definition: formats.h:64
#define lrint
Definition: tablegen.h:53
An instance of a filter.
Definition: avfilter.h:305
int height
Definition: frame.h:236
int w
width of the cropped area
Definition: vf_crop.c:80
internal API functions
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:431
#define AV_PIX_FMT_FLAG_PLANAR
At least one pixel component is not in the first data plane.
Definition: pixdesc.h:144
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:240
simple arithmetic expression evaluator
static int filter_frame(AVFilterLink *link, AVFrame *frame)
Definition: vf_crop.c:242
char * y_expr
Definition: vf_crop.c:88