vf_thumbnail.c 7.4 KB

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