FFmpeg
opencl.c
Go to the documentation of this file.
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18 
19 #include <stdio.h>
20 #include <string.h>
21 
22 #include "libavutil/mem.h"
23 #include "libavutil/pixdesc.h"
24 
25 #include "formats.h"
26 #include "opencl.h"
27 
29 {
30  const static enum AVPixelFormat pix_fmts[] = {
33  };
34 
36 }
37 
39  AVBufferRef *device)
40 {
41  OpenCLFilterContext *ctx = avctx->priv;
42 
43  av_buffer_unref(&ctx->device_ref);
44 
45  ctx->device_ref = av_buffer_ref(device);
46  if (!ctx->device_ref)
47  return AVERROR(ENOMEM);
48 
49  ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
50  ctx->hwctx = ctx->device->hwctx;
51 
52  return 0;
53 }
54 
56 {
57  AVFilterContext *avctx = inlink->dst;
58  OpenCLFilterContext *ctx = avctx->priv;
59  AVHWFramesContext *input_frames;
60  int err;
61 
62  if (!inlink->hw_frames_ctx) {
63  av_log(avctx, AV_LOG_ERROR, "OpenCL filtering requires a "
64  "hardware frames context on the input.\n");
65  return AVERROR(EINVAL);
66  }
67 
68  // Extract the device and default output format from the first input.
69  if (avctx->inputs[0] != inlink)
70  return 0;
71 
72  input_frames = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
73  if (input_frames->format != AV_PIX_FMT_OPENCL)
74  return AVERROR(EINVAL);
75 
76  err = opencl_filter_set_device(avctx, input_frames->device_ref);
77  if (err < 0)
78  return err;
79 
80  // Default output parameters match input parameters.
81  if (ctx->output_format == AV_PIX_FMT_NONE)
82  ctx->output_format = input_frames->sw_format;
83  if (!ctx->output_width)
84  ctx->output_width = inlink->w;
85  if (!ctx->output_height)
86  ctx->output_height = inlink->h;
87 
88  return 0;
89 }
90 
92 {
93  AVFilterContext *avctx = outlink->src;
94  OpenCLFilterContext *ctx = avctx->priv;
95  AVBufferRef *output_frames_ref = NULL;
96  AVHWFramesContext *output_frames;
97  int err;
98 
99  av_buffer_unref(&outlink->hw_frames_ctx);
100 
101  if (!ctx->device_ref) {
102  if (!avctx->hw_device_ctx) {
103  av_log(avctx, AV_LOG_ERROR, "OpenCL filtering requires an "
104  "OpenCL device.\n");
105  return AVERROR(EINVAL);
106  }
107 
108  err = opencl_filter_set_device(avctx, avctx->hw_device_ctx);
109  if (err < 0)
110  return err;
111  }
112 
113  output_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
114  if (!output_frames_ref) {
115  err = AVERROR(ENOMEM);
116  goto fail;
117  }
118  output_frames = (AVHWFramesContext*)output_frames_ref->data;
119 
120  output_frames->format = AV_PIX_FMT_OPENCL;
121  output_frames->sw_format = ctx->output_format;
122  output_frames->width = ctx->output_width;
123  output_frames->height = ctx->output_height;
124 
125  err = av_hwframe_ctx_init(output_frames_ref);
126  if (err < 0) {
127  av_log(avctx, AV_LOG_ERROR, "Failed to initialise output "
128  "frames: %d.\n", err);
129  goto fail;
130  }
131 
132  outlink->hw_frames_ctx = output_frames_ref;
133  outlink->w = ctx->output_width;
134  outlink->h = ctx->output_height;
135 
136  return 0;
137 fail:
138  av_buffer_unref(&output_frames_ref);
139  return err;
140 }
141 
143 {
144  OpenCLFilterContext *ctx = avctx->priv;
145 
146  ctx->output_format = AV_PIX_FMT_NONE;
147 
148  return 0;
149 }
150 
152 {
153  OpenCLFilterContext *ctx = avctx->priv;
154  cl_int cle;
155 
156  if (ctx->program) {
157  cle = clReleaseProgram(ctx->program);
158  if (cle != CL_SUCCESS)
159  av_log(avctx, AV_LOG_ERROR, "Failed to release "
160  "program: %d.\n", cle);
161  }
162 
163  av_buffer_unref(&ctx->device_ref);
164 }
165 
167  const char **program_source_array,
168  int nb_strings)
169 {
170  OpenCLFilterContext *ctx = avctx->priv;
171  cl_int cle;
172 
173  ctx->program = clCreateProgramWithSource(ctx->hwctx->context, nb_strings,
174  program_source_array,
175  NULL, &cle);
176  if (!ctx->program) {
177  av_log(avctx, AV_LOG_ERROR, "Failed to create program: %d.\n", cle);
178  return AVERROR(EIO);
179  }
180 
181  cle = clBuildProgram(ctx->program, 1, &ctx->hwctx->device_id,
182  NULL, NULL, NULL);
183  if (cle != CL_SUCCESS) {
184  av_log(avctx, AV_LOG_ERROR, "Failed to build program: %d.\n", cle);
185 
186  if (cle == CL_BUILD_PROGRAM_FAILURE) {
187  char *log;
188  size_t log_length;
189 
190  clGetProgramBuildInfo(ctx->program, ctx->hwctx->device_id,
191  CL_PROGRAM_BUILD_LOG, 0, NULL, &log_length);
192 
193  log = av_malloc(log_length);
194  if (log) {
195  cle = clGetProgramBuildInfo(ctx->program,
196  ctx->hwctx->device_id,
197  CL_PROGRAM_BUILD_LOG,
198  log_length, log, NULL);
199  if (cle == CL_SUCCESS)
200  av_log(avctx, AV_LOG_ERROR, "Build log:\n%s\n", log);
201  }
202 
203  av_free(log);
204  }
205 
206  clReleaseProgram(ctx->program);
207  ctx->program = NULL;
208  return AVERROR(EIO);
209  }
210 
211  return 0;
212 }
213 
215  const char *filename)
216 {
217  FILE *file;
218  char *src = NULL;
219  size_t pos, len, rb;
220  const char *src_const;
221  int err;
222 
223  file = av_fopen_utf8(filename, "r");
224  if (!file) {
225  av_log(avctx, AV_LOG_ERROR, "Unable to open program "
226  "source file \"%s\".\n", filename);
227  return AVERROR(ENOENT);
228  }
229 
230  len = 1 << 16;
231  pos = 0;
232 
233  err = av_reallocp(&src, len);
234  if (err < 0)
235  goto fail;
236 
237  err = snprintf(src, len, "#line 1 \"%s\"\n", filename);
238  if (err < 0) {
239  err = AVERROR(errno);
240  goto fail;
241  }
242  if (err > len / 2) {
243  err = AVERROR(EINVAL);
244  goto fail;
245  }
246  pos = err;
247 
248  while (1) {
249  rb = fread(src + pos, 1, len - pos - 1, file);
250  if (rb == 0 && ferror(file)) {
251  err = AVERROR(EIO);
252  goto fail;
253  }
254  pos += rb;
255  if (pos < len)
256  break;
257  len <<= 1;
258  err = av_reallocp(&src, len);
259  if (err < 0)
260  goto fail;
261  }
262  src[pos] = 0;
263 
264  src_const = src;
265 
266  err = ff_opencl_filter_load_program(avctx, &src_const, 1);
267 fail:
268  fclose(file);
269  av_freep(&src);
270  return err;
271 }
272 
274  size_t *work_size,
275  AVFrame *frame, int plane,
276  int block_alignment)
277 {
278  cl_mem image;
279  cl_mem_object_type type;
280  size_t width, height;
281  cl_int cle;
282 
283  if (frame->format != AV_PIX_FMT_OPENCL) {
284  av_log(avctx, AV_LOG_ERROR, "Invalid frame format %s, "
285  "opencl required.\n", av_get_pix_fmt_name(frame->format));
286  return AVERROR(EINVAL);
287  }
288 
289  image = (cl_mem)frame->data[plane];
290  if (!image) {
291  av_log(avctx, AV_LOG_ERROR, "Plane %d required but not set.\n",
292  plane);
293  return AVERROR(EINVAL);
294  }
295 
296  cle = clGetMemObjectInfo(image, CL_MEM_TYPE, sizeof(type),
297  &type, NULL);
298  if (cle != CL_SUCCESS) {
299  av_log(avctx, AV_LOG_ERROR, "Failed to query object type of "
300  "plane %d: %d.\n", plane, cle);
301  return AVERROR_UNKNOWN;
302  }
303  if (type != CL_MEM_OBJECT_IMAGE2D) {
304  av_log(avctx, AV_LOG_ERROR, "Plane %d is not a 2D image.\n",
305  plane);
306  return AVERROR(EINVAL);
307  }
308 
309  cle = clGetImageInfo(image, CL_IMAGE_WIDTH, sizeof(size_t),
310  &width, NULL);
311  if (cle != CL_SUCCESS) {
312  av_log(avctx, AV_LOG_ERROR, "Failed to query plane %d width: %d.\n",
313  plane, cle);
314  return AVERROR_UNKNOWN;
315  }
316 
317  cle = clGetImageInfo(image, CL_IMAGE_HEIGHT, sizeof(size_t),
318  &height, NULL);
319  if (cle != CL_SUCCESS) {
320  av_log(avctx, AV_LOG_ERROR, "Failed to query plane %d height: %d.\n",
321  plane, cle);
322  return AVERROR_UNKNOWN;
323  }
324 
325  if (block_alignment) {
326  width = FFALIGN(width, block_alignment);
327  height = FFALIGN(height, block_alignment);
328  }
329 
330  work_size[0] = width;
331  work_size[1] = height;
332 
333  return 0;
334 }
335 
336 void ff_opencl_print_const_matrix_3x3(AVBPrint *buf, const char *name_str,
337  double mat[3][3])
338 {
339  int i, j;
340  av_bprintf(buf, "__constant float %s[9] = {\n", name_str);
341  for (i = 0; i < 3; i++) {
342  for (j = 0; j < 3; j++)
343  av_bprintf(buf, " %.5ff,", mat[i][j]);
344  av_bprintf(buf, "\n");
345  }
346  av_bprintf(buf, "};\n");
347 }
348 
349 cl_ulong ff_opencl_get_event_time(cl_event event) {
350  cl_ulong time_start;
351  cl_ulong time_end;
352 
353  clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL);
354  clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL);
355 
356  return time_end - time_start;
357 }
AVPixelFormat
AVPixelFormat
Pixel format.
Definition: pixfmt.h:64
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
AVBufferRef::data
uint8_t * data
The data buffer.
Definition: buffer.h:90
AVHWFramesContext::format
enum AVPixelFormat format
The pixel format identifying the underlying HW surface type.
Definition: hwcontext.h:209
inlink
The exact code depends on how similar the blocks are and how related they are to the and needs to apply these operations to the correct inlink or outlink if there are several Macros are available to factor that when no extra processing is inlink
Definition: filter_design.txt:212
av_hwframe_ctx_init
int av_hwframe_ctx_init(AVBufferRef *ref)
Finalize the context before use.
Definition: hwcontext.c:333
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:303
pixdesc.h
av_hwframe_ctx_alloc
AVBufferRef * av_hwframe_ctx_alloc(AVBufferRef *device_ref_in)
Allocate an AVHWFramesContext tied to a given device context.
Definition: hwcontext.c:247
opencl.h
AVFilterContext::hw_device_ctx
AVBufferRef * hw_device_ctx
For filters which will create hardware frames, sets the device the filter should create them in.
Definition: avfilter.h:402
ff_opencl_filter_load_program
int ff_opencl_filter_load_program(AVFilterContext *avctx, const char **program_source_array, int nb_strings)
Load a new OpenCL program from strings in memory.
Definition: opencl.c:166
av_buffer_ref
AVBufferRef * av_buffer_ref(const AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition: buffer.c:103
AVERROR_UNKNOWN
#define AVERROR_UNKNOWN
Unknown error, typically from an external library.
Definition: error.h:73
AVHWFramesContext::width
int width
The allocated dimensions of the frames in this pool.
Definition: hwcontext.h:229
av_malloc
#define av_malloc(s)
Definition: tableprint_vlc.h:31
formats.h
ff_opencl_filter_work_size_from_image
int ff_opencl_filter_work_size_from_image(AVFilterContext *avctx, size_t *work_size, AVFrame *frame, int plane, int block_alignment)
Find the work size needed needed for a given plane of an image.
Definition: opencl.c:273
AVFilterContext::priv
void * priv
private data for use by the filter
Definition: avfilter.h:361
fail
#define fail()
Definition: checkasm.h:127
type
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf type
Definition: writing_filters.txt:86
ff_opencl_filter_config_output
int ff_opencl_filter_config_output(AVFilterLink *outlink)
Create a suitable hardware frames context for the output.
Definition: opencl.c:91
AVHWDeviceContext
This struct aggregates all the (hardware/vendor-specific) "high-level" state, i.e.
Definition: hwcontext.h:61
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:180
av_fopen_utf8
FILE * av_fopen_utf8(const char *path, const char *mode)
Open a file using a UTF-8 filename.
Definition: file_open.c:158
AVHWFramesContext::height
int height
Definition: hwcontext.h:229
width
#define width
ff_set_common_formats_from_list
int ff_set_common_formats_from_list(AVFilterContext *ctx, const int *fmts)
Equivalent to ff_set_common_formats(ctx, ff_make_format_list(fmts))
Definition: formats.c:703
pix_fmts
static enum AVPixelFormat pix_fmts[]
Definition: libkvazaar.c:290
ctx
AVFormatContext * ctx
Definition: movenc.c:48
if
if(ret)
Definition: filter_design.txt:179
NULL
#define NULL
Definition: coverity.c:32
AVHWFramesContext::sw_format
enum AVPixelFormat sw_format
The pixel format identifying the actual data layout of the hardware frames.
Definition: hwcontext.h:222
av_buffer_unref
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
Definition: buffer.c:139
AVHWFramesContext::device_ref
AVBufferRef * device_ref
A reference to the parent AVHWDeviceContext.
Definition: hwcontext.h:141
AVFilterContext::inputs
AVFilterLink ** inputs
array of pointers to input links
Definition: avfilter.h:354
src
#define src
Definition: vp8dsp.c:255
opencl_filter_set_device
static int opencl_filter_set_device(AVFilterContext *avctx, AVBufferRef *device)
Definition: opencl.c:38
AV_PIX_FMT_OPENCL
@ AV_PIX_FMT_OPENCL
Hardware surfaces for OpenCL.
Definition: pixfmt.h:325
av_reallocp
int av_reallocp(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory through a pointer to a pointer.
Definition: mem.c:185
height
#define height
ff_opencl_filter_config_input
int ff_opencl_filter_config_input(AVFilterLink *inlink)
Check that the input link contains a suitable hardware frames context and extract the device from it.
Definition: opencl.c:55
i
int i
Definition: input.c:406
ff_opencl_print_const_matrix_3x3
void ff_opencl_print_const_matrix_3x3(AVBPrint *buf, const char *name_str, double mat[3][3])
Print a 3x3 matrix into a buffer as __constant array, which could be included in an OpenCL program.
Definition: opencl.c:336
len
int len
Definition: vorbis_enc_data.h:426
AVHWFramesContext
This struct describes a set or pool of "hardware" frames (i.e.
Definition: hwcontext.h:124
ff_opencl_filter_init
int ff_opencl_filter_init(AVFilterContext *avctx)
Initialise an OpenCL filter context.
Definition: opencl.c:142
frame
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return or at least make progress towards producing a frame
Definition: filter_design.txt:264
pos
unsigned int pos
Definition: spdifenc.c:412
av_bprintf
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition: bprint.c:93
AV_PIX_FMT_NONE
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:65
ff_opencl_filter_load_program_from_file
int ff_opencl_filter_load_program_from_file(AVFilterContext *avctx, const char *filename)
Load a new OpenCL program from a file.
Definition: opencl.c:214
OpenCLFilterContext
Definition: opencl.h:36
ff_opencl_filter_uninit
void ff_opencl_filter_uninit(AVFilterContext *avctx)
Uninitialise an OpenCL filter context.
Definition: opencl.c:151
AVFilterContext
An instance of a filter.
Definition: avfilter.h:346
mem.h
AVBufferRef
A reference to a data buffer.
Definition: buffer.h:82
ff_opencl_get_event_time
cl_ulong ff_opencl_get_event_time(cl_event event)
Gets the command start and end times for the given event and returns the difference (the time that th...
Definition: opencl.c:349
av_free
#define av_free(p)
Definition: tableprint_vlc.h:34
FFALIGN
#define FFALIGN(x, a)
Definition: macros.h:78
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:35
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:28
snprintf
#define snprintf
Definition: snprintf.h:34
ff_opencl_filter_query_formats
int ff_opencl_filter_query_formats(AVFilterContext *avctx)
Return that all inputs and outputs support only AV_PIX_FMT_OPENCL.
Definition: opencl.c:28
av_get_pix_fmt_name
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
Definition: pixdesc.c:2460