You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

239 lines
7.2KB

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