]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_thumbnail.c
b2f1e9483e572d4dc11ed0dce63a0abb9bc0a97b
[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  * @url http://notbrainsurgery.livejournal.com/29773.html
28  */
29
30 #include "avfilter.h"
31
32 #define HIST_SIZE (3*256)
33
34 struct thumb_frame {
35     AVFilterBufferRef *buf;     ///< cached frame
36     int histogram[HIST_SIZE];   ///< RGB color distribution histogram of the frame
37 };
38
39 typedef struct {
40     int n;                      ///< current frame
41     int n_frames;               ///< number of frames for analysis
42     struct thumb_frame *frames; ///< the n_frames frames
43 } ThumbContext;
44
45 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
46 {
47     ThumbContext *thumb = ctx->priv;
48
49     if (!args) {
50         thumb->n_frames = 100;
51     } else {
52         int n = sscanf(args, "%d", &thumb->n_frames);
53         if (n != 1 || thumb->n_frames < 2) {
54             thumb->n_frames = 0;
55             av_log(ctx, AV_LOG_ERROR,
56                    "Invalid number of frames specified (minimum is 2).\n");
57             return AVERROR(ENOMEM);
58         }
59     }
60     thumb->frames = av_calloc(thumb->n_frames, sizeof(*thumb->frames));
61     if (!thumb->frames) {
62         av_log(ctx, AV_LOG_ERROR,
63                "Allocation failure, try to lower the number of frames\n");
64         return AVERROR(ENOMEM);
65     }
66     av_log(ctx, AV_LOG_INFO, "batch size: %d frames\n", thumb->n_frames);
67     return 0;
68 }
69
70 static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
71 {
72     int i, j;
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];
78
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]]++;
85         }
86         p += picref->linesize[0];
87     }
88 }
89
90 /**
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
95  */
96 static double frame_sum_square_err(const int *hist, const double *median)
97 {
98     int i;
99     double err, sum_sq_err = 0;
100
101     for (i = 0; i < HIST_SIZE; i++) {
102         err = median[i] - (double)hist[i];
103         sum_sq_err += err*err;
104     }
105     return sum_sq_err;
106 }
107
108 static void end_frame(AVFilterLink *inlink)
109 {
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;
116
117     // keep a reference of each frame
118     thumb->frames[thumb->n].buf = inlink->cur_buf;
119
120     // no selection until the buffer of N frames is filled up
121     if (thumb->n < thumb->n_frames - 1) {
122         thumb->n++;
123         return;
124     }
125
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;
131     }
132
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;
138     }
139
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)
144             continue;
145         avfilter_unref_buffer(thumb->frames[i].buf);
146         thumb->frames[i].buf = NULL;
147     }
148     thumb->n = 0;
149
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);
158 }
159
160 static av_cold void uninit(AVFilterContext *ctx)
161 {
162     int i;
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;
167     }
168     av_freep(&thumb->frames);
169 }
170
171 static void null_start_frame(AVFilterLink *link, AVFilterBufferRef *picref) { }
172
173 static int request_frame(AVFilterLink *link)
174 {
175     ThumbContext *thumb = link->src->priv;
176
177     /* loop until a frame thumbnail is available (when a frame is queued,
178      * thumb->n is reset to zero) */
179     while (thumb->n) {
180         int ret = avfilter_request_frame(link->src->inputs[0]);
181         if (ret < 0)
182             return ret;
183     }
184     return 0;
185 }
186
187 static int poll_frame(AVFilterLink *link)
188 {
189     ThumbContext *thumb  = link->src->priv;
190     AVFilterLink *inlink = link->src->inputs[0];
191     int ret, available_frames = avfilter_poll_frame(inlink);
192
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)
196         return 0;
197
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)
201         return 1;
202
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;
207 }
208
209 static int query_formats(AVFilterContext *ctx)
210 {
211     static const enum PixelFormat pix_fmts[] = {
212         PIX_FMT_RGB24, PIX_FMT_BGR24,
213         PIX_FMT_NONE
214     };
215     avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
216     return 0;
217 }
218
219 AVFilter avfilter_vf_thumbnail = {
220     .name          = "thumbnail",
221     .description   = NULL_IF_CONFIG_SMALL("Select the most representative frame in a given sequence of consecutive frames."),
222     .priv_size     = sizeof(ThumbContext),
223     .init          = init,
224     .uninit        = uninit,
225     .query_formats = query_formats,
226     .inputs        = (const AVFilterPad[]) {
227         {   .name             = "default",
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,
233         },{ .name = NULL }
234     },
235     .outputs       = (const AVFilterPad[]) {
236         {   .name             = "default",
237             .type             = AVMEDIA_TYPE_VIDEO,
238             .request_frame    = request_frame,
239             .poll_frame       = poll_frame,
240             .rej_perms        = AV_PERM_REUSE2,
241         },{ .name = NULL }
242     },
243 };