blob: ec6a8be490b08d513e6997ea76216d7d4223a6cc [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
henrika3d7346f2016-07-29 16:20:47 +020011#include <algorithm>
12
pbos@webrtc.org811269d2013-07-11 13:24:38 +000013#include "webrtc/modules/audio_device/audio_device_buffer.h"
andrew@webrtc.org25534502013-09-13 00:02:13 +000014
henrika3d7346f2016-07-29 16:20:47 +020015#include "webrtc/base/arraysize.h"
henrika6c4d0f02016-07-14 05:54:19 -070016#include "webrtc/base/bind.h"
henrika3f33e2a2016-07-06 00:33:57 -070017#include "webrtc/base/checks.h"
18#include "webrtc/base/logging.h"
Peter Kastingdce40cf2015-08-24 14:52:23 -070019#include "webrtc/base/format_macros.h"
henrika6c4d0f02016-07-14 05:54:19 -070020#include "webrtc/base/timeutils.h"
henrikaf06f35a2016-09-09 14:23:11 +020021#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
pbos@webrtc.org811269d2013-07-11 13:24:38 +000022#include "webrtc/modules/audio_device/audio_device_config.h"
henrikaf06f35a2016-09-09 14:23:11 +020023#include "webrtc/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;
henrika6c4d0f02016-07-14 05:54:19 -070039
henrika0fd68012016-07-04 13:01:19 +020040AudioDeviceBuffer::AudioDeviceBuffer()
henrika49810512016-08-22 05:56:12 -070041 : audio_transport_cb_(nullptr),
henrika6c4d0f02016-07-14 05:54:19 -070042 task_queue_(kTimerQueueName),
henrikaba156cf2016-10-31 08:18:50 -070043 playing_(false),
44 recording_(false),
henrika49810512016-08-22 05:56:12 -070045 rec_sample_rate_(0),
46 play_sample_rate_(0),
47 rec_channels_(0),
48 play_channels_(0),
henrika49810512016-08-22 05:56:12 -070049 rec_bytes_per_sample_(0),
50 play_bytes_per_sample_(0),
henrika49810512016-08-22 05:56:12 -070051 current_mic_level_(0),
52 new_mic_level_(0),
53 typing_status_(false),
54 play_delay_ms_(0),
55 rec_delay_ms_(0),
56 clock_drift_(0),
henrika6c4d0f02016-07-14 05:54:19 -070057 num_stat_reports_(0),
58 rec_callbacks_(0),
59 last_rec_callbacks_(0),
60 play_callbacks_(0),
61 last_play_callbacks_(0),
62 rec_samples_(0),
63 last_rec_samples_(0),
64 play_samples_(0),
65 last_play_samples_(0),
henrikaba156cf2016-10-31 08:18:50 -070066 last_timer_task_time_(0),
henrikaf06f35a2016-09-09 14:23:11 +020067 max_rec_level_(0),
68 max_play_level_(0),
henrika3355f6d2016-10-21 12:45:25 +020069 rec_stat_count_(0),
henrikaba156cf2016-10-31 08:18:50 -070070 play_stat_count_(0),
71 play_start_time_(0),
72 rec_start_time_(0),
73 only_silence_recorded_(true) {
henrika3f33e2a2016-07-06 00:33:57 -070074 LOG(INFO) << "AudioDeviceBuffer::ctor";
niklase@google.com470e71d2011-07-07 08:21:25 +000075}
76
henrika0fd68012016-07-04 13:01:19 +020077AudioDeviceBuffer::~AudioDeviceBuffer() {
henrika6c4d0f02016-07-14 05:54:19 -070078 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrikaba156cf2016-10-31 08:18:50 -070079 RTC_DCHECK(!playing_);
80 RTC_DCHECK(!recording_);
henrika3f33e2a2016-07-06 00:33:57 -070081 LOG(INFO) << "AudioDeviceBuffer::~dtor";
niklase@google.com470e71d2011-07-07 08:21:25 +000082}
83
henrika0fd68012016-07-04 13:01:19 +020084int32_t AudioDeviceBuffer::RegisterAudioCallback(
henrika49810512016-08-22 05:56:12 -070085 AudioTransport* audio_callback) {
henrika3f33e2a2016-07-06 00:33:57 -070086 LOG(INFO) << __FUNCTION__;
henrika5588a132016-10-18 05:14:30 -070087 rtc::CritScope lock(&lock_cb_);
henrika49810512016-08-22 05:56:12 -070088 audio_transport_cb_ = audio_callback;
henrika0fd68012016-07-04 13:01:19 +020089 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +000090}
91
henrikaba156cf2016-10-31 08:18:50 -070092void AudioDeviceBuffer::StartPlayout() {
henrika49810512016-08-22 05:56:12 -070093 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrikaba156cf2016-10-31 08:18:50 -070094 // TODO(henrika): allow for usage of DCHECK(!playing_) here instead. Today the
95 // ADM allows calling Start(), Start() by ignoring the second call but it
96 // makes more sense to only allow one call.
97 if (playing_) {
98 return;
henrika6c4d0f02016-07-14 05:54:19 -070099 }
henrikaba156cf2016-10-31 08:18:50 -0700100 LOG(INFO) << __FUNCTION__;
101 // Clear members tracking playout stats and do it on the task queue.
102 task_queue_.PostTask([this] { ResetPlayStats(); });
103 // Start a periodic timer based on task queue if not already done by the
104 // recording side.
105 if (!recording_) {
106 StartPeriodicLogging();
107 }
108 const uint64_t now_time = rtc::TimeMillis();
109 // Clear members that are only touched on the main (creating) thread.
110 play_start_time_ = now_time;
111 last_playout_time_ = now_time;
112 playing_ = true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000113}
114
henrikaba156cf2016-10-31 08:18:50 -0700115void AudioDeviceBuffer::StartRecording() {
henrika49810512016-08-22 05:56:12 -0700116 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrikaba156cf2016-10-31 08:18:50 -0700117 if (recording_) {
118 return;
henrika6c4d0f02016-07-14 05:54:19 -0700119 }
henrikaba156cf2016-10-31 08:18:50 -0700120 LOG(INFO) << __FUNCTION__;
121 // Clear members tracking recording stats and do it on the task queue.
122 task_queue_.PostTask([this] { ResetRecStats(); });
123 // Start a periodic timer based on task queue if not already done by the
124 // playout side.
125 if (!playing_) {
126 StartPeriodicLogging();
127 }
128 // Clear members that will be touched on the main (creating) thread.
129 rec_start_time_ = rtc::TimeMillis();
130 recording_ = true;
131 // And finally a member which can be modified on the native audio thread.
132 // It is safe to do so since we know by design that the owning ADM has not
133 // yet started the native audio recording.
134 only_silence_recorded_ = true;
135}
136
137void AudioDeviceBuffer::StopPlayout() {
138 RTC_DCHECK(thread_checker_.CalledOnValidThread());
139 if (!playing_) {
140 return;
141 }
142 LOG(INFO) << __FUNCTION__;
143 playing_ = false;
144 // Stop periodic logging if no more media is active.
145 if (!recording_) {
146 StopPeriodicLogging();
147 }
148 // Add diagnostic logging of delta times for playout callbacks. We are doing
149 // this wihout a lock since playout should be stopped by now and it a minor
150 // conflict during stop will not have a great impact on the total statistics.
151 const size_t time_since_start = rtc::TimeSince(play_start_time_);
152 if (time_since_start > kMinValidCallTimeTimeInMilliseconds) {
153 size_t total_diff_time = 0;
154 int num_measurements = 0;
155 LOG(INFO) << "[playout diff time => #measurements]";
156 for (size_t diff = 0; diff < arraysize(playout_diff_times_); ++diff) {
157 uint32_t num_elements = playout_diff_times_[diff];
158 if (num_elements > 0) {
159 total_diff_time += num_elements * diff;
160 num_measurements += num_elements;
161 LOG(INFO) << "[" << diff << " => " << num_elements << "]";
162 }
163 }
164 if (num_measurements > 0) {
165 LOG(INFO) << "total_diff_time: " << total_diff_time << ", "
166 << "num_measurements: " << num_measurements << ", "
167 << "average: "
168 << static_cast<float>(total_diff_time) / num_measurements;
169 }
170 }
171 LOG(INFO) << "total playout time: " << time_since_start;
172}
173
174void AudioDeviceBuffer::StopRecording() {
175 RTC_DCHECK(thread_checker_.CalledOnValidThread());
176 if (!recording_) {
177 return;
178 }
179 LOG(INFO) << __FUNCTION__;
180 recording_ = false;
181 // Stop periodic logging if no more media is active.
182 if (!playing_) {
183 StopPeriodicLogging();
184 }
185 // Add UMA histogram to keep track of the case when only zeros have been
186 // recorded. Measurements (max of absolute level) are taken twice per second,
187 // which means that if e.g 10 seconds of audio has been recorded, a total of
188 // 20 level estimates must all be identical to zero to trigger the histogram.
189 // |only_silence_recorded_| can only be cleared on the native audio thread
190 // that drives audio capture but we know by design that the audio has stopped
191 // when this method is called, hence there should not be aby conflicts. Also,
192 // the fact that |only_silence_recorded_| can be affected during the complete
193 // call makes chances of conflicts with potentially one last callback very
194 // small.
195 const size_t time_since_start = rtc::TimeSince(rec_start_time_);
196 if (time_since_start > kMinValidCallTimeTimeInMilliseconds) {
197 const int only_zeros = static_cast<int>(only_silence_recorded_);
198 RTC_HISTOGRAM_BOOLEAN("WebRTC.Audio.RecordedOnlyZeros", only_zeros);
199 LOG(INFO) << "HISTOGRAM(WebRTC.Audio.RecordedOnlyZeros): " << only_zeros;
200 }
201 LOG(INFO) << "total recording time: " << time_since_start;
niklase@google.com470e71d2011-07-07 08:21:25 +0000202}
203
henrika0fd68012016-07-04 13:01:19 +0200204int32_t AudioDeviceBuffer::SetRecordingSampleRate(uint32_t fsHz) {
henrika3f33e2a2016-07-06 00:33:57 -0700205 LOG(INFO) << "SetRecordingSampleRate(" << fsHz << ")";
henrika5588a132016-10-18 05:14:30 -0700206 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrika49810512016-08-22 05:56:12 -0700207 rec_sample_rate_ = fsHz;
henrika0fd68012016-07-04 13:01:19 +0200208 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000209}
210
henrika0fd68012016-07-04 13:01:19 +0200211int32_t AudioDeviceBuffer::SetPlayoutSampleRate(uint32_t fsHz) {
henrika3f33e2a2016-07-06 00:33:57 -0700212 LOG(INFO) << "SetPlayoutSampleRate(" << fsHz << ")";
henrika5588a132016-10-18 05:14:30 -0700213 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrika49810512016-08-22 05:56:12 -0700214 play_sample_rate_ = fsHz;
henrika0fd68012016-07-04 13:01:19 +0200215 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000216}
217
henrika0fd68012016-07-04 13:01:19 +0200218int32_t AudioDeviceBuffer::RecordingSampleRate() const {
henrika49810512016-08-22 05:56:12 -0700219 return rec_sample_rate_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000220}
221
henrika0fd68012016-07-04 13:01:19 +0200222int32_t AudioDeviceBuffer::PlayoutSampleRate() const {
henrika49810512016-08-22 05:56:12 -0700223 return play_sample_rate_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000224}
225
henrika0fd68012016-07-04 13:01:19 +0200226int32_t AudioDeviceBuffer::SetRecordingChannels(size_t channels) {
henrika49810512016-08-22 05:56:12 -0700227 LOG(INFO) << "SetRecordingChannels(" << channels << ")";
henrika5588a132016-10-18 05:14:30 -0700228 rtc::CritScope lock(&lock_);
henrika49810512016-08-22 05:56:12 -0700229 rec_channels_ = channels;
henrika5588a132016-10-18 05:14:30 -0700230 rec_bytes_per_sample_ = sizeof(int16_t) * channels;
henrika0fd68012016-07-04 13:01:19 +0200231 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000232}
233
henrika0fd68012016-07-04 13:01:19 +0200234int32_t AudioDeviceBuffer::SetPlayoutChannels(size_t channels) {
henrika49810512016-08-22 05:56:12 -0700235 LOG(INFO) << "SetPlayoutChannels(" << channels << ")";
henrika5588a132016-10-18 05:14:30 -0700236 rtc::CritScope lock(&lock_);
henrika49810512016-08-22 05:56:12 -0700237 play_channels_ = channels;
henrika5588a132016-10-18 05:14:30 -0700238 play_bytes_per_sample_ = sizeof(int16_t) * channels;
henrika0fd68012016-07-04 13:01:19 +0200239 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000240}
241
henrika0fd68012016-07-04 13:01:19 +0200242int32_t AudioDeviceBuffer::SetRecordingChannel(
243 const AudioDeviceModule::ChannelType channel) {
henrika5588a132016-10-18 05:14:30 -0700244 LOG(INFO) << "SetRecordingChannel(" << channel << ")";
245 LOG(LS_WARNING) << "Not implemented";
246 // Add DCHECK to ensure that user does not try to use this API with a non-
247 // default parameter.
248 RTC_DCHECK_EQ(channel, AudioDeviceModule::kChannelBoth);
249 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +0000250}
251
henrika0fd68012016-07-04 13:01:19 +0200252int32_t AudioDeviceBuffer::RecordingChannel(
253 AudioDeviceModule::ChannelType& channel) const {
henrika5588a132016-10-18 05:14:30 -0700254 LOG(LS_WARNING) << "Not implemented";
255 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +0000256}
257
henrika0fd68012016-07-04 13:01:19 +0200258size_t AudioDeviceBuffer::RecordingChannels() const {
henrika49810512016-08-22 05:56:12 -0700259 return rec_channels_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000260}
261
henrika0fd68012016-07-04 13:01:19 +0200262size_t AudioDeviceBuffer::PlayoutChannels() const {
henrika49810512016-08-22 05:56:12 -0700263 return play_channels_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000264}
265
henrika0fd68012016-07-04 13:01:19 +0200266int32_t AudioDeviceBuffer::SetCurrentMicLevel(uint32_t level) {
henrika49810512016-08-22 05:56:12 -0700267 current_mic_level_ = level;
henrika0fd68012016-07-04 13:01:19 +0200268 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000269}
270
henrika49810512016-08-22 05:56:12 -0700271int32_t AudioDeviceBuffer::SetTypingStatus(bool typing_status) {
272 typing_status_ = typing_status;
henrika0fd68012016-07-04 13:01:19 +0200273 return 0;
niklas.enbom@webrtc.org3be565b2013-05-07 21:04:24 +0000274}
275
henrika0fd68012016-07-04 13:01:19 +0200276uint32_t AudioDeviceBuffer::NewMicLevel() const {
henrika49810512016-08-22 05:56:12 -0700277 return new_mic_level_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000278}
279
henrika49810512016-08-22 05:56:12 -0700280void AudioDeviceBuffer::SetVQEData(int play_delay_ms,
281 int rec_delay_ms,
282 int clock_drift) {
283 play_delay_ms_ = play_delay_ms;
284 rec_delay_ms_ = rec_delay_ms;
285 clock_drift_ = clock_drift;
niklase@google.com470e71d2011-07-07 08:21:25 +0000286}
287
pbos@webrtc.org25509882013-04-09 10:30:35 +0000288int32_t AudioDeviceBuffer::StartInputFileRecording(
henrika0fd68012016-07-04 13:01:19 +0200289 const char fileName[kAdmMaxFileNameSize]) {
henrika49810512016-08-22 05:56:12 -0700290 LOG(LS_WARNING) << "Not implemented";
291 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000292}
293
henrika0fd68012016-07-04 13:01:19 +0200294int32_t AudioDeviceBuffer::StopInputFileRecording() {
henrika49810512016-08-22 05:56:12 -0700295 LOG(LS_WARNING) << "Not implemented";
henrika0fd68012016-07-04 13:01:19 +0200296 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000297}
298
pbos@webrtc.org25509882013-04-09 10:30:35 +0000299int32_t AudioDeviceBuffer::StartOutputFileRecording(
henrika0fd68012016-07-04 13:01:19 +0200300 const char fileName[kAdmMaxFileNameSize]) {
henrika49810512016-08-22 05:56:12 -0700301 LOG(LS_WARNING) << "Not implemented";
henrikacf327b42016-08-19 16:37:53 +0200302 return 0;
303}
304
henrika49810512016-08-22 05:56:12 -0700305int32_t AudioDeviceBuffer::StopOutputFileRecording() {
306 LOG(LS_WARNING) << "Not implemented";
307 return 0;
308}
309
310int32_t AudioDeviceBuffer::SetRecordedBuffer(const void* audio_buffer,
311 size_t num_samples) {
henrika3355f6d2016-10-21 12:45:25 +0200312 const size_t rec_channels = [&] {
henrika5588a132016-10-18 05:14:30 -0700313 rtc::CritScope lock(&lock_);
henrika3355f6d2016-10-21 12:45:25 +0200314 return rec_channels_;
henrika5588a132016-10-18 05:14:30 -0700315 }();
316 // Copy the complete input buffer to the local buffer.
henrika3355f6d2016-10-21 12:45:25 +0200317 const size_t size_in_bytes = num_samples * rec_channels * sizeof(int16_t);
henrika5588a132016-10-18 05:14:30 -0700318 const size_t old_size = rec_buffer_.size();
319 rec_buffer_.SetData(static_cast<const uint8_t*>(audio_buffer), size_in_bytes);
320 // Keep track of the size of the recording buffer. Only updated when the
321 // size changes, which is a rare event.
322 if (old_size != rec_buffer_.size()) {
323 LOG(LS_INFO) << "Size of recording buffer: " << rec_buffer_.size();
henrika0fd68012016-07-04 13:01:19 +0200324 }
henrikaba156cf2016-10-31 08:18:50 -0700325 // Derive a new level value twice per second and check if it is non-zero.
henrika3355f6d2016-10-21 12:45:25 +0200326 int16_t max_abs = 0;
327 RTC_DCHECK_LT(rec_stat_count_, 50);
328 if (++rec_stat_count_ >= 50) {
329 const size_t size = num_samples * rec_channels;
330 // Returns the largest absolute value in a signed 16-bit vector.
331 max_abs = WebRtcSpl_MaxAbsValueW16(
332 reinterpret_cast<const int16_t*>(rec_buffer_.data()), size);
333 rec_stat_count_ = 0;
henrikaba156cf2016-10-31 08:18:50 -0700334 // Set |only_silence_recorded_| to false as soon as at least one detection
335 // of a non-zero audio packet is found. It can only be restored to true
336 // again by restarting the call.
337 if (max_abs > 0) {
338 only_silence_recorded_ = false;
339 }
henrika3355f6d2016-10-21 12:45:25 +0200340 }
henrika6c4d0f02016-07-14 05:54:19 -0700341 // Update some stats but do it on the task queue to ensure that the members
henrika3355f6d2016-10-21 12:45:25 +0200342 // are modified and read on the same thread. Note that |max_abs| will be
343 // zero in most calls and then have no effect of the stats. It is only updated
344 // approximately two times per second and can then change the stats.
henrikaba156cf2016-10-31 08:18:50 -0700345 task_queue_.PostTask(
346 [this, max_abs, num_samples] { UpdateRecStats(max_abs, num_samples); });
henrika0fd68012016-07-04 13:01:19 +0200347 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000348}
349
henrika0fd68012016-07-04 13:01:19 +0200350int32_t AudioDeviceBuffer::DeliverRecordedData() {
henrika5588a132016-10-18 05:14:30 -0700351 rtc::CritScope lock(&lock_cb_);
henrika49810512016-08-22 05:56:12 -0700352 if (!audio_transport_cb_) {
henrika3f33e2a2016-07-06 00:33:57 -0700353 LOG(LS_WARNING) << "Invalid audio transport";
niklase@google.com470e71d2011-07-07 08:21:25 +0000354 return 0;
henrika0fd68012016-07-04 13:01:19 +0200355 }
henrika5588a132016-10-18 05:14:30 -0700356 const size_t rec_bytes_per_sample = [&] {
357 rtc::CritScope lock(&lock_);
358 return rec_bytes_per_sample_;
359 }();
360 uint32_t new_mic_level(0);
361 uint32_t total_delay_ms = play_delay_ms_ + rec_delay_ms_;
362 size_t num_samples = rec_buffer_.size() / rec_bytes_per_sample;
363 int32_t res = audio_transport_cb_->RecordedDataIsAvailable(
364 rec_buffer_.data(), num_samples, rec_bytes_per_sample_, rec_channels_,
365 rec_sample_rate_, total_delay_ms, clock_drift_, current_mic_level_,
366 typing_status_, new_mic_level);
henrika0fd68012016-07-04 13:01:19 +0200367 if (res != -1) {
henrika5588a132016-10-18 05:14:30 -0700368 new_mic_level_ = new_mic_level;
henrika49810512016-08-22 05:56:12 -0700369 } else {
370 LOG(LS_ERROR) << "RecordedDataIsAvailable() failed";
henrika0fd68012016-07-04 13:01:19 +0200371 }
henrika0fd68012016-07-04 13:01:19 +0200372 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000373}
374
henrika49810512016-08-22 05:56:12 -0700375int32_t AudioDeviceBuffer::RequestPlayoutData(size_t num_samples) {
henrika3d7346f2016-07-29 16:20:47 +0200376 // Measure time since last function call and update an array where the
377 // position/index corresponds to time differences (in milliseconds) between
378 // two successive playout callbacks, and the stored value is the number of
379 // times a given time difference was found.
380 int64_t now_time = rtc::TimeMillis();
381 size_t diff_time = rtc::TimeDiff(now_time, last_playout_time_);
382 // Truncate at 500ms to limit the size of the array.
383 diff_time = std::min(kMaxDeltaTimeInMs, diff_time);
384 last_playout_time_ = now_time;
385 playout_diff_times_[diff_time]++;
386
henrika3355f6d2016-10-21 12:45:25 +0200387 const size_t play_channels = [&] {
henrika5588a132016-10-18 05:14:30 -0700388 rtc::CritScope lock(&lock_);
henrika3355f6d2016-10-21 12:45:25 +0200389 return play_channels_;
henrika5588a132016-10-18 05:14:30 -0700390 }();
henrika0fd68012016-07-04 13:01:19 +0200391
henrika5588a132016-10-18 05:14:30 -0700392 // The consumer can change the request size on the fly and we therefore
393 // resize the buffer accordingly. Also takes place at the first call to this
394 // method.
henrika3355f6d2016-10-21 12:45:25 +0200395 const size_t play_bytes_per_sample = play_channels * sizeof(int16_t);
henrika5588a132016-10-18 05:14:30 -0700396 const size_t size_in_bytes = num_samples * play_bytes_per_sample;
397 if (play_buffer_.size() != size_in_bytes) {
398 play_buffer_.SetSize(size_in_bytes);
399 LOG(LS_INFO) << "Size of playout buffer: " << play_buffer_.size();
400 }
401
henrika49810512016-08-22 05:56:12 -0700402 size_t num_samples_out(0);
henrikaba156cf2016-10-31 08:18:50 -0700403 {
404 rtc::CritScope lock(&lock_cb_);
405
406 // It is currently supported to start playout without a valid audio
407 // transport object. Leads to warning and silence.
408 if (!audio_transport_cb_) {
409 LOG(LS_WARNING) << "Invalid audio transport";
410 return 0;
411 }
412
413 // Retrieve new 16-bit PCM audio data using the audio transport instance.
414 int64_t elapsed_time_ms = -1;
415 int64_t ntp_time_ms = -1;
416 uint32_t res = audio_transport_cb_->NeedMorePlayData(
417 num_samples, play_bytes_per_sample_, play_channels, play_sample_rate_,
418 play_buffer_.data(), num_samples_out, &elapsed_time_ms, &ntp_time_ms);
419 if (res != 0) {
420 LOG(LS_ERROR) << "NeedMorePlayData() failed";
421 }
henrika0fd68012016-07-04 13:01:19 +0200422 }
423
henrika3355f6d2016-10-21 12:45:25 +0200424 // Derive a new level value twice per second.
425 int16_t max_abs = 0;
426 RTC_DCHECK_LT(play_stat_count_, 50);
427 if (++play_stat_count_ >= 50) {
428 const size_t size = num_samples * play_channels;
429 // Returns the largest absolute value in a signed 16-bit vector.
430 max_abs = WebRtcSpl_MaxAbsValueW16(
431 reinterpret_cast<const int16_t*>(play_buffer_.data()), size);
432 play_stat_count_ = 0;
433 }
434 // Update some stats but do it on the task queue to ensure that the members
435 // are modified and read on the same thread. Note that |max_abs| will be
436 // zero in most calls and then have no effect of the stats. It is only updated
437 // approximately two times per second and can then change the stats.
henrikaba156cf2016-10-31 08:18:50 -0700438 task_queue_.PostTask([this, max_abs, num_samples_out] {
439 UpdatePlayStats(max_abs, num_samples_out);
440 });
henrika49810512016-08-22 05:56:12 -0700441 return static_cast<int32_t>(num_samples_out);
niklase@google.com470e71d2011-07-07 08:21:25 +0000442}
443
henrika49810512016-08-22 05:56:12 -0700444int32_t AudioDeviceBuffer::GetPlayoutData(void* audio_buffer) {
henrika5588a132016-10-18 05:14:30 -0700445 RTC_DCHECK_GT(play_buffer_.size(), 0u);
446 const size_t play_bytes_per_sample = [&] {
447 rtc::CritScope lock(&lock_);
448 return play_bytes_per_sample_;
449 }();
450 memcpy(audio_buffer, play_buffer_.data(), play_buffer_.size());
451 return static_cast<int32_t>(play_buffer_.size() / play_bytes_per_sample);
niklase@google.com470e71d2011-07-07 08:21:25 +0000452}
453
henrikaba156cf2016-10-31 08:18:50 -0700454void AudioDeviceBuffer::StartPeriodicLogging() {
455 task_queue_.PostTask(rtc::Bind(&AudioDeviceBuffer::LogStats, this,
456 AudioDeviceBuffer::LOG_START));
henrika6c4d0f02016-07-14 05:54:19 -0700457}
458
henrikaba156cf2016-10-31 08:18:50 -0700459void AudioDeviceBuffer::StopPeriodicLogging() {
460 task_queue_.PostTask(rtc::Bind(&AudioDeviceBuffer::LogStats, this,
461 AudioDeviceBuffer::LOG_STOP));
462}
463
464void AudioDeviceBuffer::LogStats(LogState state) {
henrika6c4d0f02016-07-14 05:54:19 -0700465 RTC_DCHECK(task_queue_.IsCurrent());
henrika6c4d0f02016-07-14 05:54:19 -0700466 int64_t now_time = rtc::TimeMillis();
henrikaba156cf2016-10-31 08:18:50 -0700467 if (state == AudioDeviceBuffer::LOG_START) {
468 // Reset counters at start. We will not add any logging in this state but
469 // the timer will started by posting a new (delayed) task.
470 num_stat_reports_ = 0;
471 last_timer_task_time_ = now_time;
472 } else if (state == AudioDeviceBuffer::LOG_STOP) {
473 // Stop logging and posting new tasks.
474 return;
475 } else if (state == AudioDeviceBuffer::LOG_ACTIVE) {
476 // Default state. Just keep on logging.
477 }
henrika6c4d0f02016-07-14 05:54:19 -0700478
henrikaba156cf2016-10-31 08:18:50 -0700479 int64_t next_callback_time = now_time + kTimerIntervalInMilliseconds;
480 int64_t time_since_last = rtc::TimeDiff(now_time, last_timer_task_time_);
481 last_timer_task_time_ = now_time;
482
483 // Log the latest statistics but skip the first round just after state was
484 // set to LOG_START. Hence, first printed log will be after ~10 seconds.
henrikaa6d26ec2016-09-20 04:44:04 -0700485 if (++num_stat_reports_ > 1 && time_since_last > 0) {
henrika6c4d0f02016-07-14 05:54:19 -0700486 uint32_t diff_samples = rec_samples_ - last_rec_samples_;
henrikaa6d26ec2016-09-20 04:44:04 -0700487 float rate = diff_samples / (static_cast<float>(time_since_last) / 1000.0);
henrika6c4d0f02016-07-14 05:54:19 -0700488 LOG(INFO) << "[REC : " << time_since_last << "msec, "
henrika49810512016-08-22 05:56:12 -0700489 << rec_sample_rate_ / 1000
henrika6c4d0f02016-07-14 05:54:19 -0700490 << "kHz] callbacks: " << rec_callbacks_ - last_rec_callbacks_
491 << ", "
492 << "samples: " << diff_samples << ", "
henrikaa6d26ec2016-09-20 04:44:04 -0700493 << "rate: " << static_cast<int>(rate + 0.5) << ", "
henrikaf06f35a2016-09-09 14:23:11 +0200494 << "level: " << max_rec_level_;
henrika6c4d0f02016-07-14 05:54:19 -0700495
496 diff_samples = play_samples_ - last_play_samples_;
henrikaa6d26ec2016-09-20 04:44:04 -0700497 rate = diff_samples / (static_cast<float>(time_since_last) / 1000.0);
henrika6c4d0f02016-07-14 05:54:19 -0700498 LOG(INFO) << "[PLAY: " << time_since_last << "msec, "
henrika49810512016-08-22 05:56:12 -0700499 << play_sample_rate_ / 1000
henrika6c4d0f02016-07-14 05:54:19 -0700500 << "kHz] callbacks: " << play_callbacks_ - last_play_callbacks_
501 << ", "
502 << "samples: " << diff_samples << ", "
henrikaa6d26ec2016-09-20 04:44:04 -0700503 << "rate: " << static_cast<int>(rate + 0.5) << ", "
henrikaf06f35a2016-09-09 14:23:11 +0200504 << "level: " << max_play_level_;
505 }
506
henrika6c4d0f02016-07-14 05:54:19 -0700507 last_rec_callbacks_ = rec_callbacks_;
508 last_play_callbacks_ = play_callbacks_;
509 last_rec_samples_ = rec_samples_;
510 last_play_samples_ = play_samples_;
henrikaf06f35a2016-09-09 14:23:11 +0200511 max_rec_level_ = 0;
512 max_play_level_ = 0;
henrika6c4d0f02016-07-14 05:54:19 -0700513
514 int64_t time_to_wait_ms = next_callback_time - rtc::TimeMillis();
515 RTC_DCHECK_GT(time_to_wait_ms, 0) << "Invalid timer interval";
516
henrikaba156cf2016-10-31 08:18:50 -0700517 // Keep posting new (delayed) tasks until state is changed to kLogStop.
518 task_queue_.PostDelayedTask(rtc::Bind(&AudioDeviceBuffer::LogStats, this,
519 AudioDeviceBuffer::LOG_ACTIVE),
henrika6c4d0f02016-07-14 05:54:19 -0700520 time_to_wait_ms);
521}
522
henrikaf06f35a2016-09-09 14:23:11 +0200523void AudioDeviceBuffer::ResetRecStats() {
henrikaba156cf2016-10-31 08:18:50 -0700524 RTC_DCHECK(task_queue_.IsCurrent());
henrikaf06f35a2016-09-09 14:23:11 +0200525 rec_callbacks_ = 0;
526 last_rec_callbacks_ = 0;
527 rec_samples_ = 0;
528 last_rec_samples_ = 0;
529 max_rec_level_ = 0;
henrikaf06f35a2016-09-09 14:23:11 +0200530}
531
532void AudioDeviceBuffer::ResetPlayStats() {
henrikaba156cf2016-10-31 08:18:50 -0700533 RTC_DCHECK(task_queue_.IsCurrent());
henrikaf06f35a2016-09-09 14:23:11 +0200534 play_callbacks_ = 0;
535 last_play_callbacks_ = 0;
536 play_samples_ = 0;
537 last_play_samples_ = 0;
538 max_play_level_ = 0;
539}
540
henrika3355f6d2016-10-21 12:45:25 +0200541void AudioDeviceBuffer::UpdateRecStats(int16_t max_abs, size_t num_samples) {
henrika6c4d0f02016-07-14 05:54:19 -0700542 RTC_DCHECK(task_queue_.IsCurrent());
543 ++rec_callbacks_;
544 rec_samples_ += num_samples;
henrika3355f6d2016-10-21 12:45:25 +0200545 if (max_abs > max_rec_level_) {
546 max_rec_level_ = max_abs;
henrikaf06f35a2016-09-09 14:23:11 +0200547 }
henrika6c4d0f02016-07-14 05:54:19 -0700548}
549
henrika3355f6d2016-10-21 12:45:25 +0200550void AudioDeviceBuffer::UpdatePlayStats(int16_t max_abs, size_t num_samples) {
henrika6c4d0f02016-07-14 05:54:19 -0700551 RTC_DCHECK(task_queue_.IsCurrent());
552 ++play_callbacks_;
553 play_samples_ += num_samples;
henrika3355f6d2016-10-21 12:45:25 +0200554 if (max_abs > max_play_level_) {
555 max_play_level_ = max_abs;
henrikaf06f35a2016-09-09 14:23:11 +0200556 }
henrika6c4d0f02016-07-14 05:54:19 -0700557}
558
niklase@google.com470e71d2011-07-07 08:21:25 +0000559} // namespace webrtc