2 * Copyright (c) 2011 Smartjog S.A.S, Clément Bœsch <clement.boesch@smartjog.com>
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
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.
26 * Simplified version of algorithm by Vadim Zaliva <lord@crocodile.org>.
27 * @see http://notbrainsurgery.livejournal.com/29773.html
33 #define HIST_SIZE (3*256)
36 AVFilterBufferRef *buf; ///< cached frame
37 int histogram[HIST_SIZE]; ///< RGB color distribution histogram of the frame
41 int n; ///< current frame
42 int n_frames; ///< number of frames for analysis
43 struct thumb_frame *frames; ///< the n_frames frames
46 static av_cold int init(AVFilterContext *ctx, const char *args)
48 ThumbContext *thumb = ctx->priv;
51 thumb->n_frames = 100;
53 int n = sscanf(args, "%d", &thumb->n_frames);
54 if (n != 1 || thumb->n_frames < 2) {
56 av_log(ctx, AV_LOG_ERROR,
57 "Invalid number of frames specified (minimum is 2).\n");
58 return AVERROR(EINVAL);
61 thumb->frames = av_calloc(thumb->n_frames, sizeof(*thumb->frames));
63 av_log(ctx, AV_LOG_ERROR,
64 "Allocation failure, try to lower the number of frames\n");
65 return AVERROR(ENOMEM);
67 av_log(ctx, AV_LOG_VERBOSE, "batch size: %d frames\n", thumb->n_frames);
71 static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
74 AVFilterContext *ctx = inlink->dst;
75 ThumbContext *thumb = ctx->priv;
76 int *hist = thumb->frames[thumb->n].histogram;
77 AVFilterBufferRef *picref = inlink->cur_buf;
78 const uint8_t *p = picref->data[0] + y * picref->linesize[0];
80 // update current frame RGB histogram
81 for (j = 0; j < h; j++) {
82 for (i = 0; i < inlink->w; i++) {
83 hist[0*256 + p[i*3 ]]++;
84 hist[1*256 + p[i*3 + 1]]++;
85 hist[2*256 + p[i*3 + 2]]++;
87 p += picref->linesize[0];
93 * @brief Compute Sum-square deviation to estimate "closeness".
94 * @param hist color distribution histogram
95 * @param median average color distribution histogram
96 * @return sum of squared errors
98 static double frame_sum_square_err(const int *hist, const double *median)
101 double err, sum_sq_err = 0;
103 for (i = 0; i < HIST_SIZE; i++) {
104 err = median[i] - (double)hist[i];
105 sum_sq_err += err*err;
110 static int end_frame(AVFilterLink *inlink)
112 int i, j, best_frame_idx = 0;
113 double avg_hist[HIST_SIZE] = {0}, sq_err, min_sq_err = -1;
114 AVFilterLink *outlink = inlink->dst->outputs[0];
115 ThumbContext *thumb = inlink->dst->priv;
116 AVFilterContext *ctx = inlink->dst;
117 AVFilterBufferRef *picref;
119 // keep a reference of each frame
120 thumb->frames[thumb->n].buf = inlink->cur_buf;
121 inlink->cur_buf = NULL;
123 // no selection until the buffer of N frames is filled up
124 if (thumb->n < thumb->n_frames - 1) {
129 // average histogram of the N frames
130 for (j = 0; j < FF_ARRAY_ELEMS(avg_hist); j++) {
131 for (i = 0; i < thumb->n_frames; i++)
132 avg_hist[j] += (double)thumb->frames[i].histogram[j];
133 avg_hist[j] /= thumb->n_frames;
136 // find the frame closer to the average using the sum of squared errors
137 for (i = 0; i < thumb->n_frames; i++) {
138 sq_err = frame_sum_square_err(thumb->frames[i].histogram, avg_hist);
139 if (i == 0 || sq_err < min_sq_err)
140 best_frame_idx = i, min_sq_err = sq_err;
143 // free and reset everything (except the best frame buffer)
144 for (i = 0; i < thumb->n_frames; i++) {
145 memset(thumb->frames[i].histogram, 0, sizeof(thumb->frames[i].histogram));
146 if (i == best_frame_idx)
148 avfilter_unref_buffer(thumb->frames[i].buf);
149 thumb->frames[i].buf = NULL;
153 // raise the chosen one
154 picref = thumb->frames[best_frame_idx].buf;
155 av_log(ctx, AV_LOG_INFO, "frame id #%d (pts_time=%f) selected\n",
156 best_frame_idx, picref->pts * av_q2d(inlink->time_base));
157 ff_start_frame(outlink, picref);
158 thumb->frames[best_frame_idx].buf = NULL;
159 ff_draw_slice(outlink, 0, inlink->h, 1);
160 return ff_end_frame(outlink);
163 static av_cold void uninit(AVFilterContext *ctx)
166 ThumbContext *thumb = ctx->priv;
167 for (i = 0; i < thumb->n_frames && thumb->frames[i].buf; i++) {
168 avfilter_unref_buffer(thumb->frames[i].buf);
169 thumb->frames[i].buf = NULL;
171 av_freep(&thumb->frames);
174 static int null_start_frame(AVFilterLink *link, AVFilterBufferRef *picref) { return 0; }
176 static int request_frame(AVFilterLink *link)
178 ThumbContext *thumb = link->src->priv;
180 /* loop until a frame thumbnail is available (when a frame is queued,
181 * thumb->n is reset to zero) */
183 int ret = ff_request_frame(link->src->inputs[0]);
190 static int poll_frame(AVFilterLink *link)
192 ThumbContext *thumb = link->src->priv;
193 AVFilterLink *inlink = link->src->inputs[0];
194 int ret, available_frames = ff_poll_frame(inlink);
196 /* If the input link is not able to provide any frame, we can't do anything
197 * at the moment and thus have zero thumbnail available. */
198 if (!available_frames)
201 /* Since at least one frame is available and the next frame will allow us
202 * to compute a thumbnail, we can return 1 frame. */
203 if (thumb->n == thumb->n_frames - 1)
206 /* we have some frame(s) available in the input link, but not yet enough to
207 * output a thumbnail, so we request more */
208 ret = ff_request_frame(inlink);
209 return ret < 0 ? ret : 0;
212 static int query_formats(AVFilterContext *ctx)
214 static const enum PixelFormat pix_fmts[] = {
215 PIX_FMT_RGB24, PIX_FMT_BGR24,
218 ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
222 AVFilter avfilter_vf_thumbnail = {
224 .description = NULL_IF_CONFIG_SMALL("Select the most representative frame in a given sequence of consecutive frames."),
225 .priv_size = sizeof(ThumbContext),
228 .query_formats = query_formats,
229 .inputs = (const AVFilterPad[]) {
231 .type = AVMEDIA_TYPE_VIDEO,
232 .get_video_buffer = ff_null_get_video_buffer,
233 .min_perms = AV_PERM_PRESERVE,
234 .start_frame = null_start_frame,
235 .draw_slice = draw_slice,
236 .end_frame = end_frame,
239 .outputs = (const AVFilterPad[]) {
241 .type = AVMEDIA_TYPE_VIDEO,
242 .request_frame = request_frame,
243 .poll_frame = poll_frame,