]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_thumbnail_cuda.c
Merge commit '871b4f3654636ed64560e86b9faa33828d195ceb'
[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_internal.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/pixdesc.h"
29
30 #include "avfilter.h"
31 #include "internal.h"
32
33 #define HIST_SIZE (3*256)
34 #define DIV_UP(a, b) ( ((a) + (b) - 1) / (b) )
35 #define BLOCKX 32
36 #define BLOCKY 16
37
38 static const enum AVPixelFormat supported_formats[] = {
39     AV_PIX_FMT_NV12,
40     AV_PIX_FMT_YUV420P,
41     AV_PIX_FMT_YUV444P,
42     AV_PIX_FMT_P010,
43     AV_PIX_FMT_P016,
44     AV_PIX_FMT_YUV444P16,
45 };
46
47 struct thumb_frame {
48     AVFrame *buf;               ///< cached frame
49     int histogram[HIST_SIZE];   ///< RGB color distribution histogram of the frame
50 };
51
52 typedef struct ThumbnailCudaContext {
53     const AVClass *class;
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
58
59     AVBufferRef *hw_frames_ctx;
60
61     CUmodule    cu_module;
62
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;
71
72     CUdeviceptr data;
73 } ThumbnailCudaContext;
74
75 #define OFFSET(x) offsetof(ThumbnailCudaContext, x)
76 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
77
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 },
80     { NULL }
81 };
82
83 AVFILTER_DEFINE_CLASS(thumbnail_cuda);
84
85 static av_cold int init(AVFilterContext *ctx)
86 {
87     ThumbnailCudaContext *s = ctx->priv;
88
89     s->frames = av_calloc(s->n_frames, sizeof(*s->frames));
90     if (!s->frames) {
91         av_log(ctx, AV_LOG_ERROR,
92                "Allocation failure, try to lower the number of frames\n");
93         return AVERROR(ENOMEM);
94     }
95     av_log(ctx, AV_LOG_VERBOSE, "batch size: %d frames\n", s->n_frames);
96     return 0;
97 }
98
99 /**
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
104  */
105 static double frame_sum_square_err(const int *hist, const double *median)
106 {
107     int i;
108     double err, sum_sq_err = 0;
109
110     for (i = 0; i < HIST_SIZE; i++) {
111         err = median[i] - (double)hist[i];
112         sum_sq_err += err*err;
113     }
114     return sum_sq_err;
115 }
116
117 static AVFrame *get_best_frame(AVFilterContext *ctx)
118 {
119     AVFrame *picref;
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;
124
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;
130     }
131
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;
137     }
138
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);
144     }
145     s->n = 0;
146
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;
153
154     return picref;
155 }
156
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)
159 {
160     CUdeviceptr src_devptr = (CUdeviceptr)src_dptr;
161     void *args[] = { &histogram, &src_width, &src_height };
162     CUDA_ARRAY_DESCRIPTOR desc;
163
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;
169     }
170     else {
171         desc.Format = CU_AD_FORMAT_UNSIGNED_INT16;
172     }
173
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);
176
177     return 0;
178 }
179
180 static int thumbnail(AVFilterContext *ctx, int *histogram, AVFrame *in)
181 {
182     AVHWFramesContext *in_frames_ctx = (AVHWFramesContext*)in->hw_frames_ctx->data;
183     ThumbnailCudaContext *s = ctx->priv;
184
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);
191         break;
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);
199         break;
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);
207         break;
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);
214         break;
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);
222         break;
223     default:
224         return AVERROR_BUG;
225     }
226
227     return 0;
228 }
229
230 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
231 {
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;
238     CUresult err;
239     CUcontext dummy;
240     CUDA_MEMCPY2D cpy = { 0 };
241     int ret = 0;
242
243     // keep a reference of each frame
244     s->frames[s->n].buf = frame;
245
246     err = cuCtxPushCurrent(device_hwctx->cuda_ctx);
247     if (err != CUDA_SUCCESS)
248         return AVERROR_UNKNOWN;
249
250     cuMemsetD8(s->data, 0, HIST_SIZE * sizeof(int));
251
252     thumbnail(ctx, (int*)s->data, frame);
253
254     cpy.srcMemoryType = CU_MEMORYTYPE_DEVICE;
255     cpy.dstMemoryType = CU_MEMORYTYPE_HOST;
256     cpy.srcDevice = s->data;
257     cpy.dstHost = hist;
258     cpy.srcPitch = HIST_SIZE * sizeof(int);
259     cpy.dstPitch = HIST_SIZE * sizeof(int);
260     cpy.WidthInBytes = HIST_SIZE * sizeof(int);
261     cpy.Height = 1;
262
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;
267     }
268
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)
271     {
272         for (int i = 256; i < HIST_SIZE; i++)
273             hist[i] = 4 * hist[i];
274     }
275
276     cuCtxPopCurrent(&dummy);
277     if (ret < 0)
278         return ret;
279
280     // no selection until the buffer of N frames is filled up
281     s->n++;
282     if (s->n < s->n_frames)
283         return 0;
284
285     return ff_filter_frame(outlink, get_best_frame(ctx));
286 }
287
288 static av_cold void uninit(AVFilterContext *ctx)
289 {
290     int i;
291     ThumbnailCudaContext *s = ctx->priv;
292
293     if (s->data) {
294         cuMemFree(s->data);
295         s->data = 0;
296     }
297
298     if (s->cu_module) {
299         cuModuleUnload(s->cu_module);
300         s->cu_module = NULL;
301     }
302
303     for (i = 0; i < s->n_frames && s->frames[i].buf; i++)
304         av_frame_free(&s->frames[i].buf);
305     av_freep(&s->frames);
306 }
307
308 static int request_frame(AVFilterLink *link)
309 {
310     AVFilterContext *ctx = link->src;
311     ThumbnailCudaContext *s = ctx->priv;
312     int ret = ff_request_frame(ctx->inputs[0]);
313
314     if (ret == AVERROR_EOF && s->n) {
315         ret = ff_filter_frame(link, get_best_frame(ctx));
316         if (ret < 0)
317             return ret;
318         ret = AVERROR_EOF;
319     }
320     if (ret < 0)
321         return ret;
322     return 0;
323 }
324
325 static int format_is_supported(enum AVPixelFormat fmt)
326 {
327     int i;
328
329     for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++)
330         if (supported_formats[i] == fmt)
331             return 1;
332     return 0;
333 }
334
335 static int config_props(AVFilterLink *inlink)
336 {
337     AVFilterContext *ctx = inlink->dst;
338     ThumbnailCudaContext *s = ctx->priv;
339     AVHWFramesContext     *hw_frames_ctx = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
340     AVCUDADeviceContext *device_hwctx = hw_frames_ctx->device_ctx->hwctx;
341     CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
342     CUresult err;
343
344     extern char vf_thumbnail_cuda_ptx[];
345
346     err = cuCtxPushCurrent(cuda_ctx);
347     if (err != CUDA_SUCCESS) {
348         av_log(ctx, AV_LOG_ERROR, "Error pushing cuda context\n");
349         return AVERROR_UNKNOWN;
350     }
351
352     err = cuModuleLoadData(&s->cu_module, vf_thumbnail_cuda_ptx);
353     if (err != CUDA_SUCCESS) {
354         av_log(ctx, AV_LOG_ERROR, "Error loading module data\n");
355         return AVERROR_UNKNOWN;
356     }
357
358     cuModuleGetFunction(&s->cu_func_uchar, s->cu_module, "Thumbnail_uchar");
359     cuModuleGetFunction(&s->cu_func_uchar2, s->cu_module, "Thumbnail_uchar2");
360     cuModuleGetFunction(&s->cu_func_ushort, s->cu_module, "Thumbnail_ushort");
361     cuModuleGetFunction(&s->cu_func_ushort2, s->cu_module, "Thumbnail_ushort2");
362
363     cuModuleGetTexRef(&s->cu_tex_uchar, s->cu_module, "uchar_tex");
364     cuModuleGetTexRef(&s->cu_tex_uchar2, s->cu_module, "uchar2_tex");
365     cuModuleGetTexRef(&s->cu_tex_ushort, s->cu_module, "ushort_tex");
366     cuModuleGetTexRef(&s->cu_tex_ushort2, s->cu_module, "ushort2_tex");
367
368     cuTexRefSetFlags(s->cu_tex_uchar, CU_TRSF_READ_AS_INTEGER);
369     cuTexRefSetFlags(s->cu_tex_uchar2, CU_TRSF_READ_AS_INTEGER);
370     cuTexRefSetFlags(s->cu_tex_ushort, CU_TRSF_READ_AS_INTEGER);
371     cuTexRefSetFlags(s->cu_tex_ushort2, CU_TRSF_READ_AS_INTEGER);
372
373     cuTexRefSetFilterMode(s->cu_tex_uchar, CU_TR_FILTER_MODE_LINEAR);
374     cuTexRefSetFilterMode(s->cu_tex_uchar2, CU_TR_FILTER_MODE_LINEAR);
375     cuTexRefSetFilterMode(s->cu_tex_ushort, CU_TR_FILTER_MODE_LINEAR);
376     cuTexRefSetFilterMode(s->cu_tex_ushort2, CU_TR_FILTER_MODE_LINEAR);
377
378     err = cuMemAlloc(&s->data, HIST_SIZE * sizeof(int));
379     if (err != CUDA_SUCCESS) {
380         av_log(ctx, AV_LOG_ERROR, "Error allocating cuda memory\n");
381         return AVERROR_UNKNOWN;
382     }
383
384     cuCtxPopCurrent(&dummy);
385
386     s->hw_frames_ctx = ctx->inputs[0]->hw_frames_ctx;
387
388     ctx->outputs[0]->hw_frames_ctx = av_buffer_ref(s->hw_frames_ctx);
389     if (!ctx->outputs[0]->hw_frames_ctx)
390         return AVERROR(ENOMEM);
391
392     s->tb = inlink->time_base;
393
394     if (!format_is_supported(hw_frames_ctx->sw_format)) {
395         av_log(ctx, AV_LOG_ERROR, "Unsupported input format: %s\n", av_get_pix_fmt_name(hw_frames_ctx->sw_format));
396         return AVERROR(ENOSYS);
397     }
398
399     return 0;
400 }
401
402 static int query_formats(AVFilterContext *ctx)
403 {
404     static const enum AVPixelFormat pix_fmts[] = {
405         AV_PIX_FMT_CUDA,
406         AV_PIX_FMT_NONE
407     };
408     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
409     if (!fmts_list)
410         return AVERROR(ENOMEM);
411     return ff_set_common_formats(ctx, fmts_list);
412 }
413
414 static const AVFilterPad thumbnail_cuda_inputs[] = {
415     {
416         .name         = "default",
417         .type         = AVMEDIA_TYPE_VIDEO,
418         .config_props = config_props,
419         .filter_frame = filter_frame,
420     },
421     { NULL }
422 };
423
424 static const AVFilterPad thumbnail_cuda_outputs[] = {
425     {
426         .name          = "default",
427         .type          = AVMEDIA_TYPE_VIDEO,
428         .request_frame = request_frame,
429     },
430     { NULL }
431 };
432
433 AVFilter ff_vf_thumbnail_cuda = {
434     .name          = "thumbnail_cuda",
435     .description   = NULL_IF_CONFIG_SMALL("Select the most representative frame in a given sequence of consecutive frames."),
436     .priv_size     = sizeof(ThumbnailCudaContext),
437     .init          = init,
438     .uninit        = uninit,
439     .query_formats = query_formats,
440     .inputs        = thumbnail_cuda_inputs,
441     .outputs       = thumbnail_cuda_outputs,
442     .priv_class    = &thumbnail_cuda_class,
443     .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,
444 };