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_internal.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/pixdesc.h"
33 #define HIST_SIZE (3*256)
34 #define DIV_UP(a, b) ( ((a) + (b) - 1) / (b) )
38 static const enum AVPixelFormat supported_formats[] = {
48 AVFrame *buf; ///< cached frame
49 int histogram[HIST_SIZE]; ///< RGB color distribution histogram of the frame
52 typedef struct ThumbnailCudaContext {
54 int n; ///< current frame
55 int n_frames; ///< number of frames for analysis
56 struct thumb_frame *frames; ///< the n_frames frames
57 AVRational tb; ///< copy of the input timebase to ease access
59 AVBufferRef *hw_frames_ctx;
63 CUfunction cu_func_uchar;
64 CUfunction cu_func_uchar2;
65 CUfunction cu_func_ushort;
66 CUfunction cu_func_ushort2;
67 CUtexref cu_tex_uchar;
68 CUtexref cu_tex_uchar2;
69 CUtexref cu_tex_ushort;
70 CUtexref cu_tex_ushort2;
73 } ThumbnailCudaContext;
75 #define OFFSET(x) offsetof(ThumbnailCudaContext, x)
76 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
78 static const AVOption thumbnail_cuda_options[] = {
79 { "n", "set the frames batch size", OFFSET(n_frames), AV_OPT_TYPE_INT, {.i64=100}, 2, INT_MAX, FLAGS },
83 AVFILTER_DEFINE_CLASS(thumbnail_cuda);
85 static av_cold int init(AVFilterContext *ctx)
87 ThumbnailCudaContext *s = ctx->priv;
89 s->frames = av_calloc(s->n_frames, sizeof(*s->frames));
91 av_log(ctx, AV_LOG_ERROR,
92 "Allocation failure, try to lower the number of frames\n");
93 return AVERROR(ENOMEM);
95 av_log(ctx, AV_LOG_VERBOSE, "batch size: %d frames\n", s->n_frames);
100 * @brief Compute Sum-square deviation to estimate "closeness".
101 * @param hist color distribution histogram
102 * @param median average color distribution histogram
103 * @return sum of squared errors
105 static double frame_sum_square_err(const int *hist, const double *median)
108 double err, sum_sq_err = 0;
110 for (i = 0; i < HIST_SIZE; i++) {
111 err = median[i] - (double)hist[i];
112 sum_sq_err += err*err;
117 static AVFrame *get_best_frame(AVFilterContext *ctx)
120 ThumbnailCudaContext *s = ctx->priv;
121 int i, j, best_frame_idx = 0;
122 int nb_frames = s->n;
123 double avg_hist[HIST_SIZE] = {0}, sq_err, min_sq_err = -1;
125 // average histogram of the N frames
126 for (j = 0; j < FF_ARRAY_ELEMS(avg_hist); j++) {
127 for (i = 0; i < nb_frames; i++)
128 avg_hist[j] += (double)s->frames[i].histogram[j];
129 avg_hist[j] /= nb_frames;
132 // find the frame closer to the average using the sum of squared errors
133 for (i = 0; i < nb_frames; i++) {
134 sq_err = frame_sum_square_err(s->frames[i].histogram, avg_hist);
135 if (i == 0 || sq_err < min_sq_err)
136 best_frame_idx = i, min_sq_err = sq_err;
139 // free and reset everything (except the best frame buffer)
140 for (i = 0; i < nb_frames; i++) {
141 memset(s->frames[i].histogram, 0, sizeof(s->frames[i].histogram));
142 if (i != best_frame_idx)
143 av_frame_free(&s->frames[i].buf);
147 // raise the chosen one
148 picref = s->frames[best_frame_idx].buf;
149 av_log(ctx, AV_LOG_INFO, "frame id #%d (pts_time=%f) selected "
150 "from a set of %d images\n", best_frame_idx,
151 picref->pts * av_q2d(s->tb), nb_frames);
152 s->frames[best_frame_idx].buf = NULL;
157 static int thumbnail_kernel(ThumbnailCudaContext *s, CUfunction func, CUtexref tex, int channels,
158 int *histogram, uint8_t *src_dptr, int src_width, int src_height, int src_pitch, int pixel_size)
160 CUdeviceptr src_devptr = (CUdeviceptr)src_dptr;
161 void *args[] = { &histogram, &src_width, &src_height };
162 CUDA_ARRAY_DESCRIPTOR desc;
164 desc.Width = src_width;
165 desc.Height = src_height;
166 desc.NumChannels = channels;
167 if (pixel_size == 1) {
168 desc.Format = CU_AD_FORMAT_UNSIGNED_INT8;
171 desc.Format = CU_AD_FORMAT_UNSIGNED_INT16;
174 cuTexRefSetAddress2D_v3(tex, &desc, src_devptr, src_pitch);
175 cuLaunchKernel(func, DIV_UP(src_width, BLOCKX), DIV_UP(src_height, BLOCKY), 1, BLOCKX, BLOCKY, 1, 0, 0, args, NULL);
180 static int thumbnail(AVFilterContext *ctx, int *histogram, AVFrame *in)
182 AVHWFramesContext *in_frames_ctx = (AVHWFramesContext*)in->hw_frames_ctx->data;
183 ThumbnailCudaContext *s = ctx->priv;
185 switch (in_frames_ctx->sw_format) {
186 case AV_PIX_FMT_NV12:
187 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
188 histogram, in->data[0], in->width, in->height, in->linesize[0], 1);
189 thumbnail_kernel(s, s->cu_func_uchar2, s->cu_tex_uchar2, 2,
190 histogram + 256, in->data[1], in->width / 2, in->height / 2, in->linesize[1], 1);
192 case AV_PIX_FMT_YUV420P:
193 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
194 histogram, in->data[0], in->width, in->height, in->linesize[0], 1);
195 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
196 histogram + 256, in->data[1], in->width / 2, in->height / 2, in->linesize[1], 1);
197 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
198 histogram + 512, in->data[2], in->width / 2, in->height / 2, in->linesize[2], 1);
200 case AV_PIX_FMT_YUV444P:
201 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
202 histogram, in->data[0], in->width, in->height, in->linesize[0], 1);
203 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
204 histogram + 256, in->data[1], in->width, in->height, in->linesize[1], 1);
205 thumbnail_kernel(s, s->cu_func_uchar, s->cu_tex_uchar, 1,
206 histogram + 512, in->data[2], in->width, in->height, in->linesize[2], 1);
208 case AV_PIX_FMT_P010LE:
209 case AV_PIX_FMT_P016LE:
210 thumbnail_kernel(s, s->cu_func_ushort, s->cu_tex_ushort, 1,
211 histogram, in->data[0], in->width, in->height, in->linesize[0], 2);
212 thumbnail_kernel(s, s->cu_func_ushort2, s->cu_tex_ushort2, 2,
213 histogram + 256, in->data[1], in->width / 2, in->height / 2, in->linesize[1], 2);
215 case AV_PIX_FMT_YUV444P16:
216 thumbnail_kernel(s, s->cu_func_ushort2, s->cu_tex_uchar, 1,
217 histogram, in->data[0], in->width, in->height, in->linesize[0], 2);
218 thumbnail_kernel(s, s->cu_func_ushort2, s->cu_tex_uchar, 1,
219 histogram + 256, in->data[1], in->width, in->height, in->linesize[1], 2);
220 thumbnail_kernel(s, s->cu_func_ushort2, s->cu_tex_uchar, 1,
221 histogram + 512, in->data[2], in->width, in->height, in->linesize[2], 2);
230 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
232 AVFilterContext *ctx = inlink->dst;
233 ThumbnailCudaContext *s = ctx->priv;
234 AVFilterLink *outlink = ctx->outputs[0];
235 int *hist = s->frames[s->n].histogram;
236 AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)s->hw_frames_ctx->data;
237 AVCUDADeviceContext *device_hwctx = hw_frames_ctx->device_ctx->hwctx;
240 CUDA_MEMCPY2D cpy = { 0 };
243 // keep a reference of each frame
244 s->frames[s->n].buf = frame;
246 err = cuCtxPushCurrent(device_hwctx->cuda_ctx);
247 if (err != CUDA_SUCCESS)
248 return AVERROR_UNKNOWN;
250 cuMemsetD8(s->data, 0, HIST_SIZE * sizeof(int));
252 thumbnail(ctx, (int*)s->data, frame);
254 cpy.srcMemoryType = CU_MEMORYTYPE_DEVICE;
255 cpy.dstMemoryType = CU_MEMORYTYPE_HOST;
256 cpy.srcDevice = s->data;
258 cpy.srcPitch = HIST_SIZE * sizeof(int);
259 cpy.dstPitch = HIST_SIZE * sizeof(int);
260 cpy.WidthInBytes = HIST_SIZE * sizeof(int);
263 err = cuMemcpy2D(&cpy);
264 if (err != CUDA_SUCCESS) {
265 av_log(ctx, AV_LOG_ERROR, "Error transferring the data from the CUDA frame\n");
266 return AVERROR_UNKNOWN;
269 if (hw_frames_ctx->sw_format == AV_PIX_FMT_NV12 || hw_frames_ctx->sw_format == AV_PIX_FMT_YUV420P ||
270 hw_frames_ctx->sw_format == AV_PIX_FMT_P010LE || hw_frames_ctx->sw_format == AV_PIX_FMT_P016LE)
273 for (i = 256; i < HIST_SIZE; i++)
274 hist[i] = 4 * hist[i];
277 cuCtxPopCurrent(&dummy);
281 // no selection until the buffer of N frames is filled up
283 if (s->n < s->n_frames)
286 return ff_filter_frame(outlink, get_best_frame(ctx));
289 static av_cold void uninit(AVFilterContext *ctx)
292 ThumbnailCudaContext *s = ctx->priv;
300 cuModuleUnload(s->cu_module);
304 for (i = 0; i < s->n_frames && s->frames[i].buf; i++)
305 av_frame_free(&s->frames[i].buf);
306 av_freep(&s->frames);
309 static int request_frame(AVFilterLink *link)
311 AVFilterContext *ctx = link->src;
312 ThumbnailCudaContext *s = ctx->priv;
313 int ret = ff_request_frame(ctx->inputs[0]);
315 if (ret == AVERROR_EOF && s->n) {
316 ret = ff_filter_frame(link, get_best_frame(ctx));
326 static int format_is_supported(enum AVPixelFormat fmt)
330 for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++)
331 if (supported_formats[i] == fmt)
336 static int config_props(AVFilterLink *inlink)
338 AVFilterContext *ctx = inlink->dst;
339 ThumbnailCudaContext *s = ctx->priv;
340 AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
341 AVCUDADeviceContext *device_hwctx = hw_frames_ctx->device_ctx->hwctx;
342 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
345 extern char vf_thumbnail_cuda_ptx[];
347 err = cuCtxPushCurrent(cuda_ctx);
348 if (err != CUDA_SUCCESS) {
349 av_log(ctx, AV_LOG_ERROR, "Error pushing cuda context\n");
350 return AVERROR_UNKNOWN;
353 err = cuModuleLoadData(&s->cu_module, vf_thumbnail_cuda_ptx);
354 if (err != CUDA_SUCCESS) {
355 av_log(ctx, AV_LOG_ERROR, "Error loading module data\n");
356 return AVERROR_UNKNOWN;
359 cuModuleGetFunction(&s->cu_func_uchar, s->cu_module, "Thumbnail_uchar");
360 cuModuleGetFunction(&s->cu_func_uchar2, s->cu_module, "Thumbnail_uchar2");
361 cuModuleGetFunction(&s->cu_func_ushort, s->cu_module, "Thumbnail_ushort");
362 cuModuleGetFunction(&s->cu_func_ushort2, s->cu_module, "Thumbnail_ushort2");
364 cuModuleGetTexRef(&s->cu_tex_uchar, s->cu_module, "uchar_tex");
365 cuModuleGetTexRef(&s->cu_tex_uchar2, s->cu_module, "uchar2_tex");
366 cuModuleGetTexRef(&s->cu_tex_ushort, s->cu_module, "ushort_tex");
367 cuModuleGetTexRef(&s->cu_tex_ushort2, s->cu_module, "ushort2_tex");
369 cuTexRefSetFlags(s->cu_tex_uchar, CU_TRSF_READ_AS_INTEGER);
370 cuTexRefSetFlags(s->cu_tex_uchar2, CU_TRSF_READ_AS_INTEGER);
371 cuTexRefSetFlags(s->cu_tex_ushort, CU_TRSF_READ_AS_INTEGER);
372 cuTexRefSetFlags(s->cu_tex_ushort2, CU_TRSF_READ_AS_INTEGER);
374 cuTexRefSetFilterMode(s->cu_tex_uchar, CU_TR_FILTER_MODE_LINEAR);
375 cuTexRefSetFilterMode(s->cu_tex_uchar2, CU_TR_FILTER_MODE_LINEAR);
376 cuTexRefSetFilterMode(s->cu_tex_ushort, CU_TR_FILTER_MODE_LINEAR);
377 cuTexRefSetFilterMode(s->cu_tex_ushort2, CU_TR_FILTER_MODE_LINEAR);
379 err = cuMemAlloc(&s->data, HIST_SIZE * sizeof(int));
380 if (err != CUDA_SUCCESS) {
381 av_log(ctx, AV_LOG_ERROR, "Error allocating cuda memory\n");
382 return AVERROR_UNKNOWN;
385 cuCtxPopCurrent(&dummy);
387 s->hw_frames_ctx = ctx->inputs[0]->hw_frames_ctx;
389 ctx->outputs[0]->hw_frames_ctx = av_buffer_ref(s->hw_frames_ctx);
390 if (!ctx->outputs[0]->hw_frames_ctx)
391 return AVERROR(ENOMEM);
393 s->tb = inlink->time_base;
395 if (!format_is_supported(hw_frames_ctx->sw_format)) {
396 av_log(ctx, AV_LOG_ERROR, "Unsupported input format: %s\n", av_get_pix_fmt_name(hw_frames_ctx->sw_format));
397 return AVERROR(ENOSYS);
403 static int query_formats(AVFilterContext *ctx)
405 static const enum AVPixelFormat pix_fmts[] = {
409 AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
411 return AVERROR(ENOMEM);
412 return ff_set_common_formats(ctx, fmts_list);
415 static const AVFilterPad thumbnail_cuda_inputs[] = {
418 .type = AVMEDIA_TYPE_VIDEO,
419 .config_props = config_props,
420 .filter_frame = filter_frame,
425 static const AVFilterPad thumbnail_cuda_outputs[] = {
428 .type = AVMEDIA_TYPE_VIDEO,
429 .request_frame = request_frame,
434 AVFilter ff_vf_thumbnail_cuda = {
435 .name = "thumbnail_cuda",
436 .description = NULL_IF_CONFIG_SMALL("Select the most representative frame in a given sequence of consecutive frames."),
437 .priv_size = sizeof(ThumbnailCudaContext),
440 .query_formats = query_formats,
441 .inputs = thumbnail_cuda_inputs,
442 .outputs = thumbnail_cuda_outputs,
443 .priv_class = &thumbnail_cuda_class,
444 .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,