avutil/opencl: check strtol for failure
[ffmpeg.git] / libavutil / opencl.c
1 /*
2  * Copyright (C) 2012 Peng Gao <peng@multicorewareinc.com>
3  * Copyright (C) 2012 Li   Cao <li@multicorewareinc.com>
4  * Copyright (C) 2012 Wei  Gao <weigao@multicorewareinc.com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "opencl.h"
24 #include "avstring.h"
25 #include "log.h"
26 #include "avassert.h"
27
28 #if HAVE_PTHREADS
29
30 #include <pthread.h>
31 static pthread_mutex_t atomic_opencl_lock = PTHREAD_MUTEX_INITIALIZER;
32
33 #define LOCK_OPENCL pthread_mutex_lock(&atomic_opencl_lock);
34 #define UNLOCK_OPENCL pthread_mutex_unlock(&atomic_opencl_lock);
35
36 #elif !HAVE_THREADS
37 #define LOCK_OPENCL
38 #define UNLOCK_OPENCL
39 #endif
40
41
42 #define MAX_KERNEL_NUM 500
43 #define MAX_KERNEL_CODE_NUM 200
44
45 typedef struct {
46     int dev_idx;
47     int platform_idx;
48 } UserSpecDevInfo;
49
50 typedef struct {
51     int is_compiled;
52     const char *kernel_string;
53 } KernelCode;
54
55 typedef struct {
56     int init_count;
57     UserSpecDevInfo usr_spec_dev_info;
58     cl_platform_id platform_id;
59     cl_device_type device_type;
60     cl_context context;
61     cl_device_id *device_ids;
62     cl_device_id device_id;
63     cl_command_queue command_queue;
64     int program_count;
65     cl_program programs[MAX_KERNEL_CODE_NUM];
66     int kernel_code_count;
67     KernelCode kernel_code[MAX_KERNEL_CODE_NUM];
68     int kernel_count;
69     /**
70      * if set to 1, the OpenCL environment was created by the user and
71      * passed as AVOpenCLExternalEnv when initing ,0:created by opencl wrapper.
72      */
73     int is_user_created;
74 } GPUEnv;
75
76 typedef struct {
77     const AVClass *class;
78     int log_offset;
79     void *log_ctx;
80 } OpenclUtils;
81
82 static const AVClass openclutils_class = {
83     .class_name                = "OPENCLUTILS",
84     .item_name                 = av_default_item_name,
85     .version                   = LIBAVUTIL_VERSION_INT,
86     .log_level_offset_offset   = offsetof(OpenclUtils, log_offset),
87     .parent_log_context_offset = offsetof(OpenclUtils, log_ctx),
88 };
89
90 static OpenclUtils openclutils = {&openclutils_class};
91
92 static GPUEnv gpu_env;
93
94 typedef struct {
95     int err_code;
96     const char *err_str;
97 } OpenclErrorMsg;
98
99 static const OpenclErrorMsg opencl_err_msg[] = {
100     {CL_DEVICE_NOT_FOUND,                               "DEVICE NOT FOUND"},
101     {CL_DEVICE_NOT_AVAILABLE,                           "DEVICE NOT AVAILABLE"},
102     {CL_COMPILER_NOT_AVAILABLE,                         "COMPILER NOT AVAILABLE"},
103     {CL_MEM_OBJECT_ALLOCATION_FAILURE,                  "MEM OBJECT ALLOCATION FAILURE"},
104     {CL_OUT_OF_RESOURCES,                               "OUT OF RESOURCES"},
105     {CL_OUT_OF_HOST_MEMORY,                             "OUT OF HOST MEMORY"},
106     {CL_PROFILING_INFO_NOT_AVAILABLE,                   "PROFILING INFO NOT AVAILABLE"},
107     {CL_MEM_COPY_OVERLAP,                               "MEM COPY OVERLAP"},
108     {CL_IMAGE_FORMAT_MISMATCH,                          "IMAGE FORMAT MISMATCH"},
109     {CL_IMAGE_FORMAT_NOT_SUPPORTED,                     "IMAGE FORMAT NOT_SUPPORTED"},
110     {CL_BUILD_PROGRAM_FAILURE,                          "BUILD PROGRAM FAILURE"},
111     {CL_MAP_FAILURE,                                    "MAP FAILURE"},
112     {CL_MISALIGNED_SUB_BUFFER_OFFSET,                   "MISALIGNED SUB BUFFER OFFSET"},
113     {CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST,      "EXEC STATUS ERROR FOR EVENTS IN WAIT LIST"},
114     {CL_COMPILE_PROGRAM_FAILURE,                        "COMPILE PROGRAM FAILURE"},
115     {CL_LINKER_NOT_AVAILABLE,                           "LINKER NOT AVAILABLE"},
116     {CL_LINK_PROGRAM_FAILURE,                           "LINK PROGRAM FAILURE"},
117     {CL_DEVICE_PARTITION_FAILED,                        "DEVICE PARTITION FAILED"},
118     {CL_KERNEL_ARG_INFO_NOT_AVAILABLE,                  "KERNEL ARG INFO NOT AVAILABLE"},
119     {CL_INVALID_VALUE,                                  "INVALID VALUE"},
120     {CL_INVALID_DEVICE_TYPE,                            "INVALID DEVICE TYPE"},
121     {CL_INVALID_PLATFORM,                               "INVALID PLATFORM"},
122     {CL_INVALID_DEVICE,                                 "INVALID DEVICE"},
123     {CL_INVALID_CONTEXT,                                "INVALID CONTEXT"},
124     {CL_INVALID_QUEUE_PROPERTIES,                       "INVALID QUEUE PROPERTIES"},
125     {CL_INVALID_COMMAND_QUEUE,                          "INVALID COMMAND QUEUE"},
126     {CL_INVALID_HOST_PTR,                               "INVALID HOST PTR"},
127     {CL_INVALID_MEM_OBJECT,                             "INVALID MEM OBJECT"},
128     {CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,                "INVALID IMAGE FORMAT DESCRIPTOR"},
129     {CL_INVALID_IMAGE_SIZE,                             "INVALID IMAGE SIZE"},
130     {CL_INVALID_SAMPLER,                                "INVALID SAMPLER"},
131     {CL_INVALID_BINARY,                                 "INVALID BINARY"},
132     {CL_INVALID_BUILD_OPTIONS,                          "INVALID BUILD OPTIONS"},
133     {CL_INVALID_PROGRAM,                                "INVALID PROGRAM"},
134     {CL_INVALID_PROGRAM_EXECUTABLE,                     "INVALID PROGRAM EXECUTABLE"},
135     {CL_INVALID_KERNEL_NAME,                            "INVALID KERNEL NAME"},
136     {CL_INVALID_KERNEL_DEFINITION,                      "INVALID KERNEL DEFINITION"},
137     {CL_INVALID_KERNEL,                                 "INVALID KERNEL"},
138     {CL_INVALID_ARG_INDEX,                              "INVALID ARG INDEX"},
139     {CL_INVALID_ARG_VALUE,                              "INVALID ARG VALUE"},
140     {CL_INVALID_ARG_SIZE,                               "INVALID ARG_SIZE"},
141     {CL_INVALID_KERNEL_ARGS,                            "INVALID KERNEL ARGS"},
142     {CL_INVALID_WORK_DIMENSION,                         "INVALID WORK DIMENSION"},
143     {CL_INVALID_WORK_GROUP_SIZE,                        "INVALID WORK GROUP SIZE"},
144     {CL_INVALID_WORK_ITEM_SIZE,                         "INVALID WORK ITEM SIZE"},
145     {CL_INVALID_GLOBAL_OFFSET,                          "INVALID GLOBAL OFFSET"},
146     {CL_INVALID_EVENT_WAIT_LIST,                        "INVALID EVENT WAIT LIST"},
147     {CL_INVALID_EVENT,                                  "INVALID EVENT"},
148     {CL_INVALID_OPERATION,                              "INVALID OPERATION"},
149     {CL_INVALID_GL_OBJECT,                              "INVALID GL OBJECT"},
150     {CL_INVALID_BUFFER_SIZE,                            "INVALID BUFFER SIZE"},
151     {CL_INVALID_MIP_LEVEL,                              "INVALID MIP LEVEL"},
152     {CL_INVALID_GLOBAL_WORK_SIZE,                       "INVALID GLOBAL WORK SIZE"},
153     {CL_INVALID_PROPERTY,                               "INVALID PROPERTY"},
154     {CL_INVALID_IMAGE_DESCRIPTOR,                       "INVALID IMAGE DESCRIPTOR"},
155     {CL_INVALID_COMPILER_OPTIONS,                       "INVALID COMPILER OPTIONS"},
156     {CL_INVALID_LINKER_OPTIONS,                         "INVALID LINKER OPTIONS"},
157     {CL_INVALID_DEVICE_PARTITION_COUNT,                 "INVALID DEVICE PARTITION COUNT"},
158 };
159
160 static const char *opencl_errstr(cl_int status)
161 {
162     int i;
163     for (i = 0; i < sizeof(opencl_err_msg); i++) {
164         if (opencl_err_msg[i].err_code == status)
165             return opencl_err_msg[i].err_str;
166     }
167     return "unknown error";
168 }
169
170 AVOpenCLExternalEnv *av_opencl_alloc_external_env(void)
171 {
172     AVOpenCLExternalEnv *ext = av_mallocz(sizeof(AVOpenCLExternalEnv));
173     if (!ext) {
174         av_log(&openclutils, AV_LOG_ERROR,
175                "Could not malloc external opencl environment data space\n");
176     }
177     return ext;
178 }
179
180 void av_opencl_free_external_env(AVOpenCLExternalEnv **ext_opencl_env)
181 {
182     av_freep(ext_opencl_env);
183 }
184
185 int av_opencl_register_kernel_code(const char *kernel_code)
186 {
187     int i, ret = 0;
188     LOCK_OPENCL;
189     if (gpu_env.kernel_code_count >= MAX_KERNEL_CODE_NUM) {
190         av_log(&openclutils, AV_LOG_ERROR,
191                "Could not register kernel code, maximum number of registered kernel code %d already reached\n",
192                MAX_KERNEL_CODE_NUM);
193         ret = AVERROR(EINVAL);
194         goto end;
195     }
196     for (i = 0; i < gpu_env.kernel_code_count; i++) {
197         if (gpu_env.kernel_code[i].kernel_string == kernel_code) {
198             av_log(&openclutils, AV_LOG_WARNING, "Same kernel code has been registered\n");
199             goto end;
200         }
201     }
202     gpu_env.kernel_code[gpu_env.kernel_code_count].kernel_string = kernel_code;
203     gpu_env.kernel_code[gpu_env.kernel_code_count].is_compiled = 0;
204     gpu_env.kernel_code_count++;
205 end:
206     UNLOCK_OPENCL;
207     return ret;
208 }
209
210 int av_opencl_create_kernel(AVOpenCLKernelEnv *env, const char *kernel_name)
211 {
212     cl_int status;
213     int i, ret = 0;
214     LOCK_OPENCL;
215     if (strlen(kernel_name) + 1 > AV_OPENCL_MAX_KERNEL_NAME_SIZE) {
216         av_log(&openclutils, AV_LOG_ERROR, "Created kernel name %s is too long\n", kernel_name);
217         ret = AVERROR(EINVAL);
218         goto end;
219     }
220     if (!env->kernel) {
221         if (gpu_env.kernel_count >= MAX_KERNEL_NUM) {
222             av_log(&openclutils, AV_LOG_ERROR,
223                    "Could not create kernel with name '%s', maximum number of kernels %d already reached\n",
224                    kernel_name, MAX_KERNEL_NUM);
225             ret = AVERROR(EINVAL);
226             goto end;
227         }
228         if (gpu_env.program_count == 0) {
229             av_log(&openclutils, AV_LOG_ERROR, "Program count of OpenCL is 0, can not create kernel\n");
230             ret = AVERROR(EINVAL);
231             goto end;
232         }
233         for (i = 0; i < gpu_env.program_count; i++) {
234             env->kernel = clCreateKernel(gpu_env.programs[i], kernel_name, &status);
235             if (status == CL_SUCCESS)
236                 break;
237         }
238         if (status != CL_SUCCESS) {
239             av_log(&openclutils, AV_LOG_ERROR, "Could not create OpenCL kernel: %s\n", opencl_errstr(status));
240             ret = AVERROR_EXTERNAL;
241             goto end;
242         }
243         gpu_env.kernel_count++;
244         env->command_queue = gpu_env.command_queue;
245         av_strlcpy(env->kernel_name, kernel_name, sizeof(env->kernel_name));
246     }
247 end:
248     UNLOCK_OPENCL;
249     return ret;
250 }
251
252 void av_opencl_release_kernel(AVOpenCLKernelEnv *env)
253 {
254     cl_int status;
255     LOCK_OPENCL
256     if (!env->kernel)
257         goto end;
258     status = clReleaseKernel(env->kernel);
259     if (status != CL_SUCCESS) {
260         av_log(&openclutils, AV_LOG_ERROR, "Could not release kernel: %s\n",
261               opencl_errstr(status));
262     }
263     env->kernel = NULL;
264     env->command_queue = NULL;
265     env->kernel_name[0] = 0;
266     gpu_env.kernel_count--;
267 end:
268     UNLOCK_OPENCL
269 }
270
271 static int init_opencl_env(GPUEnv *gpu_env, AVOpenCLExternalEnv *ext_opencl_env)
272 {
273     size_t device_length;
274     cl_int status;
275     cl_uint num_platforms, num_devices;
276     cl_platform_id *platform_ids = NULL;
277     cl_context_properties cps[3];
278     char platform_name[100];
279     int i, ret = 0;
280     cl_device_type device_type[] = {CL_DEVICE_TYPE_GPU, CL_DEVICE_TYPE_CPU, CL_DEVICE_TYPE_DEFAULT};
281     if (ext_opencl_env) {
282         if (gpu_env->is_user_created)
283             return 0;
284         gpu_env->platform_id     = ext_opencl_env->platform_id;
285         gpu_env->is_user_created = 1;
286         gpu_env->command_queue   = ext_opencl_env->command_queue;
287         gpu_env->context         = ext_opencl_env->context;
288         gpu_env->device_ids      = ext_opencl_env->device_ids;
289         gpu_env->device_id       = ext_opencl_env->device_id;
290         gpu_env->device_type     = ext_opencl_env->device_type;
291     } else {
292         if (!gpu_env->is_user_created) {
293             status = clGetPlatformIDs(0, NULL, &num_platforms);
294             if (status != CL_SUCCESS) {
295                 av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL platform ids: %s\n", opencl_errstr(status));
296                 return AVERROR_EXTERNAL;
297             }
298             if (gpu_env->usr_spec_dev_info.platform_idx >= 0) {
299                 if (num_platforms < gpu_env->usr_spec_dev_info.platform_idx + 1) {
300                     av_log(&openclutils, AV_LOG_ERROR, "User set platform index not exist\n");
301                     return AVERROR(EINVAL);
302                 }
303             }
304             if (num_platforms > 0) {
305                 platform_ids = av_mallocz(num_platforms * sizeof(cl_platform_id));
306                 if (!platform_ids) {
307                     ret = AVERROR(ENOMEM);
308                     goto end;
309                 }
310                 status = clGetPlatformIDs(num_platforms, platform_ids, NULL);
311                 if (status != CL_SUCCESS) {
312                     av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL platform ids: %s\n", opencl_errstr(status));
313                     ret = AVERROR_EXTERNAL;
314                     goto end;
315                 }
316                 i = 0;
317                 if (gpu_env->usr_spec_dev_info.platform_idx >= 0) {
318                     i = gpu_env->usr_spec_dev_info.platform_idx;
319                 }
320                 while (i < num_platforms) {
321                     status = clGetPlatformInfo(platform_ids[i], CL_PLATFORM_VENDOR,
322                                                sizeof(platform_name), platform_name,
323                                                NULL);
324
325                     if (status != CL_SUCCESS) {
326                         av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL platform info: %s\n", opencl_errstr(status));
327                         ret = AVERROR_EXTERNAL;
328                         goto end;
329                     }
330                     gpu_env->platform_id = platform_ids[i];
331                     status = clGetDeviceIDs(gpu_env->platform_id, CL_DEVICE_TYPE_GPU,
332                                             0, NULL, &num_devices);
333                     if (status != CL_SUCCESS) {
334                         av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL device number:%s\n", opencl_errstr(status));
335                         ret = AVERROR_EXTERNAL;
336                         goto end;
337                     }
338                     if (num_devices == 0) {
339                         //find CPU device
340                         status = clGetDeviceIDs(gpu_env->platform_id, CL_DEVICE_TYPE_CPU,
341                                              0, NULL, &num_devices);
342                     }
343                     if (status != CL_SUCCESS) {
344                         av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL device ids: %s\n", opencl_errstr(status));
345                         ret = AVERROR(EINVAL);
346                         goto end;
347                     }
348                     if (num_devices)
349                        break;
350                     if (gpu_env->usr_spec_dev_info.platform_idx >= 0) {
351                         av_log(&openclutils, AV_LOG_ERROR, "Device number of user set platform is 0\n");
352                         ret = AVERROR_EXTERNAL;
353                         goto end;
354                     }
355                     i++;
356
357                 }
358             }
359             if (!gpu_env->platform_id) {
360                 av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL platforms\n");
361                 ret = AVERROR_EXTERNAL;
362                 goto end;
363             }
364             if (gpu_env->usr_spec_dev_info.dev_idx >= 0) {
365                 if (num_devices < gpu_env->usr_spec_dev_info.dev_idx + 1) {
366                     av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL device idx in the user set platform\n");
367                     ret = AVERROR(EINVAL);
368                     goto end;
369                 }
370             }
371
372             /*
373              * Use available platform.
374              */
375             av_log(&openclutils, AV_LOG_VERBOSE, "Platform Name: %s\n", platform_name);
376             cps[0] = CL_CONTEXT_PLATFORM;
377             cps[1] = (cl_context_properties)gpu_env->platform_id;
378             cps[2] = 0;
379
380             /* Check for GPU. */
381             for (i = 0; i < sizeof(device_type); i++) {
382                 gpu_env->device_type = device_type[i];
383                 gpu_env->context     = clCreateContextFromType(cps, gpu_env->device_type,
384                                                                NULL, NULL, &status);
385                 if (status != CL_SUCCESS) {
386                     av_log(&openclutils, AV_LOG_ERROR,
387                            "Could not get OpenCL context from device type: %s\n", opencl_errstr(status));
388                     ret = AVERROR_EXTERNAL;
389                     goto end;
390                 }
391                 if (gpu_env->context)
392                     break;
393             }
394             if (!gpu_env->context) {
395                 av_log(&openclutils, AV_LOG_ERROR,
396                        "Could not get OpenCL context from device type\n");
397                 ret = AVERROR_EXTERNAL;
398                 goto end;
399             }
400             /* Detect OpenCL devices. */
401             /* First, get the size of device list data */
402             status = clGetContextInfo(gpu_env->context, CL_CONTEXT_DEVICES,
403                                       0, NULL, &device_length);
404             if (status != CL_SUCCESS) {
405                 av_log(&openclutils, AV_LOG_ERROR,
406                        "Could not get OpenCL device length: %s\n", opencl_errstr(status));
407                 ret = AVERROR_EXTERNAL;
408                 goto end;
409             }
410             if (device_length == 0) {
411                 av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL device length\n");
412                 ret = AVERROR_EXTERNAL;
413                 goto end;
414             }
415             /* Now allocate memory for device list based on the size we got earlier */
416             gpu_env->device_ids = av_mallocz(device_length);
417             if (!gpu_env->device_ids) {
418                 ret = AVERROR(ENOMEM);
419                 goto end;
420             }
421             /* Now, get the device list data */
422             status = clGetContextInfo(gpu_env->context, CL_CONTEXT_DEVICES, device_length,
423                                       gpu_env->device_ids, NULL);
424             if (status != CL_SUCCESS) {
425                 av_log(&openclutils, AV_LOG_ERROR,
426                        "Could not get OpenCL context info: %s\n", opencl_errstr(status));
427                 ret = AVERROR_EXTERNAL;
428                 goto end;
429             }
430             /* Create OpenCL command queue. */
431             i = 0;
432             if (gpu_env->usr_spec_dev_info.dev_idx >= 0) {
433                 i = gpu_env->usr_spec_dev_info.dev_idx;
434             }
435             gpu_env->command_queue = clCreateCommandQueue(gpu_env->context, gpu_env->device_ids[i],
436                                                           0, &status);
437             if (status != CL_SUCCESS) {
438                 av_log(&openclutils, AV_LOG_ERROR,
439                        "Could not create OpenCL command queue: %s\n", opencl_errstr(status));
440                 ret = AVERROR_EXTERNAL;
441                 goto end;
442             }
443         }
444     }
445 end:
446     av_free(platform_ids);
447     return ret;
448 }
449
450 static int compile_kernel_file(GPUEnv *gpu_env, const char *build_options)
451 {
452     cl_int status;
453     char *temp, *source_str = NULL;
454     size_t source_str_len = 0;
455     int i, ret = 0;
456
457     for (i = 0; i < gpu_env->kernel_code_count; i++) {
458         if (!gpu_env->kernel_code[i].is_compiled)
459             source_str_len += strlen(gpu_env->kernel_code[i].kernel_string);
460     }
461     if (!source_str_len) {
462         return 0;
463     }
464     source_str = av_mallocz(source_str_len + 1);
465     if (!source_str) {
466         return AVERROR(ENOMEM);
467     }
468     temp = source_str;
469     for (i = 0; i < gpu_env->kernel_code_count; i++) {
470         if (!gpu_env->kernel_code[i].is_compiled) {
471             memcpy(temp, gpu_env->kernel_code[i].kernel_string,
472                         strlen(gpu_env->kernel_code[i].kernel_string));
473             gpu_env->kernel_code[i].is_compiled = 1;
474             temp += strlen(gpu_env->kernel_code[i].kernel_string);
475         }
476     }
477     /* create a CL program using the kernel source */
478     gpu_env->programs[gpu_env->program_count] = clCreateProgramWithSource(gpu_env->context,
479                                                            1, (const char **)(&source_str),
480                                                                    &source_str_len, &status);
481     if(status != CL_SUCCESS) {
482         av_log(&openclutils, AV_LOG_ERROR,
483                "Could not create OpenCL program with source code: %s\n", opencl_errstr(status));
484         ret = AVERROR_EXTERNAL;
485         goto end;
486     }
487     if (!gpu_env->programs[gpu_env->program_count]) {
488         av_log(&openclutils, AV_LOG_ERROR, "Created program is NULL\n");
489         ret = AVERROR_EXTERNAL;
490         goto end;
491     }
492     i = 0;
493     if (gpu_env->usr_spec_dev_info.dev_idx >= 0)
494         i = gpu_env->usr_spec_dev_info.dev_idx;
495     /* create a cl program executable for all the devices specified */
496     if (!gpu_env->is_user_created)
497         status = clBuildProgram(gpu_env->programs[gpu_env->program_count], 1, &gpu_env->device_ids[i],
498                                 build_options, NULL, NULL);
499     else
500         status = clBuildProgram(gpu_env->programs[gpu_env->program_count], 1, &(gpu_env->device_id),
501                                  build_options, NULL, NULL);
502
503     if (status != CL_SUCCESS) {
504         av_log(&openclutils, AV_LOG_ERROR,
505                "Could not compile OpenCL kernel: %s\n", opencl_errstr(status));
506         ret = AVERROR_EXTERNAL;
507         goto end;
508     }
509     gpu_env->program_count++;
510 end:
511     av_free(source_str);
512     return ret;
513 }
514
515 int av_opencl_init(AVDictionary *options, AVOpenCLExternalEnv *ext_opencl_env)
516 {
517     int ret = 0;
518     AVDictionaryEntry *opt_build_entry;
519     AVDictionaryEntry *opt_platform_entry;
520     AVDictionaryEntry *opt_device_entry;
521     char *pos;
522     LOCK_OPENCL
523     if (!gpu_env.init_count) {
524         opt_platform_entry = av_dict_get(options, "platform_idx", NULL, 0);
525         opt_device_entry   = av_dict_get(options, "device_idx", NULL, 0);
526         /* initialize devices, context, command_queue */
527         gpu_env.usr_spec_dev_info.platform_idx = -1;
528         gpu_env.usr_spec_dev_info.dev_idx = -1;
529         if (opt_platform_entry) {
530             gpu_env.usr_spec_dev_info.platform_idx = strtol(opt_platform_entry->value, &pos, 10);
531             if (pos == opt_platform_entry->value) {
532                 av_log(&openclutils, AV_LOG_ERROR, "Platform index should be a number\n");
533                 ret = AVERROR(EINVAL);
534                 goto end;
535             }
536         }
537         if (opt_device_entry) {
538             gpu_env.usr_spec_dev_info.dev_idx = strtol(opt_device_entry->value, &pos, 10);
539             if (pos == opt_platform_entry->value) {
540                 av_log(&openclutils, AV_LOG_ERROR, "Device index should be a number\n");
541                 ret = AVERROR(EINVAL);
542                 goto end;
543             }
544         }
545         ret = init_opencl_env(&gpu_env, ext_opencl_env);
546         if (ret < 0)
547             goto end;
548     }
549     /*initialize program, kernel_name, kernel_count*/
550     opt_build_entry = av_dict_get(options, "build_options", NULL, 0);
551     if (opt_build_entry)
552         ret = compile_kernel_file(&gpu_env, opt_build_entry->value);
553     else
554         ret = compile_kernel_file(&gpu_env, NULL);
555     if (ret < 0)
556         goto end;
557     av_assert1(gpu_env.kernel_code_count > 0);
558     gpu_env.init_count++;
559
560 end:
561     UNLOCK_OPENCL
562     return ret;
563 }
564
565 void av_opencl_uninit(void)
566 {
567     cl_int status;
568     int i;
569     LOCK_OPENCL
570     gpu_env.init_count--;
571     if (gpu_env.is_user_created)
572         goto end;
573     if (gpu_env.init_count > 0 || gpu_env.kernel_count > 0)
574         goto end;
575     for (i = 0; i < gpu_env.program_count; i++) {
576         if (gpu_env.programs[i]) {
577             status = clReleaseProgram(gpu_env.programs[i]);
578             if (status != CL_SUCCESS) {
579                 av_log(&openclutils, AV_LOG_ERROR,
580                        "Could not release OpenCL program: %s\n", opencl_errstr(status));
581             }
582             gpu_env.programs[i] = NULL;
583         }
584     }
585     if (gpu_env.command_queue) {
586         status = clReleaseCommandQueue(gpu_env.command_queue);
587         if (status != CL_SUCCESS) {
588             av_log(&openclutils, AV_LOG_ERROR,
589                    "Could not release OpenCL command queue: %s\n", opencl_errstr(status));
590         }
591         gpu_env.command_queue = NULL;
592     }
593     if (gpu_env.context) {
594         status = clReleaseContext(gpu_env.context);
595         if (status != CL_SUCCESS) {
596             av_log(&openclutils, AV_LOG_ERROR,
597                    "Could not release OpenCL context: %s\n", opencl_errstr(status));
598         }
599         gpu_env.context = NULL;
600     }
601     av_freep(&(gpu_env.device_ids));
602 end:
603     UNLOCK_OPENCL
604 }
605
606 int av_opencl_buffer_create(cl_mem *cl_buf, size_t cl_buf_size, int flags, void *host_ptr)
607 {
608     cl_int status;
609     *cl_buf = clCreateBuffer(gpu_env.context, flags, cl_buf_size, host_ptr, &status);
610     if (status != CL_SUCCESS) {
611         av_log(&openclutils, AV_LOG_ERROR, "Could not create OpenCL buffer: %s\n", opencl_errstr(status));
612         return AVERROR_EXTERNAL;
613     }
614     return 0;
615 }
616
617 void av_opencl_buffer_release(cl_mem *cl_buf)
618 {
619     cl_int status = 0;
620     if (!cl_buf)
621         return;
622     status = clReleaseMemObject(*cl_buf);
623     if (status != CL_SUCCESS) {
624         av_log(&openclutils, AV_LOG_ERROR,
625                "Could not release OpenCL buffer: %s\n", opencl_errstr(status));
626     }
627     memset(cl_buf, 0, sizeof(*cl_buf));
628 }
629
630 int av_opencl_buffer_write(cl_mem dst_cl_buf, uint8_t *src_buf, size_t buf_size)
631 {
632     cl_int status;
633     void *mapped = clEnqueueMapBuffer(gpu_env.command_queue, dst_cl_buf,
634                                       CL_TRUE,CL_MAP_WRITE, 0, sizeof(uint8_t) * buf_size,
635                                       0, NULL, NULL, &status);
636
637     if (status != CL_SUCCESS) {
638         av_log(&openclutils, AV_LOG_ERROR,
639                "Could not map OpenCL buffer: %s\n", opencl_errstr(status));
640         return AVERROR_EXTERNAL;
641     }
642     memcpy(mapped, src_buf, buf_size);
643
644     status = clEnqueueUnmapMemObject(gpu_env.command_queue, dst_cl_buf, mapped, 0, NULL, NULL);
645     if (status != CL_SUCCESS) {
646         av_log(&openclutils, AV_LOG_ERROR,
647                "Could not unmap OpenCL buffer: %s\n", opencl_errstr(status));
648         return AVERROR_EXTERNAL;
649     }
650     return 0;
651 }
652
653 int av_opencl_buffer_read(uint8_t *dst_buf, cl_mem src_cl_buf, size_t buf_size)
654 {
655     cl_int status;
656     void *mapped = clEnqueueMapBuffer(gpu_env.command_queue, src_cl_buf,
657                                       CL_TRUE,CL_MAP_READ, 0, buf_size,
658                                       0, NULL, NULL, &status);
659
660     if (status != CL_SUCCESS) {
661         av_log(&openclutils, AV_LOG_ERROR,
662                "Could not map OpenCL buffer: %s\n", opencl_errstr(status));
663         return AVERROR_EXTERNAL;
664     }
665     memcpy(dst_buf, mapped, buf_size);
666
667     status = clEnqueueUnmapMemObject(gpu_env.command_queue, src_cl_buf, mapped, 0, NULL, NULL);
668     if (status != CL_SUCCESS) {
669         av_log(&openclutils, AV_LOG_ERROR,
670                "Could not unmap OpenCL buffer: %s\n", opencl_errstr(status));
671         return AVERROR_EXTERNAL;
672     }
673     return 0;
674 }
675
676 int av_opencl_buffer_write_image(cl_mem dst_cl_buf, size_t cl_buffer_size, int dst_cl_offset,
677                                  uint8_t **src_data, int *plane_size, int plane_num)
678 {
679     int i, buffer_size = 0;
680     uint8_t *temp;
681     cl_int status;
682     void *mapped;
683     if ((unsigned int)plane_num > 8) {
684         return AVERROR(EINVAL);
685     }
686     for (i = 0;i < plane_num;i++) {
687         buffer_size += plane_size[i];
688     }
689     if (buffer_size > cl_buffer_size) {
690         av_log(&openclutils, AV_LOG_ERROR,
691                "Cannot write image to OpenCL buffer: buffer too small\n");
692         return AVERROR(EINVAL);
693     }
694     mapped = clEnqueueMapBuffer(gpu_env.command_queue, dst_cl_buf,
695                                 CL_TRUE,CL_MAP_WRITE, 0, buffer_size + dst_cl_offset,
696                                 0, NULL, NULL, &status);
697     if (status != CL_SUCCESS) {
698         av_log(&openclutils, AV_LOG_ERROR,
699                "Could not map OpenCL buffer: %s\n", opencl_errstr(status));
700         return AVERROR_EXTERNAL;
701     }
702     temp = mapped;
703     temp += dst_cl_offset;
704     for (i = 0; i < plane_num; i++) {
705         memcpy(temp, src_data[i], plane_size[i]);
706         temp += plane_size[i];
707     }
708     status = clEnqueueUnmapMemObject(gpu_env.command_queue, dst_cl_buf, mapped, 0, NULL, NULL);
709     if (status != CL_SUCCESS) {
710         av_log(&openclutils, AV_LOG_ERROR,
711                "Could not unmap OpenCL buffer: %s\n", opencl_errstr(status));
712         return AVERROR_EXTERNAL;
713     }
714     return 0;
715 }
716
717 int av_opencl_buffer_read_image(uint8_t **dst_data, int *plane_size, int plane_num,
718                                 cl_mem src_cl_buf, size_t cl_buffer_size)
719 {
720     int i,buffer_size = 0,ret = 0;
721     uint8_t *temp;
722     void *mapped;
723     cl_int status;
724     if ((unsigned int)plane_num > 8) {
725         return AVERROR(EINVAL);
726     }
727     for (i = 0; i < plane_num; i++) {
728         buffer_size += plane_size[i];
729     }
730     if (buffer_size > cl_buffer_size) {
731         av_log(&openclutils, AV_LOG_ERROR,
732                "Cannot write image to CPU buffer: OpenCL buffer too small\n");
733         return AVERROR(EINVAL);
734     }
735     mapped = clEnqueueMapBuffer(gpu_env.command_queue, src_cl_buf,
736                                 CL_TRUE,CL_MAP_READ, 0, buffer_size,
737                                 0, NULL, NULL, &status);
738
739     if (status != CL_SUCCESS) {
740         av_log(&openclutils, AV_LOG_ERROR,
741                "Could not map OpenCL buffer: %s\n", opencl_errstr(status));
742         return AVERROR_EXTERNAL;
743     }
744     temp = mapped;
745     if (ret >= 0) {
746         for (i = 0; i < plane_num; i++) {
747             memcpy(dst_data[i], temp, plane_size[i]);
748             temp += plane_size[i];
749         }
750     }
751     status = clEnqueueUnmapMemObject(gpu_env.command_queue, src_cl_buf, mapped, 0, NULL, NULL);
752     if (status != CL_SUCCESS) {
753         av_log(&openclutils, AV_LOG_ERROR,
754                "Could not unmap OpenCL buffer: %s\n", opencl_errstr(status));
755         return AVERROR_EXTERNAL;
756     }
757     return 0;
758 }