]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_thumbnail.c
Merge remote-tracking branch 'qatar/master'
[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 static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
72 {
73     int i, j;
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];
79
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]]++;
86         }
87         p += picref->linesize[0];
88     }
89 }
90
91 /**
92  * @brief        Compute Sum-square deviation to estimate "closeness".
93  * @param hist   color distribution histogram
94  * @param median average color distribution histogram
95  * @return       sum of squared errors
96  */
97 static double frame_sum_square_err(const int *hist, const double *median)
98 {
99     int i;
100     double err, sum_sq_err = 0;
101
102     for (i = 0; i < HIST_SIZE; i++) {
103         err = median[i] - (double)hist[i];
104         sum_sq_err += err*err;
105     }
106     return sum_sq_err;
107 }
108
109 static void end_frame(AVFilterLink *inlink)
110 {
111     int i, j, best_frame_idx = 0;
112     double avg_hist[HIST_SIZE] = {0}, sq_err, min_sq_err = -1;
113     AVFilterLink *outlink = inlink->dst->outputs[0];
114     ThumbContext *thumb   = inlink->dst->priv;
115     AVFilterContext *ctx  = inlink->dst;
116     AVFilterBufferRef *picref;
117
118     // keep a reference of each frame
119     thumb->frames[thumb->n].buf = inlink->cur_buf;
120
121     // no selection until the buffer of N frames is filled up
122     if (thumb->n < thumb->n_frames - 1) {
123         thumb->n++;
124         return;
125     }
126
127     // average histogram of the N frames
128     for (j = 0; j < FF_ARRAY_ELEMS(avg_hist); j++) {
129         for (i = 0; i < thumb->n_frames; i++)
130             avg_hist[j] += (double)thumb->frames[i].histogram[j];
131         avg_hist[j] /= thumb->n_frames;
132     }
133
134     // find the frame closer to the average using the sum of squared errors
135     for (i = 0; i < thumb->n_frames; i++) {
136         sq_err = frame_sum_square_err(thumb->frames[i].histogram, avg_hist);
137         if (i == 0 || sq_err < min_sq_err)
138             best_frame_idx = i, min_sq_err = sq_err;
139     }
140
141     // free and reset everything (except the best frame buffer)
142     for (i = 0; i < thumb->n_frames; i++) {
143         memset(thumb->frames[i].histogram, 0, sizeof(thumb->frames[i].histogram));
144         if (i == best_frame_idx)
145             continue;
146         avfilter_unref_buffer(thumb->frames[i].buf);
147         thumb->frames[i].buf = NULL;
148     }
149     thumb->n = 0;
150
151     // raise the chosen one
152     picref = thumb->frames[best_frame_idx].buf;
153     av_log(ctx, AV_LOG_INFO, "frame id #%d (pts_time=%f) selected\n",
154            best_frame_idx, picref->pts * av_q2d(inlink->time_base));
155     ff_start_frame(outlink, picref);
156     thumb->frames[best_frame_idx].buf = NULL;
157     ff_draw_slice(outlink, 0, inlink->h, 1);
158     ff_end_frame(outlink);
159 }
160
161 static av_cold void uninit(AVFilterContext *ctx)
162 {
163     int i;
164     ThumbContext *thumb = ctx->priv;
165     for (i = 0; i < thumb->n_frames && thumb->frames[i].buf; i++) {
166         avfilter_unref_buffer(thumb->frames[i].buf);
167         thumb->frames[i].buf = NULL;
168     }
169     av_freep(&thumb->frames);
170 }
171
172 static void null_start_frame(AVFilterLink *link, AVFilterBufferRef *picref) { }
173
174 static int request_frame(AVFilterLink *link)
175 {
176     ThumbContext *thumb = link->src->priv;
177
178     /* loop until a frame thumbnail is available (when a frame is queued,
179      * thumb->n is reset to zero) */
180     do {
181         int ret = ff_request_frame(link->src->inputs[0]);
182         if (ret < 0)
183             return ret;
184     } while (thumb->n);
185     return 0;
186 }
187
188 static int poll_frame(AVFilterLink *link)
189 {
190     ThumbContext *thumb  = link->src->priv;
191     AVFilterLink *inlink = link->src->inputs[0];
192     int ret, available_frames = ff_poll_frame(inlink);
193
194     /* If the input link is not able to provide any frame, we can't do anything
195      * at the moment and thus have zero thumbnail available. */
196     if (!available_frames)
197         return 0;
198
199     /* Since at least one frame is available and the next frame will allow us
200      * to compute a thumbnail, we can return 1 frame. */
201     if (thumb->n == thumb->n_frames - 1)
202         return 1;
203
204     /* we have some frame(s) available in the input link, but not yet enough to
205      * output a thumbnail, so we request more */
206     ret = ff_request_frame(inlink);
207     return ret < 0 ? ret : 0;
208 }
209
210 static int query_formats(AVFilterContext *ctx)
211 {
212     static const enum PixelFormat pix_fmts[] = {
213         PIX_FMT_RGB24, PIX_FMT_BGR24,
214         PIX_FMT_NONE
215     };
216     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
217     return 0;
218 }
219
220 AVFilter avfilter_vf_thumbnail = {
221     .name          = "thumbnail",
222     .description   = NULL_IF_CONFIG_SMALL("Select the most representative frame in a given sequence of consecutive frames."),
223     .priv_size     = sizeof(ThumbContext),
224     .init          = init,
225     .uninit        = uninit,
226     .query_formats = query_formats,
227     .inputs        = (const AVFilterPad[]) {
228         {   .name             = "default",
229             .type             = AVMEDIA_TYPE_VIDEO,
230             .get_video_buffer = ff_null_get_video_buffer,
231             .start_frame      = null_start_frame,
232             .draw_slice       = draw_slice,
233             .end_frame        = end_frame,
234         },{ .name = NULL }
235     },
236     .outputs       = (const AVFilterPad[]) {
237         {   .name             = "default",
238             .type             = AVMEDIA_TYPE_VIDEO,
239             .request_frame    = request_frame,
240             .poll_frame       = poll_frame,
241             .rej_perms        = AV_PERM_REUSE2,
242         },{ .name = NULL }
243     },
244 };