vf_thumbnail.c 8.0 KB

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