Snap for 4872253 from f3109fa2ca63f714d79f9c9639d2c79dfdb7edf0 to pi-dr1-release

Change-Id: Ib207644ba17258853250bddac2b6b15ebef91016
diff --git a/system/egl/egl.cpp b/system/egl/egl.cpp
index 16285f9..dca98f3 100644
--- a/system/egl/egl.cpp
+++ b/system/egl/egl.cpp
@@ -1642,9 +1642,9 @@
         return EGL_TRUE;
     }
 
+    // Destroy surfaces while the previous context is still current.
+    EGLContext_t* prevCtx = tInfo->currentContext;
     if (tInfo->currentContext) {
-        EGLContext_t* prevCtx = tInfo->currentContext;
-
         if (prevCtx->draw) {
             static_cast<egl_surface_t *>(prevCtx->draw)->setIsCurrent(false);
         }
@@ -1652,11 +1652,6 @@
             static_cast<egl_surface_t *>(prevCtx->read)->setIsCurrent(false);
         }
         s_destroyPendingSurfacesInContext(tInfo->currentContext);
-
-        if (prevCtx->deletePending && prevCtx != context) {
-            tInfo->currentContext = 0;
-            eglDestroyContext(dpy, prevCtx);
-        }
     }
 
     if (context && (context->flags & EGLContext_t::IS_CURRENT) && (context != tInfo->currentContext)) {
@@ -1768,11 +1763,15 @@
 
     }
 
+    // Delete the previous context here
     if (tInfo->currentContext && (tInfo->currentContext != context)) {
         tInfo->currentContext->flags &= ~EGLContext_t::IS_CURRENT;
+        if (tInfo->currentContext->deletePending && tInfo->currentContext != context) {
+            eglDestroyContext(dpy, tInfo->currentContext);
+        }
     }
 
-    //Now make current
+    // Now the new context is current in tInfo
     tInfo->currentContext = context;
 
     //Check maybe we need to init the encoder, if it's first eglMakeCurrent