Put orphan effect chain back if orphan effect creation failed

Bug: 309578734
Test: atest CtsMediaAudioTestCases
Test: atest audioeffect_tests
Change-Id: I9b6d6c350106b233d3ea856bfa4df81ce35a54ec
Merged-In: I9b6d6c350106b233d3ea856bfa4df81ce35a54ec
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index 7ecca4f..d5d778f 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -4417,6 +4417,10 @@
                 chain->createEffect(effect, desc, effectId, sessionId, pinned);
         if (llStatus != NO_ERROR) {
             *status = llStatus;
+            // if the effect chain was not created here, put it back
+            if (!chainCreated) {
+                putOrphanEffectChain_l(chain);
+            }
             return nullptr;
         }
         effect->setMode(getMode());
@@ -4441,17 +4445,20 @@
     if (lStatus == OK) {
         lStatus = effect->addHandle(handle.get());
     }
+    // in case of lStatus error, EffectHandle will still return and caller should do the clear
     if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
         if (effectCreated) {
             chain->removeEffect(effect);
         }
+        // if the effect chain was not created here, put it back
+        if (!chainCreated) {
+            putOrphanEffectChain_l(chain);
+        }
     } else {
         if (enabled != NULL) {
             *enabled = (int)effect->isEnabled();
         }
-        if (chainCreated) {
-            putOrphanEffectChain_l(chain);
-        }
+        putOrphanEffectChain_l(chain);
     }
     *status = lStatus;
     return handle;