]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_thumbnail.c
Merge commit '6a27ae28f9bde981e85c82cf5bf42c5f43fb6f13'
[ffmpeg] / libavfilter / vf_thumbnail.c
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 "avfilter.h"
31 #include "internal.h"
32
33 #define HIST_SIZE (3*256)
34
35 struct thumb_frame {
36     AVFilterBufferRef *buf;     ///< cached frame
37     int histogram[HIST_SIZE];   ///< RGB color distribution histogram of the frame
38 };
39
40 typedef struct {
41     int n;                      ///< current frame
42     int n_frames;               ///< number of frames for analysis
43     struct thumb_frame *frames; ///< the n_frames frames
44 } ThumbContext;
45
46 static av_cold int init(AVFilterContext *ctx, const char *args)
47 {
48     ThumbContext *thumb = ctx->priv;
49
50     if (!args) {
51         thumb->n_frames = 100;
52     } else {
53         int n = sscanf(args, "%d", &thumb->n_frames);
54         if (n != 1 || thumb->n_frames < 2) {
55             thumb->n_frames = 0;
56             av_log(ctx, AV_LOG_ERROR,
57                    "Invalid number of frames specified (minimum is 2).\n");
58             return AVERROR(EINVAL);
59         }
60     }
61     thumb->frames = av_calloc(thumb->n_frames, sizeof(*thumb->frames));
62     if (!thumb->frames) {
63         av_log(ctx, AV_LOG_ERROR,
64                "Allocation failure, try to lower the number of frames\n");
65         return AVERROR(ENOMEM);
66     }
67     av_log(ctx, AV_LOG_VERBOSE, "batch size: %d frames\n", thumb->n_frames);
68     return 0;
69 }
70
71 /**
72  * @brief        Compute Sum-square deviation to estimate "closeness".
73  * @param hist   color distribution histogram
74  * @param median average color distribution histogram
75  * @return       sum of squared errors
76  */
77 static double frame_sum_square_err(const int *hist, const double *median)
78 {
79     int i;
80     double err, sum_sq_err = 0;
81
82     for (i = 0; i < HIST_SIZE; i++) {
83         err = median[i] - (double)hist[i];
84         sum_sq_err += err*err;
85     }
86     return sum_sq_err;
87 }
88
89 static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
90 {
91     int i, j, best_frame_idx = 0;
92     double avg_hist[HIST_SIZE] = {0}, sq_err, min_sq_err = -1;
93     AVFilterContext *ctx  = inlink->dst;
94     ThumbContext *thumb   = ctx->priv;
95     AVFilterLink *outlink = ctx->outputs[0];
96     AVFilterBufferRef *picref;
97     int *hist = thumb->frames[thumb->n].histogram;
98     const uint8_t *p = frame->data[0];
99
100     // keep a reference of each frame
101     thumb->frames[thumb->n].buf = frame;
102
103     // update current frame RGB histogram
104     for (j = 0; j < inlink->h; j++) {
105         for (i = 0; i < inlink->w; i++) {
106             hist[0*256 + p[i*3    ]]++;
107             hist[1*256 + p[i*3 + 1]]++;
108             hist[2*256 + p[i*3 + 2]]++;
109         }
110         p += frame->linesize[0];
111     }
112
113     // no selection until the buffer of N frames is filled up
114     if (thumb->n < thumb->n_frames - 1) {
115         thumb->n++;
116         return 0;
117     }
118
119     // average histogram of the N frames
120     for (j = 0; j < FF_ARRAY_ELEMS(avg_hist); j++) {
121         for (i = 0; i < thumb->n_frames; i++)
122             avg_hist[j] += (double)thumb->frames[i].histogram[j];
123         avg_hist[j] /= thumb->n_frames;
124     }
125
126     // find the frame closer to the average using the sum of squared errors
127     for (i = 0; i < thumb->n_frames; i++) {
128         sq_err = frame_sum_square_err(thumb->frames[i].histogram, avg_hist);
129         if (i == 0 || sq_err < min_sq_err)
130             best_frame_idx = i, min_sq_err = sq_err;
131     }
132
133     // free and reset everything (except the best frame buffer)
134     for (i = 0; i < thumb->n_frames; i++) {
135         memset(thumb->frames[i].histogram, 0, sizeof(thumb->frames[i].histogram));
136         if (i == best_frame_idx)
137             continue;
138         avfilter_unref_bufferp(&thumb->frames[i].buf);
139     }
140     thumb->n = 0;
141
142     // raise the chosen one
143     picref = thumb->frames[best_frame_idx].buf;
144     av_log(ctx, AV_LOG_INFO, "frame id #%d (pts_time=%f) selected\n",
145            best_frame_idx, picref->pts * av_q2d(inlink->time_base));
146     thumb->frames[best_frame_idx].buf = NULL;
147     return ff_filter_frame(outlink, picref);
148 }
149
150 static av_cold void uninit(AVFilterContext *ctx)
151 {
152     int i;
153     ThumbContext *thumb = ctx->priv;
154     for (i = 0; i < thumb->n_frames && thumb->frames[i].buf; i++)
155         avfilter_unref_bufferp(&thumb->frames[i].buf);
156     av_freep(&thumb->frames);
157 }
158
159 static int request_frame(AVFilterLink *link)
160 {
161     ThumbContext *thumb = link->src->priv;
162
163     /* loop until a frame thumbnail is available (when a frame is queued,
164      * thumb->n is reset to zero) */
165     do {
166         int ret = ff_request_frame(link->src->inputs[0]);
167         if (ret < 0)
168             return ret;
169     } while (thumb->n);
170     return 0;
171 }
172
173 static int poll_frame(AVFilterLink *link)
174 {
175     ThumbContext *thumb  = link->src->priv;
176     AVFilterLink *inlink = link->src->inputs[0];
177     int ret, available_frames = ff_poll_frame(inlink);
178
179     /* If the input link is not able to provide any frame, we can't do anything
180      * at the moment and thus have zero thumbnail available. */
181     if (!available_frames)
182         return 0;
183
184     /* Since at least one frame is available and the next frame will allow us
185      * to compute a thumbnail, we can return 1 frame. */
186     if (thumb->n == thumb->n_frames - 1)
187         return 1;
188
189     /* we have some frame(s) available in the input link, but not yet enough to
190      * output a thumbnail, so we request more */
191     ret = ff_request_frame(inlink);
192     return ret < 0 ? ret : 0;
193 }
194
195 static int query_formats(AVFilterContext *ctx)
196 {
197     static const enum AVPixelFormat pix_fmts[] = {
198         AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
199         AV_PIX_FMT_NONE
200     };
201     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
202     return 0;
203 }
204
205 static const AVFilterPad thumbnail_inputs[] = {
206     {
207         .name             = "default",
208         .type             = AVMEDIA_TYPE_VIDEO,
209         .get_video_buffer = ff_null_get_video_buffer,
210         .min_perms        = AV_PERM_PRESERVE,
211         .filter_frame     = filter_frame,
212     },
213     { NULL }
214 };
215
216 static const AVFilterPad thumbnail_outputs[] = {
217     {
218         .name          = "default",
219         .type          = AVMEDIA_TYPE_VIDEO,
220         .request_frame = request_frame,
221         .poll_frame    = poll_frame,
222     },
223     { NULL }
224 };
225
226 AVFilter avfilter_vf_thumbnail = {
227     .name          = "thumbnail",
228     .description   = NULL_IF_CONFIG_SMALL("Select the most representative frame in a given sequence of consecutive frames."),
229     .priv_size     = sizeof(ThumbContext),
230     .init          = init,
231     .uninit        = uninit,
232     .query_formats = query_formats,
233     .inputs        = thumbnail_inputs,
234     .outputs       = thumbnail_outputs,
235 };