2 * Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved.
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 * DEALINGS IN THE SOFTWARE.
25 #include "libavutil/hwcontext.h"
26 #include "libavutil/hwcontext_cuda.h"
27 #include "libavutil/cuda_check.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/pixdesc.h"
34 #define CHECK_CU(x) FF_CUDA_CHECK(ctx, x)
36 #define HIST_SIZE (3*256)
37 #define DIV_UP(a, b) ( ((a) + (b) - 1) / (b) )
41 static const enum AVPixelFormat supported_formats[] = {
51 AVFrame *buf; ///< cached frame
52 int histogram[HIST_SIZE]; ///< RGB color distribution histogram of the frame
55 typedef struct ThumbnailCudaContext {
57 int n; ///< current frame
58 int n_frames; ///< number of frames for analysis
59 struct thumb_frame *frames; ///< the n_frames frames
60 AVRational tb; ///< copy of the input timebase to ease access
62 AVBufferRef *hw_frames_ctx;
66 CUfunction cu_func_uchar;
67 CUfunction cu_func_uchar2;
68 CUfunction cu_func_ushort;
69 CUfunction cu_func_ushort2;
70 CUtexref cu_tex_uchar;
71 CUtexref cu_tex_uchar2;
72 CUtexref cu_tex_ushort;
73 CUtexref cu_tex_ushort2;
76 } ThumbnailCudaContext;
78 #define OFFSET(x) offsetof(ThumbnailCudaContext, x)
79 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
81 static const AVOption thumbnail_cuda_options[] = {
82 { "n", "set the frames batch size", OFFSET(n_frames), AV_OPT_TYPE_INT, {.i64=100}, 2, INT_MAX, FLAGS },
86 AVFILTER_DEFINE_CLASS(thumbnail_cuda);
88 static av_cold int init(AVFilterContext *ctx)
90 ThumbnailCudaContext *s = ctx->priv;
92 s->frames = av_calloc(s->n_frames, sizeof(*s->frames));
94 av_log(ctx, AV_LOG_ERROR,
95 "Allocation failure, try to lower the number of frames\n");
96 return AVERROR(ENOMEM);
98 av_log(ctx, AV_LOG_VERBOSE, "batch size: %d frames\n", s->n_frames);
103 * @brief Compute Sum-square deviation to estimate "closeness".
104 * @param hist color distribution histogram
105 * @param median average color distribution histogram
106 * @return sum of squared errors
108 static double frame_sum_square_err(const int *hist, const double *median)
111 double err, sum_sq_err = 0;
113 for (i = 0; i < HIST_SIZE; i++) {
114 err = median[i] - (double)hist[i];
115 sum_sq_err += err*err;
120 static AVFrame *get_best_frame(AVFilterContext *ctx)
123 ThumbnailCudaContext *s = ctx->priv;
124 int i, j, best_frame_idx = 0;
125 int nb_frames = s->n;
126 double avg_hist[HIST_SIZE] = {0}, sq_err, min_sq_err = -1;
128 // average histogram of the N frames
129 for (j = 0; j < FF_ARRAY_ELEMS(avg_hist); j++) {
130 for (i = 0; i < nb_frames; i++)
131 avg_hist[j] += (double)s->frames[i].histogram[j];
132 avg_hist[j] /= nb_frames;
135 // find the frame closer to the average using the sum of squared errors
136 for (i = 0; i < nb_frames; i++) {
137 sq_err = frame_sum_square_err(s->frames[i].histogram, avg_hist);
138 if (i == 0 || sq_err < min_sq_err)
139 best_frame_idx = i, min_sq_err = sq_err;
142 // free and reset everything (except the best frame buffer)
143 for (i = 0; i < nb_frames; i++) {
144 memset(s->frames[i].histogram, 0, sizeof(s->frames[i].histogram));
145 if (i != best_frame_idx)
146 av_frame_free(&s->frames[i].buf);
150 // raise the chosen one
151 picref = s->frames[best_frame_idx].buf;
152 av_log(ctx, AV_LOG_INFO, "frame id #%d (pts_time=%f) selected "
153 "from a set of %d images\n", best_frame_idx,
154 picref->pts * av_q2d(s->tb), nb_frames);
155 s->frames[best_frame_idx].buf = NULL;
160 static int thumbnail_kernel(ThumbnailCudaContext *ctx, CUfunction func, CUtexref tex, int channels,
161 int *histogram, uint8_t *src_dptr, int src_width, int src_height, int src_pitch, int pixel_size)
163 CUdeviceptr src_devptr = (CUdeviceptr)src_dptr;
164 void *args[] = { &histogram, &src_width, &src_height };
165 CUDA_ARRAY_DESCRIPTOR desc;
167 desc.Width = src_width;
168 desc.Height = src_height;
169 desc.NumChannels = channels;
170 if (pixel_size == 1) {
171 desc.Format = CU_AD_FORMAT_UNSIGNED_INT8;
174 desc.Format = CU_AD_FORMAT_UNSIGNED_INT16;
177 CHECK_CU(cuTexRefSetAddress2D_v3(tex, &desc, src_devptr, src_pitch));
178 CHECK_CU(cuLaunchKernel(func,
179 DIV_UP(src_width, BLOCKX), DIV_UP(src_height, BLOCKY), 1,
180 BLOCKX, BLOCKY, 1, 0, 0, args, NULL));
185 static int thumbnail(AVFilterContext *ctx, int *histogram, AVFrame *in)
187 AVHWFramesContext *in_frames_ctx = (AVHWFramesContext*)in->hw_frames_ctx->data;
188 ThumbnailCudaContext *s = ctx->priv;
190 switch (in_frames_ctx->sw_format) {
191 case AV_PIX_FMT_NV12:
192 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
193 histogram, in->data[0], in->width, in->height, in->linesize[0], 1);
194 thumbnail_kernel(s, s->cu_func_uchar2, s->cu_tex_uchar2, 2,
195 histogram + 256, in->data[1], in->width / 2, in->height / 2, in->linesize[1], 1);
197 case AV_PIX_FMT_YUV420P:
198 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
199 histogram, in->data[0], in->width, in->height, in->linesize[0], 1);
200 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
201 histogram + 256, in->data[1], in->width / 2, in->height / 2, in->linesize[1], 1);
202 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
203 histogram + 512, in->data[2], in->width / 2, in->height / 2, in->linesize[2], 1);
205 case AV_PIX_FMT_YUV444P:
206 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
207 histogram, in->data[0], in->width, in->height, in->linesize[0], 1);
208 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
209 histogram + 256, in->data[1], in->width, in->height, in->linesize[1], 1);
210 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
211 histogram + 512, in->data[2], in->width, in->height, in->linesize[2], 1);
213 case AV_PIX_FMT_P010LE:
214 case AV_PIX_FMT_P016LE:
215 thumbnail_kernel(s, s->cu_func_ushort, s->cu_tex_ushort, 1,
216 histogram, in->data[0], in->width, in->height, in->linesize[0], 2);
217 thumbnail_kernel(s, s->cu_func_ushort2, s->cu_tex_ushort2, 2,
218 histogram + 256, in->data[1], in->width / 2, in->height / 2, in->linesize[1], 2);
220 case AV_PIX_FMT_YUV444P16:
221 thumbnail_kernel(s, s->cu_func_ushort2, s->cu_tex_uchar, 1,
222 histogram, in->data[0], in->width, in->height, in->linesize[0], 2);
223 thumbnail_kernel(s, s->cu_func_ushort2, s->cu_tex_uchar, 1,
224 histogram + 256, in->data[1], in->width, in->height, in->linesize[1], 2);
225 thumbnail_kernel(s, s->cu_func_ushort2, s->cu_tex_uchar, 1,
226 histogram + 512, in->data[2], in->width, in->height, in->linesize[2], 2);
235 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
237 AVFilterContext *ctx = inlink->dst;
238 ThumbnailCudaContext *s = ctx->priv;
239 AVFilterLink *outlink = ctx->outputs[0];
240 int *hist = s->frames[s->n].histogram;
241 AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)s->hw_frames_ctx->data;
242 AVCUDADeviceContext *device_hwctx = hw_frames_ctx->device_ctx->hwctx;
244 CUDA_MEMCPY2D cpy = { 0 };
247 // keep a reference of each frame
248 s->frames[s->n].buf = frame;
250 ret = CHECK_CU(cuCtxPushCurrent(device_hwctx->cuda_ctx));
254 CHECK_CU(cuMemsetD8(s->data, 0, HIST_SIZE * sizeof(int)));
256 thumbnail(ctx, (int*)s->data, frame);
258 cpy.srcMemoryType = CU_MEMORYTYPE_DEVICE;
259 cpy.dstMemoryType = CU_MEMORYTYPE_HOST;
260 cpy.srcDevice = s->data;
262 cpy.srcPitch = HIST_SIZE * sizeof(int);
263 cpy.dstPitch = HIST_SIZE * sizeof(int);
264 cpy.WidthInBytes = HIST_SIZE * sizeof(int);
267 ret = CHECK_CU(cuMemcpy2D(&cpy));
271 if (hw_frames_ctx->sw_format == AV_PIX_FMT_NV12 || hw_frames_ctx->sw_format == AV_PIX_FMT_YUV420P ||
272 hw_frames_ctx->sw_format == AV_PIX_FMT_P010LE || hw_frames_ctx->sw_format == AV_PIX_FMT_P016LE)
275 for (i = 256; i < HIST_SIZE; i++)
276 hist[i] = 4 * hist[i];
279 CHECK_CU(cuCtxPopCurrent(&dummy));
283 // no selection until the buffer of N frames is filled up
285 if (s->n < s->n_frames)
288 return ff_filter_frame(outlink, get_best_frame(ctx));
291 static av_cold void uninit(AVFilterContext *ctx)
294 ThumbnailCudaContext *s = ctx->priv;
297 CHECK_CU(cuMemFree(s->data));
302 CHECK_CU(cuModuleUnload(s->cu_module));
306 for (i = 0; i < s->n_frames && s->frames[i].buf; i++)
307 av_frame_free(&s->frames[i].buf);
308 av_freep(&s->frames);
311 static int request_frame(AVFilterLink *link)
313 AVFilterContext *ctx = link->src;
314 ThumbnailCudaContext *s = ctx->priv;
315 int ret = ff_request_frame(ctx->inputs[0]);
317 if (ret == AVERROR_EOF && s->n) {
318 ret = ff_filter_frame(link, get_best_frame(ctx));
328 static int format_is_supported(enum AVPixelFormat fmt)
332 for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++)
333 if (supported_formats[i] == fmt)
338 static int config_props(AVFilterLink *inlink)
340 AVFilterContext *ctx = inlink->dst;
341 ThumbnailCudaContext *s = ctx->priv;
342 AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
343 AVCUDADeviceContext *device_hwctx = hw_frames_ctx->device_ctx->hwctx;
344 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
347 extern char vf_thumbnail_cuda_ptx[];
349 ret = CHECK_CU(cuCtxPushCurrent(cuda_ctx));
353 ret = CHECK_CU(cuModuleLoadData(&s->cu_module, vf_thumbnail_cuda_ptx));
357 CHECK_CU(cuModuleGetFunction(&s->cu_func_uchar, s->cu_module, "Thumbnail_uchar"));
358 CHECK_CU(cuModuleGetFunction(&s->cu_func_uchar2, s->cu_module, "Thumbnail_uchar2"));
359 CHECK_CU(cuModuleGetFunction(&s->cu_func_ushort, s->cu_module, "Thumbnail_ushort"));
360 CHECK_CU(cuModuleGetFunction(&s->cu_func_ushort2, s->cu_module, "Thumbnail_ushort2"));
362 CHECK_CU(cuModuleGetTexRef(&s->cu_tex_uchar, s->cu_module, "uchar_tex"));
363 CHECK_CU(cuModuleGetTexRef(&s->cu_tex_uchar2, s->cu_module, "uchar2_tex"));
364 CHECK_CU(cuModuleGetTexRef(&s->cu_tex_ushort, s->cu_module, "ushort_tex"));
365 CHECK_CU(cuModuleGetTexRef(&s->cu_tex_ushort2, s->cu_module, "ushort2_tex"));
367 CHECK_CU(cuTexRefSetFlags(s->cu_tex_uchar, CU_TRSF_READ_AS_INTEGER));
368 CHECK_CU(cuTexRefSetFlags(s->cu_tex_uchar2, CU_TRSF_READ_AS_INTEGER));
369 CHECK_CU(cuTexRefSetFlags(s->cu_tex_ushort, CU_TRSF_READ_AS_INTEGER));
370 CHECK_CU(cuTexRefSetFlags(s->cu_tex_ushort2, CU_TRSF_READ_AS_INTEGER));
372 CHECK_CU(cuTexRefSetFilterMode(s->cu_tex_uchar, CU_TR_FILTER_MODE_LINEAR));
373 CHECK_CU(cuTexRefSetFilterMode(s->cu_tex_uchar2, CU_TR_FILTER_MODE_LINEAR));
374 CHECK_CU(cuTexRefSetFilterMode(s->cu_tex_ushort, CU_TR_FILTER_MODE_LINEAR));
375 CHECK_CU(cuTexRefSetFilterMode(s->cu_tex_ushort2, CU_TR_FILTER_MODE_LINEAR));
377 ret = CHECK_CU(cuMemAlloc(&s->data, HIST_SIZE * sizeof(int)));
381 CHECK_CU(cuCtxPopCurrent(&dummy));
383 s->hw_frames_ctx = ctx->inputs[0]->hw_frames_ctx;
385 ctx->outputs[0]->hw_frames_ctx = av_buffer_ref(s->hw_frames_ctx);
386 if (!ctx->outputs[0]->hw_frames_ctx)
387 return AVERROR(ENOMEM);
389 s->tb = inlink->time_base;
391 if (!format_is_supported(hw_frames_ctx->sw_format)) {
392 av_log(ctx, AV_LOG_ERROR, "Unsupported input format: %s\n", av_get_pix_fmt_name(hw_frames_ctx->sw_format));
393 return AVERROR(ENOSYS);
399 static int query_formats(AVFilterContext *ctx)
401 static const enum AVPixelFormat pix_fmts[] = {
405 AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
407 return AVERROR(ENOMEM);
408 return ff_set_common_formats(ctx, fmts_list);
411 static const AVFilterPad thumbnail_cuda_inputs[] = {
414 .type = AVMEDIA_TYPE_VIDEO,
415 .config_props = config_props,
416 .filter_frame = filter_frame,
421 static const AVFilterPad thumbnail_cuda_outputs[] = {
424 .type = AVMEDIA_TYPE_VIDEO,
425 .request_frame = request_frame,
430 AVFilter ff_vf_thumbnail_cuda = {
431 .name = "thumbnail_cuda",
432 .description = NULL_IF_CONFIG_SMALL("Select the most representative frame in a given sequence of consecutive frames."),
433 .priv_size = sizeof(ThumbnailCudaContext),
436 .query_formats = query_formats,
437 .inputs = thumbnail_cuda_inputs,
438 .outputs = thumbnail_cuda_outputs,
439 .priv_class = &thumbnail_cuda_class,
440 .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,