]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_thumbnail_cuda.c
Merge commit 'ca44fa5d7fda7e954f3ebfeb5b0d6d1be55fcaa3'
[ffmpeg] / libavfilter / vf_thumbnail_cuda.c
1 /*
2 * Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved.
3 *
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:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
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.
21 */
22
23 #include <cuda.h>
24
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"
30
31 #include "avfilter.h"
32 #include "internal.h"
33
34 #define CHECK_CU(x) FF_CUDA_CHECK(ctx, x)
35
36 #define HIST_SIZE (3*256)
37 #define DIV_UP(a, b) ( ((a) + (b) - 1) / (b) )
38 #define BLOCKX 32
39 #define BLOCKY 16
40
41 static const enum AVPixelFormat supported_formats[] = {
42     AV_PIX_FMT_NV12,
43     AV_PIX_FMT_YUV420P,
44     AV_PIX_FMT_YUV444P,
45     AV_PIX_FMT_P010,
46     AV_PIX_FMT_P016,
47     AV_PIX_FMT_YUV444P16,
48 };
49
50 struct thumb_frame {
51     AVFrame *buf;               ///< cached frame
52     int histogram[HIST_SIZE];   ///< RGB color distribution histogram of the frame
53 };
54
55 typedef struct ThumbnailCudaContext {
56     const AVClass *class;
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
61
62     AVBufferRef *hw_frames_ctx;
63
64     CUmodule    cu_module;
65
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;
74
75     CUdeviceptr data;
76 } ThumbnailCudaContext;
77
78 #define OFFSET(x) offsetof(ThumbnailCudaContext, x)
79 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
80
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 },
83     { NULL }
84 };
85
86 AVFILTER_DEFINE_CLASS(thumbnail_cuda);
87
88 static av_cold int init(AVFilterContext *ctx)
89 {
90     ThumbnailCudaContext *s = ctx->priv;
91
92     s->frames = av_calloc(s->n_frames, sizeof(*s->frames));
93     if (!s->frames) {
94         av_log(ctx, AV_LOG_ERROR,
95                "Allocation failure, try to lower the number of frames\n");
96         return AVERROR(ENOMEM);
97     }
98     av_log(ctx, AV_LOG_VERBOSE, "batch size: %d frames\n", s->n_frames);
99     return 0;
100 }
101
102 /**
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
107  */
108 static double frame_sum_square_err(const int *hist, const double *median)
109 {
110     int i;
111     double err, sum_sq_err = 0;
112
113     for (i = 0; i < HIST_SIZE; i++) {
114         err = median[i] - (double)hist[i];
115         sum_sq_err += err*err;
116     }
117     return sum_sq_err;
118 }
119
120 static AVFrame *get_best_frame(AVFilterContext *ctx)
121 {
122     AVFrame *picref;
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;
127
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;
133     }
134
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;
140     }
141
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);
147     }
148     s->n = 0;
149
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;
156
157     return picref;
158 }
159
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)
162 {
163     CUdeviceptr src_devptr = (CUdeviceptr)src_dptr;
164     void *args[] = { &histogram, &src_width, &src_height };
165     CUDA_ARRAY_DESCRIPTOR desc;
166
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;
172     }
173     else {
174         desc.Format = CU_AD_FORMAT_UNSIGNED_INT16;
175     }
176
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));
181
182     return 0;
183 }
184
185 static int thumbnail(AVFilterContext *ctx, int *histogram, AVFrame *in)
186 {
187     AVHWFramesContext *in_frames_ctx = (AVHWFramesContext*)in->hw_frames_ctx->data;
188     ThumbnailCudaContext *s = ctx->priv;
189
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);
196         break;
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);
204         break;
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);
212         break;
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);
219         break;
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);
227         break;
228     default:
229         return AVERROR_BUG;
230     }
231
232     return 0;
233 }
234
235 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
236 {
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;
243     CUcontext dummy;
244     CUDA_MEMCPY2D cpy = { 0 };
245     int ret = 0;
246
247     // keep a reference of each frame
248     s->frames[s->n].buf = frame;
249
250     ret = CHECK_CU(cuCtxPushCurrent(device_hwctx->cuda_ctx));
251     if (ret < 0)
252         return ret;
253
254     CHECK_CU(cuMemsetD8(s->data, 0, HIST_SIZE * sizeof(int)));
255
256     thumbnail(ctx, (int*)s->data, frame);
257
258     cpy.srcMemoryType = CU_MEMORYTYPE_DEVICE;
259     cpy.dstMemoryType = CU_MEMORYTYPE_HOST;
260     cpy.srcDevice = s->data;
261     cpy.dstHost = hist;
262     cpy.srcPitch = HIST_SIZE * sizeof(int);
263     cpy.dstPitch = HIST_SIZE * sizeof(int);
264     cpy.WidthInBytes = HIST_SIZE * sizeof(int);
265     cpy.Height = 1;
266
267     ret = CHECK_CU(cuMemcpy2D(&cpy));
268     if (ret < 0)
269         return ret;
270
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)
273     {
274         int i;
275         for (i = 256; i < HIST_SIZE; i++)
276             hist[i] = 4 * hist[i];
277     }
278
279     CHECK_CU(cuCtxPopCurrent(&dummy));
280     if (ret < 0)
281         return ret;
282
283     // no selection until the buffer of N frames is filled up
284     s->n++;
285     if (s->n < s->n_frames)
286         return 0;
287
288     return ff_filter_frame(outlink, get_best_frame(ctx));
289 }
290
291 static av_cold void uninit(AVFilterContext *ctx)
292 {
293     int i;
294     ThumbnailCudaContext *s = ctx->priv;
295
296     if (s->data) {
297         CHECK_CU(cuMemFree(s->data));
298         s->data = 0;
299     }
300
301     if (s->cu_module) {
302         CHECK_CU(cuModuleUnload(s->cu_module));
303         s->cu_module = NULL;
304     }
305
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);
309 }
310
311 static int request_frame(AVFilterLink *link)
312 {
313     AVFilterContext *ctx = link->src;
314     ThumbnailCudaContext *s = ctx->priv;
315     int ret = ff_request_frame(ctx->inputs[0]);
316
317     if (ret == AVERROR_EOF && s->n) {
318         ret = ff_filter_frame(link, get_best_frame(ctx));
319         if (ret < 0)
320             return ret;
321         ret = AVERROR_EOF;
322     }
323     if (ret < 0)
324         return ret;
325     return 0;
326 }
327
328 static int format_is_supported(enum AVPixelFormat fmt)
329 {
330     int i;
331
332     for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++)
333         if (supported_formats[i] == fmt)
334             return 1;
335     return 0;
336 }
337
338 static int config_props(AVFilterLink *inlink)
339 {
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;
345     int ret;
346
347     extern char vf_thumbnail_cuda_ptx[];
348
349     ret = CHECK_CU(cuCtxPushCurrent(cuda_ctx));
350     if (ret < 0)
351         return ret;
352
353     ret = CHECK_CU(cuModuleLoadData(&s->cu_module, vf_thumbnail_cuda_ptx));
354     if (ret < 0)
355         return ret;
356
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"));
361
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"));
366
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));
371
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));
376
377     ret = CHECK_CU(cuMemAlloc(&s->data, HIST_SIZE * sizeof(int)));
378     if (ret < 0)
379         return ret;
380
381     CHECK_CU(cuCtxPopCurrent(&dummy));
382
383     s->hw_frames_ctx = ctx->inputs[0]->hw_frames_ctx;
384
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);
388
389     s->tb = inlink->time_base;
390
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);
394     }
395
396     return 0;
397 }
398
399 static int query_formats(AVFilterContext *ctx)
400 {
401     static const enum AVPixelFormat pix_fmts[] = {
402         AV_PIX_FMT_CUDA,
403         AV_PIX_FMT_NONE
404     };
405     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
406     if (!fmts_list)
407         return AVERROR(ENOMEM);
408     return ff_set_common_formats(ctx, fmts_list);
409 }
410
411 static const AVFilterPad thumbnail_cuda_inputs[] = {
412     {
413         .name         = "default",
414         .type         = AVMEDIA_TYPE_VIDEO,
415         .config_props = config_props,
416         .filter_frame = filter_frame,
417     },
418     { NULL }
419 };
420
421 static const AVFilterPad thumbnail_cuda_outputs[] = {
422     {
423         .name          = "default",
424         .type          = AVMEDIA_TYPE_VIDEO,
425         .request_frame = request_frame,
426     },
427     { NULL }
428 };
429
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),
434     .init          = init,
435     .uninit        = uninit,
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,
441 };