Bump minor for 3.3
[ffmpeg.git] / libavutil / opencl.c
index 799425e..af35770 100644 (file)
@@ -1,7 +1,8 @@
 /*
 /*
- * Copyright (C) 2012 Peng Gao <peng@multicorewareinc.com>
- * Copyright (C) 2012 Li   Cao <li@multicorewareinc.com>
- * Copyright (C) 2012 Wei  Gao <weigao@multicorewareinc.com>
+ * Copyright (C) 2012 Peng  Gao     <peng@multicorewareinc.com>
+ * Copyright (C) 2012 Li    Cao     <li@multicorewareinc.com>
+ * Copyright (C) 2012 Wei   Gao     <weigao@multicorewareinc.com>
+ * Copyright (C) 2013 Lenny Wang    <lwanghpc@gmail.com>
  *
  * This file is part of FFmpeg.
  *
  *
  * This file is part of FFmpeg.
  *
 #include "avstring.h"
 #include "log.h"
 #include "avassert.h"
 #include "avstring.h"
 #include "log.h"
 #include "avassert.h"
+#include "opt.h"
 
 
-#if HAVE_PTHREADS
+#if HAVE_THREADS
+#include "thread.h"
+#include "atomic.h"
 
 
-#include <pthread.h>
-static pthread_mutex_t atomic_opencl_lock = PTHREAD_MUTEX_INITIALIZER;
-
-#define LOCK_OPENCL pthread_mutex_lock(&atomic_opencl_lock);
-#define UNLOCK_OPENCL pthread_mutex_unlock(&atomic_opencl_lock);
-
-#elif !HAVE_THREADS
+static pthread_mutex_t * volatile atomic_opencl_lock = NULL;
+#define LOCK_OPENCL pthread_mutex_lock(atomic_opencl_lock)
+#define UNLOCK_OPENCL pthread_mutex_unlock(atomic_opencl_lock)
+#else
 #define LOCK_OPENCL
 #define UNLOCK_OPENCL
 #endif
 
 #define LOCK_OPENCL
 #define UNLOCK_OPENCL
 #endif
 
-
-#define MAX_KERNEL_NUM 500
 #define MAX_KERNEL_CODE_NUM 200
 
 typedef struct {
 #define MAX_KERNEL_CODE_NUM 200
 
 typedef struct {
-    int dev_idx;
-    int platform_idx;
-} UserSpecDevInfo;
-
-typedef struct {
     int is_compiled;
     const char *kernel_string;
 } KernelCode;
 
 typedef struct {
     int is_compiled;
     const char *kernel_string;
 } KernelCode;
 
 typedef struct {
+    const AVClass *class;
+    int log_offset;
+    void *log_ctx;
     int init_count;
     int init_count;
-    UserSpecDevInfo usr_spec_dev_info;
+    int opt_init_flag;
+     /**
+     * if set to 1, the OpenCL environment was created by the user and
+     * passed as AVOpenCLExternalEnv when initing ,0:created by opencl wrapper.
+     */
+    int is_user_created;
+    int platform_idx;
+    int device_idx;
     cl_platform_id platform_id;
     cl_device_type device_type;
     cl_context context;
     cl_platform_id platform_id;
     cl_device_type device_type;
     cl_context context;
-    cl_device_id *device_ids;
     cl_device_id device_id;
     cl_command_queue command_queue;
     cl_device_id device_id;
     cl_command_queue command_queue;
-    int program_count;
-    cl_program programs[MAX_KERNEL_CODE_NUM];
     int kernel_code_count;
     KernelCode kernel_code[MAX_KERNEL_CODE_NUM];
     int kernel_code_count;
     KernelCode kernel_code[MAX_KERNEL_CODE_NUM];
-    int kernel_count;
-    /**
-     * if set to 1, the OpenCL environment was created by the user and
-     * passed as AVOpenCLExternalEnv when initing ,0:created by opencl wrapper.
-     */
-    int is_user_created;
-} GPUEnv;
+    AVOpenCLDeviceList device_list;
+} OpenclContext;
 
 
-typedef struct {
-    const AVClass *class;
-    int log_offset;
-    void *log_ctx;
-} OpenclUtils;
+#define OFFSET(x) offsetof(OpenclContext, x)
+
+static const AVOption opencl_options[] = {
+     { "platform_idx",        "set platform index value",  OFFSET(platform_idx),  AV_OPT_TYPE_INT,    {.i64=-1}, -1, INT_MAX},
+     { "device_idx",          "set device index value",    OFFSET(device_idx),    AV_OPT_TYPE_INT,    {.i64=-1}, -1, INT_MAX},
+     { NULL }
+};
 
 static const AVClass openclutils_class = {
 
 static const AVClass openclutils_class = {
-    .class_name                = "OPENCLUTILS",
+    .class_name                = "opencl",
+    .option                    = opencl_options,
     .item_name                 = av_default_item_name,
     .version                   = LIBAVUTIL_VERSION_INT,
     .item_name                 = av_default_item_name,
     .version                   = LIBAVUTIL_VERSION_INT,
-    .log_level_offset_offset   = offsetof(OpenclUtils, log_offset),
-    .parent_log_context_offset = offsetof(OpenclUtils, log_ctx),
+    .log_level_offset_offset   = offsetof(OpenclContext, log_offset),
+    .parent_log_context_offset = offsetof(OpenclContext, log_ctx),
 };
 
 };
 
-static OpenclUtils openclutils = {&openclutils_class};
+static OpenclContext opencl_ctx = {&openclutils_class};
 
 
-static GPUEnv gpu_env;
+static const cl_device_type device_type[] = {CL_DEVICE_TYPE_GPU, CL_DEVICE_TYPE_CPU};
 
 typedef struct {
     int err_code;
 
 typedef struct {
     int err_code;
@@ -157,21 +156,253 @@ static const OpenclErrorMsg opencl_err_msg[] = {
     {CL_INVALID_DEVICE_PARTITION_COUNT,                 "INVALID DEVICE PARTITION COUNT"},
 };
 
     {CL_INVALID_DEVICE_PARTITION_COUNT,                 "INVALID DEVICE PARTITION COUNT"},
 };
 
-static const char *opencl_errstr(cl_int status)
+const char *av_opencl_errstr(cl_int status)
 {
     int i;
 {
     int i;
-    for (i = 0; i < sizeof(opencl_err_msg); i++) {
+    for (i = 0; i < FF_ARRAY_ELEMS(opencl_err_msg); i++) {
         if (opencl_err_msg[i].err_code == status)
             return opencl_err_msg[i].err_str;
     }
     return "unknown error";
 }
 
         if (opencl_err_msg[i].err_code == status)
             return opencl_err_msg[i].err_str;
     }
     return "unknown error";
 }
 
+static void free_device_list(AVOpenCLDeviceList *device_list)
+{
+    int i, j;
+    if (!device_list)
+        return;
+    for (i = 0; i < device_list->platform_num; i++) {
+        if (!device_list->platform_node[i])
+            continue;
+        for (j = 0; j < device_list->platform_node[i]->device_num; j++) {
+            av_freep(&(device_list->platform_node[i]->device_node[j]->device_name));
+            av_freep(&(device_list->platform_node[i]->device_node[j]));
+        }
+        av_freep(&device_list->platform_node[i]->device_node);
+        av_freep(&(device_list->platform_node[i]->platform_name));
+        av_freep(&device_list->platform_node[i]);
+    }
+    av_freep(&device_list->platform_node);
+    device_list->platform_num = 0;
+}
+
+static int get_device_list(AVOpenCLDeviceList *device_list)
+{
+    cl_int status;
+    int i, j, k, device_num, total_devices_num, ret = 0;
+    int *devices_num;
+    cl_platform_id *platform_ids = NULL;
+    cl_device_id *device_ids = NULL;
+    AVOpenCLDeviceNode *device_node = NULL;
+    size_t platform_name_size = 0;
+    size_t device_name_size = 0;
+    status = clGetPlatformIDs(0, NULL, &device_list->platform_num);
+    if (status != CL_SUCCESS) {
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Could not get OpenCL platform ids: %s\n", av_opencl_errstr(status));
+        return AVERROR_EXTERNAL;
+    }
+    platform_ids = av_mallocz_array(device_list->platform_num, sizeof(cl_platform_id));
+    if (!platform_ids)
+        return AVERROR(ENOMEM);
+    status = clGetPlatformIDs(device_list->platform_num, platform_ids, NULL);
+    if (status != CL_SUCCESS) {
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+                "Could not get OpenCL platform ids: %s\n", av_opencl_errstr(status));
+        ret = AVERROR_EXTERNAL;
+        goto end;
+    }
+    device_list->platform_node = av_mallocz_array(device_list->platform_num, sizeof(AVOpenCLPlatformNode *));
+    if (!device_list->platform_node) {
+        ret = AVERROR(ENOMEM);
+        goto end;
+    }
+    devices_num = av_mallocz(sizeof(int) * FF_ARRAY_ELEMS(device_type));
+    if (!devices_num) {
+        ret = AVERROR(ENOMEM);
+        goto end;
+    }
+    for (i = 0; i < device_list->platform_num; i++) {
+        device_list->platform_node[i] = av_mallocz(sizeof(AVOpenCLPlatformNode));
+        if (!device_list->platform_node[i]) {
+            ret = AVERROR(ENOMEM);
+            goto end;
+        }
+        device_list->platform_node[i]->platform_id = platform_ids[i];
+        status = clGetPlatformInfo(platform_ids[i], CL_PLATFORM_VENDOR,
+                                   0, NULL, &platform_name_size);
+        if (status != CL_SUCCESS) {
+            av_log(&opencl_ctx, AV_LOG_WARNING,
+                    "Could not get size of platform name: %s\n", av_opencl_errstr(status));
+        } else {
+            device_list->platform_node[i]->platform_name = av_malloc(platform_name_size * sizeof(char));
+            if (!device_list->platform_node[i]->platform_name) {
+                av_log(&opencl_ctx, AV_LOG_WARNING,
+                        "Could not allocate memory for device name: %s\n", av_opencl_errstr(status));
+            } else {
+                status = clGetPlatformInfo(platform_ids[i], CL_PLATFORM_VENDOR,
+                                           platform_name_size * sizeof(char),
+                                           device_list->platform_node[i]->platform_name, NULL);
+                if (status != CL_SUCCESS) {
+                    av_log(&opencl_ctx, AV_LOG_WARNING,
+                            "Could not get platform name: %s\n", av_opencl_errstr(status));
+                }
+            }
+        }
+        total_devices_num = 0;
+        for (j = 0; j < FF_ARRAY_ELEMS(device_type); j++) {
+            status = clGetDeviceIDs(device_list->platform_node[i]->platform_id,
+                                    device_type[j], 0, NULL, &devices_num[j]);
+            total_devices_num += devices_num[j];
+        }
+        device_list->platform_node[i]->device_node = av_mallocz_array(total_devices_num, sizeof(AVOpenCLDeviceNode *));
+        if (!device_list->platform_node[i]->device_node) {
+            ret = AVERROR(ENOMEM);
+            goto end;
+        }
+        for (j = 0; j < FF_ARRAY_ELEMS(device_type); j++) {
+            if (devices_num[j]) {
+                device_ids = av_mallocz_array(devices_num[j], sizeof(cl_device_id));
+                if (!device_ids) {
+                    ret = AVERROR(ENOMEM);
+                    goto end;
+                }
+                status = clGetDeviceIDs(device_list->platform_node[i]->platform_id, device_type[j],
+                                        devices_num[j], device_ids, NULL);
+                if (status != CL_SUCCESS) {
+                    av_log(&opencl_ctx, AV_LOG_WARNING,
+                            "Could not get device ID: %s:\n", av_opencl_errstr(status));
+                    av_freep(&device_ids);
+                    continue;
+                }
+                for (k = 0; k < devices_num[j]; k++) {
+                    device_num = device_list->platform_node[i]->device_num;
+                    device_list->platform_node[i]->device_node[device_num] = av_mallocz(sizeof(AVOpenCLDeviceNode));
+                    if (!device_list->platform_node[i]->device_node[device_num]) {
+                        ret = AVERROR(ENOMEM);
+                        goto end;
+                    }
+                    device_node = device_list->platform_node[i]->device_node[device_num];
+                    device_node->device_id = device_ids[k];
+                    device_node->device_type = device_type[j];
+                    status = clGetDeviceInfo(device_node->device_id, CL_DEVICE_NAME,
+                                             0, NULL, &device_name_size);
+                    if (status != CL_SUCCESS) {
+                        av_log(&opencl_ctx, AV_LOG_WARNING,
+                                "Could not get size of device name: %s\n", av_opencl_errstr(status));
+                        continue;
+                    }
+                    device_node->device_name = av_malloc(device_name_size * sizeof(char));
+                    if (!device_node->device_name) {
+                        av_log(&opencl_ctx, AV_LOG_WARNING,
+                                "Could not allocate memory for device name: %s\n", av_opencl_errstr(status));
+                        continue;
+                    }
+                    status = clGetDeviceInfo(device_node->device_id, CL_DEVICE_NAME,
+                                             device_name_size * sizeof(char),
+                                             device_node->device_name, NULL);
+                    if (status != CL_SUCCESS) {
+                        av_log(&opencl_ctx, AV_LOG_WARNING,
+                                "Could not get device name: %s\n", av_opencl_errstr(status));
+                        continue;
+                    }
+                    device_list->platform_node[i]->device_num++;
+                }
+                av_freep(&device_ids);
+            }
+        }
+    }
+end:
+    av_freep(&platform_ids);
+    av_freep(&devices_num);
+    av_freep(&device_ids);
+    if (ret < 0)
+        free_device_list(device_list);
+    return ret;
+}
+
+int av_opencl_get_device_list(AVOpenCLDeviceList **device_list)
+{
+    int ret = 0;
+    *device_list = av_mallocz(sizeof(AVOpenCLDeviceList));
+    if (!(*device_list)) {
+        av_log(&opencl_ctx, AV_LOG_ERROR, "Could not allocate opencl device list\n");
+        return AVERROR(ENOMEM);
+    }
+    ret = get_device_list(*device_list);
+    if (ret < 0) {
+        av_log(&opencl_ctx, AV_LOG_ERROR, "Could not get device list from environment\n");
+        free_device_list(*device_list);
+        av_freep(device_list);
+        return ret;
+    }
+    return ret;
+}
+
+void av_opencl_free_device_list(AVOpenCLDeviceList **device_list)
+{
+    free_device_list(*device_list);
+    av_freep(device_list);
+}
+
+static inline int init_opencl_mtx(void)
+{
+#if HAVE_THREADS
+    if (!atomic_opencl_lock) {
+        int err;
+        pthread_mutex_t *tmp = av_malloc(sizeof(pthread_mutex_t));
+        if (!tmp)
+            return AVERROR(ENOMEM);
+        if ((err = pthread_mutex_init(tmp, NULL))) {
+            av_free(tmp);
+            return AVERROR(err);
+        }
+        if (avpriv_atomic_ptr_cas((void * volatile *)&atomic_opencl_lock, NULL, tmp)) {
+            pthread_mutex_destroy(tmp);
+            av_free(tmp);
+        }
+    }
+#endif
+    return 0;
+}
+
+int av_opencl_set_option(const char *key, const char *val)
+{
+    int ret = init_opencl_mtx( );
+    if (ret < 0)
+        return ret;
+    LOCK_OPENCL;
+    if (!opencl_ctx.opt_init_flag) {
+        av_opt_set_defaults(&opencl_ctx);
+        opencl_ctx.opt_init_flag = 1;
+    }
+    ret = av_opt_set(&opencl_ctx, key, val, 0);
+    UNLOCK_OPENCL;
+    return ret;
+}
+
+int av_opencl_get_option(const char *key, uint8_t **out_val)
+{
+    int ret = 0;
+    LOCK_OPENCL;
+    ret = av_opt_get(&opencl_ctx, key, 0, out_val);
+    UNLOCK_OPENCL;
+    return ret;
+}
+
+void av_opencl_free_option(void)
+{
+    /*FIXME: free openclutils context*/
+    LOCK_OPENCL;
+    av_opt_free(&opencl_ctx);
+    UNLOCK_OPENCL;
+}
+
 AVOpenCLExternalEnv *av_opencl_alloc_external_env(void)
 {
     AVOpenCLExternalEnv *ext = av_mallocz(sizeof(AVOpenCLExternalEnv));
     if (!ext) {
 AVOpenCLExternalEnv *av_opencl_alloc_external_env(void)
 {
     AVOpenCLExternalEnv *ext = av_mallocz(sizeof(AVOpenCLExternalEnv));
     if (!ext) {
-        av_log(&openclutils, AV_LOG_ERROR,
+        av_log(&opencl_ctx, AV_LOG_ERROR,
                "Could not malloc external opencl environment data space\n");
     }
     return ext;
                "Could not malloc external opencl environment data space\n");
     }
     return ext;
@@ -184,415 +415,275 @@ void av_opencl_free_external_env(AVOpenCLExternalEnv **ext_opencl_env)
 
 int av_opencl_register_kernel_code(const char *kernel_code)
 {
 
 int av_opencl_register_kernel_code(const char *kernel_code)
 {
-    int i, ret = 0;
+    int i, ret = init_opencl_mtx( );
+    if (ret < 0)
+        return ret;
     LOCK_OPENCL;
     LOCK_OPENCL;
-    if (gpu_env.kernel_code_count >= MAX_KERNEL_CODE_NUM) {
-        av_log(&openclutils, AV_LOG_ERROR,
+    if (opencl_ctx.kernel_code_count >= MAX_KERNEL_CODE_NUM) {
+        av_log(&opencl_ctx, AV_LOG_ERROR,
                "Could not register kernel code, maximum number of registered kernel code %d already reached\n",
                MAX_KERNEL_CODE_NUM);
         ret = AVERROR(EINVAL);
         goto end;
     }
                "Could not register kernel code, maximum number of registered kernel code %d already reached\n",
                MAX_KERNEL_CODE_NUM);
         ret = AVERROR(EINVAL);
         goto end;
     }
-    for (i = 0; i < gpu_env.kernel_code_count; i++) {
-        if (gpu_env.kernel_code[i].kernel_string == kernel_code) {
-            av_log(&openclutils, AV_LOG_WARNING, "Same kernel code has been registered\n");
+    for (i = 0; i < opencl_ctx.kernel_code_count; i++) {
+        if (opencl_ctx.kernel_code[i].kernel_string == kernel_code) {
+            av_log(&opencl_ctx, AV_LOG_WARNING, "Same kernel code has been registered\n");
             goto end;
         }
     }
             goto end;
         }
     }
-    gpu_env.kernel_code[gpu_env.kernel_code_count].kernel_string = kernel_code;
-    gpu_env.kernel_code[gpu_env.kernel_code_count].is_compiled = 0;
-    gpu_env.kernel_code_count++;
+    opencl_ctx.kernel_code[opencl_ctx.kernel_code_count].kernel_string = kernel_code;
+    opencl_ctx.kernel_code[opencl_ctx.kernel_code_count].is_compiled = 0;
+    opencl_ctx.kernel_code_count++;
 end:
     UNLOCK_OPENCL;
     return ret;
 }
 
 end:
     UNLOCK_OPENCL;
     return ret;
 }
 
-int av_opencl_create_kernel(AVOpenCLKernelEnv *env, const char *kernel_name)
+cl_program av_opencl_compile(const char *program_name, const char *build_opts)
 {
 {
-    cl_int status;
-    int i, ret = 0;
+    int i;
+    cl_int status, build_status;
+    int kernel_code_idx = 0;
+    const char *kernel_source = NULL;
+    size_t kernel_code_len;
+    char* ptr = NULL;
+    cl_program program = NULL;
+    size_t log_size;
+    char *log = NULL;
+
     LOCK_OPENCL;
     LOCK_OPENCL;
-    if (strlen(kernel_name) + 1 > AV_OPENCL_MAX_KERNEL_NAME_SIZE) {
-        av_log(&openclutils, AV_LOG_ERROR, "Created kernel name %s is too long\n", kernel_name);
-        ret = AVERROR(EINVAL);
+    for (i = 0; i < opencl_ctx.kernel_code_count; i++) {
+        // identify a program using a unique name within the kernel source
+        ptr = av_stristr(opencl_ctx.kernel_code[i].kernel_string, program_name);
+        if (ptr && !opencl_ctx.kernel_code[i].is_compiled) {
+            kernel_source = opencl_ctx.kernel_code[i].kernel_string;
+            kernel_code_len = strlen(opencl_ctx.kernel_code[i].kernel_string);
+            kernel_code_idx = i;
+            break;
+        }
+    }
+    if (!kernel_source) {
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Unable to find OpenCL kernel source '%s'\n", program_name);
         goto end;
     }
         goto end;
     }
-    if (!env->kernel) {
-        if (gpu_env.kernel_count >= MAX_KERNEL_NUM) {
-            av_log(&openclutils, AV_LOG_ERROR,
-                   "Could not create kernel with name '%s', maximum number of kernels %d already reached\n",
-                   kernel_name, MAX_KERNEL_NUM);
-            ret = AVERROR(EINVAL);
-            goto end;
-        }
-        for (i = 0; i < gpu_env.program_count; i++) {
-            env->kernel = clCreateKernel(gpu_env.programs[i], kernel_name, &status);
-            if (status == CL_SUCCESS)
-                break;
-        }
-        if (status != CL_SUCCESS) {
-            av_log(&openclutils, AV_LOG_ERROR, "Could not create OpenCL kernel: %s\n", opencl_errstr(status));
-            ret = AVERROR_EXTERNAL;
-            goto end;
+
+    /* create a CL program from kernel source */
+    program = clCreateProgramWithSource(opencl_ctx.context, 1, &kernel_source, &kernel_code_len, &status);
+    if(status != CL_SUCCESS) {
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Unable to create OpenCL program '%s': %s\n", program_name, av_opencl_errstr(status));
+        program = NULL;
+        goto end;
+    }
+
+    build_status = clBuildProgram(program, 1, &(opencl_ctx.device_id), build_opts, NULL, NULL);
+    status = clGetProgramBuildInfo(program, opencl_ctx.device_id,
+                                   CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);
+    if (status != CL_SUCCESS) {
+        av_log(&opencl_ctx, AV_LOG_WARNING,
+               "Failed to get compilation log: %s\n",
+               av_opencl_errstr(status));
+    } else {
+        log = av_malloc(log_size);
+        if (log) {
+            status = clGetProgramBuildInfo(program, opencl_ctx.device_id,
+                                           CL_PROGRAM_BUILD_LOG, log_size,
+                                           log, NULL);
+            if (status != CL_SUCCESS) {
+                av_log(&opencl_ctx, AV_LOG_WARNING,
+                       "Failed to get compilation log: %s\n",
+                       av_opencl_errstr(status));
+            } else {
+                int level = build_status == CL_SUCCESS ? AV_LOG_DEBUG :
+                                                         AV_LOG_ERROR;
+                av_log(&opencl_ctx, level, "Compilation log:\n%s\n", log);
+            }
         }
         }
-        gpu_env.kernel_count++;
-        env->command_queue = gpu_env.command_queue;
-        av_strlcpy(env->kernel_name, kernel_name, sizeof(env->kernel_name));
+        av_freep(&log);
+    }
+    if (build_status != CL_SUCCESS) {
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Compilation failed with OpenCL program '%s': %s\n",
+               program_name, av_opencl_errstr(build_status));
+        program = NULL;
+        goto end;
     }
     }
+
+    opencl_ctx.kernel_code[kernel_code_idx].is_compiled = 1;
 end:
     UNLOCK_OPENCL;
 end:
     UNLOCK_OPENCL;
-    return ret;
+    return program;
 }
 
 }
 
-void av_opencl_release_kernel(AVOpenCLKernelEnv *env)
+cl_command_queue av_opencl_get_command_queue(void)
 {
 {
-    cl_int status;
-    LOCK_OPENCL
-    if (!env->kernel)
-        goto end;
-    status = clReleaseKernel(env->kernel);
-    if (status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR, "Could not release kernel: %s\n",
-              opencl_errstr(status));
-    }
-    env->kernel = NULL;
-    env->command_queue = NULL;
-    env->kernel_name[0] = 0;
-    gpu_env.kernel_count--;
-end:
-    UNLOCK_OPENCL
+    return opencl_ctx.command_queue;
 }
 
 }
 
-static int init_opencl_env(GPUEnv *gpu_env, AVOpenCLExternalEnv *ext_opencl_env)
+static int init_opencl_env(OpenclContext *opencl_ctx, AVOpenCLExternalEnv *ext_opencl_env)
 {
 {
-    size_t device_length;
     cl_int status;
     cl_int status;
-    cl_uint num_platforms, num_devices;
-    cl_platform_id *platform_ids = NULL;
     cl_context_properties cps[3];
     cl_context_properties cps[3];
-    char platform_name[100];
     int i, ret = 0;
     int i, ret = 0;
-    cl_device_type device_type[] = {CL_DEVICE_TYPE_GPU, CL_DEVICE_TYPE_CPU, CL_DEVICE_TYPE_DEFAULT};
+    AVOpenCLDeviceNode *device_node = NULL;
+
     if (ext_opencl_env) {
     if (ext_opencl_env) {
-        if (gpu_env->is_user_created)
+        if (opencl_ctx->is_user_created)
             return 0;
             return 0;
-        gpu_env->platform_id     = ext_opencl_env->platform_id;
-        gpu_env->is_user_created = 1;
-        gpu_env->command_queue   = ext_opencl_env->command_queue;
-        gpu_env->context         = ext_opencl_env->context;
-        gpu_env->device_ids      = ext_opencl_env->device_ids;
-        gpu_env->device_id       = ext_opencl_env->device_id;
-        gpu_env->device_type     = ext_opencl_env->device_type;
+        opencl_ctx->platform_id     = ext_opencl_env->platform_id;
+        opencl_ctx->is_user_created = 1;
+        opencl_ctx->command_queue   = ext_opencl_env->command_queue;
+        opencl_ctx->context         = ext_opencl_env->context;
+        opencl_ctx->device_id       = ext_opencl_env->device_id;
+        opencl_ctx->device_type     = ext_opencl_env->device_type;
     } else {
     } else {
-        if (!gpu_env->is_user_created) {
-            status = clGetPlatformIDs(0, NULL, &num_platforms);
-            if (status != CL_SUCCESS) {
-                av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL platform ids: %s\n", opencl_errstr(status));
-                return AVERROR_EXTERNAL;
-            }
-            if (gpu_env->usr_spec_dev_info.platform_idx >= 0) {
-                if (num_platforms < gpu_env->usr_spec_dev_info.platform_idx + 1) {
-                    av_log(&openclutils, AV_LOG_ERROR, "User set platform index not exist\n");
-                    return AVERROR(EINVAL);
+        if (!opencl_ctx->is_user_created) {
+            if (!opencl_ctx->device_list.platform_num) {
+                ret = get_device_list(&opencl_ctx->device_list);
+                if (ret < 0) {
+                    return ret;
                 }
             }
                 }
             }
-            if (num_platforms > 0) {
-                platform_ids = av_mallocz(num_platforms * sizeof(cl_platform_id));
-                if (!platform_ids) {
-                    ret = AVERROR(ENOMEM);
-                    goto end;
-                }
-                status = clGetPlatformIDs(num_platforms, platform_ids, NULL);
-                if (status != CL_SUCCESS) {
-                    av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL platform ids: %s\n", opencl_errstr(status));
-                    ret = AVERROR_EXTERNAL;
-                    goto end;
+            if (opencl_ctx->platform_idx >= 0) {
+                if (opencl_ctx->device_list.platform_num < opencl_ctx->platform_idx + 1) {
+                    av_log(opencl_ctx, AV_LOG_ERROR, "User set platform index not exist\n");
+                    return AVERROR(EINVAL);
                 }
                 }
-                i = 0;
-                if (gpu_env->usr_spec_dev_info.platform_idx >= 0) {
-                    i = gpu_env->usr_spec_dev_info.platform_idx;
+                if (!opencl_ctx->device_list.platform_node[opencl_ctx->platform_idx]->device_num) {
+                    av_log(opencl_ctx, AV_LOG_ERROR, "No devices in user specific platform with index %d\n",
+                           opencl_ctx->platform_idx);
+                    return AVERROR(EINVAL);
                 }
                 }
-                while (i < num_platforms) {
-                    status = clGetPlatformInfo(platform_ids[i], CL_PLATFORM_VENDOR,
-                                               sizeof(platform_name), platform_name,
-                                               NULL);
-
-                    if (status != CL_SUCCESS) {
-                        av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL platform info: %s\n", opencl_errstr(status));
-                        ret = AVERROR_EXTERNAL;
-                        goto end;
-                    }
-                    gpu_env->platform_id = platform_ids[i];
-                    status = clGetDeviceIDs(gpu_env->platform_id, CL_DEVICE_TYPE_GPU,
-                                            0, NULL, &num_devices);
-                    if (status != CL_SUCCESS) {
-                        av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL device number:%s\n", opencl_errstr(status));
-                        ret = AVERROR_EXTERNAL;
-                        goto end;
-                    }
-                    if (num_devices == 0) {
-                        //find CPU device
-                        status = clGetDeviceIDs(gpu_env->platform_id, CL_DEVICE_TYPE_CPU,
-                                             0, NULL, &num_devices);
-                    }
-                    if (status != CL_SUCCESS) {
-                        av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL device ids: %s\n", opencl_errstr(status));
-                        ret = AVERROR(EINVAL);
-                        goto end;
-                    }
-                    if (num_devices)
-                       break;
-                    if (gpu_env->usr_spec_dev_info.platform_idx >= 0) {
-                        av_log(&openclutils, AV_LOG_ERROR, "Device number of user set platform is 0\n");
-                        ret = AVERROR_EXTERNAL;
-                        goto end;
+                opencl_ctx->platform_id = opencl_ctx->device_list.platform_node[opencl_ctx->platform_idx]->platform_id;
+            } else {
+                /* get a usable platform by default*/
+                for (i = 0; i < opencl_ctx->device_list.platform_num; i++) {
+                    if (opencl_ctx->device_list.platform_node[i]->device_num) {
+                        opencl_ctx->platform_id = opencl_ctx->device_list.platform_node[i]->platform_id;
+                        opencl_ctx->platform_idx = i;
+                        break;
                     }
                     }
-                    i++;
-
                 }
             }
                 }
             }
-            if (!gpu_env->platform_id) {
-                av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL platforms\n");
-                ret = AVERROR_EXTERNAL;
-                goto end;
+            if (!opencl_ctx->platform_id) {
+                av_log(opencl_ctx, AV_LOG_ERROR, "Could not get OpenCL platforms\n");
+                return AVERROR_EXTERNAL;
             }
             }
-            if (gpu_env->usr_spec_dev_info.dev_idx >= 0) {
-                if (num_devices < gpu_env->usr_spec_dev_info.dev_idx + 1) {
-                    av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL device idx in the user set platform\n");
-                    ret = AVERROR(EINVAL);
-                    goto end;
+            /* get a usable device*/
+            if (opencl_ctx->device_idx >= 0) {
+                if (opencl_ctx->device_list.platform_node[opencl_ctx->platform_idx]->device_num < opencl_ctx->device_idx + 1) {
+                    av_log(opencl_ctx, AV_LOG_ERROR,
+                           "Could not get OpenCL device idx %d in the user set platform\n", opencl_ctx->platform_idx);
+                    return AVERROR(EINVAL);
                 }
                 }
+            } else {
+                opencl_ctx->device_idx = 0;
             }
 
             }
 
+            device_node = opencl_ctx->device_list.platform_node[opencl_ctx->platform_idx]->device_node[opencl_ctx->device_idx];
+            opencl_ctx->device_id = device_node->device_id;
+            opencl_ctx->device_type = device_node->device_type;
+
             /*
              * Use available platform.
              */
             /*
              * Use available platform.
              */
-            av_log(&openclutils, AV_LOG_VERBOSE, "Platform Name: %s\n", platform_name);
+            av_log(opencl_ctx, AV_LOG_VERBOSE, "Platform Name: %s, Device Name: %s\n",
+                   opencl_ctx->device_list.platform_node[opencl_ctx->platform_idx]->platform_name,
+                   device_node->device_name);
             cps[0] = CL_CONTEXT_PLATFORM;
             cps[0] = CL_CONTEXT_PLATFORM;
-            cps[1] = (cl_context_properties)gpu_env->platform_id;
+            cps[1] = (cl_context_properties)opencl_ctx->platform_id;
             cps[2] = 0;
 
             cps[2] = 0;
 
-            /* Check for GPU. */
-            for (i = 0; i < sizeof(device_type); i++) {
-                gpu_env->device_type = device_type[i];
-                gpu_env->context     = clCreateContextFromType(cps, gpu_env->device_type,
-                                                               NULL, NULL, &status);
-                if (status != CL_SUCCESS) {
-                    av_log(&openclutils, AV_LOG_ERROR,
-                           "Could not get OpenCL context from device type: %s\n", opencl_errstr(status));
-                    ret = AVERROR_EXTERNAL;
-                    goto end;
-                }
-                if (gpu_env->context)
-                    break;
-            }
-            if (!gpu_env->context) {
-                av_log(&openclutils, AV_LOG_ERROR,
-                       "Could not get OpenCL context from device type\n");
-                ret = AVERROR_EXTERNAL;
-                goto end;
-            }
-            /* Detect OpenCL devices. */
-            /* First, get the size of device list data */
-            status = clGetContextInfo(gpu_env->context, CL_CONTEXT_DEVICES,
-                                      0, NULL, &device_length);
+            opencl_ctx->context = clCreateContextFromType(cps, opencl_ctx->device_type,
+                                                       NULL, NULL, &status);
             if (status != CL_SUCCESS) {
             if (status != CL_SUCCESS) {
-                av_log(&openclutils, AV_LOG_ERROR,
-                       "Could not get OpenCL device length: %s\n", opencl_errstr(status));
-                ret = AVERROR_EXTERNAL;
-                goto end;
-            }
-            if (device_length == 0) {
-                av_log(&openclutils, AV_LOG_ERROR, "Could not get OpenCL device length\n");
-                ret = AVERROR_EXTERNAL;
-                goto end;
-            }
-            /* Now allocate memory for device list based on the size we got earlier */
-            gpu_env->device_ids = av_mallocz(device_length);
-            if (!gpu_env->device_ids) {
-                ret = AVERROR(ENOMEM);
-                goto end;
-            }
-            /* Now, get the device list data */
-            status = clGetContextInfo(gpu_env->context, CL_CONTEXT_DEVICES, device_length,
-                                      gpu_env->device_ids, NULL);
-            if (status != CL_SUCCESS) {
-                av_log(&openclutils, AV_LOG_ERROR,
-                       "Could not get OpenCL context info: %s\n", opencl_errstr(status));
-                ret = AVERROR_EXTERNAL;
-                goto end;
-            }
-            /* Create OpenCL command queue. */
-            i = 0;
-            if (gpu_env->usr_spec_dev_info.dev_idx >= 0) {
-                i = gpu_env->usr_spec_dev_info.dev_idx;
+                av_log(opencl_ctx, AV_LOG_ERROR,
+                       "Could not get OpenCL context from device type: %s\n", av_opencl_errstr(status));
+                return AVERROR_EXTERNAL;
             }
             }
-            gpu_env->command_queue = clCreateCommandQueue(gpu_env->context, gpu_env->device_ids[i],
+            opencl_ctx->command_queue = clCreateCommandQueue(opencl_ctx->context, opencl_ctx->device_id,
                                                           0, &status);
             if (status != CL_SUCCESS) {
                                                           0, &status);
             if (status != CL_SUCCESS) {
-                av_log(&openclutils, AV_LOG_ERROR,
-                       "Could not create OpenCL command queue: %s\n", opencl_errstr(status));
-                ret = AVERROR_EXTERNAL;
-                goto end;
+                av_log(opencl_ctx, AV_LOG_ERROR,
+                       "Could not create OpenCL command queue: %s\n", av_opencl_errstr(status));
+                return AVERROR_EXTERNAL;
             }
         }
     }
             }
         }
     }
-end:
-    av_free(platform_ids);
     return ret;
 }
 
     return ret;
 }
 
-static int compile_kernel_file(GPUEnv *gpu_env, const char *build_options)
+int av_opencl_init(AVOpenCLExternalEnv *ext_opencl_env)
 {
 {
-    cl_int status;
-    char *temp, *source_str = NULL;
-    size_t source_str_len = 0;
-    int i, ret = 0;
-
-    for (i = 0; i < gpu_env->kernel_code_count; i++) {
-        if (!gpu_env->kernel_code[i].is_compiled)
-            source_str_len += strlen(gpu_env->kernel_code[i].kernel_string);
-    }
-    if (!source_str_len) {
-        return 0;
-    }
-    source_str = av_mallocz(source_str_len + 1);
-    if (!source_str) {
-        return AVERROR(ENOMEM);
-    }
-    temp = source_str;
-    for (i = 0; i < gpu_env->kernel_code_count; i++) {
-        if (!gpu_env->kernel_code[i].is_compiled) {
-            memcpy(temp, gpu_env->kernel_code[i].kernel_string,
-                        strlen(gpu_env->kernel_code[i].kernel_string));
-            gpu_env->kernel_code[i].is_compiled = 1;
-            temp += strlen(gpu_env->kernel_code[i].kernel_string);
-        }
-    }
-    /* create a CL program using the kernel source */
-    gpu_env->programs[gpu_env->program_count] = clCreateProgramWithSource(gpu_env->context,
-                                                           1, (const char **)(&source_str),
-                                                                   &source_str_len, &status);
-    if(status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR,
-               "Could not create OpenCL program with source code: %s\n", opencl_errstr(status));
-        ret = AVERROR_EXTERNAL;
-        goto end;
-    }
-    if (!gpu_env->programs[gpu_env->program_count]) {
-        av_log(&openclutils, AV_LOG_ERROR, "Created program is NULL\n");
-        ret = AVERROR_EXTERNAL;
-        goto end;
-    }
-    i = 0;
-    if (gpu_env->usr_spec_dev_info.dev_idx >= 0)
-        i = gpu_env->usr_spec_dev_info.dev_idx;
-    /* create a cl program executable for all the devices specified */
-    if (!gpu_env->is_user_created)
-        status = clBuildProgram(gpu_env->programs[gpu_env->program_count], 1, &gpu_env->device_ids[i],
-                                build_options, NULL, NULL);
-    else
-        status = clBuildProgram(gpu_env->programs[gpu_env->program_count], 1, &(gpu_env->device_id),
-                                 build_options, NULL, NULL);
-
-    if (status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR,
-               "Could not compile OpenCL kernel: %s\n", opencl_errstr(status));
-        ret = AVERROR_EXTERNAL;
-        goto end;
-    }
-    gpu_env->program_count++;
-end:
-    av_free(source_str);
-    return ret;
-}
-
-int av_opencl_init(AVDictionary *options, AVOpenCLExternalEnv *ext_opencl_env)
-{
-    int ret = 0;
-    AVDictionaryEntry *opt_build_entry;
-    AVDictionaryEntry *opt_platform_entry;
-    AVDictionaryEntry *opt_device_entry;
-    LOCK_OPENCL
-    if (!gpu_env.init_count) {
-        opt_platform_entry = av_dict_get(options, "platform_idx", NULL, 0);
-        opt_device_entry   = av_dict_get(options, "device_idx", NULL, 0);
-        /* initialize devices, context, command_queue */
-        gpu_env.usr_spec_dev_info.platform_idx = -1;
-        gpu_env.usr_spec_dev_info.dev_idx = -1;
-        if (opt_platform_entry) {
-            gpu_env.usr_spec_dev_info.platform_idx = strtol(opt_platform_entry->value, NULL, 10);
-        }
-        if (opt_device_entry) {
-            gpu_env.usr_spec_dev_info.dev_idx = strtol(opt_device_entry->value, NULL, 10);
+    int ret = init_opencl_mtx( );
+    if (ret < 0)
+        return ret;
+    LOCK_OPENCL;
+    if (!opencl_ctx.init_count) {
+        if (!opencl_ctx.opt_init_flag) {
+            av_opt_set_defaults(&opencl_ctx);
+            opencl_ctx.opt_init_flag = 1;
         }
         }
-        ret = init_opencl_env(&gpu_env, ext_opencl_env);
+        ret = init_opencl_env(&opencl_ctx, ext_opencl_env);
         if (ret < 0)
             goto end;
         if (ret < 0)
             goto end;
+        if (opencl_ctx.kernel_code_count <= 0) {
+            av_log(&opencl_ctx, AV_LOG_ERROR,
+                   "No kernel code is registered, compile kernel file failed\n");
+            ret = AVERROR(EINVAL);
+            goto end;
+        }
     }
     }
-    /*initialize program, kernel_name, kernel_count*/
-    opt_build_entry = av_dict_get(options, "build_options", NULL, 0);
-    if (opt_build_entry)
-        ret = compile_kernel_file(&gpu_env, opt_build_entry->value);
-    else
-        ret = compile_kernel_file(&gpu_env, NULL);
-    if (ret < 0)
-        goto end;
-    av_assert1(gpu_env.kernel_code_count > 0);
-    gpu_env.init_count++;
-
+    opencl_ctx.init_count++;
 end:
 end:
-    UNLOCK_OPENCL
+    UNLOCK_OPENCL;
     return ret;
 }
 
 void av_opencl_uninit(void)
 {
     return ret;
 }
 
 void av_opencl_uninit(void)
 {
-    cl_int status;
     int i;
     int i;
-    LOCK_OPENCL
-    gpu_env.init_count--;
-    if (gpu_env.is_user_created)
+    cl_int status;
+    LOCK_OPENCL;
+    opencl_ctx.init_count--;
+    if (opencl_ctx.is_user_created)
         goto end;
         goto end;
-    if (gpu_env.init_count > 0 || gpu_env.kernel_count > 0)
+    if (opencl_ctx.init_count > 0)
         goto end;
         goto end;
-    for (i = 0; i < gpu_env.program_count; i++) {
-        if (gpu_env.programs[i]) {
-            status = clReleaseProgram(gpu_env.programs[i]);
-            if (status != CL_SUCCESS) {
-                av_log(&openclutils, AV_LOG_ERROR,
-                       "Could not release OpenCL program: %s\n", opencl_errstr(status));
-            }
-            gpu_env.programs[i] = NULL;
-        }
-    }
-    if (gpu_env.command_queue) {
-        status = clReleaseCommandQueue(gpu_env.command_queue);
+    if (opencl_ctx.command_queue) {
+        status = clReleaseCommandQueue(opencl_ctx.command_queue);
         if (status != CL_SUCCESS) {
         if (status != CL_SUCCESS) {
-            av_log(&openclutils, AV_LOG_ERROR,
-                   "Could not release OpenCL command queue: %s\n", opencl_errstr(status));
+            av_log(&opencl_ctx, AV_LOG_ERROR,
+                   "Could not release OpenCL command queue: %s\n", av_opencl_errstr(status));
         }
         }
-        gpu_env.command_queue = NULL;
+        opencl_ctx.command_queue = NULL;
     }
     }
-    if (gpu_env.context) {
-        status = clReleaseContext(gpu_env.context);
+    if (opencl_ctx.context) {
+        status = clReleaseContext(opencl_ctx.context);
         if (status != CL_SUCCESS) {
         if (status != CL_SUCCESS) {
-            av_log(&openclutils, AV_LOG_ERROR,
-                   "Could not release OpenCL context: %s\n", opencl_errstr(status));
+            av_log(&opencl_ctx, AV_LOG_ERROR,
+                   "Could not release OpenCL context: %s\n", av_opencl_errstr(status));
         }
         }
-        gpu_env.context = NULL;
+        opencl_ctx.context = NULL;
+    }
+    for (i = 0; i < opencl_ctx.kernel_code_count; i++) {
+        opencl_ctx.kernel_code[i].is_compiled = 0;
     }
     }
-    av_freep(&(gpu_env.device_ids));
+    free_device_list(&opencl_ctx.device_list);
 end:
 end:
-    UNLOCK_OPENCL
+    if (opencl_ctx.init_count <= 0)
+        av_opt_free(&opencl_ctx); //FIXME: free openclutils context
+    UNLOCK_OPENCL;
 }
 
 int av_opencl_buffer_create(cl_mem *cl_buf, size_t cl_buf_size, int flags, void *host_ptr)
 {
     cl_int status;
 }
 
 int av_opencl_buffer_create(cl_mem *cl_buf, size_t cl_buf_size, int flags, void *host_ptr)
 {
     cl_int status;
-    *cl_buf = clCreateBuffer(gpu_env.context, flags, cl_buf_size, host_ptr, &status);
+    *cl_buf = clCreateBuffer(opencl_ctx.context, flags, cl_buf_size, host_ptr, &status);
     if (status != CL_SUCCESS) {
     if (status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR, "Could not create OpenCL buffer: %s\n", opencl_errstr(status));
+        av_log(&opencl_ctx, AV_LOG_ERROR, "Could not create OpenCL buffer: %s\n", av_opencl_errstr(status));
         return AVERROR_EXTERNAL;
     }
     return 0;
         return AVERROR_EXTERNAL;
     }
     return 0;
@@ -605,8 +696,8 @@ void av_opencl_buffer_release(cl_mem *cl_buf)
         return;
     status = clReleaseMemObject(*cl_buf);
     if (status != CL_SUCCESS) {
         return;
     status = clReleaseMemObject(*cl_buf);
     if (status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR,
-               "Could not release OpenCL buffer: %s\n", opencl_errstr(status));
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Could not release OpenCL buffer: %s\n", av_opencl_errstr(status));
     }
     memset(cl_buf, 0, sizeof(*cl_buf));
 }
     }
     memset(cl_buf, 0, sizeof(*cl_buf));
 }
@@ -614,21 +705,21 @@ void av_opencl_buffer_release(cl_mem *cl_buf)
 int av_opencl_buffer_write(cl_mem dst_cl_buf, uint8_t *src_buf, size_t buf_size)
 {
     cl_int status;
 int av_opencl_buffer_write(cl_mem dst_cl_buf, uint8_t *src_buf, size_t buf_size)
 {
     cl_int status;
-    void *mapped = clEnqueueMapBuffer(gpu_env.command_queue, dst_cl_buf,
-                                      CL_TRUE,CL_MAP_WRITE, 0, sizeof(uint8_t) * buf_size,
+    void *mapped = clEnqueueMapBuffer(opencl_ctx.command_queue, dst_cl_buf,
+                                      CL_TRUE, CL_MAP_WRITE, 0, sizeof(uint8_t) * buf_size,
                                       0, NULL, NULL, &status);
 
     if (status != CL_SUCCESS) {
                                       0, NULL, NULL, &status);
 
     if (status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR,
-               "Could not map OpenCL buffer: %s\n", opencl_errstr(status));
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Could not map OpenCL buffer: %s\n", av_opencl_errstr(status));
         return AVERROR_EXTERNAL;
     }
     memcpy(mapped, src_buf, buf_size);
 
         return AVERROR_EXTERNAL;
     }
     memcpy(mapped, src_buf, buf_size);
 
-    status = clEnqueueUnmapMemObject(gpu_env.command_queue, dst_cl_buf, mapped, 0, NULL, NULL);
+    status = clEnqueueUnmapMemObject(opencl_ctx.command_queue, dst_cl_buf, mapped, 0, NULL, NULL);
     if (status != CL_SUCCESS) {
     if (status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR,
-               "Could not unmap OpenCL buffer: %s\n", opencl_errstr(status));
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Could not unmap OpenCL buffer: %s\n", av_opencl_errstr(status));
         return AVERROR_EXTERNAL;
     }
     return 0;
         return AVERROR_EXTERNAL;
     }
     return 0;
@@ -637,21 +728,21 @@ int av_opencl_buffer_write(cl_mem dst_cl_buf, uint8_t *src_buf, size_t buf_size)
 int av_opencl_buffer_read(uint8_t *dst_buf, cl_mem src_cl_buf, size_t buf_size)
 {
     cl_int status;
 int av_opencl_buffer_read(uint8_t *dst_buf, cl_mem src_cl_buf, size_t buf_size)
 {
     cl_int status;
-    void *mapped = clEnqueueMapBuffer(gpu_env.command_queue, src_cl_buf,
-                                      CL_TRUE,CL_MAP_READ, 0, buf_size,
+    void *mapped = clEnqueueMapBuffer(opencl_ctx.command_queue, src_cl_buf,
+                                      CL_TRUE, CL_MAP_READ, 0, buf_size,
                                       0, NULL, NULL, &status);
 
     if (status != CL_SUCCESS) {
                                       0, NULL, NULL, &status);
 
     if (status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR,
-               "Could not map OpenCL buffer: %s\n", opencl_errstr(status));
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Could not map OpenCL buffer: %s\n", av_opencl_errstr(status));
         return AVERROR_EXTERNAL;
     }
     memcpy(dst_buf, mapped, buf_size);
 
         return AVERROR_EXTERNAL;
     }
     memcpy(dst_buf, mapped, buf_size);
 
-    status = clEnqueueUnmapMemObject(gpu_env.command_queue, src_cl_buf, mapped, 0, NULL, NULL);
+    status = clEnqueueUnmapMemObject(opencl_ctx.command_queue, src_cl_buf, mapped, 0, NULL, NULL);
     if (status != CL_SUCCESS) {
     if (status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR,
-               "Could not unmap OpenCL buffer: %s\n", opencl_errstr(status));
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Could not unmap OpenCL buffer: %s\n", av_opencl_errstr(status));
         return AVERROR_EXTERNAL;
     }
     return 0;
         return AVERROR_EXTERNAL;
     }
     return 0;
@@ -671,16 +762,16 @@ int av_opencl_buffer_write_image(cl_mem dst_cl_buf, size_t cl_buffer_size, int d
         buffer_size += plane_size[i];
     }
     if (buffer_size > cl_buffer_size) {
         buffer_size += plane_size[i];
     }
     if (buffer_size > cl_buffer_size) {
-        av_log(&openclutils, AV_LOG_ERROR,
+        av_log(&opencl_ctx, AV_LOG_ERROR,
                "Cannot write image to OpenCL buffer: buffer too small\n");
         return AVERROR(EINVAL);
     }
                "Cannot write image to OpenCL buffer: buffer too small\n");
         return AVERROR(EINVAL);
     }
-    mapped = clEnqueueMapBuffer(gpu_env.command_queue, dst_cl_buf,
-                                CL_TRUE,CL_MAP_WRITE, 0, buffer_size + dst_cl_offset,
+    mapped = clEnqueueMapBuffer(opencl_ctx.command_queue, dst_cl_buf,
+                                CL_TRUE, CL_MAP_WRITE, 0, buffer_size + dst_cl_offset,
                                 0, NULL, NULL, &status);
     if (status != CL_SUCCESS) {
                                 0, NULL, NULL, &status);
     if (status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR,
-               "Could not map OpenCL buffer: %s\n", opencl_errstr(status));
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Could not map OpenCL buffer: %s\n", av_opencl_errstr(status));
         return AVERROR_EXTERNAL;
     }
     temp = mapped;
         return AVERROR_EXTERNAL;
     }
     temp = mapped;
@@ -689,10 +780,10 @@ int av_opencl_buffer_write_image(cl_mem dst_cl_buf, size_t cl_buffer_size, int d
         memcpy(temp, src_data[i], plane_size[i]);
         temp += plane_size[i];
     }
         memcpy(temp, src_data[i], plane_size[i]);
         temp += plane_size[i];
     }
-    status = clEnqueueUnmapMemObject(gpu_env.command_queue, dst_cl_buf, mapped, 0, NULL, NULL);
+    status = clEnqueueUnmapMemObject(opencl_ctx.command_queue, dst_cl_buf, mapped, 0, NULL, NULL);
     if (status != CL_SUCCESS) {
     if (status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR,
-               "Could not unmap OpenCL buffer: %s\n", opencl_errstr(status));
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Could not unmap OpenCL buffer: %s\n", av_opencl_errstr(status));
         return AVERROR_EXTERNAL;
     }
     return 0;
         return AVERROR_EXTERNAL;
     }
     return 0;
@@ -712,17 +803,17 @@ int av_opencl_buffer_read_image(uint8_t **dst_data, int *plane_size, int plane_n
         buffer_size += plane_size[i];
     }
     if (buffer_size > cl_buffer_size) {
         buffer_size += plane_size[i];
     }
     if (buffer_size > cl_buffer_size) {
-        av_log(&openclutils, AV_LOG_ERROR,
+        av_log(&opencl_ctx, AV_LOG_ERROR,
                "Cannot write image to CPU buffer: OpenCL buffer too small\n");
         return AVERROR(EINVAL);
     }
                "Cannot write image to CPU buffer: OpenCL buffer too small\n");
         return AVERROR(EINVAL);
     }
-    mapped = clEnqueueMapBuffer(gpu_env.command_queue, src_cl_buf,
-                                CL_TRUE,CL_MAP_READ, 0, buffer_size,
+    mapped = clEnqueueMapBuffer(opencl_ctx.command_queue, src_cl_buf,
+                                CL_TRUE, CL_MAP_READ, 0, buffer_size,
                                 0, NULL, NULL, &status);
 
     if (status != CL_SUCCESS) {
                                 0, NULL, NULL, &status);
 
     if (status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR,
-               "Could not map OpenCL buffer: %s\n", opencl_errstr(status));
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Could not map OpenCL buffer: %s\n", av_opencl_errstr(status));
         return AVERROR_EXTERNAL;
     }
     temp = mapped;
         return AVERROR_EXTERNAL;
     }
     temp = mapped;
@@ -732,11 +823,53 @@ int av_opencl_buffer_read_image(uint8_t **dst_data, int *plane_size, int plane_n
             temp += plane_size[i];
         }
     }
             temp += plane_size[i];
         }
     }
-    status = clEnqueueUnmapMemObject(gpu_env.command_queue, src_cl_buf, mapped, 0, NULL, NULL);
+    status = clEnqueueUnmapMemObject(opencl_ctx.command_queue, src_cl_buf, mapped, 0, NULL, NULL);
     if (status != CL_SUCCESS) {
     if (status != CL_SUCCESS) {
-        av_log(&openclutils, AV_LOG_ERROR,
-               "Could not unmap OpenCL buffer: %s\n", opencl_errstr(status));
+        av_log(&opencl_ctx, AV_LOG_ERROR,
+               "Could not unmap OpenCL buffer: %s\n", av_opencl_errstr(status));
         return AVERROR_EXTERNAL;
     }
     return 0;
 }
         return AVERROR_EXTERNAL;
     }
     return 0;
 }
+
+int64_t av_opencl_benchmark(AVOpenCLDeviceNode *device_node, cl_platform_id platform,
+                            int64_t (*benchmark)(AVOpenCLExternalEnv *ext_opencl_env))
+{
+    int64_t ret = 0;
+    cl_int status;
+    cl_context_properties cps[3];
+    AVOpenCLExternalEnv *ext_opencl_env = NULL;
+
+    ext_opencl_env = av_opencl_alloc_external_env();
+    ext_opencl_env->device_id = device_node->device_id;
+    ext_opencl_env->device_type = device_node->device_type;
+    av_log(&opencl_ctx, AV_LOG_VERBOSE, "Performing test on OpenCL device %s\n",
+           device_node->device_name);
+
+    cps[0] = CL_CONTEXT_PLATFORM;
+    cps[1] = (cl_context_properties)platform;
+    cps[2] = 0;
+    ext_opencl_env->context = clCreateContextFromType(cps, ext_opencl_env->device_type,
+                                                      NULL, NULL, &status);
+    if (status != CL_SUCCESS || !ext_opencl_env->context) {
+        ret = AVERROR_EXTERNAL;
+        goto end;
+    }
+    ext_opencl_env->command_queue = clCreateCommandQueue(ext_opencl_env->context,
+                                                         ext_opencl_env->device_id, 0, &status);
+    if (status != CL_SUCCESS || !ext_opencl_env->command_queue) {
+        ret = AVERROR_EXTERNAL;
+        goto end;
+    }
+    ret = benchmark(ext_opencl_env);
+    if (ret < 0)
+        av_log(&opencl_ctx, AV_LOG_ERROR, "Benchmark failed with OpenCL device %s\n",
+               device_node->device_name);
+end:
+    if (ext_opencl_env->command_queue)
+        clReleaseCommandQueue(ext_opencl_env->command_queue);
+    if (ext_opencl_env->context)
+        clReleaseContext(ext_opencl_env->context);
+    av_opencl_free_external_env(&ext_opencl_env);
+    return ret;
+}