FFmpeg
vf_thumbnail.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2011 Smartjog S.A.S, Clément Bœsch <clement.boesch@smartjog.com>
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  * Potential thumbnail lookup filter to reduce the risk of an inappropriate
24  * selection (such as a black frame) we could get with an absolute seek.
25  *
26  * Simplified version of algorithm by Vadim Zaliva <lord@crocodile.org>.
27  * @see http://notbrainsurgery.livejournal.com/29773.html
28  */
29 
30 #include "libavutil/opt.h"
31 #include "avfilter.h"
32 #include "internal.h"
33 
34 #define HIST_SIZE (3*256)
35 
36 struct thumb_frame {
37  AVFrame *buf; ///< cached frame
38  int histogram[HIST_SIZE]; ///< RGB color distribution histogram of the frame
39 };
40 
41 typedef struct ThumbContext {
42  const AVClass *class;
43  int n; ///< current frame
44  int n_frames; ///< number of frames for analysis
45  struct thumb_frame *frames; ///< the n_frames frames
46  AVRational tb; ///< copy of the input timebase to ease access
47 } ThumbContext;
48 
49 #define OFFSET(x) offsetof(ThumbContext, x)
50 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
51 
52 static const AVOption thumbnail_options[] = {
53  { "n", "set the frames batch size", OFFSET(n_frames), AV_OPT_TYPE_INT, {.i64=100}, 2, INT_MAX, FLAGS },
54  { NULL }
55 };
56 
58 
60 {
61  ThumbContext *s = ctx->priv;
62 
63  s->frames = av_calloc(s->n_frames, sizeof(*s->frames));
64  if (!s->frames) {
66  "Allocation failure, try to lower the number of frames\n");
67  return AVERROR(ENOMEM);
68  }
69  av_log(ctx, AV_LOG_VERBOSE, "batch size: %d frames\n", s->n_frames);
70  return 0;
71 }
72 
73 /**
74  * @brief Compute Sum-square deviation to estimate "closeness".
75  * @param hist color distribution histogram
76  * @param median average color distribution histogram
77  * @return sum of squared errors
78  */
79 static double frame_sum_square_err(const int *hist, const double *median)
80 {
81  int i;
82  double err, sum_sq_err = 0;
83 
84  for (i = 0; i < HIST_SIZE; i++) {
85  err = median[i] - (double)hist[i];
86  sum_sq_err += err*err;
87  }
88  return sum_sq_err;
89 }
90 
92 {
93  AVFrame *picref;
94  ThumbContext *s = ctx->priv;
95  int i, j, best_frame_idx = 0;
96  int nb_frames = s->n;
97  double avg_hist[HIST_SIZE] = {0}, sq_err, min_sq_err = -1;
98 
99  // average histogram of the N frames
100  for (j = 0; j < FF_ARRAY_ELEMS(avg_hist); j++) {
101  for (i = 0; i < nb_frames; i++)
102  avg_hist[j] += (double)s->frames[i].histogram[j];
103  avg_hist[j] /= nb_frames;
104  }
105 
106  // find the frame closer to the average using the sum of squared errors
107  for (i = 0; i < nb_frames; i++) {
108  sq_err = frame_sum_square_err(s->frames[i].histogram, avg_hist);
109  if (i == 0 || sq_err < min_sq_err)
110  best_frame_idx = i, min_sq_err = sq_err;
111  }
112 
113  // free and reset everything (except the best frame buffer)
114  for (i = 0; i < nb_frames; i++) {
115  memset(s->frames[i].histogram, 0, sizeof(s->frames[i].histogram));
116  if (i != best_frame_idx)
117  av_frame_free(&s->frames[i].buf);
118  }
119  s->n = 0;
120 
121  // raise the chosen one
122  picref = s->frames[best_frame_idx].buf;
123  av_log(ctx, AV_LOG_INFO, "frame id #%d (pts_time=%f) selected "
124  "from a set of %d images\n", best_frame_idx,
125  picref->pts * av_q2d(s->tb), nb_frames);
126  s->frames[best_frame_idx].buf = NULL;
127 
128  return picref;
129 }
130 
132 {
133  int i, j;
134  AVFilterContext *ctx = inlink->dst;
135  ThumbContext *s = ctx->priv;
136  AVFilterLink *outlink = ctx->outputs[0];
137  int *hist = s->frames[s->n].histogram;
138  const uint8_t *p = frame->data[0];
139 
140  // keep a reference of each frame
141  s->frames[s->n].buf = frame;
142 
143  // update current frame RGB histogram
144  for (j = 0; j < inlink->h; j++) {
145  for (i = 0; i < inlink->w; i++) {
146  hist[0*256 + p[i*3 ]]++;
147  hist[1*256 + p[i*3 + 1]]++;
148  hist[2*256 + p[i*3 + 2]]++;
149  }
150  p += frame->linesize[0];
151  }
152 
153  // no selection until the buffer of N frames is filled up
154  s->n++;
155  if (s->n < s->n_frames)
156  return 0;
157 
158  return ff_filter_frame(outlink, get_best_frame(ctx));
159 }
160 
162 {
163  int i;
164  ThumbContext *s = ctx->priv;
165  for (i = 0; i < s->n_frames && s->frames[i].buf; i++)
166  av_frame_free(&s->frames[i].buf);
167  av_freep(&s->frames);
168 }
169 
171 {
172  AVFilterContext *ctx = link->src;
173  ThumbContext *s = ctx->priv;
174  int ret = ff_request_frame(ctx->inputs[0]);
175 
176  if (ret == AVERROR_EOF && s->n) {
178  if (ret < 0)
179  return ret;
180  ret = AVERROR_EOF;
181  }
182  if (ret < 0)
183  return ret;
184  return 0;
185 }
186 
188 {
189  AVFilterContext *ctx = inlink->dst;
190  ThumbContext *s = ctx->priv;
191 
192  s->tb = inlink->time_base;
193  return 0;
194 }
195 
197 {
198  static const enum AVPixelFormat pix_fmts[] = {
201  };
203  if (!fmts_list)
204  return AVERROR(ENOMEM);
205  return ff_set_common_formats(ctx, fmts_list);
206 }
207 
208 static const AVFilterPad thumbnail_inputs[] = {
209  {
210  .name = "default",
211  .type = AVMEDIA_TYPE_VIDEO,
212  .config_props = config_props,
213  .filter_frame = filter_frame,
214  },
215  { NULL }
216 };
217 
218 static const AVFilterPad thumbnail_outputs[] = {
219  {
220  .name = "default",
221  .type = AVMEDIA_TYPE_VIDEO,
222  .request_frame = request_frame,
223  },
224  { NULL }
225 };
226 
228  .name = "thumbnail",
229  .description = NULL_IF_CONFIG_SMALL("Select the most representative frame in a given sequence of consecutive frames."),
230  .priv_size = sizeof(ThumbContext),
231  .init = init,
232  .uninit = uninit,
236  .priv_class = &thumbnail_class,
237 };
ThumbContext
Definition: vf_thumbnail.c:41
AVPixelFormat
AVPixelFormat
Pixel format.
Definition: pixfmt.h:64
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
AVFILTER_DEFINE_CLASS
AVFILTER_DEFINE_CLASS(thumbnail)
ff_make_format_list
AVFilterFormats * ff_make_format_list(const int *fmts)
Create a list of supported formats.
Definition: formats.c:283
ff_filter_frame
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:1080
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:55
thumb_frame::histogram
int histogram[HIST_SIZE]
RGB color distribution histogram of the frame.
Definition: vf_thumbnail.c:38
thumb_frame::buf
AVFrame * buf
cached frame
Definition: vf_thumbnail.c:37
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:202
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:295
AVFrame::pts
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:388
AVOption
AVOption.
Definition: opt.h:246
ff_request_frame
int ff_request_frame(AVFilterLink *link)
Request an input frame from the filter at the other end of the link.
Definition: avfilter.c:407
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
AV_PIX_FMT_BGR24
@ AV_PIX_FMT_BGR24
packed RGB 8:8:8, 24bpp, BGRBGR...
Definition: pixfmt.h:69
AVFilter::name
const char * name
Filter name.
Definition: avfilter.h:148
OFFSET
#define OFFSET(x)
Definition: vf_thumbnail.c:49
AVFilterFormats
A list of supported formats for one end of a filter link.
Definition: formats.h:64
thumb_frame
Definition: vf_thumbnail.c:36
ThumbContext::frames
struct thumb_frame * frames
the n_frames frames
Definition: vf_thumbnail.c:45
AVFilterPad
A filter pad used for either input or output.
Definition: internal.h:54
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
av_cold
#define av_cold
Definition: attributes.h:84
ff_set_common_formats
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
query_formats
static int query_formats(AVFilterContext *ctx)
Definition: vf_thumbnail.c:196
s
#define s(width, name)
Definition: cbs_vp9.c:257
av_q2d
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition: rational.h:104
ThumbContext::tb
AVRational tb
copy of the input timebase to ease access
Definition: vf_thumbnail.c:46
outputs
static const AVFilterPad outputs[]
Definition: af_acontrast.c:203
pix_fmts
static enum AVPixelFormat pix_fmts[]
Definition: libkvazaar.c:275
ctx
AVFormatContext * ctx
Definition: movenc.c:48
ThumbContext::n_frames
int n_frames
number of frames for analysis
Definition: vf_thumbnail.c:44
get_best_frame
static AVFrame * get_best_frame(AVFilterContext *ctx)
Definition: vf_thumbnail.c:91
link
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 link
Definition: filter_design.txt:23
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:67
NULL
#define NULL
Definition: coverity.c:32
AVRational
Rational number (pair of numerator and denominator).
Definition: rational.h:58
FLAGS
#define FLAGS
Definition: vf_thumbnail.c:50
config_props
static int config_props(AVFilterLink *inlink)
Definition: vf_thumbnail.c:187
inputs
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 inputs
Definition: filter_design.txt:243
AV_PIX_FMT_RGB24
@ AV_PIX_FMT_RGB24
packed RGB 8:8:8, 24bpp, RGBRGB...
Definition: pixfmt.h:68
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:188
request_frame
static int request_frame(AVFilterLink *link)
Definition: vf_thumbnail.c:170
thumbnail_outputs
static const AVFilterPad thumbnail_outputs[]
Definition: vf_thumbnail.c:218
uninit
static av_cold void uninit(AVFilterContext *ctx)
Definition: vf_thumbnail.c:161
ThumbContext::n
int n
current frame
Definition: vf_thumbnail.c:43
AV_LOG_INFO
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
internal.h
thumbnail
static int thumbnail(AVFilterContext *ctx, int *histogram, AVFrame *in)
Definition: vf_thumbnail_cuda.c:197
filter_frame
static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
Definition: vf_thumbnail.c:131
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:259
ff_vf_thumbnail
AVFilter ff_vf_thumbnail
Definition: vf_thumbnail.c:227
frame_sum_square_err
static double frame_sum_square_err(const int *hist, const double *median)
Compute Sum-square deviation to estimate "closeness".
Definition: vf_thumbnail.c:79
uint8_t
uint8_t
Definition: audio_convert.c:194
AVFilterPad::name
const char * name
Pad name.
Definition: internal.h:60
AVFilter
Filter definition.
Definition: avfilter.h:144
ret
ret
Definition: filter_design.txt:187
HIST_SIZE
#define HIST_SIZE
Definition: vf_thumbnail.c:34
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:264
FF_ARRAY_ELEMS
#define FF_ARRAY_ELEMS(a)
Definition: sinewin_tablegen_template.c:38
av_calloc
void * av_calloc(size_t nmemb, size_t size)
Non-inlined equivalent of av_mallocz_array().
Definition: mem.c:244
AV_PIX_FMT_NONE
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:65
AV_OPT_TYPE_INT
@ AV_OPT_TYPE_INT
Definition: opt.h:223
thumbnail_inputs
static const AVFilterPad thumbnail_inputs[]
Definition: vf_thumbnail.c:208
avfilter.h
AVFilterContext
An instance of a filter.
Definition: avfilter.h:338
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:35
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:28
init
static av_cold int init(AVFilterContext *ctx)
Definition: vf_thumbnail.c:59
thumbnail_options
static const AVOption thumbnail_options[]
Definition: vf_thumbnail.c:52