blob: f80319df17ce64a37f6522f099c2a13bce2586e4 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
xians@webrtc.org20aabbb2012-02-20 09:17:41 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Jonas Olssona4d87372019-07-05 19:08:33 +020011#include "modules/audio_device/audio_device_buffer.h"
12
Yves Gerey988cc082018-10-23 12:03:01 +020013#include <string.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020014
henrika7be78832017-06-13 17:34:16 +020015#include <cmath>
Yves Gerey988cc082018-10-23 12:03:01 +020016#include <cstddef>
17#include <cstdint>
andrew@webrtc.org25534502013-09-13 00:02:13 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "common_audio/signal_processing/include/signal_processing_library.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/checks.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "system_wrappers/include/metrics.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000024
niklase@google.com470e71d2011-07-07 08:21:25 +000025namespace webrtc {
26
henrika6c4d0f02016-07-14 05:54:19 -070027static const char kTimerQueueName[] = "AudioDeviceBufferTimer";
28
29// Time between two sucessive calls to LogStats().
30static const size_t kTimerIntervalInSeconds = 10;
31static const size_t kTimerIntervalInMilliseconds =
32 kTimerIntervalInSeconds * rtc::kNumMillisecsPerSec;
henrikaba156cf2016-10-31 08:18:50 -070033// Min time required to qualify an audio session as a "call". If playout or
34// recording has been active for less than this time we will not store any
35// logs or UMA stats but instead consider the call as too short.
36static const size_t kMinValidCallTimeTimeInSeconds = 10;
37static const size_t kMinValidCallTimeTimeInMilliseconds =
38 kMinValidCallTimeTimeInSeconds * rtc::kNumMillisecsPerSec;
henrika7be78832017-06-13 17:34:16 +020039#ifdef AUDIO_DEVICE_PLAYS_SINUS_TONE
40static const double k2Pi = 6.28318530717959;
41#endif
henrika6c4d0f02016-07-14 05:54:19 -070042
Danil Chapovalov1c41be62019-04-01 09:16:12 +020043AudioDeviceBuffer::AudioDeviceBuffer(TaskQueueFactory* task_queue_factory)
44 : task_queue_(task_queue_factory->CreateTaskQueue(
45 kTimerQueueName,
46 TaskQueueFactory::Priority::NORMAL)),
henrikaf5022222016-11-07 15:56:59 +010047 audio_transport_cb_(nullptr),
henrika49810512016-08-22 05:56:12 -070048 rec_sample_rate_(0),
49 play_sample_rate_(0),
50 rec_channels_(0),
51 play_channels_(0),
henrikaf5022222016-11-07 15:56:59 +010052 playing_(false),
53 recording_(false),
henrika49810512016-08-22 05:56:12 -070054 typing_status_(false),
55 play_delay_ms_(0),
56 rec_delay_ms_(0),
Olov Brändströmb732bd52022-01-28 15:07:39 +010057 capture_timestamp_ns_(0),
henrika6c4d0f02016-07-14 05:54:19 -070058 num_stat_reports_(0),
henrikaf5022222016-11-07 15:56:59 +010059 last_timer_task_time_(0),
henrika3355f6d2016-10-21 12:45:25 +020060 rec_stat_count_(0),
henrikaba156cf2016-10-31 08:18:50 -070061 play_stat_count_(0),
62 play_start_time_(0),
henrika0b3a6382016-11-11 02:28:50 -080063 only_silence_recorded_(true),
64 log_stats_(false) {
Harald Alvestrand97597c02021-11-04 12:01:23 +000065 RTC_LOG(LS_INFO) << "AudioDeviceBuffer::ctor";
henrika7be78832017-06-13 17:34:16 +020066#ifdef AUDIO_DEVICE_PLAYS_SINUS_TONE
67 phase_ = 0.0;
Harald Alvestrandef5b21e2021-11-27 21:31:08 +000068 RTC_LOG(LS_WARNING) << "AUDIO_DEVICE_PLAYS_SINUS_TONE is defined!";
henrika7be78832017-06-13 17:34:16 +020069#endif
niklase@google.com470e71d2011-07-07 08:21:25 +000070}
71
henrika0fd68012016-07-04 13:01:19 +020072AudioDeviceBuffer::~AudioDeviceBuffer() {
henrikaf5022222016-11-07 15:56:59 +010073 RTC_DCHECK_RUN_ON(&main_thread_checker_);
henrikaba156cf2016-10-31 08:18:50 -070074 RTC_DCHECK(!playing_);
75 RTC_DCHECK(!recording_);
Harald Alvestrand97597c02021-11-04 12:01:23 +000076 RTC_LOG(LS_INFO) << "AudioDeviceBuffer::~dtor";
niklase@google.com470e71d2011-07-07 08:21:25 +000077}
78
henrika0fd68012016-07-04 13:01:19 +020079int32_t AudioDeviceBuffer::RegisterAudioCallback(
henrika49810512016-08-22 05:56:12 -070080 AudioTransport* audio_callback) {
henrikaf5022222016-11-07 15:56:59 +010081 RTC_DCHECK_RUN_ON(&main_thread_checker_);
Harald Alvestrand97597c02021-11-04 12:01:23 +000082 RTC_DLOG(LS_INFO) << __FUNCTION__;
henrikaf5022222016-11-07 15:56:59 +010083 if (playing_ || recording_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010084 RTC_LOG(LS_ERROR) << "Failed to set audio transport since media was active";
henrikaf5022222016-11-07 15:56:59 +010085 return -1;
86 }
henrika49810512016-08-22 05:56:12 -070087 audio_transport_cb_ = audio_callback;
henrika0fd68012016-07-04 13:01:19 +020088 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +000089}
90
henrikaba156cf2016-10-31 08:18:50 -070091void AudioDeviceBuffer::StartPlayout() {
henrikaf5022222016-11-07 15:56:59 +010092 RTC_DCHECK_RUN_ON(&main_thread_checker_);
henrikaba156cf2016-10-31 08:18:50 -070093 // TODO(henrika): allow for usage of DCHECK(!playing_) here instead. Today the
94 // ADM allows calling Start(), Start() by ignoring the second call but it
95 // makes more sense to only allow one call.
96 if (playing_) {
97 return;
henrika6c4d0f02016-07-14 05:54:19 -070098 }
Harald Alvestrand97597c02021-11-04 12:01:23 +000099 RTC_DLOG(LS_INFO) << __FUNCTION__;
henrikaba156cf2016-10-31 08:18:50 -0700100 // Clear members tracking playout stats and do it on the task queue.
101 task_queue_.PostTask([this] { ResetPlayStats(); });
102 // Start a periodic timer based on task queue if not already done by the
103 // recording side.
104 if (!recording_) {
105 StartPeriodicLogging();
106 }
nissedeb95f32016-11-28 01:54:54 -0800107 const int64_t now_time = rtc::TimeMillis();
henrikaba156cf2016-10-31 08:18:50 -0700108 // Clear members that are only touched on the main (creating) thread.
109 play_start_time_ = now_time;
henrikaba156cf2016-10-31 08:18:50 -0700110 playing_ = true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000111}
112
henrikaba156cf2016-10-31 08:18:50 -0700113void AudioDeviceBuffer::StartRecording() {
henrikaf5022222016-11-07 15:56:59 +0100114 RTC_DCHECK_RUN_ON(&main_thread_checker_);
henrikaba156cf2016-10-31 08:18:50 -0700115 if (recording_) {
116 return;
henrika6c4d0f02016-07-14 05:54:19 -0700117 }
Harald Alvestrand97597c02021-11-04 12:01:23 +0000118 RTC_DLOG(LS_INFO) << __FUNCTION__;
henrikaba156cf2016-10-31 08:18:50 -0700119 // Clear members tracking recording stats and do it on the task queue.
120 task_queue_.PostTask([this] { ResetRecStats(); });
121 // Start a periodic timer based on task queue if not already done by the
122 // playout side.
123 if (!playing_) {
124 StartPeriodicLogging();
125 }
126 // Clear members that will be touched on the main (creating) thread.
127 rec_start_time_ = rtc::TimeMillis();
128 recording_ = true;
129 // And finally a member which can be modified on the native audio thread.
130 // It is safe to do so since we know by design that the owning ADM has not
131 // yet started the native audio recording.
132 only_silence_recorded_ = true;
133}
134
135void AudioDeviceBuffer::StopPlayout() {
henrikaf5022222016-11-07 15:56:59 +0100136 RTC_DCHECK_RUN_ON(&main_thread_checker_);
henrikaba156cf2016-10-31 08:18:50 -0700137 if (!playing_) {
138 return;
139 }
Harald Alvestrand97597c02021-11-04 12:01:23 +0000140 RTC_DLOG(LS_INFO) << __FUNCTION__;
henrikaba156cf2016-10-31 08:18:50 -0700141 playing_ = false;
142 // Stop periodic logging if no more media is active.
143 if (!recording_) {
144 StopPeriodicLogging();
145 }
Harald Alvestrand97597c02021-11-04 12:01:23 +0000146 RTC_LOG(LS_INFO) << "total playout time: "
147 << rtc::TimeSince(play_start_time_);
henrikaba156cf2016-10-31 08:18:50 -0700148}
149
150void AudioDeviceBuffer::StopRecording() {
henrikaf5022222016-11-07 15:56:59 +0100151 RTC_DCHECK_RUN_ON(&main_thread_checker_);
henrikaba156cf2016-10-31 08:18:50 -0700152 if (!recording_) {
153 return;
154 }
Harald Alvestrand97597c02021-11-04 12:01:23 +0000155 RTC_DLOG(LS_INFO) << __FUNCTION__;
henrikaba156cf2016-10-31 08:18:50 -0700156 recording_ = false;
157 // Stop periodic logging if no more media is active.
158 if (!playing_) {
159 StopPeriodicLogging();
160 }
161 // Add UMA histogram to keep track of the case when only zeros have been
162 // recorded. Measurements (max of absolute level) are taken twice per second,
163 // which means that if e.g 10 seconds of audio has been recorded, a total of
164 // 20 level estimates must all be identical to zero to trigger the histogram.
Artem Titov0146a342021-07-28 20:03:05 +0200165 // `only_silence_recorded_` can only be cleared on the native audio thread
henrikaba156cf2016-10-31 08:18:50 -0700166 // that drives audio capture but we know by design that the audio has stopped
167 // when this method is called, hence there should not be aby conflicts. Also,
Artem Titov0146a342021-07-28 20:03:05 +0200168 // the fact that `only_silence_recorded_` can be affected during the complete
henrikaba156cf2016-10-31 08:18:50 -0700169 // call makes chances of conflicts with potentially one last callback very
170 // small.
171 const size_t time_since_start = rtc::TimeSince(rec_start_time_);
172 if (time_since_start > kMinValidCallTimeTimeInMilliseconds) {
173 const int only_zeros = static_cast<int>(only_silence_recorded_);
174 RTC_HISTOGRAM_BOOLEAN("WebRTC.Audio.RecordedOnlyZeros", only_zeros);
Harald Alvestrand97597c02021-11-04 12:01:23 +0000175 RTC_LOG(LS_INFO) << "HISTOGRAM(WebRTC.Audio.RecordedOnlyZeros): "
176 << only_zeros;
henrikaba156cf2016-10-31 08:18:50 -0700177 }
Harald Alvestrand97597c02021-11-04 12:01:23 +0000178 RTC_LOG(LS_INFO) << "total recording time: " << time_since_start;
niklase@google.com470e71d2011-07-07 08:21:25 +0000179}
180
henrika0fd68012016-07-04 13:01:19 +0200181int32_t AudioDeviceBuffer::SetRecordingSampleRate(uint32_t fsHz) {
Harald Alvestrand97597c02021-11-04 12:01:23 +0000182 RTC_LOG(LS_INFO) << "SetRecordingSampleRate(" << fsHz << ")";
henrika49810512016-08-22 05:56:12 -0700183 rec_sample_rate_ = fsHz;
henrika0fd68012016-07-04 13:01:19 +0200184 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000185}
186
henrika0fd68012016-07-04 13:01:19 +0200187int32_t AudioDeviceBuffer::SetPlayoutSampleRate(uint32_t fsHz) {
Harald Alvestrand97597c02021-11-04 12:01:23 +0000188 RTC_LOG(LS_INFO) << "SetPlayoutSampleRate(" << fsHz << ")";
henrika49810512016-08-22 05:56:12 -0700189 play_sample_rate_ = fsHz;
henrika0fd68012016-07-04 13:01:19 +0200190 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000191}
192
henrikacfbd26d2018-09-05 11:36:22 +0200193uint32_t AudioDeviceBuffer::RecordingSampleRate() const {
henrika49810512016-08-22 05:56:12 -0700194 return rec_sample_rate_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000195}
196
henrikacfbd26d2018-09-05 11:36:22 +0200197uint32_t AudioDeviceBuffer::PlayoutSampleRate() const {
henrika49810512016-08-22 05:56:12 -0700198 return play_sample_rate_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000199}
200
henrika0fd68012016-07-04 13:01:19 +0200201int32_t AudioDeviceBuffer::SetRecordingChannels(size_t channels) {
Harald Alvestrand97597c02021-11-04 12:01:23 +0000202 RTC_LOG(LS_INFO) << "SetRecordingChannels(" << channels << ")";
henrika49810512016-08-22 05:56:12 -0700203 rec_channels_ = channels;
henrika0fd68012016-07-04 13:01:19 +0200204 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000205}
206
henrika0fd68012016-07-04 13:01:19 +0200207int32_t AudioDeviceBuffer::SetPlayoutChannels(size_t channels) {
Harald Alvestrand97597c02021-11-04 12:01:23 +0000208 RTC_LOG(LS_INFO) << "SetPlayoutChannels(" << channels << ")";
henrika49810512016-08-22 05:56:12 -0700209 play_channels_ = channels;
henrika0fd68012016-07-04 13:01:19 +0200210 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000211}
212
henrika0fd68012016-07-04 13:01:19 +0200213size_t AudioDeviceBuffer::RecordingChannels() const {
henrika49810512016-08-22 05:56:12 -0700214 return rec_channels_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000215}
216
henrika0fd68012016-07-04 13:01:19 +0200217size_t AudioDeviceBuffer::PlayoutChannels() const {
henrika49810512016-08-22 05:56:12 -0700218 return play_channels_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000219}
220
henrika49810512016-08-22 05:56:12 -0700221int32_t AudioDeviceBuffer::SetTypingStatus(bool typing_status) {
222 typing_status_ = typing_status;
henrika0fd68012016-07-04 13:01:19 +0200223 return 0;
niklas.enbom@webrtc.org3be565b2013-05-07 21:04:24 +0000224}
225
Yves Gerey665174f2018-06-19 15:03:05 +0200226void AudioDeviceBuffer::SetVQEData(int play_delay_ms, int rec_delay_ms) {
henrika49810512016-08-22 05:56:12 -0700227 play_delay_ms_ = play_delay_ms;
228 rec_delay_ms_ = rec_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +0000229}
230
henrika49810512016-08-22 05:56:12 -0700231int32_t AudioDeviceBuffer::SetRecordedBuffer(const void* audio_buffer,
henrika51e96082016-11-10 00:40:37 -0800232 size_t samples_per_channel) {
Olov Brändströmb732bd52022-01-28 15:07:39 +0100233 return SetRecordedBuffer(audio_buffer, samples_per_channel, 0);
234}
235
236int32_t AudioDeviceBuffer::SetRecordedBuffer(const void* audio_buffer,
237 size_t samples_per_channel,
238 int64_t capture_timestamp_ns) {
henrika5588a132016-10-18 05:14:30 -0700239 // Copy the complete input buffer to the local buffer.
henrika5588a132016-10-18 05:14:30 -0700240 const size_t old_size = rec_buffer_.size();
henrika51e96082016-11-10 00:40:37 -0800241 rec_buffer_.SetData(static_cast<const int16_t*>(audio_buffer),
242 rec_channels_ * samples_per_channel);
henrika5588a132016-10-18 05:14:30 -0700243 // Keep track of the size of the recording buffer. Only updated when the
244 // size changes, which is a rare event.
245 if (old_size != rec_buffer_.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100246 RTC_LOG(LS_INFO) << "Size of recording buffer: " << rec_buffer_.size();
henrika0fd68012016-07-04 13:01:19 +0200247 }
henrika51e96082016-11-10 00:40:37 -0800248
Olov Brändströmb732bd52022-01-28 15:07:39 +0100249 capture_timestamp_ns_ = capture_timestamp_ns;
250
henrikaba156cf2016-10-31 08:18:50 -0700251 // Derive a new level value twice per second and check if it is non-zero.
henrika3355f6d2016-10-21 12:45:25 +0200252 int16_t max_abs = 0;
253 RTC_DCHECK_LT(rec_stat_count_, 50);
254 if (++rec_stat_count_ >= 50) {
henrika3355f6d2016-10-21 12:45:25 +0200255 // Returns the largest absolute value in a signed 16-bit vector.
henrika51e96082016-11-10 00:40:37 -0800256 max_abs = WebRtcSpl_MaxAbsValueW16(rec_buffer_.data(), rec_buffer_.size());
henrika3355f6d2016-10-21 12:45:25 +0200257 rec_stat_count_ = 0;
Artem Titov0146a342021-07-28 20:03:05 +0200258 // Set `only_silence_recorded_` to false as soon as at least one detection
henrikaba156cf2016-10-31 08:18:50 -0700259 // of a non-zero audio packet is found. It can only be restored to true
260 // again by restarting the call.
261 if (max_abs > 0) {
262 only_silence_recorded_ = false;
263 }
henrika3355f6d2016-10-21 12:45:25 +0200264 }
henrika87d11cd2017-02-08 07:16:56 -0800265 // Update recording stats which is used as base for periodic logging of the
266 // audio input state.
267 UpdateRecStats(max_abs, samples_per_channel);
henrika0fd68012016-07-04 13:01:19 +0200268 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000269}
270
henrika0fd68012016-07-04 13:01:19 +0200271int32_t AudioDeviceBuffer::DeliverRecordedData() {
henrika49810512016-08-22 05:56:12 -0700272 if (!audio_transport_cb_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100273 RTC_LOG(LS_WARNING) << "Invalid audio transport";
niklase@google.com470e71d2011-07-07 08:21:25 +0000274 return 0;
henrika0fd68012016-07-04 13:01:19 +0200275 }
henrika51e96082016-11-10 00:40:37 -0800276 const size_t frames = rec_buffer_.size() / rec_channels_;
277 const size_t bytes_per_frame = rec_channels_ * sizeof(int16_t);
Fredrik Solenberg1a50cd52018-01-16 09:19:38 +0100278 uint32_t new_mic_level_dummy = 0;
henrika5588a132016-10-18 05:14:30 -0700279 uint32_t total_delay_ms = play_delay_ms_ + rec_delay_ms_;
henrika5588a132016-10-18 05:14:30 -0700280 int32_t res = audio_transport_cb_->RecordedDataIsAvailable(
henrika51e96082016-11-10 00:40:37 -0800281 rec_buffer_.data(), frames, bytes_per_frame, rec_channels_,
Fredrik Solenberg1a50cd52018-01-16 09:19:38 +0100282 rec_sample_rate_, total_delay_ms, 0, 0, typing_status_,
Olov Brändströmb732bd52022-01-28 15:07:39 +0100283 new_mic_level_dummy, capture_timestamp_ns_);
Fredrik Solenberg1a50cd52018-01-16 09:19:38 +0100284 if (res == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100285 RTC_LOG(LS_ERROR) << "RecordedDataIsAvailable() failed";
henrika0fd68012016-07-04 13:01:19 +0200286 }
henrika0fd68012016-07-04 13:01:19 +0200287 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000288}
289
henrika51e96082016-11-10 00:40:37 -0800290int32_t AudioDeviceBuffer::RequestPlayoutData(size_t samples_per_channel) {
henrika51e96082016-11-10 00:40:37 -0800291 // The consumer can change the requested size on the fly and we therefore
henrika5588a132016-10-18 05:14:30 -0700292 // resize the buffer accordingly. Also takes place at the first call to this
293 // method.
henrika51e96082016-11-10 00:40:37 -0800294 const size_t total_samples = play_channels_ * samples_per_channel;
295 if (play_buffer_.size() != total_samples) {
296 play_buffer_.SetSize(total_samples);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100297 RTC_LOG(LS_INFO) << "Size of playout buffer: " << play_buffer_.size();
henrika5588a132016-10-18 05:14:30 -0700298 }
299
henrika49810512016-08-22 05:56:12 -0700300 size_t num_samples_out(0);
henrikaf5022222016-11-07 15:56:59 +0100301 // It is currently supported to start playout without a valid audio
302 // transport object. Leads to warning and silence.
303 if (!audio_transport_cb_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100304 RTC_LOG(LS_WARNING) << "Invalid audio transport";
henrikaf5022222016-11-07 15:56:59 +0100305 return 0;
306 }
henrikaba156cf2016-10-31 08:18:50 -0700307
henrikaf5022222016-11-07 15:56:59 +0100308 // Retrieve new 16-bit PCM audio data using the audio transport instance.
309 int64_t elapsed_time_ms = -1;
310 int64_t ntp_time_ms = -1;
henrika51e96082016-11-10 00:40:37 -0800311 const size_t bytes_per_frame = play_channels_ * sizeof(int16_t);
henrikaf5022222016-11-07 15:56:59 +0100312 uint32_t res = audio_transport_cb_->NeedMorePlayData(
henrika51e96082016-11-10 00:40:37 -0800313 samples_per_channel, bytes_per_frame, play_channels_, play_sample_rate_,
henrikaf5022222016-11-07 15:56:59 +0100314 play_buffer_.data(), num_samples_out, &elapsed_time_ms, &ntp_time_ms);
315 if (res != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100316 RTC_LOG(LS_ERROR) << "NeedMorePlayData() failed";
henrika0fd68012016-07-04 13:01:19 +0200317 }
318
henrika3355f6d2016-10-21 12:45:25 +0200319 // Derive a new level value twice per second.
320 int16_t max_abs = 0;
321 RTC_DCHECK_LT(play_stat_count_, 50);
322 if (++play_stat_count_ >= 50) {
henrika3355f6d2016-10-21 12:45:25 +0200323 // Returns the largest absolute value in a signed 16-bit vector.
henrika51e96082016-11-10 00:40:37 -0800324 max_abs =
325 WebRtcSpl_MaxAbsValueW16(play_buffer_.data(), play_buffer_.size());
henrika3355f6d2016-10-21 12:45:25 +0200326 play_stat_count_ = 0;
327 }
henrika87d11cd2017-02-08 07:16:56 -0800328 // Update playout stats which is used as base for periodic logging of the
329 // audio output state.
henrika76535de2017-09-11 01:25:55 -0700330 UpdatePlayStats(max_abs, num_samples_out / play_channels_);
331 return static_cast<int32_t>(num_samples_out / play_channels_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000332}
333
henrika49810512016-08-22 05:56:12 -0700334int32_t AudioDeviceBuffer::GetPlayoutData(void* audio_buffer) {
kwibergaf476c72016-11-28 15:21:39 -0800335 RTC_DCHECK_GT(play_buffer_.size(), 0);
henrika7be78832017-06-13 17:34:16 +0200336#ifdef AUDIO_DEVICE_PLAYS_SINUS_TONE
337 const double phase_increment =
338 k2Pi * 440.0 / static_cast<double>(play_sample_rate_);
339 int16_t* destination_r = reinterpret_cast<int16_t*>(audio_buffer);
henrika29e865a2018-04-24 13:22:31 +0200340 if (play_channels_ == 1) {
341 for (size_t i = 0; i < play_buffer_.size(); ++i) {
342 destination_r[i] = static_cast<int16_t>((sin(phase_) * (1 << 14)));
343 phase_ += phase_increment;
344 }
345 } else if (play_channels_ == 2) {
346 for (size_t i = 0; i < play_buffer_.size() / 2; ++i) {
347 destination_r[2 * i] = destination_r[2 * i + 1] =
348 static_cast<int16_t>((sin(phase_) * (1 << 14)));
349 phase_ += phase_increment;
350 }
henrika7be78832017-06-13 17:34:16 +0200351 }
352#else
henrika51e96082016-11-10 00:40:37 -0800353 memcpy(audio_buffer, play_buffer_.data(),
henrika7be78832017-06-13 17:34:16 +0200354 play_buffer_.size() * sizeof(int16_t));
355#endif
henrika51e96082016-11-10 00:40:37 -0800356 // Return samples per channel or number of frames.
357 return static_cast<int32_t>(play_buffer_.size() / play_channels_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000358}
359
henrikaba156cf2016-10-31 08:18:50 -0700360void AudioDeviceBuffer::StartPeriodicLogging() {
Niels Möllerf77aa812021-01-14 11:50:19 +0100361 task_queue_.PostTask([this] { LogStats(AudioDeviceBuffer::LOG_START); });
henrika6c4d0f02016-07-14 05:54:19 -0700362}
363
henrikaba156cf2016-10-31 08:18:50 -0700364void AudioDeviceBuffer::StopPeriodicLogging() {
Niels Möllerf77aa812021-01-14 11:50:19 +0100365 task_queue_.PostTask([this] { LogStats(AudioDeviceBuffer::LOG_STOP); });
henrikaba156cf2016-10-31 08:18:50 -0700366}
367
368void AudioDeviceBuffer::LogStats(LogState state) {
henrikaf5022222016-11-07 15:56:59 +0100369 RTC_DCHECK_RUN_ON(&task_queue_);
henrika6c4d0f02016-07-14 05:54:19 -0700370 int64_t now_time = rtc::TimeMillis();
henrika0b3a6382016-11-11 02:28:50 -0800371
henrikaba156cf2016-10-31 08:18:50 -0700372 if (state == AudioDeviceBuffer::LOG_START) {
373 // Reset counters at start. We will not add any logging in this state but
374 // the timer will started by posting a new (delayed) task.
375 num_stat_reports_ = 0;
376 last_timer_task_time_ = now_time;
henrika0b3a6382016-11-11 02:28:50 -0800377 log_stats_ = true;
henrikaba156cf2016-10-31 08:18:50 -0700378 } else if (state == AudioDeviceBuffer::LOG_STOP) {
379 // Stop logging and posting new tasks.
henrika0b3a6382016-11-11 02:28:50 -0800380 log_stats_ = false;
henrikaba156cf2016-10-31 08:18:50 -0700381 } else if (state == AudioDeviceBuffer::LOG_ACTIVE) {
henrika0b3a6382016-11-11 02:28:50 -0800382 // Keep logging unless logging was disabled while task was posted.
383 }
384
385 // Avoid adding more logs since we are in STOP mode.
386 if (!log_stats_) {
387 return;
henrikaba156cf2016-10-31 08:18:50 -0700388 }
henrika6c4d0f02016-07-14 05:54:19 -0700389
henrikaba156cf2016-10-31 08:18:50 -0700390 int64_t next_callback_time = now_time + kTimerIntervalInMilliseconds;
391 int64_t time_since_last = rtc::TimeDiff(now_time, last_timer_task_time_);
392 last_timer_task_time_ = now_time;
393
henrika87d11cd2017-02-08 07:16:56 -0800394 Stats stats;
395 {
Markus Handell5f612822020-07-08 10:13:20 +0200396 MutexLock lock(&lock_);
henrika87d11cd2017-02-08 07:16:56 -0800397 stats = stats_;
398 stats_.max_rec_level = 0;
399 stats_.max_play_level = 0;
400 }
401
henrikacfbd26d2018-09-05 11:36:22 +0200402 // Cache current sample rate from atomic members.
403 const uint32_t rec_sample_rate = rec_sample_rate_;
404 const uint32_t play_sample_rate = play_sample_rate_;
405
406 // Log the latest statistics but skip the first two rounds just after state
407 // was set to LOG_START to ensure that we have at least one full stable
408 // 10-second interval for sample-rate estimation. Hence, first printed log
409 // will be after ~20 seconds.
henrikac5fe1662018-09-13 16:57:01 +0200410 if (++num_stat_reports_ > 2 &&
411 static_cast<size_t>(time_since_last) > kTimerIntervalInMilliseconds / 2) {
henrika87d11cd2017-02-08 07:16:56 -0800412 uint32_t diff_samples = stats.rec_samples - last_stats_.rec_samples;
henrikaa6d26ec2016-09-20 04:44:04 -0700413 float rate = diff_samples / (static_cast<float>(time_since_last) / 1000.0);
henrikacfbd26d2018-09-05 11:36:22 +0200414 uint32_t abs_diff_rate_in_percent = 0;
henrikaf1239b52018-09-25 15:39:22 +0200415 if (rec_sample_rate > 0 && rate > 0) {
henrikacfbd26d2018-09-05 11:36:22 +0200416 abs_diff_rate_in_percent = static_cast<uint32_t>(
417 0.5f +
418 ((100.0f * std::abs(rate - rec_sample_rate)) / rec_sample_rate));
419 RTC_HISTOGRAM_PERCENTAGE("WebRTC.Audio.RecordSampleRateOffsetInPercent",
420 abs_diff_rate_in_percent);
Harald Alvestrand97597c02021-11-04 12:01:23 +0000421 RTC_LOG(LS_INFO) << "[REC : " << time_since_last << "msec, "
422 << rec_sample_rate / 1000 << "kHz] callbacks: "
423 << stats.rec_callbacks - last_stats_.rec_callbacks
424 << ", "
425 "samples: "
426 << diff_samples
427 << ", "
428 "rate: "
429 << static_cast<int>(rate + 0.5)
430 << ", "
431 "rate diff: "
432 << abs_diff_rate_in_percent
433 << "%, "
434 "level: "
435 << stats.max_rec_level;
henrikacfbd26d2018-09-05 11:36:22 +0200436 }
henrika6c4d0f02016-07-14 05:54:19 -0700437
henrika87d11cd2017-02-08 07:16:56 -0800438 diff_samples = stats.play_samples - last_stats_.play_samples;
henrikaa6d26ec2016-09-20 04:44:04 -0700439 rate = diff_samples / (static_cast<float>(time_since_last) / 1000.0);
henrikacfbd26d2018-09-05 11:36:22 +0200440 abs_diff_rate_in_percent = 0;
henrikaf1239b52018-09-25 15:39:22 +0200441 if (play_sample_rate > 0 && rate > 0) {
henrikacfbd26d2018-09-05 11:36:22 +0200442 abs_diff_rate_in_percent = static_cast<uint32_t>(
443 0.5f +
444 ((100.0f * std::abs(rate - play_sample_rate)) / play_sample_rate));
445 RTC_HISTOGRAM_PERCENTAGE("WebRTC.Audio.PlayoutSampleRateOffsetInPercent",
446 abs_diff_rate_in_percent);
Harald Alvestrand97597c02021-11-04 12:01:23 +0000447 RTC_LOG(LS_INFO) << "[PLAY: " << time_since_last << "msec, "
448 << play_sample_rate / 1000 << "kHz] callbacks: "
449 << stats.play_callbacks - last_stats_.play_callbacks
450 << ", "
451 "samples: "
452 << diff_samples
453 << ", "
454 "rate: "
455 << static_cast<int>(rate + 0.5)
456 << ", "
457 "rate diff: "
458 << abs_diff_rate_in_percent
459 << "%, "
460 "level: "
461 << stats.max_play_level;
henrikacfbd26d2018-09-05 11:36:22 +0200462 }
henrikaf06f35a2016-09-09 14:23:11 +0200463 }
henrikacfbd26d2018-09-05 11:36:22 +0200464 last_stats_ = stats;
henrikaf06f35a2016-09-09 14:23:11 +0200465
henrika6c4d0f02016-07-14 05:54:19 -0700466 int64_t time_to_wait_ms = next_callback_time - rtc::TimeMillis();
467 RTC_DCHECK_GT(time_to_wait_ms, 0) << "Invalid timer interval";
468
henrikaba156cf2016-10-31 08:18:50 -0700469 // Keep posting new (delayed) tasks until state is changed to kLogStop.
Niels Möllerf77aa812021-01-14 11:50:19 +0100470 task_queue_.PostDelayedTask(
471 [this] { AudioDeviceBuffer::LogStats(AudioDeviceBuffer::LOG_ACTIVE); },
472 time_to_wait_ms);
henrika6c4d0f02016-07-14 05:54:19 -0700473}
474
henrikaf06f35a2016-09-09 14:23:11 +0200475void AudioDeviceBuffer::ResetRecStats() {
henrikaf5022222016-11-07 15:56:59 +0100476 RTC_DCHECK_RUN_ON(&task_queue_);
henrika87d11cd2017-02-08 07:16:56 -0800477 last_stats_.ResetRecStats();
Markus Handell5f612822020-07-08 10:13:20 +0200478 MutexLock lock(&lock_);
henrika87d11cd2017-02-08 07:16:56 -0800479 stats_.ResetRecStats();
henrikaf06f35a2016-09-09 14:23:11 +0200480}
481
482void AudioDeviceBuffer::ResetPlayStats() {
henrikaf5022222016-11-07 15:56:59 +0100483 RTC_DCHECK_RUN_ON(&task_queue_);
henrika87d11cd2017-02-08 07:16:56 -0800484 last_stats_.ResetPlayStats();
Markus Handell5f612822020-07-08 10:13:20 +0200485 MutexLock lock(&lock_);
henrika87d11cd2017-02-08 07:16:56 -0800486 stats_.ResetPlayStats();
henrikaf06f35a2016-09-09 14:23:11 +0200487}
488
henrika51e96082016-11-10 00:40:37 -0800489void AudioDeviceBuffer::UpdateRecStats(int16_t max_abs,
490 size_t samples_per_channel) {
Markus Handell5f612822020-07-08 10:13:20 +0200491 MutexLock lock(&lock_);
henrika87d11cd2017-02-08 07:16:56 -0800492 ++stats_.rec_callbacks;
493 stats_.rec_samples += samples_per_channel;
494 if (max_abs > stats_.max_rec_level) {
495 stats_.max_rec_level = max_abs;
henrikaf06f35a2016-09-09 14:23:11 +0200496 }
henrika6c4d0f02016-07-14 05:54:19 -0700497}
498
henrika51e96082016-11-10 00:40:37 -0800499void AudioDeviceBuffer::UpdatePlayStats(int16_t max_abs,
500 size_t samples_per_channel) {
Markus Handell5f612822020-07-08 10:13:20 +0200501 MutexLock lock(&lock_);
henrika87d11cd2017-02-08 07:16:56 -0800502 ++stats_.play_callbacks;
503 stats_.play_samples += samples_per_channel;
504 if (max_abs > stats_.max_play_level) {
505 stats_.max_play_level = max_abs;
henrikaf06f35a2016-09-09 14:23:11 +0200506 }
henrika6c4d0f02016-07-14 05:54:19 -0700507}
508
niklase@google.com470e71d2011-07-07 08:21:25 +0000509} // namespace webrtc