AudioState extensions

Follow up to https://webrtc-review.googlesource.com/c/src/+/378140.

Make sure that AudioState::SetRecording(false) calls
adm::StopRecording() also in the scenario that the adm has been initilized
"some other path", i.e. WebRtcVoiceSendChannel if init_recording_on_send
(default true)

BUG=b/397376626

Change-Id: I9ff259eb797f2a9521f143da31c3622a0bc52ade
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/378043
Commit-Queue: Jonas Oreland <jonaso@webrtc.org>
Reviewed-by: Jakob Ivarsson‎ <jakobi@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#43951}
diff --git a/audio/audio_state.cc b/audio/audio_state.cc
index fb0a140..3c96802 100644
--- a/audio/audio_state.cc
+++ b/audio/audio_state.cc
@@ -140,6 +140,7 @@
 void AudioState::SetRecording(bool enabled) {
   RTC_LOG(LS_INFO) << "SetRecording(" << enabled << ")";
   RTC_DCHECK_RUN_ON(&thread_checker_);
+  auto* adm = config_.audio_device_module.get();
   if (recording_enabled_ != enabled) {
     auto* adm = config_.audio_device_module.get();
     recording_enabled_ = enabled;
@@ -152,6 +153,10 @@
     } else {
       adm->StopRecording();
     }
+  } else if (!enabled && adm->RecordingIsInitialized()) {
+    // The recording can also be initialized by WebRtcVoiceSendChannel
+    // options_.init_recording_on_send.
+    adm->StopRecording();
   }
 }
 
diff --git a/audio/audio_state_unittest.cc b/audio/audio_state_unittest.cc
index 63a7229..c2b55bb 100644
--- a/audio/audio_state_unittest.cc
+++ b/audio/audio_state_unittest.cc
@@ -388,6 +388,24 @@
   audio_state->RemoveSendingStream(&stream);
 }
 
+// The recording can also be initialized by WebRtcVoiceSendChannel
+// options_.init_recording_on_send. Make sure StopRecording is still
+// being called in this scenario.
+TEST_P(AudioStateTest, CallStopRecordingIfRecordingIsInitialized) {
+  ConfigHelper helper(GetParam());
+  rtc::scoped_refptr<internal::AudioState> audio_state(
+      rtc::make_ref_counted<internal::AudioState>(helper.config()));
+
+  auto* adm = reinterpret_cast<MockAudioDeviceModule*>(
+      helper.config().audio_device_module.get());
+
+  audio_state->SetRecording(false);
+
+  EXPECT_CALL(*adm, RecordingIsInitialized()).WillOnce(testing::Return(true));
+  EXPECT_CALL(*adm, StopRecording());
+  audio_state->SetRecording(false);
+}
+
 INSTANTIATE_TEST_SUITE_P(AudioStateTest,
                          AudioStateTest,
                          Values(ConfigHelper::Params({false, false}),