Wire up the microphone toggle to the audio service

Bug: 162549680
Test: When mic is disabled, test that audio gets muted. Also test that
          virtual record works so services like captioning still work.
Change-Id: I6f9c762086cfa3900ec9585aaf68e458c9dadff5
diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp
index a898dff..80022c8 100644
--- a/services/audiopolicy/service/AudioPolicyService.cpp
+++ b/services/audiopolicy/service/AudioPolicyService.cpp
@@ -529,6 +529,11 @@
 
     for (size_t i =0; i < mAudioRecordClients.size(); i++) {
         sp<AudioRecordClient> current = mAudioRecordClients[i];
+        if (!isVirtualSource(current->attributes.source)
+                && isUserSensorPrivacyEnabledForUid(current->uid)) {
+            setAppState_l(current->portId, APP_STATE_IDLE);
+            continue;
+        }
         if (!current->active) {
             continue;
         }
@@ -978,6 +983,16 @@
     return NO_INIT;
 }
 
+bool AudioPolicyService::isUserSensorPrivacyEnabledForUid(uid_t uid) {
+    userid_t userId = multiuser_get_user_id(uid);
+    if (mMicrophoneSensorPrivacyPolicies.find(userId) == mMicrophoneSensorPrivacyPolicies.end()) {
+        sp<SensorPrivacyPolicy> userPolicy = new SensorPrivacyPolicy(this);
+        userPolicy->registerSelfForMicrophoneOnly(userId);
+        mMicrophoneSensorPrivacyPolicies[userId] = userPolicy;
+    }
+    return mMicrophoneSensorPrivacyPolicies[userId]->isSensorPrivacyEnabled();
+}
+
 status_t AudioPolicyService::printHelp(int out) {
     return dprintf(out, "Audio policy service commands:\n"
         "  get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
@@ -1211,6 +1226,14 @@
     spm.addSensorPrivacyListener(this);
 }
 
+void AudioPolicyService::SensorPrivacyPolicy::registerSelfForMicrophoneOnly(int userId) {
+    SensorPrivacyManager spm;
+    mSensorPrivacyEnabled = spm.isIndividualSensorPrivacyEnabled(userId,
+            SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE);
+    spm.addIndividualSensorPrivacyListener(userId,
+            SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE, this);
+}
+
 void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
     SensorPrivacyManager spm;
     spm.removeSensorPrivacyListener(this);