]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_thumbnail.c
Merge commit 'd15c21e5fa3961f10026da1a3080a3aa3cf4cec9'
[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 int 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     return 0;
90 }
91
92 /**
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
97  */
98 static double frame_sum_square_err(const int *hist, const double *median)
99 {
100     int i;
101     double err, sum_sq_err = 0;
102
103     for (i = 0; i < HIST_SIZE; i++) {
104         err = median[i] - (double)hist[i];
105         sum_sq_err += err*err;
106     }
107     return sum_sq_err;
108 }
109
110 static int  end_frame(AVFilterLink *inlink)
111 {
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;
118
119     // keep a reference of each frame
120     thumb->frames[thumb->n].buf = inlink->cur_buf;
121     inlink->cur_buf = NULL;
122
123     // no selection until the buffer of N frames is filled up
124     if (thumb->n < thumb->n_frames - 1) {
125         thumb->n++;
126         return 0;
127     }
128
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;
134     }
135
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;
141     }
142
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)
147             continue;
148         avfilter_unref_buffer(thumb->frames[i].buf);
149         thumb->frames[i].buf = NULL;
150     }
151     thumb->n = 0;
152
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);
161 }
162
163 static av_cold void uninit(AVFilterContext *ctx)
164 {
165     int i;
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;
170     }
171     av_freep(&thumb->frames);
172 }
173
174 static int null_start_frame(AVFilterLink *link, AVFilterBufferRef *picref) { return 0; }
175
176 static int request_frame(AVFilterLink *link)
177 {
178     ThumbContext *thumb = link->src->priv;
179
180     /* loop until a frame thumbnail is available (when a frame is queued,
181      * thumb->n is reset to zero) */
182     do {
183         int ret = ff_request_frame(link->src->inputs[0]);
184         if (ret < 0)
185             return ret;
186     } while (thumb->n);
187     return 0;
188 }
189
190 static int poll_frame(AVFilterLink *link)
191 {
192     ThumbContext *thumb  = link->src->priv;
193     AVFilterLink *inlink = link->src->inputs[0];
194     int ret, available_frames = ff_poll_frame(inlink);
195
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)
199         return 0;
200
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)
204         return 1;
205
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;
210 }
211
212 static int query_formats(AVFilterContext *ctx)
213 {
214     static const enum AVPixelFormat pix_fmts[] = {
215         AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
216         AV_PIX_FMT_NONE
217     };
218     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
219     return 0;
220 }
221
222 AVFilter avfilter_vf_thumbnail = {
223     .name          = "thumbnail",
224     .description   = NULL_IF_CONFIG_SMALL("Select the most representative frame in a given sequence of consecutive frames."),
225     .priv_size     = sizeof(ThumbContext),
226     .init          = init,
227     .uninit        = uninit,
228     .query_formats = query_formats,
229     .inputs        = (const AVFilterPad[]) {
230         {   .name             = "default",
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,
237         },{ .name = NULL }
238     },
239     .outputs       = (const AVFilterPad[]) {
240         {   .name             = "default",
241             .type             = AVMEDIA_TYPE_VIDEO,
242             .request_frame    = request_frame,
243             .poll_frame       = poll_frame,
244         },{ .name = NULL }
245     },
246 };