FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavfilter/vf_crop.c
Date: 2025-04-25 22:50:00
Exec Total Coverage
Lines: 113 161 70.2%
Functions: 6 7 85.7%
Branches: 35 76 46.1%

Line Branch Exec Source
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 "filters.h"
30 #include "formats.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 "t", ///< timestamp expressed in seconds
54 NULL
55 };
56
57 enum var_name {
58 VAR_IN_W, VAR_IW,
59 VAR_IN_H, VAR_IH,
60 VAR_OUT_W, VAR_OW,
61 VAR_OUT_H, VAR_OH,
62 VAR_A,
63 VAR_SAR,
64 VAR_DAR,
65 VAR_HSUB,
66 VAR_VSUB,
67 VAR_X,
68 VAR_Y,
69 VAR_N,
70 VAR_T,
71 VAR_VARS_NB
72 };
73
74 typedef struct CropContext {
75 const AVClass *class;
76 int x; ///< x offset of the non-cropped area with respect to the input area
77 int y; ///< y offset of the non-cropped area with respect to the input area
78 int w; ///< width of the cropped area
79 int h; ///< height of the cropped area
80
81 AVRational out_sar; ///< output sample aspect ratio
82 int keep_aspect; ///< keep display aspect ratio when cropping
83 int exact; ///< exact cropping, for subsampled formats
84
85 int max_step[4]; ///< max pixel step for each plane, expressed as a number of bytes
86 int hsub, vsub; ///< chroma subsampling
87 char *x_expr, *y_expr, *w_expr, *h_expr;
88 AVExpr *x_pexpr, *y_pexpr; /* parsed expressions for x and y */
89 double var_values[VAR_VARS_NB];
90 } CropContext;
91
92 203 static int query_formats(const AVFilterContext *ctx,
93 AVFilterFormatsConfig **cfg_in,
94 AVFilterFormatsConfig **cfg_out)
95 {
96 203 int reject_flags = AV_PIX_FMT_FLAG_BITSTREAM | FF_PIX_FMT_FLAG_SW_FLAT_SUB;
97
98 203 return ff_set_common_formats2(ctx, cfg_in, cfg_out,
99 ff_formats_pixdesc_filter(0, reject_flags));
100 }
101
102 401 static av_cold void uninit(AVFilterContext *ctx)
103 {
104 401 CropContext *s = ctx->priv;
105
106 401 av_expr_free(s->x_pexpr);
107 401 s->x_pexpr = NULL;
108 401 av_expr_free(s->y_pexpr);
109 401 s->y_pexpr = NULL;
110 401 }
111
112 3254 static inline int normalize_double(int *n, double d)
113 {
114 3254 int ret = 0;
115
116
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 3254 times.
3254 if (isnan(d)) {
117 ret = AVERROR(EINVAL);
118
2/4
✓ Branch 0 taken 3254 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 3254 times.
3254 } else if (d > INT_MAX || d < INT_MIN) {
119 *n = d > INT_MAX ? INT_MAX : INT_MIN;
120 ret = AVERROR(EINVAL);
121 } else
122 3254 *n = lrint(d);
123
124 3254 return ret;
125 }
126
127 202 static int config_input(AVFilterLink *link)
128 {
129 202 AVFilterContext *ctx = link->dst;
130 202 CropContext *s = ctx->priv;
131 202 const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(link->format);
132 int ret;
133 const char *expr;
134 double res;
135
136 202 s->var_values[VAR_IN_W] = s->var_values[VAR_IW] = ctx->inputs[0]->w;
137 202 s->var_values[VAR_IN_H] = s->var_values[VAR_IH] = ctx->inputs[0]->h;
138 202 s->var_values[VAR_A] = (float) link->w / link->h;
139
2/2
✓ Branch 0 taken 4 times.
✓ Branch 1 taken 198 times.
202 s->var_values[VAR_SAR] = link->sample_aspect_ratio.num ? av_q2d(link->sample_aspect_ratio) : 1;
140 202 s->var_values[VAR_DAR] = s->var_values[VAR_A] * s->var_values[VAR_SAR];
141 202 s->var_values[VAR_HSUB] = 1<<pix_desc->log2_chroma_w;
142 202 s->var_values[VAR_VSUB] = 1<<pix_desc->log2_chroma_h;
143 202 s->var_values[VAR_X] = NAN;
144 202 s->var_values[VAR_Y] = NAN;
145 202 s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = NAN;
146 202 s->var_values[VAR_OUT_H] = s->var_values[VAR_OH] = NAN;
147 202 s->var_values[VAR_N] = 0;
148 202 s->var_values[VAR_T] = NAN;
149
150 202 av_image_fill_max_pixsteps(s->max_step, NULL, pix_desc);
151
152
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 202 times.
202 if (pix_desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
153 s->hsub = 1;
154 s->vsub = 1;
155 } else {
156 202 s->hsub = pix_desc->log2_chroma_w;
157 202 s->vsub = pix_desc->log2_chroma_h;
158 }
159
160 202 av_expr_parse_and_eval(&res, (expr = s->w_expr),
161 202 var_names, s->var_values,
162 NULL, NULL, NULL, NULL, NULL, 0, ctx);
163 202 s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = res;
164
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 202 times.
202 if ((ret = av_expr_parse_and_eval(&res, (expr = s->h_expr),
165 202 var_names, s->var_values,
166 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
167 goto fail_expr;
168 202 s->var_values[VAR_OUT_H] = s->var_values[VAR_OH] = res;
169 /* evaluate again ow as it may depend on oh */
170
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 202 times.
202 if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
171 202 var_names, s->var_values,
172 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
173 goto fail_expr;
174
175 202 s->var_values[VAR_OUT_W] = s->var_values[VAR_OW] = res;
176
2/4
✓ Branch 1 taken 202 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✓ Branch 4 taken 202 times.
404 if (normalize_double(&s->w, s->var_values[VAR_OUT_W]) < 0 ||
177 202 normalize_double(&s->h, s->var_values[VAR_OUT_H]) < 0) {
178 av_log(ctx, AV_LOG_ERROR,
179 "Too big value or invalid expression for out_w/ow or out_h/oh. "
180 "Maybe the expression for out_w:'%s' or for out_h:'%s' is self-referencing.\n",
181 s->w_expr, s->h_expr);
182 return AVERROR(EINVAL);
183 }
184
185
1/2
✓ Branch 0 taken 202 times.
✗ Branch 1 not taken.
202 if (!s->exact) {
186 202 s->w &= ~((1 << s->hsub) - 1);
187 202 s->h &= ~((1 << s->vsub) - 1);
188 }
189
190 202 av_expr_free(s->x_pexpr);
191 202 av_expr_free(s->y_pexpr);
192 202 s->x_pexpr = s->y_pexpr = NULL;
193
1/2
✓ Branch 1 taken 202 times.
✗ Branch 2 not taken.
202 if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
194
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 202 times.
202 NULL, NULL, NULL, NULL, 0, ctx)) < 0 ||
195 202 (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
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 202 times.
202 if (s->keep_aspect) {
200 AVRational dar = av_mul_q(link->sample_aspect_ratio,
201 (AVRational){ link->w, link->h });
202 av_reduce(&s->out_sar.num, &s->out_sar.den,
203 (int64_t)dar.num * s->h, (int64_t)dar.den * s->w, INT_MAX);
204 } else
205 202 s->out_sar = link->sample_aspect_ratio;
206
207 202 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
2/4
✓ Branch 0 taken 202 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 202 times.
✗ Branch 3 not taken.
202 if (s->w <= 0 || s->h <= 0 ||
212
2/4
✓ Branch 0 taken 202 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 202 times.
202 s->w > link->w || s->h > link->h) {
213 av_log(ctx, AV_LOG_ERROR,
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 202 s->x = (link->w - s->w) / 2;
221 202 s->y = (link->h - s->h) / 2;
222
1/2
✓ Branch 0 taken 202 times.
✗ Branch 1 not taken.
202 if (!s->exact) {
223 202 s->x &= ~((1 << s->hsub) - 1);
224 202 s->y &= ~((1 << s->vsub) - 1);
225 }
226 202 return 0;
227
228 fail_expr:
229 av_log(ctx, AV_LOG_ERROR, "Error when evaluating the expression '%s'\n", expr);
230 return ret;
231 }
232
233 202 static int config_output(AVFilterLink *link)
234 {
235 202 CropContext *s = link->src->priv;
236 202 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
237
238
1/2
✓ Branch 0 taken 202 times.
✗ Branch 1 not taken.
202 if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
239 // Hardware frames adjust the cropping regions rather than
240 // changing the frame size.
241 } else {
242 202 link->w = s->w;
243 202 link->h = s->h;
244 }
245 202 link->sample_aspect_ratio = s->out_sar;
246
247 202 return 0;
248 }
249
250 1425 static int filter_frame(AVFilterLink *link, AVFrame *frame)
251 {
252 1425 FilterLink *l = ff_filter_link(link);
253 1425 AVFilterContext *ctx = link->dst;
254 1425 CropContext *s = ctx->priv;
255 1425 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
256 int i;
257
258 1425 s->var_values[VAR_N] = l->frame_count_out;
259 2850 s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
260
1/2
✓ Branch 0 taken 1425 times.
✗ Branch 1 not taken.
1425 NAN : frame->pts * av_q2d(link->time_base);
261 1425 s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, NULL);
262 1425 s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, NULL);
263 /* It is necessary if x is expressed from y */
264 1425 s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, NULL);
265
266 1425 normalize_double(&s->x, s->var_values[VAR_X]);
267 1425 normalize_double(&s->y, s->var_values[VAR_Y]);
268
269
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1425 times.
1425 if (s->x < 0)
270 s->x = 0;
271
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1425 times.
1425 if (s->y < 0)
272 s->y = 0;
273
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1425 times.
1425 if ((unsigned)s->x + (unsigned)s->w > link->w)
274 s->x = link->w - s->w;
275
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1425 times.
1425 if ((unsigned)s->y + (unsigned)s->h > link->h)
276 s->y = link->h - s->h;
277
1/2
✓ Branch 0 taken 1425 times.
✗ Branch 1 not taken.
1425 if (!s->exact) {
278 1425 s->x &= ~((1 << s->hsub) - 1);
279 1425 s->y &= ~((1 << s->vsub) - 1);
280 }
281
282 1425 av_log(ctx, AV_LOG_TRACE, "n:%d t:%f x:%d y:%d x+w:%d y+h:%d\n",
283 1425 (int)s->var_values[VAR_N], s->var_values[VAR_T],
284 1425 s->x, s->y, s->x+s->w, s->y+s->h);
285
286
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1425 times.
1425 if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
287 frame->crop_top += s->y;
288 frame->crop_left += s->x;
289 frame->crop_bottom = frame->height - frame->crop_top - frame->crop_bottom - s->h;
290 frame->crop_right = frame->width - frame->crop_left - frame->crop_right - s->w;
291 } else {
292 1425 frame->width = s->w;
293 1425 frame->height = s->h;
294
295 1425 frame->data[0] += s->y * frame->linesize[0];
296 1425 frame->data[0] += s->x * s->max_step[0];
297
298
2/2
✓ Branch 0 taken 1424 times.
✓ Branch 1 taken 1 times.
1425 if (!(desc->flags & AV_PIX_FMT_FLAG_PAL)) {
299
2/2
✓ Branch 0 taken 2848 times.
✓ Branch 1 taken 1424 times.
4272 for (i = 1; i < 3; i ++) {
300
2/2
✓ Branch 0 taken 2689 times.
✓ Branch 1 taken 159 times.
2848 if (frame->data[i]) {
301 2689 frame->data[i] += (s->y >> s->vsub) * frame->linesize[i];
302 2689 frame->data[i] += (s->x * s->max_step[i]) >> s->hsub;
303 }
304 }
305 }
306
307 /* alpha plane */
308
2/2
✓ Branch 0 taken 37 times.
✓ Branch 1 taken 1388 times.
1425 if (frame->data[3]) {
309 37 frame->data[3] += s->y * frame->linesize[3];
310 37 frame->data[3] += s->x * s->max_step[3];
311 }
312 }
313
314 1425 return ff_filter_frame(link->dst->outputs[0], frame);
315 }
316
317 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
318 char *res, int res_len, int flags)
319 {
320 CropContext *s = ctx->priv;
321 int ret;
322
323 if ( !strcmp(cmd, "out_w") || !strcmp(cmd, "w")
324 || !strcmp(cmd, "out_h") || !strcmp(cmd, "h")
325 || !strcmp(cmd, "x") || !strcmp(cmd, "y")) {
326
327 int old_x = s->x;
328 int old_y = s->y;
329 int old_w = s->w;
330 int old_h = s->h;
331
332 AVFilterLink *outlink = ctx->outputs[0];
333 AVFilterLink *inlink = ctx->inputs[0];
334
335 av_opt_set(s, cmd, args, 0);
336
337 if ((ret = config_input(inlink)) < 0) {
338 s->x = old_x;
339 s->y = old_y;
340 s->w = old_w;
341 s->h = old_h;
342 return ret;
343 }
344
345 ret = config_output(outlink);
346
347 } else
348 ret = AVERROR(ENOSYS);
349
350 return ret;
351 }
352
353 #define OFFSET(x) offsetof(CropContext, x)
354 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
355 #define TFLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_RUNTIME_PARAM
356
357 static const AVOption crop_options[] = {
358 { "out_w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, 0, 0, TFLAGS },
359 { "w", "set the width crop area expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, 0, 0, TFLAGS },
360 { "out_h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, 0, 0, TFLAGS },
361 { "h", "set the height crop area expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, 0, 0, TFLAGS },
362 { "x", "set the x crop area expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "(in_w-out_w)/2"}, 0, 0, TFLAGS },
363 { "y", "set the y crop area expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "(in_h-out_h)/2"}, 0, 0, TFLAGS },
364 { "keep_aspect", "keep aspect ratio", OFFSET(keep_aspect), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
365 { "exact", "do exact cropping", OFFSET(exact), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
366 { NULL }
367 };
368
369 AVFILTER_DEFINE_CLASS(crop);
370
371 static const AVFilterPad avfilter_vf_crop_inputs[] = {
372 {
373 .name = "default",
374 .type = AVMEDIA_TYPE_VIDEO,
375 .filter_frame = filter_frame,
376 .config_props = config_input,
377 },
378 };
379
380 static const AVFilterPad avfilter_vf_crop_outputs[] = {
381 {
382 .name = "default",
383 .type = AVMEDIA_TYPE_VIDEO,
384 .config_props = config_output,
385 },
386 };
387
388 const FFFilter ff_vf_crop = {
389 .p.name = "crop",
390 .p.description = NULL_IF_CONFIG_SMALL("Crop the input video."),
391 .p.priv_class = &crop_class,
392 .priv_size = sizeof(CropContext),
393 .uninit = uninit,
394 FILTER_INPUTS(avfilter_vf_crop_inputs),
395 FILTER_OUTPUTS(avfilter_vf_crop_outputs),
396 FILTER_QUERY_FUNC2(query_formats),
397 .process_command = process_command,
398 };
399