vf_thumbnail.c 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. * @file
  22. * Potential thumbnail lookup filter to reduce the risk of an inappropriate
  23. * selection (such as a black frame) we could get with an absolute seek.
  24. *
  25. * Simplified version of algorithm by Vadim Zaliva <lord@crocodile.org>.
  26. * @see http://notbrainsurgery.livejournal.com/29773.html
  27. */
  28. #include "libavutil/opt.h"
  29. #include "avfilter.h"
  30. #include "internal.h"
  31. #define HIST_SIZE (3*256)
  32. struct thumb_frame {
  33. AVFrame *buf; ///< cached frame
  34. int histogram[HIST_SIZE]; ///< RGB color distribution histogram of the frame
  35. };
  36. typedef struct ThumbContext {
  37. const AVClass *class;
  38. int n; ///< current frame
  39. int n_frames; ///< number of frames for analysis
  40. struct thumb_frame *frames; ///< the n_frames frames
  41. AVRational tb; ///< copy of the input timebase to ease access
  42. } ThumbContext;
  43. #define OFFSET(x) offsetof(ThumbContext, x)
  44. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  45. static const AVOption thumbnail_options[] = {
  46. { "n", "set the frames batch size", OFFSET(n_frames), AV_OPT_TYPE_INT, {.i64=100}, 2, INT_MAX, FLAGS },
  47. { NULL }
  48. };
  49. AVFILTER_DEFINE_CLASS(thumbnail);
  50. static av_cold int init(AVFilterContext *ctx)
  51. {
  52. ThumbContext *s = ctx->priv;
  53. s->frames = av_calloc(s->n_frames, sizeof(*s->frames));
  54. if (!s->frames) {
  55. av_log(ctx, AV_LOG_ERROR,
  56. "Allocation failure, try to lower the number of frames\n");
  57. return AVERROR(ENOMEM);
  58. }
  59. av_log(ctx, AV_LOG_VERBOSE, "batch size: %d frames\n", s->n_frames);
  60. return 0;
  61. }
  62. /**
  63. * @brief Compute Sum-square deviation to estimate "closeness".
  64. * @param hist color distribution histogram
  65. * @param median average color distribution histogram
  66. * @return sum of squared errors
  67. */
  68. static double frame_sum_square_err(const int *hist, const double *median)
  69. {
  70. int i;
  71. double err, sum_sq_err = 0;
  72. for (i = 0; i < HIST_SIZE; i++) {
  73. err = median[i] - (double)hist[i];
  74. sum_sq_err += err*err;
  75. }
  76. return sum_sq_err;
  77. }
  78. static AVFrame *get_best_frame(AVFilterContext *ctx)
  79. {
  80. AVFrame *picref;
  81. ThumbContext *s = ctx->priv;
  82. int i, j, best_frame_idx = 0;
  83. int nb_frames = s->n;
  84. double avg_hist[HIST_SIZE] = {0}, sq_err, min_sq_err = -1;
  85. // average histogram of the N frames
  86. for (j = 0; j < FF_ARRAY_ELEMS(avg_hist); j++) {
  87. for (i = 0; i < nb_frames; i++)
  88. avg_hist[j] += (double)s->frames[i].histogram[j];
  89. avg_hist[j] /= nb_frames;
  90. }
  91. // find the frame closer to the average using the sum of squared errors
  92. for (i = 0; i < nb_frames; i++) {
  93. sq_err = frame_sum_square_err(s->frames[i].histogram, avg_hist);
  94. if (i == 0 || sq_err < min_sq_err)
  95. best_frame_idx = i, min_sq_err = sq_err;
  96. }
  97. // free and reset everything (except the best frame buffer)
  98. for (i = 0; i < nb_frames; i++) {
  99. memset(s->frames[i].histogram, 0, sizeof(s->frames[i].histogram));
  100. if (i != best_frame_idx)
  101. av_frame_free(&s->frames[i].buf);
  102. }
  103. s->n = 0;
  104. // raise the chosen one
  105. picref = s->frames[best_frame_idx].buf;
  106. av_log(ctx, AV_LOG_INFO, "frame id #%d (pts_time=%f) selected "
  107. "from a set of %d images\n", best_frame_idx,
  108. picref->pts * av_q2d(s->tb), nb_frames);
  109. s->frames[best_frame_idx].buf = NULL;
  110. return picref;
  111. }
  112. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  113. {
  114. int i, j;
  115. AVFilterContext *ctx = inlink->dst;
  116. ThumbContext *s = ctx->priv;
  117. AVFilterLink *outlink = ctx->outputs[0];
  118. int *hist = s->frames[s->n].histogram;
  119. const uint8_t *p = frame->data[0];
  120. // keep a reference of each frame
  121. s->frames[s->n].buf = frame;
  122. // update current frame RGB histogram
  123. for (j = 0; j < inlink->h; j++) {
  124. for (i = 0; i < inlink->w; i++) {
  125. hist[0*256 + p[i*3 ]]++;
  126. hist[1*256 + p[i*3 + 1]]++;
  127. hist[2*256 + p[i*3 + 2]]++;
  128. }
  129. p += frame->linesize[0];
  130. }
  131. // no selection until the buffer of N frames is filled up
  132. s->n++;
  133. if (s->n < s->n_frames)
  134. return 0;
  135. return ff_filter_frame(outlink, get_best_frame(ctx));
  136. }
  137. static av_cold void uninit(AVFilterContext *ctx)
  138. {
  139. int i;
  140. ThumbContext *s = ctx->priv;
  141. for (i = 0; i < s->n_frames && s->frames[i].buf; i++)
  142. av_frame_free(&s->frames[i].buf);
  143. av_freep(&s->frames);
  144. }
  145. static int request_frame(AVFilterLink *link)
  146. {
  147. AVFilterContext *ctx = link->src;
  148. ThumbContext *s = ctx->priv;
  149. int ret = ff_request_frame(ctx->inputs[0]);
  150. if (ret == AVERROR_EOF && s->n) {
  151. ret = ff_filter_frame(link, get_best_frame(ctx));
  152. if (ret < 0)
  153. return ret;
  154. ret = AVERROR_EOF;
  155. }
  156. if (ret < 0)
  157. return ret;
  158. return 0;
  159. }
  160. static int config_props(AVFilterLink *inlink)
  161. {
  162. AVFilterContext *ctx = inlink->dst;
  163. ThumbContext *s = ctx->priv;
  164. s->tb = inlink->time_base;
  165. return 0;
  166. }
  167. static int query_formats(AVFilterContext *ctx)
  168. {
  169. static const enum AVPixelFormat pix_fmts[] = {
  170. AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
  171. AV_PIX_FMT_NONE
  172. };
  173. AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
  174. if (!fmts_list)
  175. return AVERROR(ENOMEM);
  176. return ff_set_common_formats(ctx, fmts_list);
  177. }
  178. static const AVFilterPad thumbnail_inputs[] = {
  179. {
  180. .name = "default",
  181. .type = AVMEDIA_TYPE_VIDEO,
  182. .config_props = config_props,
  183. .filter_frame = filter_frame,
  184. },
  185. { NULL }
  186. };
  187. static const AVFilterPad thumbnail_outputs[] = {
  188. {
  189. .name = "default",
  190. .type = AVMEDIA_TYPE_VIDEO,
  191. .request_frame = request_frame,
  192. },
  193. { NULL }
  194. };
  195. AVFilter ff_vf_thumbnail = {
  196. .name = "thumbnail",
  197. .description = NULL_IF_CONFIG_SMALL("Select the most representative frame in a given sequence of consecutive frames."),
  198. .priv_size = sizeof(ThumbContext),
  199. .init = init,
  200. .uninit = uninit,
  201. .query_formats = query_formats,
  202. .inputs = thumbnail_inputs,
  203. .outputs = thumbnail_outputs,
  204. .priv_class = &thumbnail_class,
  205. };