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
32 #define HIST_SIZE (3*256)
35 AVFilterBufferRef *buf; ///< cached frame
36 int histogram[HIST_SIZE]; ///< RGB color distribution histogram of the frame
40 int n; ///< current frame
41 int n_frames; ///< number of frames for analysis
42 struct thumb_frame *frames; ///< the n_frames frames
45 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
47 ThumbContext *thumb = ctx->priv;
50 thumb->n_frames = 100;
52 int n = sscanf(args, "%d", &thumb->n_frames);
53 if (n != 1 || thumb->n_frames < 2) {
55 av_log(ctx, AV_LOG_ERROR,
56 "Invalid number of frames specified (minimum is 2).\n");
57 return AVERROR(EINVAL);
60 thumb->frames = av_calloc(thumb->n_frames, sizeof(*thumb->frames));
62 av_log(ctx, AV_LOG_ERROR,
63 "Allocation failure, try to lower the number of frames\n");
64 return AVERROR(ENOMEM);
66 av_log(ctx, AV_LOG_INFO, "batch size: %d frames\n", thumb->n_frames);
70 static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
73 AVFilterContext *ctx = inlink->dst;
74 ThumbContext *thumb = ctx->priv;
75 int *hist = thumb->frames[thumb->n].histogram;
76 AVFilterBufferRef *picref = inlink->cur_buf;
77 const uint8_t *p = picref->data[0] + y * picref->linesize[0];
79 // update current frame RGB histogram
80 for (j = 0; j < h; j++) {
81 for (i = 0; i < inlink->w; i++) {
82 hist[0*256 + p[i*3 ]]++;
83 hist[1*256 + p[i*3 + 1]]++;
84 hist[2*256 + p[i*3 + 2]]++;
86 p += picref->linesize[0];
91 * @brief Compute Sum-square deviation to estimate "closeness".
92 * @param hist color distribution histogram
93 * @param median average color distribution histogram
94 * @return sum of squared errors
96 static double frame_sum_square_err(const int *hist, const double *median)
99 double err, sum_sq_err = 0;
101 for (i = 0; i < HIST_SIZE; i++) {
102 err = median[i] - (double)hist[i];
103 sum_sq_err += err*err;
108 static void end_frame(AVFilterLink *inlink)
110 int i, j, best_frame_idx = 0;
111 double avg_hist[HIST_SIZE] = {0}, sq_err, min_sq_err = -1;
112 AVFilterLink *outlink = inlink->dst->outputs[0];
113 ThumbContext *thumb = inlink->dst->priv;
114 AVFilterContext *ctx = inlink->dst;
115 AVFilterBufferRef *picref;
117 // keep a reference of each frame
118 thumb->frames[thumb->n].buf = inlink->cur_buf;
120 // no selection until the buffer of N frames is filled up
121 if (thumb->n < thumb->n_frames - 1) {
126 // average histogram of the N frames
127 for (j = 0; j < FF_ARRAY_ELEMS(avg_hist); j++) {
128 for (i = 0; i < thumb->n_frames; i++)
129 avg_hist[j] += (double)thumb->frames[i].histogram[j];
130 avg_hist[j] /= thumb->n_frames;
133 // find the frame closer to the average using the sum of squared errors
134 for (i = 0; i < thumb->n_frames; i++) {
135 sq_err = frame_sum_square_err(thumb->frames[i].histogram, avg_hist);
136 if (i == 0 || sq_err < min_sq_err)
137 best_frame_idx = i, min_sq_err = sq_err;
140 // free and reset everything (except the best frame buffer)
141 for (i = 0; i < thumb->n_frames; i++) {
142 memset(thumb->frames[i].histogram, 0, sizeof(thumb->frames[i].histogram));
143 if (i == best_frame_idx)
145 avfilter_unref_buffer(thumb->frames[i].buf);
146 thumb->frames[i].buf = NULL;
150 // raise the chosen one
151 picref = thumb->frames[best_frame_idx].buf;
152 av_log(ctx, AV_LOG_INFO, "frame id #%d (pts_time=%f) selected\n",
153 best_frame_idx, picref->pts * av_q2d(inlink->time_base));
154 avfilter_start_frame(outlink, picref);
155 thumb->frames[best_frame_idx].buf = NULL;
156 avfilter_draw_slice(outlink, 0, inlink->h, 1);
157 avfilter_end_frame(outlink);
160 static av_cold void uninit(AVFilterContext *ctx)
163 ThumbContext *thumb = ctx->priv;
164 for (i = 0; i < thumb->n_frames && thumb->frames[i].buf; i++) {
165 avfilter_unref_buffer(thumb->frames[i].buf);
166 thumb->frames[i].buf = NULL;
168 av_freep(&thumb->frames);
171 static void null_start_frame(AVFilterLink *link, AVFilterBufferRef *picref) { }
173 static int request_frame(AVFilterLink *link)
175 ThumbContext *thumb = link->src->priv;
177 /* loop until a frame thumbnail is available (when a frame is queued,
178 * thumb->n is reset to zero) */
180 int ret = avfilter_request_frame(link->src->inputs[0]);
187 static int poll_frame(AVFilterLink *link)
189 ThumbContext *thumb = link->src->priv;
190 AVFilterLink *inlink = link->src->inputs[0];
191 int ret, available_frames = avfilter_poll_frame(inlink);
193 /* If the input link is not able to provide any frame, we can't do anything
194 * at the moment and thus have zero thumbnail available. */
195 if (!available_frames)
198 /* Since at least one frame is available and the next frame will allow us
199 * to compute a thumbnail, we can return 1 frame. */
200 if (thumb->n == thumb->n_frames - 1)
203 /* we have some frame(s) available in the input link, but not yet enough to
204 * output a thumbnail, so we request more */
205 ret = avfilter_request_frame(inlink);
206 return ret < 0 ? ret : 0;
209 static int query_formats(AVFilterContext *ctx)
211 static const enum PixelFormat pix_fmts[] = {
212 PIX_FMT_RGB24, PIX_FMT_BGR24,
215 avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
219 AVFilter avfilter_vf_thumbnail = {
221 .description = NULL_IF_CONFIG_SMALL("Select the most representative frame in a given sequence of consecutive frames."),
222 .priv_size = sizeof(ThumbContext),
225 .query_formats = query_formats,
226 .inputs = (const AVFilterPad[]) {
228 .type = AVMEDIA_TYPE_VIDEO,
229 .get_video_buffer = avfilter_null_get_video_buffer,
230 .start_frame = null_start_frame,
231 .draw_slice = draw_slice,
232 .end_frame = end_frame,
235 .outputs = (const AVFilterPad[]) {
237 .type = AVMEDIA_TYPE_VIDEO,
238 .request_frame = request_frame,
239 .poll_frame = poll_frame,
240 .rej_perms = AV_PERM_REUSE2,