audiopolicy: Close the voip output before track is invalidated

With 3rd party voip application, compress voip usecase is
failed to be selected by policy when headset is inserted during
voip call.
Audio policy invalidates the track first and then closes the
direct output. Voip output count is not reset to 0 when new track
is created from restoreTrack. APM rejects voip usecae due to
this reason.
Close voip output before invalidating the track to avoid this
issue.

CRs-Fixed: 2251583
Change-Id: I9fac1974fae2565daee10fce44f4a14d6961421b
diff --git a/policy_hal/AudioPolicyManager.cpp b/policy_hal/AudioPolicyManager.cpp
index 28ba3a9..9cf20c7 100644
--- a/policy_hal/AudioPolicyManager.cpp
+++ b/policy_hal/AudioPolicyManager.cpp
@@ -247,6 +247,19 @@
         // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
         // output is suspended before any tracks are moved to it
         checkA2dpSuspend();
+
+        if (!outputs.isEmpty()) {
+            for (size_t i = 0; i < outputs.size(); i++) {
+                sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
+                // close voip output before track invalidation to allow creation of
+                // new voip stream from restoreTrack
+                if((desc->mFlags == (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_VOIP_RX)) != 0) {
+                    closeOutput(outputs[i]);
+                    outputs.remove(outputs[i]);
+                }
+            }
+        }
+
         checkOutputForAllStrategies();
         // outputs must be closed after checkOutputForAllStrategies() is executed
         if (!outputs.isEmpty()) {