Fix problem in AudioFlinger closeOutput and closeInput.

There was no garanty that the corresponding thread destructor had been already called when exiting the closeOutput() or closeInput() functions.
This contructor could be called by the thread after the exit condition is signalled. By way of consequence, closeOutputStream() could be called after
we exited closeOutput() function.

To solve the problem, the call to closeOutputStream() or closeInputStream() is moved to closeOutput() or closeInput().
diff --git a/libs/audioflinger/AudioFlinger.cpp b/libs/audioflinger/AudioFlinger.cpp
index 3276cdf..fcf8a79 100644
--- a/libs/audioflinger/AudioFlinger.cpp
+++ b/libs/audioflinger/AudioFlinger.cpp
@@ -829,9 +829,6 @@
 AudioFlinger::PlaybackThread::~PlaybackThread()
 {
     delete [] mMixBuffer;
-    if (mType != DUPLICATING) {
-        mAudioFlinger->mAudioHardware->closeOutputStream(mOutput);
-    }
 }
 
 status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
@@ -2855,7 +2852,6 @@
 
 AudioFlinger::RecordThread::~RecordThread()
 {
-    mAudioFlinger->mAudioHardware->closeInputStream(mInput);
     delete[] mRsmpInBuffer;
     if (mResampler != 0) {
         delete mResampler;
@@ -3326,7 +3322,9 @@
 
 status_t AudioFlinger::closeOutput(int output)
 {
-    PlaybackThread *thread;
+    // keep strong reference on the playback thread so that
+    // it is not destroyed while exit() is executed
+    sp <PlaybackThread> thread;
     {
         Mutex::Autolock _l(mLock);
         thread = checkPlaybackThread_l(output);
@@ -3340,7 +3338,7 @@
             for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
                 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
                     DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
-                    dupThread->removeOutputTrack((MixerThread *)thread);
+                    dupThread->removeOutputTrack((MixerThread *)thread.get());
                 }
             }
         }
@@ -3348,6 +3346,9 @@
     }
     thread->exit();
 
+    if (thread->type() != PlaybackThread::DUPLICATING) {
+        mAudioHardware->closeOutputStream(thread->getOutput());
+    }
     return NO_ERROR;
 }
 
@@ -3449,7 +3450,9 @@
 
 status_t AudioFlinger::closeInput(int input)
 {
-    RecordThread *thread;
+    // keep strong reference on the record thread so that
+    // it is not destroyed while exit() is executed
+    sp <RecordThread> thread;
     {
         Mutex::Autolock _l(mLock);
         thread = checkRecordThread_l(input);
@@ -3462,6 +3465,8 @@
     }
     thread->exit();
 
+    mAudioHardware->closeInputStream(thread->getInput());
+
     return NO_ERROR;
 }