blob: 8cc11debf4d46ccd06da7af7846fd912cece3532 [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öm092d7762022-02-07 12:21:32 +0100249 // If the timestamp is less then or equal to zero, it's not valid and are
250 // ignored. If we do antimestamp alignment on them they might accidentally
251 // become greater then zero, and will be handled as if they were a correct
252 // timestamp.
253 capture_timestamp_ns_ =
254 (capture_timestamp_ns > 0)
255 ? rtc::kNumNanosecsPerMicrosec *
256 timestamp_aligner_.TranslateTimestamp(
257 capture_timestamp_ns_ / rtc::kNumNanosecsPerMicrosec,
258 rtc::TimeMicros())
259 : capture_timestamp_ns;
henrikaba156cf2016-10-31 08:18:50 -0700260 // Derive a new level value twice per second and check if it is non-zero.
henrika3355f6d2016-10-21 12:45:25 +0200261 int16_t max_abs = 0;
262 RTC_DCHECK_LT(rec_stat_count_, 50);
263 if (++rec_stat_count_ >= 50) {
henrika3355f6d2016-10-21 12:45:25 +0200264 // Returns the largest absolute value in a signed 16-bit vector.
henrika51e96082016-11-10 00:40:37 -0800265 max_abs = WebRtcSpl_MaxAbsValueW16(rec_buffer_.data(), rec_buffer_.size());
henrika3355f6d2016-10-21 12:45:25 +0200266 rec_stat_count_ = 0;
Artem Titov0146a342021-07-28 20:03:05 +0200267 // Set `only_silence_recorded_` to false as soon as at least one detection
henrikaba156cf2016-10-31 08:18:50 -0700268 // of a non-zero audio packet is found. It can only be restored to true
269 // again by restarting the call.
270 if (max_abs > 0) {
271 only_silence_recorded_ = false;
272 }
henrika3355f6d2016-10-21 12:45:25 +0200273 }
henrika87d11cd2017-02-08 07:16:56 -0800274 // Update recording stats which is used as base for periodic logging of the
275 // audio input state.
276 UpdateRecStats(max_abs, samples_per_channel);
henrika0fd68012016-07-04 13:01:19 +0200277 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000278}
279
henrika0fd68012016-07-04 13:01:19 +0200280int32_t AudioDeviceBuffer::DeliverRecordedData() {
henrika49810512016-08-22 05:56:12 -0700281 if (!audio_transport_cb_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100282 RTC_LOG(LS_WARNING) << "Invalid audio transport";
niklase@google.com470e71d2011-07-07 08:21:25 +0000283 return 0;
henrika0fd68012016-07-04 13:01:19 +0200284 }
henrika51e96082016-11-10 00:40:37 -0800285 const size_t frames = rec_buffer_.size() / rec_channels_;
286 const size_t bytes_per_frame = rec_channels_ * sizeof(int16_t);
Fredrik Solenberg1a50cd52018-01-16 09:19:38 +0100287 uint32_t new_mic_level_dummy = 0;
henrika5588a132016-10-18 05:14:30 -0700288 uint32_t total_delay_ms = play_delay_ms_ + rec_delay_ms_;
henrika5588a132016-10-18 05:14:30 -0700289 int32_t res = audio_transport_cb_->RecordedDataIsAvailable(
henrika51e96082016-11-10 00:40:37 -0800290 rec_buffer_.data(), frames, bytes_per_frame, rec_channels_,
Fredrik Solenberg1a50cd52018-01-16 09:19:38 +0100291 rec_sample_rate_, total_delay_ms, 0, 0, typing_status_,
Olov Brändströmb732bd52022-01-28 15:07:39 +0100292 new_mic_level_dummy, capture_timestamp_ns_);
Fredrik Solenberg1a50cd52018-01-16 09:19:38 +0100293 if (res == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100294 RTC_LOG(LS_ERROR) << "RecordedDataIsAvailable() failed";
henrika0fd68012016-07-04 13:01:19 +0200295 }
henrika0fd68012016-07-04 13:01:19 +0200296 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000297}
298
henrika51e96082016-11-10 00:40:37 -0800299int32_t AudioDeviceBuffer::RequestPlayoutData(size_t samples_per_channel) {
henrika51e96082016-11-10 00:40:37 -0800300 // The consumer can change the requested size on the fly and we therefore
henrika5588a132016-10-18 05:14:30 -0700301 // resize the buffer accordingly. Also takes place at the first call to this
302 // method.
henrika51e96082016-11-10 00:40:37 -0800303 const size_t total_samples = play_channels_ * samples_per_channel;
304 if (play_buffer_.size() != total_samples) {
305 play_buffer_.SetSize(total_samples);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100306 RTC_LOG(LS_INFO) << "Size of playout buffer: " << play_buffer_.size();
henrika5588a132016-10-18 05:14:30 -0700307 }
308
henrika49810512016-08-22 05:56:12 -0700309 size_t num_samples_out(0);
henrikaf5022222016-11-07 15:56:59 +0100310 // It is currently supported to start playout without a valid audio
311 // transport object. Leads to warning and silence.
312 if (!audio_transport_cb_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100313 RTC_LOG(LS_WARNING) << "Invalid audio transport";
henrikaf5022222016-11-07 15:56:59 +0100314 return 0;
315 }
henrikaba156cf2016-10-31 08:18:50 -0700316
henrikaf5022222016-11-07 15:56:59 +0100317 // Retrieve new 16-bit PCM audio data using the audio transport instance.
318 int64_t elapsed_time_ms = -1;
319 int64_t ntp_time_ms = -1;
henrika51e96082016-11-10 00:40:37 -0800320 const size_t bytes_per_frame = play_channels_ * sizeof(int16_t);
henrikaf5022222016-11-07 15:56:59 +0100321 uint32_t res = audio_transport_cb_->NeedMorePlayData(
henrika51e96082016-11-10 00:40:37 -0800322 samples_per_channel, bytes_per_frame, play_channels_, play_sample_rate_,
henrikaf5022222016-11-07 15:56:59 +0100323 play_buffer_.data(), num_samples_out, &elapsed_time_ms, &ntp_time_ms);
324 if (res != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100325 RTC_LOG(LS_ERROR) << "NeedMorePlayData() failed";
henrika0fd68012016-07-04 13:01:19 +0200326 }
327
henrika3355f6d2016-10-21 12:45:25 +0200328 // Derive a new level value twice per second.
329 int16_t max_abs = 0;
330 RTC_DCHECK_LT(play_stat_count_, 50);
331 if (++play_stat_count_ >= 50) {
henrika3355f6d2016-10-21 12:45:25 +0200332 // Returns the largest absolute value in a signed 16-bit vector.
henrika51e96082016-11-10 00:40:37 -0800333 max_abs =
334 WebRtcSpl_MaxAbsValueW16(play_buffer_.data(), play_buffer_.size());
henrika3355f6d2016-10-21 12:45:25 +0200335 play_stat_count_ = 0;
336 }
henrika87d11cd2017-02-08 07:16:56 -0800337 // Update playout stats which is used as base for periodic logging of the
338 // audio output state.
henrika76535de2017-09-11 01:25:55 -0700339 UpdatePlayStats(max_abs, num_samples_out / play_channels_);
340 return static_cast<int32_t>(num_samples_out / play_channels_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000341}
342
henrika49810512016-08-22 05:56:12 -0700343int32_t AudioDeviceBuffer::GetPlayoutData(void* audio_buffer) {
kwibergaf476c72016-11-28 15:21:39 -0800344 RTC_DCHECK_GT(play_buffer_.size(), 0);
henrika7be78832017-06-13 17:34:16 +0200345#ifdef AUDIO_DEVICE_PLAYS_SINUS_TONE
346 const double phase_increment =
347 k2Pi * 440.0 / static_cast<double>(play_sample_rate_);
348 int16_t* destination_r = reinterpret_cast<int16_t*>(audio_buffer);
henrika29e865a2018-04-24 13:22:31 +0200349 if (play_channels_ == 1) {
350 for (size_t i = 0; i < play_buffer_.size(); ++i) {
351 destination_r[i] = static_cast<int16_t>((sin(phase_) * (1 << 14)));
352 phase_ += phase_increment;
353 }
354 } else if (play_channels_ == 2) {
355 for (size_t i = 0; i < play_buffer_.size() / 2; ++i) {
356 destination_r[2 * i] = destination_r[2 * i + 1] =
357 static_cast<int16_t>((sin(phase_) * (1 << 14)));
358 phase_ += phase_increment;
359 }
henrika7be78832017-06-13 17:34:16 +0200360 }
361#else
henrika51e96082016-11-10 00:40:37 -0800362 memcpy(audio_buffer, play_buffer_.data(),
henrika7be78832017-06-13 17:34:16 +0200363 play_buffer_.size() * sizeof(int16_t));
364#endif
henrika51e96082016-11-10 00:40:37 -0800365 // Return samples per channel or number of frames.
366 return static_cast<int32_t>(play_buffer_.size() / play_channels_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000367}
368
henrikaba156cf2016-10-31 08:18:50 -0700369void AudioDeviceBuffer::StartPeriodicLogging() {
Niels Möllerf77aa812021-01-14 11:50:19 +0100370 task_queue_.PostTask([this] { LogStats(AudioDeviceBuffer::LOG_START); });
henrika6c4d0f02016-07-14 05:54:19 -0700371}
372
henrikaba156cf2016-10-31 08:18:50 -0700373void AudioDeviceBuffer::StopPeriodicLogging() {
Niels Möllerf77aa812021-01-14 11:50:19 +0100374 task_queue_.PostTask([this] { LogStats(AudioDeviceBuffer::LOG_STOP); });
henrikaba156cf2016-10-31 08:18:50 -0700375}
376
377void AudioDeviceBuffer::LogStats(LogState state) {
henrikaf5022222016-11-07 15:56:59 +0100378 RTC_DCHECK_RUN_ON(&task_queue_);
henrika6c4d0f02016-07-14 05:54:19 -0700379 int64_t now_time = rtc::TimeMillis();
henrika0b3a6382016-11-11 02:28:50 -0800380
henrikaba156cf2016-10-31 08:18:50 -0700381 if (state == AudioDeviceBuffer::LOG_START) {
382 // Reset counters at start. We will not add any logging in this state but
383 // the timer will started by posting a new (delayed) task.
384 num_stat_reports_ = 0;
385 last_timer_task_time_ = now_time;
henrika0b3a6382016-11-11 02:28:50 -0800386 log_stats_ = true;
henrikaba156cf2016-10-31 08:18:50 -0700387 } else if (state == AudioDeviceBuffer::LOG_STOP) {
388 // Stop logging and posting new tasks.
henrika0b3a6382016-11-11 02:28:50 -0800389 log_stats_ = false;
henrikaba156cf2016-10-31 08:18:50 -0700390 } else if (state == AudioDeviceBuffer::LOG_ACTIVE) {
henrika0b3a6382016-11-11 02:28:50 -0800391 // Keep logging unless logging was disabled while task was posted.
392 }
393
394 // Avoid adding more logs since we are in STOP mode.
395 if (!log_stats_) {
396 return;
henrikaba156cf2016-10-31 08:18:50 -0700397 }
henrika6c4d0f02016-07-14 05:54:19 -0700398
henrikaba156cf2016-10-31 08:18:50 -0700399 int64_t next_callback_time = now_time + kTimerIntervalInMilliseconds;
400 int64_t time_since_last = rtc::TimeDiff(now_time, last_timer_task_time_);
401 last_timer_task_time_ = now_time;
402
henrika87d11cd2017-02-08 07:16:56 -0800403 Stats stats;
404 {
Markus Handell5f612822020-07-08 10:13:20 +0200405 MutexLock lock(&lock_);
henrika87d11cd2017-02-08 07:16:56 -0800406 stats = stats_;
407 stats_.max_rec_level = 0;
408 stats_.max_play_level = 0;
409 }
410
henrikacfbd26d2018-09-05 11:36:22 +0200411 // Cache current sample rate from atomic members.
412 const uint32_t rec_sample_rate = rec_sample_rate_;
413 const uint32_t play_sample_rate = play_sample_rate_;
414
415 // Log the latest statistics but skip the first two rounds just after state
416 // was set to LOG_START to ensure that we have at least one full stable
417 // 10-second interval for sample-rate estimation. Hence, first printed log
418 // will be after ~20 seconds.
henrikac5fe1662018-09-13 16:57:01 +0200419 if (++num_stat_reports_ > 2 &&
420 static_cast<size_t>(time_since_last) > kTimerIntervalInMilliseconds / 2) {
henrika87d11cd2017-02-08 07:16:56 -0800421 uint32_t diff_samples = stats.rec_samples - last_stats_.rec_samples;
henrikaa6d26ec2016-09-20 04:44:04 -0700422 float rate = diff_samples / (static_cast<float>(time_since_last) / 1000.0);
henrikacfbd26d2018-09-05 11:36:22 +0200423 uint32_t abs_diff_rate_in_percent = 0;
henrikaf1239b52018-09-25 15:39:22 +0200424 if (rec_sample_rate > 0 && rate > 0) {
henrikacfbd26d2018-09-05 11:36:22 +0200425 abs_diff_rate_in_percent = static_cast<uint32_t>(
426 0.5f +
427 ((100.0f * std::abs(rate - rec_sample_rate)) / rec_sample_rate));
428 RTC_HISTOGRAM_PERCENTAGE("WebRTC.Audio.RecordSampleRateOffsetInPercent",
429 abs_diff_rate_in_percent);
Harald Alvestrand97597c02021-11-04 12:01:23 +0000430 RTC_LOG(LS_INFO) << "[REC : " << time_since_last << "msec, "
431 << rec_sample_rate / 1000 << "kHz] callbacks: "
432 << stats.rec_callbacks - last_stats_.rec_callbacks
433 << ", "
434 "samples: "
435 << diff_samples
436 << ", "
437 "rate: "
438 << static_cast<int>(rate + 0.5)
439 << ", "
440 "rate diff: "
441 << abs_diff_rate_in_percent
442 << "%, "
443 "level: "
444 << stats.max_rec_level;
henrikacfbd26d2018-09-05 11:36:22 +0200445 }
henrika6c4d0f02016-07-14 05:54:19 -0700446
henrika87d11cd2017-02-08 07:16:56 -0800447 diff_samples = stats.play_samples - last_stats_.play_samples;
henrikaa6d26ec2016-09-20 04:44:04 -0700448 rate = diff_samples / (static_cast<float>(time_since_last) / 1000.0);
henrikacfbd26d2018-09-05 11:36:22 +0200449 abs_diff_rate_in_percent = 0;
henrikaf1239b52018-09-25 15:39:22 +0200450 if (play_sample_rate > 0 && rate > 0) {
henrikacfbd26d2018-09-05 11:36:22 +0200451 abs_diff_rate_in_percent = static_cast<uint32_t>(
452 0.5f +
453 ((100.0f * std::abs(rate - play_sample_rate)) / play_sample_rate));
454 RTC_HISTOGRAM_PERCENTAGE("WebRTC.Audio.PlayoutSampleRateOffsetInPercent",
455 abs_diff_rate_in_percent);
Harald Alvestrand97597c02021-11-04 12:01:23 +0000456 RTC_LOG(LS_INFO) << "[PLAY: " << time_since_last << "msec, "
457 << play_sample_rate / 1000 << "kHz] callbacks: "
458 << stats.play_callbacks - last_stats_.play_callbacks
459 << ", "
460 "samples: "
461 << diff_samples
462 << ", "
463 "rate: "
464 << static_cast<int>(rate + 0.5)
465 << ", "
466 "rate diff: "
467 << abs_diff_rate_in_percent
468 << "%, "
469 "level: "
470 << stats.max_play_level;
henrikacfbd26d2018-09-05 11:36:22 +0200471 }
henrikaf06f35a2016-09-09 14:23:11 +0200472 }
henrikacfbd26d2018-09-05 11:36:22 +0200473 last_stats_ = stats;
henrikaf06f35a2016-09-09 14:23:11 +0200474
henrika6c4d0f02016-07-14 05:54:19 -0700475 int64_t time_to_wait_ms = next_callback_time - rtc::TimeMillis();
476 RTC_DCHECK_GT(time_to_wait_ms, 0) << "Invalid timer interval";
477
henrikaba156cf2016-10-31 08:18:50 -0700478 // Keep posting new (delayed) tasks until state is changed to kLogStop.
Niels Möllerf77aa812021-01-14 11:50:19 +0100479 task_queue_.PostDelayedTask(
Danil Chapovalovc05a1be2022-07-19 13:07:12 +0200480 [this] { AudioDeviceBuffer::LogStats(AudioDeviceBuffer::LOG_ACTIVE); },
481 TimeDelta::Millis(time_to_wait_ms));
henrika6c4d0f02016-07-14 05:54:19 -0700482}
483
henrikaf06f35a2016-09-09 14:23:11 +0200484void AudioDeviceBuffer::ResetRecStats() {
henrikaf5022222016-11-07 15:56:59 +0100485 RTC_DCHECK_RUN_ON(&task_queue_);
henrika87d11cd2017-02-08 07:16:56 -0800486 last_stats_.ResetRecStats();
Markus Handell5f612822020-07-08 10:13:20 +0200487 MutexLock lock(&lock_);
henrika87d11cd2017-02-08 07:16:56 -0800488 stats_.ResetRecStats();
henrikaf06f35a2016-09-09 14:23:11 +0200489}
490
491void AudioDeviceBuffer::ResetPlayStats() {
henrikaf5022222016-11-07 15:56:59 +0100492 RTC_DCHECK_RUN_ON(&task_queue_);
henrika87d11cd2017-02-08 07:16:56 -0800493 last_stats_.ResetPlayStats();
Markus Handell5f612822020-07-08 10:13:20 +0200494 MutexLock lock(&lock_);
henrika87d11cd2017-02-08 07:16:56 -0800495 stats_.ResetPlayStats();
henrikaf06f35a2016-09-09 14:23:11 +0200496}
497
henrika51e96082016-11-10 00:40:37 -0800498void AudioDeviceBuffer::UpdateRecStats(int16_t max_abs,
499 size_t samples_per_channel) {
Markus Handell5f612822020-07-08 10:13:20 +0200500 MutexLock lock(&lock_);
henrika87d11cd2017-02-08 07:16:56 -0800501 ++stats_.rec_callbacks;
502 stats_.rec_samples += samples_per_channel;
503 if (max_abs > stats_.max_rec_level) {
504 stats_.max_rec_level = max_abs;
henrikaf06f35a2016-09-09 14:23:11 +0200505 }
henrika6c4d0f02016-07-14 05:54:19 -0700506}
507
henrika51e96082016-11-10 00:40:37 -0800508void AudioDeviceBuffer::UpdatePlayStats(int16_t max_abs,
509 size_t samples_per_channel) {
Markus Handell5f612822020-07-08 10:13:20 +0200510 MutexLock lock(&lock_);
henrika87d11cd2017-02-08 07:16:56 -0800511 ++stats_.play_callbacks;
512 stats_.play_samples += samples_per_channel;
513 if (max_abs > stats_.max_play_level) {
514 stats_.max_play_level = max_abs;
henrikaf06f35a2016-09-09 14:23:11 +0200515 }
henrika6c4d0f02016-07-14 05:54:19 -0700516}
517
niklase@google.com470e71d2011-07-07 08:21:25 +0000518} // namespace webrtc