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/file_open.h"
23 #include "libavutil/mem.h"
24 #include "libavutil/pixdesc.h"
25 
26 #include "formats.h"
27 #include "opencl.h"
28 
30  AVBufferRef *device)
31 {
32  OpenCLFilterContext *ctx = avctx->priv;
33 
34  av_buffer_unref(&ctx->device_ref);
35 
36  ctx->device_ref = av_buffer_ref(device);
37  if (!ctx->device_ref)
38  return AVERROR(ENOMEM);
39 
40  ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
41  ctx->hwctx = ctx->device->hwctx;
42 
43  return 0;
44 }
45 
47 {
48  AVFilterContext *avctx = inlink->dst;
49  OpenCLFilterContext *ctx = avctx->priv;
50  AVHWFramesContext *input_frames;
51  int err;
52 
53  if (!inlink->hw_frames_ctx) {
54  av_log(avctx, AV_LOG_ERROR, "OpenCL filtering requires a "
55  "hardware frames context on the input.\n");
56  return AVERROR(EINVAL);
57  }
58 
59  // Extract the device and default output format from the first input.
60  if (avctx->inputs[0] != inlink)
61  return 0;
62 
63  input_frames = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
64  if (input_frames->format != AV_PIX_FMT_OPENCL)
65  return AVERROR(EINVAL);
66 
67  err = opencl_filter_set_device(avctx, input_frames->device_ref);
68  if (err < 0)
69  return err;
70 
71  // Default output parameters match input parameters.
72  if (ctx->output_format == AV_PIX_FMT_NONE)
73  ctx->output_format = input_frames->sw_format;
74  if (!ctx->output_width)
75  ctx->output_width = inlink->w;
76  if (!ctx->output_height)
77  ctx->output_height = inlink->h;
78 
79  return 0;
80 }
81 
83 {
84  AVFilterContext *avctx = outlink->src;
85  OpenCLFilterContext *ctx = avctx->priv;
86  AVBufferRef *output_frames_ref = NULL;
87  AVHWFramesContext *output_frames;
88  int err;
89 
90  av_buffer_unref(&outlink->hw_frames_ctx);
91 
92  if (!ctx->device_ref) {
93  if (!avctx->hw_device_ctx) {
94  av_log(avctx, AV_LOG_ERROR, "OpenCL filtering requires an "
95  "OpenCL device.\n");
96  return AVERROR(EINVAL);
97  }
98 
99  err = opencl_filter_set_device(avctx, avctx->hw_device_ctx);
100  if (err < 0)
101  return err;
102  }
103 
104  output_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
105  if (!output_frames_ref) {
106  err = AVERROR(ENOMEM);
107  goto fail;
108  }
109  output_frames = (AVHWFramesContext*)output_frames_ref->data;
110 
111  output_frames->format = AV_PIX_FMT_OPENCL;
112  output_frames->sw_format = ctx->output_format;
113  output_frames->width = ctx->output_width;
114  output_frames->height = ctx->output_height;
115 
116  err = av_hwframe_ctx_init(output_frames_ref);
117  if (err < 0) {
118  av_log(avctx, AV_LOG_ERROR, "Failed to initialise output "
119  "frames: %d.\n", err);
120  goto fail;
121  }
122 
123  outlink->hw_frames_ctx = output_frames_ref;
124  outlink->w = ctx->output_width;
125  outlink->h = ctx->output_height;
126 
127  return 0;
128 fail:
129  av_buffer_unref(&output_frames_ref);
130  return err;
131 }
132 
134 {
135  OpenCLFilterContext *ctx = avctx->priv;
136 
137  ctx->output_format = AV_PIX_FMT_NONE;
138 
139  return 0;
140 }
141 
143 {
144  OpenCLFilterContext *ctx = avctx->priv;
145  cl_int cle;
146 
147  if (ctx->program) {
148  cle = clReleaseProgram(ctx->program);
149  if (cle != CL_SUCCESS)
150  av_log(avctx, AV_LOG_ERROR, "Failed to release "
151  "program: %d.\n", cle);
152  }
153 
154  av_buffer_unref(&ctx->device_ref);
155 }
156 
158  const char **program_source_array,
159  int nb_strings)
160 {
161  OpenCLFilterContext *ctx = avctx->priv;
162  cl_int cle;
163 
164  ctx->program = clCreateProgramWithSource(ctx->hwctx->context, nb_strings,
165  program_source_array,
166  NULL, &cle);
167  if (!ctx->program) {
168  av_log(avctx, AV_LOG_ERROR, "Failed to create program: %d.\n", cle);
169  return AVERROR(EIO);
170  }
171 
172  cle = clBuildProgram(ctx->program, 1, &ctx->hwctx->device_id,
173  NULL, NULL, NULL);
174  if (cle != CL_SUCCESS) {
175  av_log(avctx, AV_LOG_ERROR, "Failed to build program: %d.\n", cle);
176 
177  if (cle == CL_BUILD_PROGRAM_FAILURE) {
178  char *log;
179  size_t log_length;
180 
181  clGetProgramBuildInfo(ctx->program, ctx->hwctx->device_id,
182  CL_PROGRAM_BUILD_LOG, 0, NULL, &log_length);
183 
184  log = av_malloc(log_length);
185  if (log) {
186  cle = clGetProgramBuildInfo(ctx->program,
187  ctx->hwctx->device_id,
188  CL_PROGRAM_BUILD_LOG,
189  log_length, log, NULL);
190  if (cle == CL_SUCCESS)
191  av_log(avctx, AV_LOG_ERROR, "Build log:\n%s\n", log);
192  }
193 
194  av_free(log);
195  }
196 
197  clReleaseProgram(ctx->program);
198  ctx->program = NULL;
199  return AVERROR(EIO);
200  }
201 
202  return 0;
203 }
204 
206  const char *filename)
207 {
208  FILE *file;
209  char *src = NULL;
210  size_t pos, len, rb;
211  const char *src_const;
212  int err;
213 
214  file = avpriv_fopen_utf8(filename, "r");
215  if (!file) {
216  av_log(avctx, AV_LOG_ERROR, "Unable to open program "
217  "source file \"%s\".\n", filename);
218  return AVERROR(ENOENT);
219  }
220 
221  len = 1 << 16;
222  pos = 0;
223 
224  err = av_reallocp(&src, len);
225  if (err < 0)
226  goto fail;
227 
228  err = snprintf(src, len, "#line 1 \"%s\"\n", filename);
229  if (err < 0) {
230  err = AVERROR(errno);
231  goto fail;
232  }
233  if (err > len / 2) {
234  err = AVERROR(EINVAL);
235  goto fail;
236  }
237  pos = err;
238 
239  while (1) {
240  rb = fread(src + pos, 1, len - pos - 1, file);
241  if (rb == 0 && ferror(file)) {
242  err = AVERROR(EIO);
243  goto fail;
244  }
245  pos += rb;
246  if (pos + 1 < len)
247  break;
248  len <<= 1;
249  err = av_reallocp(&src, len);
250  if (err < 0)
251  goto fail;
252  }
253  src[pos] = 0;
254 
255  src_const = src;
256 
257  err = ff_opencl_filter_load_program(avctx, &src_const, 1);
258 fail:
259  fclose(file);
260  av_freep(&src);
261  return err;
262 }
263 
265  size_t *work_size,
266  AVFrame *frame, int plane,
267  int block_alignment)
268 {
269  cl_mem image;
270  cl_mem_object_type type;
271  size_t width, height;
272  cl_int cle;
273 
274  if (frame->format != AV_PIX_FMT_OPENCL) {
275  av_log(avctx, AV_LOG_ERROR, "Invalid frame format %s, "
276  "opencl required.\n", av_get_pix_fmt_name(frame->format));
277  return AVERROR(EINVAL);
278  }
279 
280  image = (cl_mem)frame->data[plane];
281  if (!image) {
282  av_log(avctx, AV_LOG_ERROR, "Plane %d required but not set.\n",
283  plane);
284  return AVERROR(EINVAL);
285  }
286 
287  cle = clGetMemObjectInfo(image, CL_MEM_TYPE, sizeof(type),
288  &type, NULL);
289  if (cle != CL_SUCCESS) {
290  av_log(avctx, AV_LOG_ERROR, "Failed to query object type of "
291  "plane %d: %d.\n", plane, cle);
292  return AVERROR_UNKNOWN;
293  }
294  if (type != CL_MEM_OBJECT_IMAGE2D) {
295  av_log(avctx, AV_LOG_ERROR, "Plane %d is not a 2D image.\n",
296  plane);
297  return AVERROR(EINVAL);
298  }
299 
300  cle = clGetImageInfo(image, CL_IMAGE_WIDTH, sizeof(size_t),
301  &width, NULL);
302  if (cle != CL_SUCCESS) {
303  av_log(avctx, AV_LOG_ERROR, "Failed to query plane %d width: %d.\n",
304  plane, cle);
305  return AVERROR_UNKNOWN;
306  }
307 
308  cle = clGetImageInfo(image, CL_IMAGE_HEIGHT, sizeof(size_t),
309  &height, NULL);
310  if (cle != CL_SUCCESS) {
311  av_log(avctx, AV_LOG_ERROR, "Failed to query plane %d height: %d.\n",
312  plane, cle);
313  return AVERROR_UNKNOWN;
314  }
315 
316  if (block_alignment) {
317  width = FFALIGN(width, block_alignment);
318  height = FFALIGN(height, block_alignment);
319  }
320 
321  work_size[0] = width;
322  work_size[1] = height;
323 
324  return 0;
325 }
326 
327 void ff_opencl_print_const_matrix_3x3(AVBPrint *buf, const char *name_str,
328  double mat[3][3])
329 {
330  int i, j;
331  av_bprintf(buf, "__constant float %s[9] = {\n", name_str);
332  for (i = 0; i < 3; i++) {
333  for (j = 0; j < 3; j++)
334  av_bprintf(buf, " %.5ff,", mat[i][j]);
335  av_bprintf(buf, "\n");
336  }
337  av_bprintf(buf, "};\n");
338 }
339 
340 cl_ulong ff_opencl_get_event_time(cl_event event) {
341  cl_ulong time_start;
342  cl_ulong time_end;
343 
344  clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL);
345  clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL);
346 
347  return time_end - time_start;
348 }
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:334
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:330
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:248
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:448
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:157
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:30
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:264
AVFilterContext::priv
void * priv
private data for use by the filter
Definition: avfilter.h:407
fail
#define fail()
Definition: checkasm.h:134
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:82
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
AVHWFramesContext::height
int height
Definition: hwcontext.h:229
width
#define width
ctx
AVFormatContext * ctx
Definition: movenc.c:48
file_open.h
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:400
opencl_filter_set_device
static int opencl_filter_set_device(AVFilterContext *avctx, AVBufferRef *device)
Definition: opencl.c:29
AV_PIX_FMT_OPENCL
@ AV_PIX_FMT_OPENCL
Hardware surfaces for OpenCL.
Definition: pixfmt.h:355
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:186
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:46
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:269
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:327
len
int len
Definition: vorbis_enc_data.h:426
avpriv_fopen_utf8
FILE * avpriv_fopen_utf8(const char *path, const char *mode)
Open a file using a UTF-8 filename.
Definition: file_open.c:159
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:133
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:413
av_bprintf
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition: bprint.c:94
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:205
OpenCLFilterContext
Definition: opencl.h:36
ff_opencl_filter_uninit
void ff_opencl_filter_uninit(AVFilterContext *avctx)
Uninitialise an OpenCL filter context.
Definition: opencl.c:142
AVFilterContext
An instance of a filter.
Definition: avfilter.h:392
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:340
av_free
#define av_free(p)
Definition: tableprint_vlc.h:33
FFALIGN
#define FFALIGN(x, a)
Definition: macros.h:78
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:34
src
INIT_CLIP pixel * src
Definition: h264pred_template.c:418
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
snprintf
#define snprintf
Definition: snprintf.h:34
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:2808