FFmpeg
vf_find_rect.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2014-2015 Michael Niedermayer <michaelni@gmx.at>
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (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
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with FFmpeg; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20 
21 /**
22  * @todo switch to dualinput
23  */
24 
25 #include "libavutil/mem.h"
26 #include "libavutil/opt.h"
27 
28 #include "filters.h"
29 #include "video.h"
30 
31 #include "lavfutils.h"
32 
33 #define MAX_MIPMAPS 5
34 
35 typedef struct FOCContext {
36  AVClass *class;
37  float threshold;
38  int mipmaps;
39  int xmin, ymin, xmax, ymax;
40  char *obj_filename;
41  int last_x, last_y;
45  int discard;
46 } FOCContext;
47 
48 #define OFFSET(x) offsetof(FOCContext, x)
49 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
50 static const AVOption find_rect_options[] = {
51  { "object", "object bitmap filename", OFFSET(obj_filename), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = FLAGS },
52  { "threshold", "set threshold", OFFSET(threshold), AV_OPT_TYPE_FLOAT, {.dbl = 0.5}, 0, 1.0, FLAGS },
53  { "mipmaps", "set mipmaps", OFFSET(mipmaps), AV_OPT_TYPE_INT, {.i64 = 3}, 1, MAX_MIPMAPS, FLAGS },
54  { "xmin", "", OFFSET(xmin), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, FLAGS },
55  { "ymin", "", OFFSET(ymin), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, FLAGS },
56  { "xmax", "", OFFSET(xmax), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, FLAGS },
57  { "ymax", "", OFFSET(ymax), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, FLAGS },
58  { "discard", "", OFFSET(discard), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS },
59  { NULL }
60 };
61 
62 AVFILTER_DEFINE_CLASS(find_rect);
63 
65 {
66  int x, y;
68  uint8_t *src, *dst;
69  if (!frame)
70  return NULL;
71 
72  frame->format = in->format;
73  frame->width = (in->width + 1) / 2;
74  frame->height = (in->height+ 1) / 2;
75 
76  if (av_frame_get_buffer(frame, 0) < 0) {
78  return NULL;
79  }
80  src = in ->data[0];
81  dst = frame->data[0];
82 
83  int w2 = in->width/2;
84  int h2 = in->height/2;
85  for(y = 0; y < h2; y++) {
86  for(x = 0; x < w2; x++) {
87  dst[x] = ( src[2*x+0]
88  + src[2*x+1]
89  + src[2*x+0 + in->linesize[0]]
90  + src[2*x+1 + in->linesize[0]]
91  + 2) >> 2;
92  }
93  src += 2*in->linesize[0];
94  dst += frame->linesize[0];
95  }
96  src = in ->data[0];
97  dst = frame->data[0];
98  for(y = 0; y < frame->height; y++) {
99  int yd = y < h2 ? in->linesize[0] : 0;
100  x = yd ? w2 : 0;
101  for(; x < frame->width; x++) {
102  dst[x] = ( src[2*x+0]
103  + src[FFMIN(2*x+1, w2)]
104  + src[2*x+0 + yd]
105  + src[FFMIN(2*x+1, w2) + yd]
106  + 2) >> 2;
107  }
108  src += 2*in->linesize[0];
109  dst += frame->linesize[0];
110  }
111 
112  return frame;
113 }
114 
115 static float compare(const AVFrame *haystack, const AVFrame *obj, int offx, int offy)
116 {
117  int x,y;
118  int o_sum_v = 0;
119  int h_sum_v = 0;
120  int64_t oo_sum_v = 0;
121  int64_t hh_sum_v = 0;
122  int64_t oh_sum_v = 0;
123  float c;
124  int n = obj->height * obj->width;
125  const uint8_t *odat = obj ->data[0];
126  const uint8_t *hdat = haystack->data[0] + offx + offy * haystack->linesize[0];
127  int64_t o_sigma, h_sigma;
128 
129  for(y = 0; y < obj->height; y++) {
130  for(x = 0; x < obj->width; x++) {
131  int o_v = odat[x];
132  int h_v = hdat[x];
133  o_sum_v += o_v;
134  h_sum_v += h_v;
135  oo_sum_v += o_v * o_v;
136  hh_sum_v += h_v * h_v;
137  oh_sum_v += o_v * h_v;
138  }
139  odat += obj->linesize[0];
140  hdat += haystack->linesize[0];
141  }
142  o_sigma = n*oo_sum_v - o_sum_v*(int64_t)o_sum_v;
143  h_sigma = n*hh_sum_v - h_sum_v*(int64_t)h_sum_v;
144 
145  if (o_sigma == 0 || h_sigma == 0)
146  return 1.0;
147 
148  c = (n*oh_sum_v - o_sum_v*(int64_t)h_sum_v) / (sqrt(o_sigma)*sqrt(h_sigma));
149 
150  return 1 - fabs(c);
151 }
152 
154 {
155  AVFilterContext *ctx = inlink->dst;
156  FOCContext *foc = ctx->priv;
157 
158  if (foc->xmax <= 0)
159  foc->xmax = inlink->w - foc->obj_frame->width;
160  if (foc->ymax <= 0)
161  foc->ymax = inlink->h - foc->obj_frame->height;
162 
163  return 0;
164 }
165 
166 static float search(FOCContext *foc, int pass, int maxpass, int xmin, int xmax, int ymin, int ymax, int *best_x, int *best_y, float best_score)
167 {
168  int x, y;
169 
170  if (pass + 1 <= maxpass) {
171  int sub_x, sub_y;
172  search(foc, pass+1, maxpass, xmin>>1, (xmax+1)>>1, ymin>>1, (ymax+1)>>1, &sub_x, &sub_y, 2.0);
173  xmin = FFMAX(xmin, 2*sub_x - 4);
174  xmax = FFMIN(xmax, 2*sub_x + 4);
175  ymin = FFMAX(ymin, 2*sub_y - 4);
176  ymax = FFMIN(ymax, 2*sub_y + 4);
177  }
178 
179  for (y = ymin; y <= ymax; y++) {
180  for (x = xmin; x <= xmax; x++) {
181  float score = compare(foc->haystack_frame[pass], foc->needle_frame[pass], x, y);
182  if (score < best_score) {
183  best_score = score;
184  *best_x = x;
185  *best_y = y;
186  }
187  }
188  }
189  return best_score;
190 }
191 
193 {
195  AVFilterContext *ctx = inlink->dst;
196  FOCContext *foc = ctx->priv;
197  float best_score;
198  int best_x, best_y;
199  int i;
200  char buf[32];
201 
202  foc->haystack_frame[0] = av_frame_clone(in);
203  for (i=1; i<foc->mipmaps; i++) {
204  foc->haystack_frame[i] = downscale(foc->haystack_frame[i-1]);
205  }
206 
207  best_score = search(foc, 0, 0,
208  FFMAX(foc->xmin, foc->last_x - 8),
209  FFMIN(foc->xmax, foc->last_x + 8),
210  FFMAX(foc->ymin, foc->last_y - 8),
211  FFMIN(foc->ymax, foc->last_y + 8),
212  &best_x, &best_y, 2.0);
213 
214  best_score = search(foc, 0, foc->mipmaps - 1, foc->xmin, foc->xmax, foc->ymin, foc->ymax,
215  &best_x, &best_y, best_score);
216 
217  for (i=0; i<MAX_MIPMAPS; i++) {
219  }
220 
221  if (best_score > foc->threshold) {
222  if (foc->discard) {
223  av_frame_free(&in);
224  return 0;
225  } else {
226  return ff_filter_frame(ctx->outputs[0], in);
227  }
228  }
229 
230  av_log(ctx, AV_LOG_INFO, "Found at n=%"PRId64" pts_time=%f x=%d y=%d with score=%f\n",
231  inl->frame_count_out, TS2D(in->pts) * av_q2d(inlink->time_base),
232  best_x, best_y, best_score);
233  foc->last_x = best_x;
234  foc->last_y = best_y;
235 
236  snprintf(buf, sizeof(buf), "%f", best_score);
237 
238  av_dict_set_int(&in->metadata, "lavfi.rect.w", foc->obj_frame->width, 0);
239  av_dict_set_int(&in->metadata, "lavfi.rect.h", foc->obj_frame->height, 0);
240  av_dict_set_int(&in->metadata, "lavfi.rect.x", best_x, 0);
241  av_dict_set_int(&in->metadata, "lavfi.rect.y", best_y, 0);
242  av_dict_set(&in->metadata, "lavfi.rect.score", buf, 0);
243 
244  return ff_filter_frame(ctx->outputs[0], in);
245 }
246 
248 {
249  FOCContext *foc = ctx->priv;
250  int i;
251 
252  for (i = 0; i < MAX_MIPMAPS; i++) {
253  av_frame_free(&foc->needle_frame[i]);
255  }
256 
257  if (foc->obj_frame)
258  av_freep(&foc->obj_frame->data[0]);
259  av_frame_free(&foc->obj_frame);
260 }
261 
263 {
264  FOCContext *foc = ctx->priv;
265  int ret, i;
266 
267  if (!foc->obj_filename) {
268  av_log(ctx, AV_LOG_ERROR, "object filename not set\n");
269  return AVERROR(EINVAL);
270  }
271 
272  foc->obj_frame = av_frame_alloc();
273  if (!foc->obj_frame)
274  return AVERROR(ENOMEM);
275 
276  if ((ret = ff_load_image(foc->obj_frame->data, foc->obj_frame->linesize,
277  &foc->obj_frame->width, &foc->obj_frame->height,
278  &foc->obj_frame->format, foc->obj_filename, ctx)) < 0)
279  return ret;
280 
281  if (foc->obj_frame->format != AV_PIX_FMT_GRAY8) {
282  av_log(ctx, AV_LOG_ERROR, "object image is not a grayscale image\n");
283  return AVERROR(EINVAL);
284  }
285 
286  foc->needle_frame[0] = av_frame_clone(foc->obj_frame);
287  for (i = 1; i < foc->mipmaps; i++) {
288  foc->needle_frame[i] = downscale(foc->needle_frame[i-1]);
289  if (!foc->needle_frame[i])
290  return AVERROR(ENOMEM);
291  }
292 
293  return 0;
294 }
295 
296 static const AVFilterPad foc_inputs[] = {
297  {
298  .name = "default",
299  .type = AVMEDIA_TYPE_VIDEO,
300  .config_props = config_input,
301  .filter_frame = filter_frame,
302  },
303 };
304 
306  .p.name = "find_rect",
307  .p.description = NULL_IF_CONFIG_SMALL("Find a user specified object."),
308  .p.flags = AVFILTER_FLAG_METADATA_ONLY,
309  .p.priv_class = &find_rect_class,
310  .priv_size = sizeof(FOCContext),
311  .init = init,
312  .uninit = uninit,
316 };
FOCContext::threshold
float threshold
Definition: vf_find_rect.c:37
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
opt.h
FLAGS
#define FLAGS
Definition: vf_find_rect.c:49
av_frame_get_buffer
int av_frame_get_buffer(AVFrame *frame, int align)
Allocate new buffer(s) for audio or video data.
Definition: frame.c:206
ff_filter_frame
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:1067
int64_t
long long int64_t
Definition: coverity.c:34
inlink
The exact code depends on how similar the blocks are and how related they are to the and needs to apply these operations to the correct inlink or outlink if there are several Macros are available to factor that when no extra processing is inlink
Definition: filter_design.txt:212
av_frame_free
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:64
FILTER_INPUTS
#define FILTER_INPUTS(array)
Definition: filters.h:263
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:427
AVFrame::pts
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:529
AVFrame::width
int width
Definition: frame.h:499
downscale
static AVFrame * downscale(AVFrame *in)
Definition: vf_find_rect.c:64
AVOption
AVOption.
Definition: opt.h:429
FOCContext::obj_filename
char * obj_filename
Definition: vf_find_rect.c:40
FFMAX
#define FFMAX(a, b)
Definition: macros.h:47
AVFilter::name
const char * name
Filter name.
Definition: avfilter.h:220
video.h
FOCContext::last_x
int last_x
Definition: vf_find_rect.c:41
AVFrame::data
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:448
FOCContext::xmin
int xmin
Definition: vf_find_rect.c:39
AVFilterPad
A filter pad used for either input or output.
Definition: filters.h:39
av_frame_alloc
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:52
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:210
av_cold
#define av_cold
Definition: attributes.h:106
ff_video_default_filterpad
const AVFilterPad ff_video_default_filterpad[1]
An AVFilterPad array whose only entry has name "default" and is of type AVMEDIA_TYPE_VIDEO.
Definition: video.c:37
FFFilter
Definition: filters.h:266
filter_frame
static int filter_frame(AVFilterLink *inlink, AVFrame *in)
Definition: vf_find_rect.c:192
av_q2d
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition: rational.h:104
FOCContext::discard
int discard
Definition: vf_find_rect.c:45
filters.h
ctx
AVFormatContext * ctx
Definition: movenc.c:49
av_frame_clone
AVFrame * av_frame_clone(const AVFrame *src)
Create a new frame that references the same data as src.
Definition: frame.c:483
AV_PIX_FMT_YUV420P
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition: pixfmt.h:73
FOCContext::ymax
int ymax
Definition: vf_find_rect.c:39
FILTER_OUTPUTS
#define FILTER_OUTPUTS(array)
Definition: filters.h:264
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:76
fabs
static __device__ float fabs(float a)
Definition: cuda_runtime.h:182
NULL
#define NULL
Definition: coverity.c:32
AV_PIX_FMT_YUVJ420P
@ AV_PIX_FMT_YUVJ420P
planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV420P and setting col...
Definition: pixfmt.h:85
AVFILTER_DEFINE_CLASS
AVFILTER_DEFINE_CLASS(find_rect)
AV_PIX_FMT_GRAY8
@ AV_PIX_FMT_GRAY8
Y , 8bpp.
Definition: pixfmt.h:81
c
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
Definition: undefined.txt:32
ff_filter_link
static FilterLink * ff_filter_link(AVFilterLink *link)
Definition: filters.h:198
TS2D
#define TS2D(ts)
Definition: filters.h:481
init
static av_cold int init(AVFilterContext *ctx)
Definition: vf_find_rect.c:262
FOCContext::mipmaps
int mipmaps
Definition: vf_find_rect.c:38
NULL_IF_CONFIG_SMALL
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:94
foc_inputs
static const AVFilterPad foc_inputs[]
Definition: vf_find_rect.c:296
FOCContext
Definition: vf_find_rect.c:35
ff_vf_find_rect
const FFFilter ff_vf_find_rect
Definition: vf_find_rect.c:305
dst
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
Definition: dsp.h:87
ff_load_image
int ff_load_image(uint8_t *data[4], int linesize[4], int *w, int *h, enum AVPixelFormat *pix_fmt, const char *filename, void *log_ctx)
Load image from filename and put the resulting image in data.
Definition: lavfutils.c:34
AVFrame::format
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames,...
Definition: frame.h:514
FOCContext::haystack_frame
AVFrame * haystack_frame[MAX_MIPMAPS]
Definition: vf_find_rect.c:44
OFFSET
#define OFFSET(x)
Definition: vf_find_rect.c:48
AV_LOG_INFO
#define AV_LOG_INFO
Standard information.
Definition: log.h:221
AV_OPT_TYPE_FLOAT
@ AV_OPT_TYPE_FLOAT
Underlying C type is float.
Definition: opt.h:271
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:256
config_input
static int config_input(AVFilterLink *inlink)
Definition: vf_find_rect.c:153
FOCContext::last_y
int last_y
Definition: vf_find_rect.c:41
FFMIN
#define FFMIN(a, b)
Definition: macros.h:49
AVFilterPad::name
const char * name
Pad name.
Definition: filters.h:45
FILTER_PIXFMTS
#define FILTER_PIXFMTS(...)
Definition: filters.h:249
FOCContext::xmax
int xmax
Definition: vf_find_rect.c:39
ret
ret
Definition: filter_design.txt:187
search
static float search(FOCContext *foc, int pass, int maxpass, int xmin, int xmax, int ymin, int ymax, int *best_x, int *best_y, float best_score)
Definition: vf_find_rect.c:166
frame
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return or at least make progress towards producing a frame
Definition: filter_design.txt:265
FOCContext::needle_frame
AVFrame * needle_frame[MAX_MIPMAPS]
Definition: vf_find_rect.c:43
FOCContext::ymin
int ymin
Definition: vf_find_rect.c:39
AVFrame::height
int height
Definition: frame.h:499
compare
static float compare(const AVFrame *haystack, const AVFrame *obj, int offx, int offy)
Definition: vf_find_rect.c:115
AV_OPT_TYPE_INT
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition: opt.h:259
AVFrame::metadata
AVDictionary * metadata
metadata.
Definition: frame.h:705
uninit
static av_cold void uninit(AVFilterContext *ctx)
Definition: vf_find_rect.c:247
AVFILTER_FLAG_METADATA_ONLY
#define AVFILTER_FLAG_METADATA_ONLY
The filter is a "metadata" filter - it does not modify the frame data in any way.
Definition: avfilter.h:183
find_rect_options
static const AVOption find_rect_options[]
Definition: vf_find_rect.c:50
lavfutils.h
MAX_MIPMAPS
#define MAX_MIPMAPS
Definition: vf_find_rect.c:33
AVFilterContext
An instance of a filter.
Definition: avfilter.h:274
av_dict_set_int
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set() that converts the value to a string and stores it.
Definition: dict.c:177
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:200
FFFilter::p
AVFilter p
The public AVFilter.
Definition: filters.h:270
mem.h
AV_OPT_TYPE_BOOL
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition: opt.h:327
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:35
av_dict_set
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:86
FOCContext::obj_frame
AVFrame * obj_frame
Definition: vf_find_rect.c:42
AVFrame::linesize
int linesize[AV_NUM_DATA_POINTERS]
For video, a positive or negative value, which is typically indicating the size in bytes of each pict...
Definition: frame.h:472
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
AV_OPT_TYPE_STRING
@ AV_OPT_TYPE_STRING
Underlying C type is a uint8_t* that is either NULL or points to a C string allocated with the av_mal...
Definition: opt.h:276
snprintf
#define snprintf
Definition: snprintf.h:34
src
#define src
Definition: vp8dsp.c:248