audio: Do not delete PatchRecord before Peer is stopped

PatchPanel::clearPatchConnections deletes PatchRecord before
the peer PatchTrack is stopped. This can cause an access to already
free'ed memory leading to a crash in PatchTrack::getNextBuffer.

Fix is to delete PatchRecord and PatchTrack only after removing
both of them from active tracks list

Bug: 22304526.
Change-Id: I7003756d3d2dd8912ce5e3b2fc31f5e82f455888
diff --git a/services/audioflinger/PatchPanel.cpp b/services/audioflinger/PatchPanel.cpp
index 9248bba..f6078a2 100644
--- a/services/audioflinger/PatchPanel.cpp
+++ b/services/audioflinger/PatchPanel.cpp
@@ -481,22 +481,31 @@
     if (patch->mRecordThread != 0) {
         if (patch->mPatchRecord != 0) {
             patch->mRecordThread->deletePatchRecord(patch->mPatchRecord);
-            patch->mPatchRecord.clear();
         }
         audioflinger->closeInputInternal_l(patch->mRecordThread);
-        patch->mRecordThread.clear();
     }
     if (patch->mPlaybackThread != 0) {
         if (patch->mPatchTrack != 0) {
             patch->mPlaybackThread->deletePatchTrack(patch->mPatchTrack);
-            patch->mPatchTrack.clear();
         }
         // if num sources == 2 we are reusing an existing playback thread so we do not close it
         if (patch->mAudioPatch.num_sources != 2) {
             audioflinger->closeOutputInternal_l(patch->mPlaybackThread);
         }
+    }
+    if (patch->mRecordThread != 0) {
+        if (patch->mPatchRecord != 0) {
+            patch->mPatchRecord.clear();
+        }
+        patch->mRecordThread.clear();
+    }
+    if (patch->mPlaybackThread != 0) {
+        if (patch->mPatchTrack != 0) {
+            patch->mPatchTrack.clear();
+        }
         patch->mPlaybackThread.clear();
     }
+
 }
 
 /* Disconnect a patch */