diff --git a/libavcodec/libx265.c b/libavcodec/libx265.c
index 27c90b323f..fce91ea789 100644
--- a/libavcodec/libx265.c
+++ b/libavcodec/libx265.c
@@ -31,6 +31,7 @@
 #include "libavutil/common.h"
 #include "libavutil/opt.h"
 #include "libavutil/pixdesc.h"
+#include "libavutil/thread.h"
 #include "avcodec.h"
 #include "internal.h"
 
@@ -49,6 +50,9 @@ typedef struct libx265Context {
     char *x265_opts;
 } libx265Context;
 
+static int open_enc_count = 0;
+static pthread_mutex_t open_enc_count_lock = PTHREAD_MUTEX_INITIALIZER;
+
 static int is_keyframe(NalUnitType naltype)
 {
     switch (naltype) {
@@ -66,19 +70,34 @@ static int is_keyframe(NalUnitType naltype)
 
 static av_cold int libx265_encode_close(AVCodecContext *avctx)
 {
+    pthread_mutex_lock(&open_enc_count_lock);
+	
     libx265Context *ctx = avctx->priv_data;
 
-    ctx->api->param_free(ctx->params);
+    if (ctx->params) {
+        ctx->api->param_free(ctx->params);
+        ctx->params = NULL;
+    }
 
-    if (ctx->encoder)
+    if (ctx->encoder) {
         ctx->api->encoder_close(ctx->encoder);
+        ctx->encoder = NULL;
+    }
 
+    if (--open_enc_count == 0)
+        ctx->api->cleanup();
+
+    pthread_mutex_unlock(&open_enc_count_lock);
+	
     return 0;
 }
 
 static av_cold int libx265_encode_init(AVCodecContext *avctx)
 {
+    pthread_mutex_lock(&open_enc_count_lock);
+	
     libx265Context *ctx = avctx->priv_data;
+    int ret;
 
     ctx->api = x265_api_get(av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth);
     if (!ctx->api)
@@ -87,7 +106,8 @@ static av_cold int libx265_encode_init(AVCodecContext *avctx)
     ctx->params = ctx->api->param_alloc();
     if (!ctx->params) {
         av_log(avctx, AV_LOG_ERROR, "Could not allocate x265 param structure.\n");
-        return AVERROR(ENOMEM);
+        ret = AVERROR(ENOMEM);
+        goto done;
     }
 
     if (ctx->api->param_default_preset(ctx->params, ctx->preset, ctx->tune) < 0) {
@@ -105,7 +125,8 @@ static av_cold int libx265_encode_init(AVCodecContext *avctx)
 
         av_log(avctx, AV_LOG_INFO, "\n");
 
-        return AVERROR(EINVAL);
+        ret = AVERROR(EINVAL);
+        goto done;
     }
 
     ctx->params->frameNumThreads = avctx->thread_count;
@@ -124,7 +145,8 @@ static av_cold int libx265_encode_init(AVCodecContext *avctx)
     if (ctx->params->sourceWidth < 16 || ctx->params->sourceHeight < 16) {
         av_log(avctx, AV_LOG_ERROR, "Image size is too small (%dx%d).\n",
                ctx->params->sourceWidth, ctx->params->sourceHeight);
-        return AVERROR(EINVAL);
+        ret = AVERROR(EINVAL);
+        goto done;
     }
 
     if ((avctx->color_primaries <= AVCOL_PRI_SMPTE432 &&
@@ -153,7 +175,8 @@ static av_cold int libx265_encode_init(AVCodecContext *avctx)
         snprintf(sar, sizeof(sar), "%d:%d", sar_num, sar_den);
         if (ctx->api->param_parse(ctx->params, "sar", sar) == X265_PARAM_BAD_VALUE) {
             av_log(avctx, AV_LOG_ERROR, "Invalid SAR: %d:%d.\n", sar_num, sar_den);
-            return AVERROR_INVALIDDATA;
+            ret = AVERROR_INVALIDDATA;
+            goto done;
         }
     }
 
@@ -186,7 +209,8 @@ static av_cold int libx265_encode_init(AVCodecContext *avctx)
             av_log(avctx, AV_LOG_ERROR,
                    "libx265 version is %d, must be at least 85 for gray encoding.\n",
                    ctx->api->api_build_number);
-            return AVERROR_INVALIDDATA;
+            ret = AVERROR_INVALIDDATA;
+            goto done;
         }
         ctx->params->internalCsp = X265_CSP_I400;
         break;
@@ -198,7 +222,8 @@ static av_cold int libx265_encode_init(AVCodecContext *avctx)
         snprintf(crf, sizeof(crf), "%2.2f", ctx->crf);
         if (ctx->api->param_parse(ctx->params, "crf", crf) == X265_PARAM_BAD_VALUE) {
             av_log(avctx, AV_LOG_ERROR, "Invalid crf: %2.2f.\n", ctx->crf);
-            return AVERROR(EINVAL);
+            ret = AVERROR(EINVAL);
+            goto done;
         }
     } else if (avctx->bit_rate > 0) {
         ctx->params->rc.bitrate         = avctx->bit_rate / 1000;
@@ -249,15 +274,16 @@ static av_cold int libx265_encode_init(AVCodecContext *avctx)
             for (i = 0; x265_profile_names[i]; i++)
                 av_log(avctx, AV_LOG_INFO, " %s", x265_profile_names[i]);
             av_log(avctx, AV_LOG_INFO, "\n");
-            return AVERROR(EINVAL);
+            ret = AVERROR(EINVAL);
+            goto done;
         }
     }
 
     ctx->encoder = ctx->api->encoder_open(ctx->params);
     if (!ctx->encoder) {
         av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");
-        libx265_encode_close(avctx);
-        return AVERROR_INVALIDDATA;
+        ret = AVERROR_INVALIDDATA;
+        goto done;
     }
 
     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
@@ -267,22 +293,39 @@ static av_cold int libx265_encode_init(AVCodecContext *avctx)
         avctx->extradata_size = ctx->api->encoder_headers(ctx->encoder, &nal, &nnal);
         if (avctx->extradata_size <= 0) {
             av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
-            libx265_encode_close(avctx);
-            return AVERROR_INVALIDDATA;
+            ret = AVERROR_INVALIDDATA;
+            goto done;
         }
 
         avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
         if (!avctx->extradata) {
             av_log(avctx, AV_LOG_ERROR,
                    "Cannot allocate HEVC header of size %d.\n", avctx->extradata_size);
-            libx265_encode_close(avctx);
-            return AVERROR(ENOMEM);
+            ret = AVERROR(ENOMEM);
+            goto done;
         }
 
         memcpy(avctx->extradata, nal[0].payload, avctx->extradata_size);
     }
 
-    return 0;
+    open_enc_count++;
+
+    ret = 0;
+done:
+    if (ret) {
+        if (ctx->params) {
+            ctx->api->param_free(ctx->params);
+            ctx->params = NULL;
+        }
+        if (ctx->encoder) {
+            ctx->api->encoder_close(ctx->encoder);
+            ctx->encoder = NULL;
+        }
+    }
+
+    pthread_mutex_unlock(&open_enc_count_lock);
+	
+    return ret;
 }
 
 static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
