1 /*
2  *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3  *
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 #include <math.h>
11 #include <stdio.h>
12 
13 #include <algorithm>
14 #include <limits>
15 #include <memory>
16 #include <queue>
17 
18 #include "common_audio/include/audio_util.h"
19 #include "common_audio/resampler/include/push_resampler.h"
20 #include "common_audio/resampler/push_sinc_resampler.h"
21 #include "common_audio/signal_processing/include/signal_processing_library.h"
22 #include "modules/audio_processing/aec_dump/aec_dump_factory.h"
23 #include "modules/audio_processing/audio_processing_impl.h"
24 #include "modules/audio_processing/beamformer/mock_nonlinear_beamformer.h"
25 #include "modules/audio_processing/common.h"
26 #include "modules/audio_processing/include/audio_processing.h"
27 #include "modules/audio_processing/include/mock_audio_processing.h"
28 #include "modules/audio_processing/level_controller/level_controller_constants.h"
29 #include "modules/audio_processing/test/protobuf_utils.h"
30 #include "modules/audio_processing/test/test_utils.h"
31 #include "modules/include/module_common_types.h"
32 #include "rtc_base/arraysize.h"
33 #include "rtc_base/checks.h"
34 #include "rtc_base/gtest_prod_util.h"
35 #include "rtc_base/ignore_wundef.h"
36 #include "rtc_base/numerics/safe_minmax.h"
37 #include "rtc_base/protobuf_utils.h"
38 #include "rtc_base/refcountedobject.h"
39 #include "rtc_base/task_queue.h"
40 #include "rtc_base/thread.h"
41 #include "system_wrappers/include/event_wrapper.h"
42 #include "test/gtest.h"
43 #include "test/testsupport/fileutils.h"
44 
45 RTC_PUSH_IGNORING_WUNDEF()
46 #ifdef WEBRTC_ANDROID_PLATFORM_BUILD
47 #include "external/webrtc/webrtc/modules/audio_processing/test/unittest.pb.h"
48 #else
49 #include "modules/audio_processing/test/unittest.pb.h"
50 #endif
51 RTC_POP_IGNORING_WUNDEF()
52 
53 namespace webrtc {
54 namespace {
55 
56 // TODO(ekmeyerson): Switch to using StreamConfig and ProcessingConfig where
57 // applicable.
58 
59 // TODO(bjornv): This is not feasible until the functionality has been
60 // re-implemented; see comment at the bottom of this file. For now, the user has
61 // to hard code the |write_ref_data| value.
62 // When false, this will compare the output data with the results stored to
63 // file. This is the typical case. When the file should be updated, it can
64 // be set to true with the command-line switch --write_ref_data.
65 bool write_ref_data = false;
66 const int32_t kChannels[] = {1, 2};
67 const int kSampleRates[] = {8000, 16000, 32000, 48000};
68 
69 #if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
70 // Android doesn't support 48kHz.
71 const int kProcessSampleRates[] = {8000, 16000, 32000};
72 #elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
73 const int kProcessSampleRates[] = {8000, 16000, 32000, 48000};
74 #endif
75 
76 enum StreamDirection { kForward = 0, kReverse };
77 
ConvertToFloat(const int16_t * int_data,ChannelBuffer<float> * cb)78 void ConvertToFloat(const int16_t* int_data, ChannelBuffer<float>* cb) {
79   ChannelBuffer<int16_t> cb_int(cb->num_frames(),
80                                 cb->num_channels());
81   Deinterleave(int_data,
82                cb->num_frames(),
83                cb->num_channels(),
84                cb_int.channels());
85   for (size_t i = 0; i < cb->num_channels(); ++i) {
86     S16ToFloat(cb_int.channels()[i],
87                cb->num_frames(),
88                cb->channels()[i]);
89   }
90 }
91 
ConvertToFloat(const AudioFrame & frame,ChannelBuffer<float> * cb)92 void ConvertToFloat(const AudioFrame& frame, ChannelBuffer<float>* cb) {
93   ConvertToFloat(frame.data(), cb);
94 }
95 
96 // Number of channels including the keyboard channel.
TotalChannelsFromLayout(AudioProcessing::ChannelLayout layout)97 size_t TotalChannelsFromLayout(AudioProcessing::ChannelLayout layout) {
98   switch (layout) {
99     case AudioProcessing::kMono:
100       return 1;
101     case AudioProcessing::kMonoAndKeyboard:
102     case AudioProcessing::kStereo:
103       return 2;
104     case AudioProcessing::kStereoAndKeyboard:
105       return 3;
106   }
107   RTC_NOTREACHED();
108   return 0;
109 }
110 
TruncateToMultipleOf10(int value)111 int TruncateToMultipleOf10(int value) {
112   return (value / 10) * 10;
113 }
114 
MixStereoToMono(const float * stereo,float * mono,size_t samples_per_channel)115 void MixStereoToMono(const float* stereo, float* mono,
116                      size_t samples_per_channel) {
117   for (size_t i = 0; i < samples_per_channel; ++i)
118     mono[i] = (stereo[i * 2] + stereo[i * 2 + 1]) / 2;
119 }
120 
MixStereoToMono(const int16_t * stereo,int16_t * mono,size_t samples_per_channel)121 void MixStereoToMono(const int16_t* stereo, int16_t* mono,
122                      size_t samples_per_channel) {
123   for (size_t i = 0; i < samples_per_channel; ++i)
124     mono[i] = (stereo[i * 2] + stereo[i * 2 + 1]) >> 1;
125 }
126 
CopyLeftToRightChannel(int16_t * stereo,size_t samples_per_channel)127 void CopyLeftToRightChannel(int16_t* stereo, size_t samples_per_channel) {
128   for (size_t i = 0; i < samples_per_channel; i++) {
129     stereo[i * 2 + 1] = stereo[i * 2];
130   }
131 }
132 
VerifyChannelsAreEqual(const int16_t * stereo,size_t samples_per_channel)133 void VerifyChannelsAreEqual(const int16_t* stereo, size_t samples_per_channel) {
134   for (size_t i = 0; i < samples_per_channel; i++) {
135     EXPECT_EQ(stereo[i * 2 + 1], stereo[i * 2]);
136   }
137 }
138 
SetFrameTo(AudioFrame * frame,int16_t value)139 void SetFrameTo(AudioFrame* frame, int16_t value) {
140   int16_t* frame_data = frame->mutable_data();
141   for (size_t i = 0; i < frame->samples_per_channel_ * frame->num_channels_;
142        ++i) {
143     frame_data[i] = value;
144   }
145 }
146 
SetFrameTo(AudioFrame * frame,int16_t left,int16_t right)147 void SetFrameTo(AudioFrame* frame, int16_t left, int16_t right) {
148   ASSERT_EQ(2u, frame->num_channels_);
149   int16_t* frame_data = frame->mutable_data();
150   for (size_t i = 0; i < frame->samples_per_channel_ * 2; i += 2) {
151     frame_data[i] = left;
152     frame_data[i + 1] = right;
153   }
154 }
155 
ScaleFrame(AudioFrame * frame,float scale)156 void ScaleFrame(AudioFrame* frame, float scale) {
157   int16_t* frame_data = frame->mutable_data();
158   for (size_t i = 0; i < frame->samples_per_channel_ * frame->num_channels_;
159        ++i) {
160     frame_data[i] = FloatS16ToS16(frame_data[i] * scale);
161   }
162 }
163 
FrameDataAreEqual(const AudioFrame & frame1,const AudioFrame & frame2)164 bool FrameDataAreEqual(const AudioFrame& frame1, const AudioFrame& frame2) {
165   if (frame1.samples_per_channel_ != frame2.samples_per_channel_) {
166     return false;
167   }
168   if (frame1.num_channels_ != frame2.num_channels_) {
169     return false;
170   }
171   if (memcmp(frame1.data(), frame2.data(),
172              frame1.samples_per_channel_ * frame1.num_channels_ *
173                  sizeof(int16_t))) {
174     return false;
175   }
176   return true;
177 }
178 
EnableAllAPComponents(AudioProcessing * ap)179 void EnableAllAPComponents(AudioProcessing* ap) {
180 #if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
181   EXPECT_NOERR(ap->echo_control_mobile()->Enable(true));
182 
183   EXPECT_NOERR(ap->gain_control()->set_mode(GainControl::kAdaptiveDigital));
184   EXPECT_NOERR(ap->gain_control()->Enable(true));
185 #elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
186   EXPECT_NOERR(ap->echo_cancellation()->enable_drift_compensation(true));
187   EXPECT_NOERR(ap->echo_cancellation()->enable_metrics(true));
188   EXPECT_NOERR(ap->echo_cancellation()->enable_delay_logging(true));
189   EXPECT_NOERR(ap->echo_cancellation()->Enable(true));
190 
191   EXPECT_NOERR(ap->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
192   EXPECT_NOERR(ap->gain_control()->set_analog_level_limits(0, 255));
193   EXPECT_NOERR(ap->gain_control()->Enable(true));
194 #endif
195 
196   AudioProcessing::Config apm_config;
197   apm_config.high_pass_filter.enabled = true;
198   ap->ApplyConfig(apm_config);
199 
200   EXPECT_NOERR(ap->level_estimator()->Enable(true));
201   EXPECT_NOERR(ap->noise_suppression()->Enable(true));
202 
203   EXPECT_NOERR(ap->voice_detection()->Enable(true));
204 }
205 
206 // These functions are only used by ApmTest.Process.
207 template <class T>
AbsValue(T a)208 T AbsValue(T a) {
209   return a > 0 ? a: -a;
210 }
211 
MaxAudioFrame(const AudioFrame & frame)212 int16_t MaxAudioFrame(const AudioFrame& frame) {
213   const size_t length = frame.samples_per_channel_ * frame.num_channels_;
214   const int16_t* frame_data = frame.data();
215   int16_t max_data = AbsValue(frame_data[0]);
216   for (size_t i = 1; i < length; i++) {
217     max_data = std::max(max_data, AbsValue(frame_data[i]));
218   }
219 
220   return max_data;
221 }
222 
223 #if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
TestStats(const AudioProcessing::Statistic & test,const audioproc::Test::Statistic & reference)224 void TestStats(const AudioProcessing::Statistic& test,
225                const audioproc::Test::Statistic& reference) {
226   EXPECT_EQ(reference.instant(), test.instant);
227   EXPECT_EQ(reference.average(), test.average);
228   EXPECT_EQ(reference.maximum(), test.maximum);
229   EXPECT_EQ(reference.minimum(), test.minimum);
230 }
231 
WriteStatsMessage(const AudioProcessing::Statistic & output,audioproc::Test::Statistic * msg)232 void WriteStatsMessage(const AudioProcessing::Statistic& output,
233                        audioproc::Test::Statistic* msg) {
234   msg->set_instant(output.instant);
235   msg->set_average(output.average);
236   msg->set_maximum(output.maximum);
237   msg->set_minimum(output.minimum);
238 }
239 #endif
240 
OpenFileAndWriteMessage(const std::string & filename,const MessageLite & msg)241 void OpenFileAndWriteMessage(const std::string& filename,
242                              const MessageLite& msg) {
243   FILE* file = fopen(filename.c_str(), "wb");
244   ASSERT_TRUE(file != NULL);
245 
246   int32_t size = msg.ByteSize();
247   ASSERT_GT(size, 0);
248   std::unique_ptr<uint8_t[]> array(new uint8_t[size]);
249   ASSERT_TRUE(msg.SerializeToArray(array.get(), size));
250 
251   ASSERT_EQ(1u, fwrite(&size, sizeof(size), 1, file));
252   ASSERT_EQ(static_cast<size_t>(size),
253       fwrite(array.get(), sizeof(array[0]), size, file));
254   fclose(file);
255 }
256 
ResourceFilePath(const std::string & name,int sample_rate_hz)257 std::string ResourceFilePath(const std::string& name, int sample_rate_hz) {
258   std::ostringstream ss;
259   // Resource files are all stereo.
260   ss << name << sample_rate_hz / 1000 << "_stereo";
261   return test::ResourcePath(ss.str(), "pcm");
262 }
263 
264 // Temporary filenames unique to this process. Used to be able to run these
265 // tests in parallel as each process needs to be running in isolation they can't
266 // have competing filenames.
267 std::map<std::string, std::string> temp_filenames;
268 
OutputFilePath(const std::string & name,int input_rate,int output_rate,int reverse_input_rate,int reverse_output_rate,size_t num_input_channels,size_t num_output_channels,size_t num_reverse_input_channels,size_t num_reverse_output_channels,StreamDirection file_direction)269 std::string OutputFilePath(const std::string& name,
270                            int input_rate,
271                            int output_rate,
272                            int reverse_input_rate,
273                            int reverse_output_rate,
274                            size_t num_input_channels,
275                            size_t num_output_channels,
276                            size_t num_reverse_input_channels,
277                            size_t num_reverse_output_channels,
278                            StreamDirection file_direction) {
279   std::ostringstream ss;
280   ss << name << "_i" << num_input_channels << "_" << input_rate / 1000 << "_ir"
281      << num_reverse_input_channels << "_" << reverse_input_rate / 1000 << "_";
282   if (num_output_channels == 1) {
283     ss << "mono";
284   } else if (num_output_channels == 2) {
285     ss << "stereo";
286   } else {
287     RTC_NOTREACHED();
288   }
289   ss << output_rate / 1000;
290   if (num_reverse_output_channels == 1) {
291     ss << "_rmono";
292   } else if (num_reverse_output_channels == 2) {
293     ss << "_rstereo";
294   } else {
295     RTC_NOTREACHED();
296   }
297   ss << reverse_output_rate / 1000;
298   ss << "_d" << file_direction << "_pcm";
299 
300   std::string filename = ss.str();
301   if (temp_filenames[filename].empty())
302     temp_filenames[filename] = test::TempFilename(test::OutputPath(), filename);
303   return temp_filenames[filename];
304 }
305 
ClearTempFiles()306 void ClearTempFiles() {
307   for (auto& kv : temp_filenames)
308     remove(kv.second.c_str());
309 }
310 
311 // Only remove "out" files. Keep "ref" files.
ClearTempOutFiles()312 void ClearTempOutFiles() {
313   for (auto it = temp_filenames.begin(); it != temp_filenames.end();) {
314     const std::string& filename = it->first;
315     if (filename.substr(0, 3).compare("out") == 0) {
316       remove(it->second.c_str());
317       temp_filenames.erase(it++);
318     } else {
319       it++;
320     }
321   }
322 }
323 
OpenFileAndReadMessage(const std::string & filename,MessageLite * msg)324 void OpenFileAndReadMessage(const std::string& filename, MessageLite* msg) {
325   FILE* file = fopen(filename.c_str(), "rb");
326   ASSERT_TRUE(file != NULL);
327   ReadMessageFromFile(file, msg);
328   fclose(file);
329 }
330 
331 // Reads a 10 ms chunk of int16 interleaved audio from the given (assumed
332 // stereo) file, converts to deinterleaved float (optionally downmixing) and
333 // returns the result in |cb|. Returns false if the file ended (or on error) and
334 // true otherwise.
335 //
336 // |int_data| and |float_data| are just temporary space that must be
337 // sufficiently large to hold the 10 ms chunk.
ReadChunk(FILE * file,int16_t * int_data,float * float_data,ChannelBuffer<float> * cb)338 bool ReadChunk(FILE* file, int16_t* int_data, float* float_data,
339                ChannelBuffer<float>* cb) {
340   // The files always contain stereo audio.
341   size_t frame_size = cb->num_frames() * 2;
342   size_t read_count = fread(int_data, sizeof(int16_t), frame_size, file);
343   if (read_count != frame_size) {
344     // Check that the file really ended.
345     RTC_DCHECK(feof(file));
346     return false;  // This is expected.
347   }
348 
349   S16ToFloat(int_data, frame_size, float_data);
350   if (cb->num_channels() == 1) {
351     MixStereoToMono(float_data, cb->channels()[0], cb->num_frames());
352   } else {
353     Deinterleave(float_data, cb->num_frames(), 2,
354                  cb->channels());
355   }
356 
357   return true;
358 }
359 
360 class ApmTest : public ::testing::Test {
361  protected:
362   ApmTest();
363   virtual void SetUp();
364   virtual void TearDown();
365 
SetUpTestCase()366   static void SetUpTestCase() {
367   }
368 
TearDownTestCase()369   static void TearDownTestCase() {
370     ClearTempFiles();
371   }
372 
373   // Used to select between int and float interface tests.
374   enum Format {
375     kIntFormat,
376     kFloatFormat
377   };
378 
379   void Init(int sample_rate_hz,
380             int output_sample_rate_hz,
381             int reverse_sample_rate_hz,
382             size_t num_input_channels,
383             size_t num_output_channels,
384             size_t num_reverse_channels,
385             bool open_output_file);
386   void Init(AudioProcessing* ap);
387   void EnableAllComponents();
388   bool ReadFrame(FILE* file, AudioFrame* frame);
389   bool ReadFrame(FILE* file, AudioFrame* frame, ChannelBuffer<float>* cb);
390   void ReadFrameWithRewind(FILE* file, AudioFrame* frame);
391   void ReadFrameWithRewind(FILE* file, AudioFrame* frame,
392                            ChannelBuffer<float>* cb);
393   void ProcessWithDefaultStreamParameters(AudioFrame* frame);
394   void ProcessDelayVerificationTest(int delay_ms, int system_delay_ms,
395                                     int delay_min, int delay_max);
396   void TestChangingChannelsInt16Interface(
397       size_t num_channels,
398       AudioProcessing::Error expected_return);
399   void TestChangingForwardChannels(size_t num_in_channels,
400                                    size_t num_out_channels,
401                                    AudioProcessing::Error expected_return);
402   void TestChangingReverseChannels(size_t num_rev_channels,
403                                    AudioProcessing::Error expected_return);
404   void RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate);
405   void RunManualVolumeChangeIsPossibleTest(int sample_rate);
406   void StreamParametersTest(Format format);
407   int ProcessStreamChooser(Format format);
408   int AnalyzeReverseStreamChooser(Format format);
409   void ProcessDebugDump(const std::string& in_filename,
410                         const std::string& out_filename,
411                         Format format,
412                         int max_size_bytes);
413   void VerifyDebugDumpTest(Format format);
414 
415   const std::string output_path_;
416   const std::string ref_filename_;
417   std::unique_ptr<AudioProcessing> apm_;
418   AudioFrame* frame_;
419   AudioFrame* revframe_;
420   std::unique_ptr<ChannelBuffer<float> > float_cb_;
421   std::unique_ptr<ChannelBuffer<float> > revfloat_cb_;
422   int output_sample_rate_hz_;
423   size_t num_output_channels_;
424   FILE* far_file_;
425   FILE* near_file_;
426   FILE* out_file_;
427 };
428 
ApmTest()429 ApmTest::ApmTest()
430     : output_path_(test::OutputPath()),
431 #if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
432       ref_filename_(test::ResourcePath("audio_processing/output_data_fixed",
433                                        "pb")),
434 #elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
435 #if defined(WEBRTC_MAC)
436       // A different file for Mac is needed because on this platform the AEC
437       // constant |kFixedDelayMs| value is 20 and not 50 as it is on the rest.
438       ref_filename_(test::ResourcePath("audio_processing/output_data_mac",
439                                        "pb")),
440 #else
441       ref_filename_(test::ResourcePath("audio_processing/output_data_float",
442                                        "pb")),
443 #endif
444 #endif
445       frame_(NULL),
446       revframe_(NULL),
447       output_sample_rate_hz_(0),
448       num_output_channels_(0),
449       far_file_(NULL),
450       near_file_(NULL),
451       out_file_(NULL) {
452   Config config;
453   config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
454   apm_.reset(AudioProcessing::Create(config));
455 }
456 
SetUp()457 void ApmTest::SetUp() {
458   ASSERT_TRUE(apm_.get() != NULL);
459 
460   frame_ = new AudioFrame();
461   revframe_ = new AudioFrame();
462 
463   Init(32000, 32000, 32000, 2, 2, 2, false);
464 }
465 
TearDown()466 void ApmTest::TearDown() {
467   if (frame_) {
468     delete frame_;
469   }
470   frame_ = NULL;
471 
472   if (revframe_) {
473     delete revframe_;
474   }
475   revframe_ = NULL;
476 
477   if (far_file_) {
478     ASSERT_EQ(0, fclose(far_file_));
479   }
480   far_file_ = NULL;
481 
482   if (near_file_) {
483     ASSERT_EQ(0, fclose(near_file_));
484   }
485   near_file_ = NULL;
486 
487   if (out_file_) {
488     ASSERT_EQ(0, fclose(out_file_));
489   }
490   out_file_ = NULL;
491 }
492 
Init(AudioProcessing * ap)493 void ApmTest::Init(AudioProcessing* ap) {
494   ASSERT_EQ(kNoErr,
495             ap->Initialize(
496                 {{{frame_->sample_rate_hz_, frame_->num_channels_},
497                   {output_sample_rate_hz_, num_output_channels_},
498                   {revframe_->sample_rate_hz_, revframe_->num_channels_},
499                   {revframe_->sample_rate_hz_, revframe_->num_channels_}}}));
500 }
501 
Init(int sample_rate_hz,int output_sample_rate_hz,int reverse_sample_rate_hz,size_t num_input_channels,size_t num_output_channels,size_t num_reverse_channels,bool open_output_file)502 void ApmTest::Init(int sample_rate_hz,
503                    int output_sample_rate_hz,
504                    int reverse_sample_rate_hz,
505                    size_t num_input_channels,
506                    size_t num_output_channels,
507                    size_t num_reverse_channels,
508                    bool open_output_file) {
509   SetContainerFormat(sample_rate_hz, num_input_channels, frame_, &float_cb_);
510   output_sample_rate_hz_ = output_sample_rate_hz;
511   num_output_channels_ = num_output_channels;
512 
513   SetContainerFormat(reverse_sample_rate_hz, num_reverse_channels, revframe_,
514                      &revfloat_cb_);
515   Init(apm_.get());
516 
517   if (far_file_) {
518     ASSERT_EQ(0, fclose(far_file_));
519   }
520   std::string filename = ResourceFilePath("far", sample_rate_hz);
521   far_file_ = fopen(filename.c_str(), "rb");
522   ASSERT_TRUE(far_file_ != NULL) << "Could not open file " <<
523       filename << "\n";
524 
525   if (near_file_) {
526     ASSERT_EQ(0, fclose(near_file_));
527   }
528   filename = ResourceFilePath("near", sample_rate_hz);
529   near_file_ = fopen(filename.c_str(), "rb");
530   ASSERT_TRUE(near_file_ != NULL) << "Could not open file " <<
531         filename << "\n";
532 
533   if (open_output_file) {
534     if (out_file_) {
535       ASSERT_EQ(0, fclose(out_file_));
536     }
537     filename = OutputFilePath(
538         "out", sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz,
539         reverse_sample_rate_hz, num_input_channels, num_output_channels,
540         num_reverse_channels, num_reverse_channels, kForward);
541     out_file_ = fopen(filename.c_str(), "wb");
542     ASSERT_TRUE(out_file_ != NULL) << "Could not open file " <<
543           filename << "\n";
544   }
545 }
546 
EnableAllComponents()547 void ApmTest::EnableAllComponents() {
548   EnableAllAPComponents(apm_.get());
549 }
550 
ReadFrame(FILE * file,AudioFrame * frame,ChannelBuffer<float> * cb)551 bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame,
552                         ChannelBuffer<float>* cb) {
553   // The files always contain stereo audio.
554   size_t frame_size = frame->samples_per_channel_ * 2;
555   size_t read_count = fread(frame->mutable_data(),
556                             sizeof(int16_t),
557                             frame_size,
558                             file);
559   if (read_count != frame_size) {
560     // Check that the file really ended.
561     EXPECT_NE(0, feof(file));
562     return false;  // This is expected.
563   }
564 
565   if (frame->num_channels_ == 1) {
566     MixStereoToMono(frame->data(), frame->mutable_data(),
567                     frame->samples_per_channel_);
568   }
569 
570   if (cb) {
571     ConvertToFloat(*frame, cb);
572   }
573   return true;
574 }
575 
ReadFrame(FILE * file,AudioFrame * frame)576 bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame) {
577   return ReadFrame(file, frame, NULL);
578 }
579 
580 // If the end of the file has been reached, rewind it and attempt to read the
581 // frame again.
ReadFrameWithRewind(FILE * file,AudioFrame * frame,ChannelBuffer<float> * cb)582 void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame,
583                                   ChannelBuffer<float>* cb) {
584   if (!ReadFrame(near_file_, frame_, cb)) {
585     rewind(near_file_);
586     ASSERT_TRUE(ReadFrame(near_file_, frame_, cb));
587   }
588 }
589 
ReadFrameWithRewind(FILE * file,AudioFrame * frame)590 void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame) {
591   ReadFrameWithRewind(file, frame, NULL);
592 }
593 
ProcessWithDefaultStreamParameters(AudioFrame * frame)594 void ApmTest::ProcessWithDefaultStreamParameters(AudioFrame* frame) {
595   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
596   apm_->echo_cancellation()->set_stream_drift_samples(0);
597   EXPECT_EQ(apm_->kNoError,
598       apm_->gain_control()->set_stream_analog_level(127));
599   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame));
600 }
601 
ProcessStreamChooser(Format format)602 int ApmTest::ProcessStreamChooser(Format format) {
603   if (format == kIntFormat) {
604     return apm_->ProcessStream(frame_);
605   }
606   return apm_->ProcessStream(float_cb_->channels(),
607                              frame_->samples_per_channel_,
608                              frame_->sample_rate_hz_,
609                              LayoutFromChannels(frame_->num_channels_),
610                              output_sample_rate_hz_,
611                              LayoutFromChannels(num_output_channels_),
612                              float_cb_->channels());
613 }
614 
AnalyzeReverseStreamChooser(Format format)615 int ApmTest::AnalyzeReverseStreamChooser(Format format) {
616   if (format == kIntFormat) {
617     return apm_->ProcessReverseStream(revframe_);
618   }
619   return apm_->AnalyzeReverseStream(
620       revfloat_cb_->channels(),
621       revframe_->samples_per_channel_,
622       revframe_->sample_rate_hz_,
623       LayoutFromChannels(revframe_->num_channels_));
624 }
625 
ProcessDelayVerificationTest(int delay_ms,int system_delay_ms,int delay_min,int delay_max)626 void ApmTest::ProcessDelayVerificationTest(int delay_ms, int system_delay_ms,
627                                            int delay_min, int delay_max) {
628   // The |revframe_| and |frame_| should include the proper frame information,
629   // hence can be used for extracting information.
630   AudioFrame tmp_frame;
631   std::queue<AudioFrame*> frame_queue;
632   bool causal = true;
633 
634   tmp_frame.CopyFrom(*revframe_);
635   SetFrameTo(&tmp_frame, 0);
636 
637   EXPECT_EQ(apm_->kNoError, apm_->Initialize());
638   // Initialize the |frame_queue| with empty frames.
639   int frame_delay = delay_ms / 10;
640   while (frame_delay < 0) {
641     AudioFrame* frame = new AudioFrame();
642     frame->CopyFrom(tmp_frame);
643     frame_queue.push(frame);
644     frame_delay++;
645     causal = false;
646   }
647   while (frame_delay > 0) {
648     AudioFrame* frame = new AudioFrame();
649     frame->CopyFrom(tmp_frame);
650     frame_queue.push(frame);
651     frame_delay--;
652   }
653   // Run for 4.5 seconds, skipping statistics from the first 2.5 seconds.  We
654   // need enough frames with audio to have reliable estimates, but as few as
655   // possible to keep processing time down.  4.5 seconds seemed to be a good
656   // compromise for this recording.
657   for (int frame_count = 0; frame_count < 450; ++frame_count) {
658     AudioFrame* frame = new AudioFrame();
659     frame->CopyFrom(tmp_frame);
660     // Use the near end recording, since that has more speech in it.
661     ASSERT_TRUE(ReadFrame(near_file_, frame));
662     frame_queue.push(frame);
663     AudioFrame* reverse_frame = frame;
664     AudioFrame* process_frame = frame_queue.front();
665     if (!causal) {
666       reverse_frame = frame_queue.front();
667       // When we call ProcessStream() the frame is modified, so we can't use the
668       // pointer directly when things are non-causal. Use an intermediate frame
669       // and copy the data.
670       process_frame = &tmp_frame;
671       process_frame->CopyFrom(*frame);
672     }
673     EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(reverse_frame));
674     EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(system_delay_ms));
675     EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(process_frame));
676     frame = frame_queue.front();
677     frame_queue.pop();
678     delete frame;
679 
680     if (frame_count == 250) {
681       int median;
682       int std;
683       float poor_fraction;
684       // Discard the first delay metrics to avoid convergence effects.
685       EXPECT_EQ(apm_->kNoError,
686                 apm_->echo_cancellation()->GetDelayMetrics(&median, &std,
687                                                            &poor_fraction));
688     }
689   }
690 
691   rewind(near_file_);
692   while (!frame_queue.empty()) {
693     AudioFrame* frame = frame_queue.front();
694     frame_queue.pop();
695     delete frame;
696   }
697   // Calculate expected delay estimate and acceptable regions. Further,
698   // limit them w.r.t. AEC delay estimation support.
699   const size_t samples_per_ms =
700       rtc::SafeMin<size_t>(16u, frame_->samples_per_channel_ / 10);
701   const int expected_median =
702       rtc::SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max);
703   const int expected_median_high = rtc::SafeClamp<int>(
704       expected_median + rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
705       delay_max);
706   const int expected_median_low = rtc::SafeClamp<int>(
707       expected_median - rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
708       delay_max);
709   // Verify delay metrics.
710   int median;
711   int std;
712   float poor_fraction;
713   EXPECT_EQ(apm_->kNoError,
714             apm_->echo_cancellation()->GetDelayMetrics(&median, &std,
715                                                        &poor_fraction));
716   EXPECT_GE(expected_median_high, median);
717   EXPECT_LE(expected_median_low, median);
718 }
719 
StreamParametersTest(Format format)720 void ApmTest::StreamParametersTest(Format format) {
721   // No errors when the components are disabled.
722   EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
723 
724   // -- Missing AGC level --
725   EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
726   EXPECT_EQ(apm_->kStreamParameterNotSetError,
727             ProcessStreamChooser(format));
728 
729   // Resets after successful ProcessStream().
730   EXPECT_EQ(apm_->kNoError,
731             apm_->gain_control()->set_stream_analog_level(127));
732   EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
733   EXPECT_EQ(apm_->kStreamParameterNotSetError,
734             ProcessStreamChooser(format));
735 
736   // Other stream parameters set correctly.
737   EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
738   EXPECT_EQ(apm_->kNoError,
739             apm_->echo_cancellation()->enable_drift_compensation(true));
740   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
741   apm_->echo_cancellation()->set_stream_drift_samples(0);
742   EXPECT_EQ(apm_->kStreamParameterNotSetError,
743             ProcessStreamChooser(format));
744   EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
745   EXPECT_EQ(apm_->kNoError,
746             apm_->echo_cancellation()->enable_drift_compensation(false));
747 
748   // -- Missing delay --
749   EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
750   EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
751   EXPECT_EQ(apm_->kStreamParameterNotSetError,
752             ProcessStreamChooser(format));
753 
754   // Resets after successful ProcessStream().
755   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
756   EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
757   EXPECT_EQ(apm_->kStreamParameterNotSetError,
758             ProcessStreamChooser(format));
759 
760   // Other stream parameters set correctly.
761   EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
762   EXPECT_EQ(apm_->kNoError,
763             apm_->echo_cancellation()->enable_drift_compensation(true));
764   apm_->echo_cancellation()->set_stream_drift_samples(0);
765   EXPECT_EQ(apm_->kNoError,
766             apm_->gain_control()->set_stream_analog_level(127));
767   EXPECT_EQ(apm_->kStreamParameterNotSetError,
768             ProcessStreamChooser(format));
769   EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
770 
771   // -- Missing drift --
772   EXPECT_EQ(apm_->kStreamParameterNotSetError,
773             ProcessStreamChooser(format));
774 
775   // Resets after successful ProcessStream().
776   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
777   apm_->echo_cancellation()->set_stream_drift_samples(0);
778   EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
779   EXPECT_EQ(apm_->kStreamParameterNotSetError,
780             ProcessStreamChooser(format));
781 
782   // Other stream parameters set correctly.
783   EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
784   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
785   EXPECT_EQ(apm_->kNoError,
786             apm_->gain_control()->set_stream_analog_level(127));
787   EXPECT_EQ(apm_->kStreamParameterNotSetError,
788             ProcessStreamChooser(format));
789 
790   // -- No stream parameters --
791   EXPECT_EQ(apm_->kNoError,
792             AnalyzeReverseStreamChooser(format));
793   EXPECT_EQ(apm_->kStreamParameterNotSetError,
794             ProcessStreamChooser(format));
795 
796   // -- All there --
797   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
798   apm_->echo_cancellation()->set_stream_drift_samples(0);
799   EXPECT_EQ(apm_->kNoError,
800             apm_->gain_control()->set_stream_analog_level(127));
801   EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
802 }
803 
TEST_F(ApmTest,StreamParametersInt)804 TEST_F(ApmTest, StreamParametersInt) {
805   StreamParametersTest(kIntFormat);
806 }
807 
TEST_F(ApmTest,StreamParametersFloat)808 TEST_F(ApmTest, StreamParametersFloat) {
809   StreamParametersTest(kFloatFormat);
810 }
811 
TEST_F(ApmTest,DefaultDelayOffsetIsZero)812 TEST_F(ApmTest, DefaultDelayOffsetIsZero) {
813   EXPECT_EQ(0, apm_->delay_offset_ms());
814   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(50));
815   EXPECT_EQ(50, apm_->stream_delay_ms());
816 }
817 
TEST_F(ApmTest,DelayOffsetWithLimitsIsSetProperly)818 TEST_F(ApmTest, DelayOffsetWithLimitsIsSetProperly) {
819   // High limit of 500 ms.
820   apm_->set_delay_offset_ms(100);
821   EXPECT_EQ(100, apm_->delay_offset_ms());
822   EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(450));
823   EXPECT_EQ(500, apm_->stream_delay_ms());
824   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
825   EXPECT_EQ(200, apm_->stream_delay_ms());
826 
827   // Low limit of 0 ms.
828   apm_->set_delay_offset_ms(-50);
829   EXPECT_EQ(-50, apm_->delay_offset_ms());
830   EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(20));
831   EXPECT_EQ(0, apm_->stream_delay_ms());
832   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
833   EXPECT_EQ(50, apm_->stream_delay_ms());
834 }
835 
TestChangingChannelsInt16Interface(size_t num_channels,AudioProcessing::Error expected_return)836 void ApmTest::TestChangingChannelsInt16Interface(
837     size_t num_channels,
838     AudioProcessing::Error expected_return) {
839   frame_->num_channels_ = num_channels;
840   EXPECT_EQ(expected_return, apm_->ProcessStream(frame_));
841   EXPECT_EQ(expected_return, apm_->ProcessReverseStream(frame_));
842 }
843 
TestChangingForwardChannels(size_t num_in_channels,size_t num_out_channels,AudioProcessing::Error expected_return)844 void ApmTest::TestChangingForwardChannels(
845     size_t num_in_channels,
846     size_t num_out_channels,
847     AudioProcessing::Error expected_return) {
848   const StreamConfig input_stream = {frame_->sample_rate_hz_, num_in_channels};
849   const StreamConfig output_stream = {output_sample_rate_hz_, num_out_channels};
850 
851   EXPECT_EQ(expected_return,
852             apm_->ProcessStream(float_cb_->channels(), input_stream,
853                                 output_stream, float_cb_->channels()));
854 }
855 
TestChangingReverseChannels(size_t num_rev_channels,AudioProcessing::Error expected_return)856 void ApmTest::TestChangingReverseChannels(
857     size_t num_rev_channels,
858     AudioProcessing::Error expected_return) {
859   const ProcessingConfig processing_config = {
860       {{frame_->sample_rate_hz_, apm_->num_input_channels()},
861        {output_sample_rate_hz_, apm_->num_output_channels()},
862        {frame_->sample_rate_hz_, num_rev_channels},
863        {frame_->sample_rate_hz_, num_rev_channels}}};
864 
865   EXPECT_EQ(
866       expected_return,
867       apm_->ProcessReverseStream(
868           float_cb_->channels(), processing_config.reverse_input_stream(),
869           processing_config.reverse_output_stream(), float_cb_->channels()));
870 }
871 
TEST_F(ApmTest,ChannelsInt16Interface)872 TEST_F(ApmTest, ChannelsInt16Interface) {
873   // Testing number of invalid and valid channels.
874   Init(16000, 16000, 16000, 4, 4, 4, false);
875 
876   TestChangingChannelsInt16Interface(0, apm_->kBadNumberChannelsError);
877 
878   for (size_t i = 1; i < 4; i++) {
879     TestChangingChannelsInt16Interface(i, kNoErr);
880     EXPECT_EQ(i, apm_->num_input_channels());
881   }
882 }
883 
TEST_F(ApmTest,Channels)884 TEST_F(ApmTest, Channels) {
885   // Testing number of invalid and valid channels.
886   Init(16000, 16000, 16000, 4, 4, 4, false);
887 
888   TestChangingForwardChannels(0, 1, apm_->kBadNumberChannelsError);
889   TestChangingReverseChannels(0, apm_->kBadNumberChannelsError);
890 
891   for (size_t i = 1; i < 4; ++i) {
892     for (size_t j = 0; j < 1; ++j) {
893       // Output channels much be one or match input channels.
894       if (j == 1 || i == j) {
895         TestChangingForwardChannels(i, j, kNoErr);
896         TestChangingReverseChannels(i, kNoErr);
897 
898         EXPECT_EQ(i, apm_->num_input_channels());
899         EXPECT_EQ(j, apm_->num_output_channels());
900         // The number of reverse channels used for processing to is always 1.
901         EXPECT_EQ(1u, apm_->num_reverse_channels());
902       } else {
903         TestChangingForwardChannels(i, j,
904                                     AudioProcessing::kBadNumberChannelsError);
905       }
906     }
907   }
908 }
909 
TEST_F(ApmTest,SampleRatesInt)910 TEST_F(ApmTest, SampleRatesInt) {
911   // Testing invalid sample rates
912   SetContainerFormat(10000, 2, frame_, &float_cb_);
913   EXPECT_EQ(apm_->kBadSampleRateError, ProcessStreamChooser(kIntFormat));
914   // Testing valid sample rates
915   int fs[] = {8000, 16000, 32000, 48000};
916   for (size_t i = 0; i < arraysize(fs); i++) {
917     SetContainerFormat(fs[i], 2, frame_, &float_cb_);
918     EXPECT_NOERR(ProcessStreamChooser(kIntFormat));
919   }
920 }
921 
TEST_F(ApmTest,EchoCancellation)922 TEST_F(ApmTest, EchoCancellation) {
923   EXPECT_EQ(apm_->kNoError,
924             apm_->echo_cancellation()->enable_drift_compensation(true));
925   EXPECT_TRUE(apm_->echo_cancellation()->is_drift_compensation_enabled());
926   EXPECT_EQ(apm_->kNoError,
927             apm_->echo_cancellation()->enable_drift_compensation(false));
928   EXPECT_FALSE(apm_->echo_cancellation()->is_drift_compensation_enabled());
929 
930   EchoCancellation::SuppressionLevel level[] = {
931     EchoCancellation::kLowSuppression,
932     EchoCancellation::kModerateSuppression,
933     EchoCancellation::kHighSuppression,
934   };
935   for (size_t i = 0; i < arraysize(level); i++) {
936     EXPECT_EQ(apm_->kNoError,
937         apm_->echo_cancellation()->set_suppression_level(level[i]));
938     EXPECT_EQ(level[i],
939         apm_->echo_cancellation()->suppression_level());
940   }
941 
942   EchoCancellation::Metrics metrics;
943   EXPECT_EQ(apm_->kNotEnabledError,
944             apm_->echo_cancellation()->GetMetrics(&metrics));
945 
946   EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
947   EXPECT_TRUE(apm_->echo_cancellation()->is_enabled());
948 
949   EXPECT_EQ(apm_->kNoError,
950             apm_->echo_cancellation()->enable_metrics(true));
951   EXPECT_TRUE(apm_->echo_cancellation()->are_metrics_enabled());
952   EXPECT_EQ(apm_->kNoError,
953             apm_->echo_cancellation()->enable_metrics(false));
954   EXPECT_FALSE(apm_->echo_cancellation()->are_metrics_enabled());
955 
956   EXPECT_EQ(apm_->kNoError,
957             apm_->echo_cancellation()->enable_delay_logging(true));
958   EXPECT_TRUE(apm_->echo_cancellation()->is_delay_logging_enabled());
959   EXPECT_EQ(apm_->kNoError,
960             apm_->echo_cancellation()->enable_delay_logging(false));
961   EXPECT_FALSE(apm_->echo_cancellation()->is_delay_logging_enabled());
962 
963   EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(false));
964   EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
965 
966   int median = 0;
967   int std = 0;
968   float poor_fraction = 0;
969   EXPECT_EQ(apm_->kNotEnabledError, apm_->echo_cancellation()->GetDelayMetrics(
970                                         &median, &std, &poor_fraction));
971 
972   EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
973   EXPECT_TRUE(apm_->echo_cancellation()->is_enabled());
974   EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(false));
975   EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
976 
977   EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
978   EXPECT_TRUE(apm_->echo_cancellation()->is_enabled());
979   EXPECT_TRUE(apm_->echo_cancellation()->aec_core() != NULL);
980   EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(false));
981   EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
982   EXPECT_FALSE(apm_->echo_cancellation()->aec_core() != NULL);
983 }
984 
TEST_F(ApmTest,DISABLED_EchoCancellationReportsCorrectDelays)985 TEST_F(ApmTest, DISABLED_EchoCancellationReportsCorrectDelays) {
986   // TODO(bjornv): Fix this test to work with DA-AEC.
987   // Enable AEC only.
988   EXPECT_EQ(apm_->kNoError,
989             apm_->echo_cancellation()->enable_drift_compensation(false));
990   EXPECT_EQ(apm_->kNoError,
991             apm_->echo_cancellation()->enable_metrics(false));
992   EXPECT_EQ(apm_->kNoError,
993             apm_->echo_cancellation()->enable_delay_logging(true));
994   EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
995   Config config;
996   config.Set<DelayAgnostic>(new DelayAgnostic(false));
997   apm_->SetExtraOptions(config);
998 
999   // Internally in the AEC the amount of lookahead the delay estimation can
1000   // handle is 15 blocks and the maximum delay is set to 60 blocks.
1001   const int kLookaheadBlocks = 15;
1002   const int kMaxDelayBlocks = 60;
1003   // The AEC has a startup time before it actually starts to process. This
1004   // procedure can flush the internal far-end buffer, which of course affects
1005   // the delay estimation. Therefore, we set a system_delay high enough to
1006   // avoid that. The smallest system_delay you can report without flushing the
1007   // buffer is 66 ms in 8 kHz.
1008   //
1009   // It is known that for 16 kHz (and 32 kHz) sampling frequency there is an
1010   // additional stuffing of 8 ms on the fly, but it seems to have no impact on
1011   // delay estimation. This should be noted though. In case of test failure,
1012   // this could be the cause.
1013   const int kSystemDelayMs = 66;
1014   // Test a couple of corner cases and verify that the estimated delay is
1015   // within a valid region (set to +-1.5 blocks). Note that these cases are
1016   // sampling frequency dependent.
1017   for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
1018     Init(kProcessSampleRates[i],
1019          kProcessSampleRates[i],
1020          kProcessSampleRates[i],
1021          2,
1022          2,
1023          2,
1024          false);
1025     // Sampling frequency dependent variables.
1026     const int num_ms_per_block =
1027         std::max(4, static_cast<int>(640 / frame_->samples_per_channel_));
1028     const int delay_min_ms = -kLookaheadBlocks * num_ms_per_block;
1029     const int delay_max_ms = (kMaxDelayBlocks - 1) * num_ms_per_block;
1030 
1031     // 1) Verify correct delay estimate at lookahead boundary.
1032     int delay_ms = TruncateToMultipleOf10(kSystemDelayMs + delay_min_ms);
1033     ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1034                                  delay_max_ms);
1035     // 2) A delay less than maximum lookahead should give an delay estimate at
1036     //    the boundary (= -kLookaheadBlocks * num_ms_per_block).
1037     delay_ms -= 20;
1038     ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1039                                  delay_max_ms);
1040     // 3) Three values around zero delay. Note that we need to compensate for
1041     //    the fake system_delay.
1042     delay_ms = TruncateToMultipleOf10(kSystemDelayMs - 10);
1043     ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1044                                  delay_max_ms);
1045     delay_ms = TruncateToMultipleOf10(kSystemDelayMs);
1046     ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1047                                  delay_max_ms);
1048     delay_ms = TruncateToMultipleOf10(kSystemDelayMs + 10);
1049     ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1050                                  delay_max_ms);
1051     // 4) Verify correct delay estimate at maximum delay boundary.
1052     delay_ms = TruncateToMultipleOf10(kSystemDelayMs + delay_max_ms);
1053     ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1054                                  delay_max_ms);
1055     // 5) A delay above the maximum delay should give an estimate at the
1056     //    boundary (= (kMaxDelayBlocks - 1) * num_ms_per_block).
1057     delay_ms += 20;
1058     ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1059                                  delay_max_ms);
1060   }
1061 }
1062 
TEST_F(ApmTest,EchoControlMobile)1063 TEST_F(ApmTest, EchoControlMobile) {
1064   // Turn AECM on (and AEC off)
1065   Init(16000, 16000, 16000, 2, 2, 2, false);
1066   EXPECT_EQ(apm_->kNoError, apm_->echo_control_mobile()->Enable(true));
1067   EXPECT_TRUE(apm_->echo_control_mobile()->is_enabled());
1068 
1069   // Toggle routing modes
1070   EchoControlMobile::RoutingMode mode[] = {
1071       EchoControlMobile::kQuietEarpieceOrHeadset,
1072       EchoControlMobile::kEarpiece,
1073       EchoControlMobile::kLoudEarpiece,
1074       EchoControlMobile::kSpeakerphone,
1075       EchoControlMobile::kLoudSpeakerphone,
1076   };
1077   for (size_t i = 0; i < arraysize(mode); i++) {
1078     EXPECT_EQ(apm_->kNoError,
1079         apm_->echo_control_mobile()->set_routing_mode(mode[i]));
1080     EXPECT_EQ(mode[i],
1081         apm_->echo_control_mobile()->routing_mode());
1082   }
1083   // Turn comfort noise off/on
1084   EXPECT_EQ(apm_->kNoError,
1085       apm_->echo_control_mobile()->enable_comfort_noise(false));
1086   EXPECT_FALSE(apm_->echo_control_mobile()->is_comfort_noise_enabled());
1087   EXPECT_EQ(apm_->kNoError,
1088       apm_->echo_control_mobile()->enable_comfort_noise(true));
1089   EXPECT_TRUE(apm_->echo_control_mobile()->is_comfort_noise_enabled());
1090   // Set and get echo path
1091   const size_t echo_path_size =
1092       apm_->echo_control_mobile()->echo_path_size_bytes();
1093   std::unique_ptr<char[]> echo_path_in(new char[echo_path_size]);
1094   std::unique_ptr<char[]> echo_path_out(new char[echo_path_size]);
1095   EXPECT_EQ(apm_->kNullPointerError,
1096             apm_->echo_control_mobile()->SetEchoPath(NULL, echo_path_size));
1097   EXPECT_EQ(apm_->kNullPointerError,
1098             apm_->echo_control_mobile()->GetEchoPath(NULL, echo_path_size));
1099   EXPECT_EQ(apm_->kBadParameterError,
1100             apm_->echo_control_mobile()->GetEchoPath(echo_path_out.get(), 1));
1101   EXPECT_EQ(apm_->kNoError,
1102             apm_->echo_control_mobile()->GetEchoPath(echo_path_out.get(),
1103                                                      echo_path_size));
1104   for (size_t i = 0; i < echo_path_size; i++) {
1105     echo_path_in[i] = echo_path_out[i] + 1;
1106   }
1107   EXPECT_EQ(apm_->kBadParameterError,
1108             apm_->echo_control_mobile()->SetEchoPath(echo_path_in.get(), 1));
1109   EXPECT_EQ(apm_->kNoError,
1110             apm_->echo_control_mobile()->SetEchoPath(echo_path_in.get(),
1111                                                      echo_path_size));
1112   EXPECT_EQ(apm_->kNoError,
1113             apm_->echo_control_mobile()->GetEchoPath(echo_path_out.get(),
1114                                                      echo_path_size));
1115   for (size_t i = 0; i < echo_path_size; i++) {
1116     EXPECT_EQ(echo_path_in[i], echo_path_out[i]);
1117   }
1118 
1119   // Process a few frames with NS in the default disabled state. This exercises
1120   // a different codepath than with it enabled.
1121   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
1122   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1123   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
1124   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1125 
1126   // Turn AECM off
1127   EXPECT_EQ(apm_->kNoError, apm_->echo_control_mobile()->Enable(false));
1128   EXPECT_FALSE(apm_->echo_control_mobile()->is_enabled());
1129 }
1130 
TEST_F(ApmTest,GainControl)1131 TEST_F(ApmTest, GainControl) {
1132   // Testing gain modes
1133   EXPECT_EQ(apm_->kNoError,
1134       apm_->gain_control()->set_mode(
1135       apm_->gain_control()->mode()));
1136 
1137   GainControl::Mode mode[] = {
1138     GainControl::kAdaptiveAnalog,
1139     GainControl::kAdaptiveDigital,
1140     GainControl::kFixedDigital
1141   };
1142   for (size_t i = 0; i < arraysize(mode); i++) {
1143     EXPECT_EQ(apm_->kNoError,
1144         apm_->gain_control()->set_mode(mode[i]));
1145     EXPECT_EQ(mode[i], apm_->gain_control()->mode());
1146   }
1147   // Testing invalid target levels
1148   EXPECT_EQ(apm_->kBadParameterError,
1149       apm_->gain_control()->set_target_level_dbfs(-3));
1150   EXPECT_EQ(apm_->kBadParameterError,
1151       apm_->gain_control()->set_target_level_dbfs(-40));
1152   // Testing valid target levels
1153   EXPECT_EQ(apm_->kNoError,
1154       apm_->gain_control()->set_target_level_dbfs(
1155       apm_->gain_control()->target_level_dbfs()));
1156 
1157   int level_dbfs[] = {0, 6, 31};
1158   for (size_t i = 0; i < arraysize(level_dbfs); i++) {
1159     EXPECT_EQ(apm_->kNoError,
1160         apm_->gain_control()->set_target_level_dbfs(level_dbfs[i]));
1161     EXPECT_EQ(level_dbfs[i], apm_->gain_control()->target_level_dbfs());
1162   }
1163 
1164   // Testing invalid compression gains
1165   EXPECT_EQ(apm_->kBadParameterError,
1166       apm_->gain_control()->set_compression_gain_db(-1));
1167   EXPECT_EQ(apm_->kBadParameterError,
1168       apm_->gain_control()->set_compression_gain_db(100));
1169 
1170   // Testing valid compression gains
1171   EXPECT_EQ(apm_->kNoError,
1172       apm_->gain_control()->set_compression_gain_db(
1173       apm_->gain_control()->compression_gain_db()));
1174 
1175   int gain_db[] = {0, 10, 90};
1176   for (size_t i = 0; i < arraysize(gain_db); i++) {
1177     EXPECT_EQ(apm_->kNoError,
1178         apm_->gain_control()->set_compression_gain_db(gain_db[i]));
1179     EXPECT_EQ(gain_db[i], apm_->gain_control()->compression_gain_db());
1180   }
1181 
1182   // Testing limiter off/on
1183   EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(false));
1184   EXPECT_FALSE(apm_->gain_control()->is_limiter_enabled());
1185   EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(true));
1186   EXPECT_TRUE(apm_->gain_control()->is_limiter_enabled());
1187 
1188   // Testing invalid level limits
1189   EXPECT_EQ(apm_->kBadParameterError,
1190       apm_->gain_control()->set_analog_level_limits(-1, 512));
1191   EXPECT_EQ(apm_->kBadParameterError,
1192       apm_->gain_control()->set_analog_level_limits(100000, 512));
1193   EXPECT_EQ(apm_->kBadParameterError,
1194       apm_->gain_control()->set_analog_level_limits(512, -1));
1195   EXPECT_EQ(apm_->kBadParameterError,
1196       apm_->gain_control()->set_analog_level_limits(512, 100000));
1197   EXPECT_EQ(apm_->kBadParameterError,
1198       apm_->gain_control()->set_analog_level_limits(512, 255));
1199 
1200   // Testing valid level limits
1201   EXPECT_EQ(apm_->kNoError,
1202       apm_->gain_control()->set_analog_level_limits(
1203       apm_->gain_control()->analog_level_minimum(),
1204       apm_->gain_control()->analog_level_maximum()));
1205 
1206   int min_level[] = {0, 255, 1024};
1207   for (size_t i = 0; i < arraysize(min_level); i++) {
1208     EXPECT_EQ(apm_->kNoError,
1209         apm_->gain_control()->set_analog_level_limits(min_level[i], 1024));
1210     EXPECT_EQ(min_level[i], apm_->gain_control()->analog_level_minimum());
1211   }
1212 
1213   int max_level[] = {0, 1024, 65535};
1214   for (size_t i = 0; i < arraysize(min_level); i++) {
1215     EXPECT_EQ(apm_->kNoError,
1216         apm_->gain_control()->set_analog_level_limits(0, max_level[i]));
1217     EXPECT_EQ(max_level[i], apm_->gain_control()->analog_level_maximum());
1218   }
1219 
1220   // TODO(ajm): stream_is_saturated() and stream_analog_level()
1221 
1222   // Turn AGC off
1223   EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
1224   EXPECT_FALSE(apm_->gain_control()->is_enabled());
1225 }
1226 
RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate)1227 void ApmTest::RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate) {
1228   Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
1229   EXPECT_EQ(apm_->kNoError,
1230             apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
1231   EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
1232 
1233   int out_analog_level = 0;
1234   for (int i = 0; i < 2000; ++i) {
1235     ReadFrameWithRewind(near_file_, frame_);
1236     // Ensure the audio is at a low level, so the AGC will try to increase it.
1237     ScaleFrame(frame_, 0.25);
1238 
1239     // Always pass in the same volume.
1240     EXPECT_EQ(apm_->kNoError,
1241         apm_->gain_control()->set_stream_analog_level(100));
1242     EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1243     out_analog_level = apm_->gain_control()->stream_analog_level();
1244   }
1245 
1246   // Ensure the AGC is still able to reach the maximum.
1247   EXPECT_EQ(255, out_analog_level);
1248 }
1249 
1250 // Verifies that despite volume slider quantization, the AGC can continue to
1251 // increase its volume.
TEST_F(ApmTest,QuantizedVolumeDoesNotGetStuck)1252 TEST_F(ApmTest, QuantizedVolumeDoesNotGetStuck) {
1253   for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
1254     RunQuantizedVolumeDoesNotGetStuckTest(kSampleRates[i]);
1255   }
1256 }
1257 
RunManualVolumeChangeIsPossibleTest(int sample_rate)1258 void ApmTest::RunManualVolumeChangeIsPossibleTest(int sample_rate) {
1259   Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
1260   EXPECT_EQ(apm_->kNoError,
1261             apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
1262   EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
1263 
1264   int out_analog_level = 100;
1265   for (int i = 0; i < 1000; ++i) {
1266     ReadFrameWithRewind(near_file_, frame_);
1267     // Ensure the audio is at a low level, so the AGC will try to increase it.
1268     ScaleFrame(frame_, 0.25);
1269 
1270     EXPECT_EQ(apm_->kNoError,
1271         apm_->gain_control()->set_stream_analog_level(out_analog_level));
1272     EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1273     out_analog_level = apm_->gain_control()->stream_analog_level();
1274   }
1275 
1276   // Ensure the volume was raised.
1277   EXPECT_GT(out_analog_level, 100);
1278   int highest_level_reached = out_analog_level;
1279   // Simulate a user manual volume change.
1280   out_analog_level = 100;
1281 
1282   for (int i = 0; i < 300; ++i) {
1283     ReadFrameWithRewind(near_file_, frame_);
1284     ScaleFrame(frame_, 0.25);
1285 
1286     EXPECT_EQ(apm_->kNoError,
1287         apm_->gain_control()->set_stream_analog_level(out_analog_level));
1288     EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1289     out_analog_level = apm_->gain_control()->stream_analog_level();
1290     // Check that AGC respected the manually adjusted volume.
1291     EXPECT_LT(out_analog_level, highest_level_reached);
1292   }
1293   // Check that the volume was still raised.
1294   EXPECT_GT(out_analog_level, 100);
1295 }
1296 
TEST_F(ApmTest,ManualVolumeChangeIsPossible)1297 TEST_F(ApmTest, ManualVolumeChangeIsPossible) {
1298   for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
1299     RunManualVolumeChangeIsPossibleTest(kSampleRates[i]);
1300   }
1301 }
1302 
1303 #if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
TEST_F(ApmTest,AgcOnlyAdaptsWhenTargetSignalIsPresent)1304 TEST_F(ApmTest, AgcOnlyAdaptsWhenTargetSignalIsPresent) {
1305   const int kSampleRateHz = 16000;
1306   const size_t kSamplesPerChannel =
1307       static_cast<size_t>(AudioProcessing::kChunkSizeMs * kSampleRateHz / 1000);
1308   const size_t kNumInputChannels = 2;
1309   const size_t kNumOutputChannels = 1;
1310   const size_t kNumChunks = 700;
1311   const float kScaleFactor = 0.25f;
1312   Config config;
1313   std::vector<webrtc::Point> geometry;
1314   geometry.push_back(webrtc::Point(0.f, 0.f, 0.f));
1315   geometry.push_back(webrtc::Point(0.05f, 0.f, 0.f));
1316   config.Set<Beamforming>(new Beamforming(true, geometry));
1317   testing::NiceMock<MockNonlinearBeamformer>* beamformer =
1318       new testing::NiceMock<MockNonlinearBeamformer>(geometry, 1u);
1319   std::unique_ptr<AudioProcessing> apm(
1320       AudioProcessing::Create(config, nullptr, nullptr, beamformer));
1321   EXPECT_EQ(kNoErr, apm->gain_control()->Enable(true));
1322   ChannelBuffer<float> src_buf(kSamplesPerChannel, kNumInputChannels);
1323   ChannelBuffer<float> dest_buf(kSamplesPerChannel, kNumOutputChannels);
1324   const size_t max_length = kSamplesPerChannel * std::max(kNumInputChannels,
1325                                                           kNumOutputChannels);
1326   std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
1327   std::unique_ptr<float[]> float_data(new float[max_length]);
1328   std::string filename = ResourceFilePath("far", kSampleRateHz);
1329   FILE* far_file = fopen(filename.c_str(), "rb");
1330   ASSERT_TRUE(far_file != NULL) << "Could not open file " << filename << "\n";
1331   const int kDefaultVolume = apm->gain_control()->stream_analog_level();
1332   const int kDefaultCompressionGain =
1333       apm->gain_control()->compression_gain_db();
1334   bool is_target = false;
1335   EXPECT_CALL(*beamformer, is_target_present())
1336       .WillRepeatedly(testing::ReturnPointee(&is_target));
1337   for (size_t i = 0; i < kNumChunks; ++i) {
1338     ASSERT_TRUE(ReadChunk(far_file,
1339                           int_data.get(),
1340                           float_data.get(),
1341                           &src_buf));
1342     for (size_t j = 0; j < kNumInputChannels; ++j) {
1343       for (size_t k = 0; k < kSamplesPerChannel; ++k) {
1344         src_buf.channels()[j][k] *= kScaleFactor;
1345       }
1346     }
1347     EXPECT_EQ(kNoErr,
1348               apm->ProcessStream(src_buf.channels(),
1349                                  src_buf.num_frames(),
1350                                  kSampleRateHz,
1351                                  LayoutFromChannels(src_buf.num_channels()),
1352                                  kSampleRateHz,
1353                                  LayoutFromChannels(dest_buf.num_channels()),
1354                                  dest_buf.channels()));
1355   }
1356   EXPECT_EQ(kDefaultVolume,
1357             apm->gain_control()->stream_analog_level());
1358   EXPECT_EQ(kDefaultCompressionGain,
1359             apm->gain_control()->compression_gain_db());
1360   rewind(far_file);
1361   is_target = true;
1362   for (size_t i = 0; i < kNumChunks; ++i) {
1363     ASSERT_TRUE(ReadChunk(far_file,
1364                           int_data.get(),
1365                           float_data.get(),
1366                           &src_buf));
1367     for (size_t j = 0; j < kNumInputChannels; ++j) {
1368       for (size_t k = 0; k < kSamplesPerChannel; ++k) {
1369         src_buf.channels()[j][k] *= kScaleFactor;
1370       }
1371     }
1372     EXPECT_EQ(kNoErr,
1373               apm->ProcessStream(src_buf.channels(),
1374                                  src_buf.num_frames(),
1375                                  kSampleRateHz,
1376                                  LayoutFromChannels(src_buf.num_channels()),
1377                                  kSampleRateHz,
1378                                  LayoutFromChannels(dest_buf.num_channels()),
1379                                  dest_buf.channels()));
1380   }
1381   EXPECT_LT(kDefaultVolume,
1382             apm->gain_control()->stream_analog_level());
1383   EXPECT_LT(kDefaultCompressionGain,
1384             apm->gain_control()->compression_gain_db());
1385   ASSERT_EQ(0, fclose(far_file));
1386 }
1387 #endif
1388 
TEST_F(ApmTest,NoiseSuppression)1389 TEST_F(ApmTest, NoiseSuppression) {
1390   // Test valid suppression levels.
1391   NoiseSuppression::Level level[] = {
1392     NoiseSuppression::kLow,
1393     NoiseSuppression::kModerate,
1394     NoiseSuppression::kHigh,
1395     NoiseSuppression::kVeryHigh
1396   };
1397   for (size_t i = 0; i < arraysize(level); i++) {
1398     EXPECT_EQ(apm_->kNoError,
1399         apm_->noise_suppression()->set_level(level[i]));
1400     EXPECT_EQ(level[i], apm_->noise_suppression()->level());
1401   }
1402 
1403   // Turn NS on/off
1404   EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(true));
1405   EXPECT_TRUE(apm_->noise_suppression()->is_enabled());
1406   EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(false));
1407   EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1408 }
1409 
TEST_F(ApmTest,HighPassFilter)1410 TEST_F(ApmTest, HighPassFilter) {
1411   // Turn HP filter on/off
1412   AudioProcessing::Config apm_config;
1413   apm_config.high_pass_filter.enabled = true;
1414   apm_->ApplyConfig(apm_config);
1415   apm_config.high_pass_filter.enabled = false;
1416   apm_->ApplyConfig(apm_config);
1417 }
1418 
TEST_F(ApmTest,LevelEstimator)1419 TEST_F(ApmTest, LevelEstimator) {
1420   // Turn level estimator on/off
1421   EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1422   EXPECT_FALSE(apm_->level_estimator()->is_enabled());
1423 
1424   EXPECT_EQ(apm_->kNotEnabledError, apm_->level_estimator()->RMS());
1425 
1426   EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1427   EXPECT_TRUE(apm_->level_estimator()->is_enabled());
1428 
1429   // Run this test in wideband; in super-wb, the splitting filter distorts the
1430   // audio enough to cause deviation from the expectation for small values.
1431   frame_->samples_per_channel_ = 160;
1432   frame_->num_channels_ = 2;
1433   frame_->sample_rate_hz_ = 16000;
1434 
1435   // Min value if no frames have been processed.
1436   EXPECT_EQ(127, apm_->level_estimator()->RMS());
1437 
1438   // Min value on zero frames.
1439   SetFrameTo(frame_, 0);
1440   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1441   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1442   EXPECT_EQ(127, apm_->level_estimator()->RMS());
1443 
1444   // Try a few RMS values.
1445   // (These also test that the value resets after retrieving it.)
1446   SetFrameTo(frame_, 32767);
1447   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1448   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1449   EXPECT_EQ(0, apm_->level_estimator()->RMS());
1450 
1451   SetFrameTo(frame_, 30000);
1452   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1453   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1454   EXPECT_EQ(1, apm_->level_estimator()->RMS());
1455 
1456   SetFrameTo(frame_, 10000);
1457   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1458   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1459   EXPECT_EQ(10, apm_->level_estimator()->RMS());
1460 
1461   SetFrameTo(frame_, 10);
1462   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1463   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1464   EXPECT_EQ(70, apm_->level_estimator()->RMS());
1465 
1466   // Verify reset after enable/disable.
1467   SetFrameTo(frame_, 32767);
1468   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1469   EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1470   EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1471   SetFrameTo(frame_, 1);
1472   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1473   EXPECT_EQ(90, apm_->level_estimator()->RMS());
1474 
1475   // Verify reset after initialize.
1476   SetFrameTo(frame_, 32767);
1477   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1478   EXPECT_EQ(apm_->kNoError, apm_->Initialize());
1479   SetFrameTo(frame_, 1);
1480   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1481   EXPECT_EQ(90, apm_->level_estimator()->RMS());
1482 }
1483 
TEST_F(ApmTest,VoiceDetection)1484 TEST_F(ApmTest, VoiceDetection) {
1485   // Test external VAD
1486   EXPECT_EQ(apm_->kNoError,
1487             apm_->voice_detection()->set_stream_has_voice(true));
1488   EXPECT_TRUE(apm_->voice_detection()->stream_has_voice());
1489   EXPECT_EQ(apm_->kNoError,
1490             apm_->voice_detection()->set_stream_has_voice(false));
1491   EXPECT_FALSE(apm_->voice_detection()->stream_has_voice());
1492 
1493   // Test valid likelihoods
1494   VoiceDetection::Likelihood likelihood[] = {
1495       VoiceDetection::kVeryLowLikelihood,
1496       VoiceDetection::kLowLikelihood,
1497       VoiceDetection::kModerateLikelihood,
1498       VoiceDetection::kHighLikelihood
1499   };
1500   for (size_t i = 0; i < arraysize(likelihood); i++) {
1501     EXPECT_EQ(apm_->kNoError,
1502               apm_->voice_detection()->set_likelihood(likelihood[i]));
1503     EXPECT_EQ(likelihood[i], apm_->voice_detection()->likelihood());
1504   }
1505 
1506   /* TODO(bjornv): Enable once VAD supports other frame lengths than 10 ms
1507   // Test invalid frame sizes
1508   EXPECT_EQ(apm_->kBadParameterError,
1509       apm_->voice_detection()->set_frame_size_ms(12));
1510 
1511   // Test valid frame sizes
1512   for (int i = 10; i <= 30; i += 10) {
1513     EXPECT_EQ(apm_->kNoError,
1514         apm_->voice_detection()->set_frame_size_ms(i));
1515     EXPECT_EQ(i, apm_->voice_detection()->frame_size_ms());
1516   }
1517   */
1518 
1519   // Turn VAD on/off
1520   EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1521   EXPECT_TRUE(apm_->voice_detection()->is_enabled());
1522   EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1523   EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1524 
1525   // Test that AudioFrame activity is maintained when VAD is disabled.
1526   EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1527   AudioFrame::VADActivity activity[] = {
1528       AudioFrame::kVadActive,
1529       AudioFrame::kVadPassive,
1530       AudioFrame::kVadUnknown
1531   };
1532   for (size_t i = 0; i < arraysize(activity); i++) {
1533     frame_->vad_activity_ = activity[i];
1534     EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1535     EXPECT_EQ(activity[i], frame_->vad_activity_);
1536   }
1537 
1538   // Test that AudioFrame activity is set when VAD is enabled.
1539   EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1540   frame_->vad_activity_ = AudioFrame::kVadUnknown;
1541   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1542   EXPECT_NE(AudioFrame::kVadUnknown, frame_->vad_activity_);
1543 
1544   // TODO(bjornv): Add tests for streamed voice; stream_has_voice()
1545 }
1546 
TEST_F(ApmTest,AllProcessingDisabledByDefault)1547 TEST_F(ApmTest, AllProcessingDisabledByDefault) {
1548   EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
1549   EXPECT_FALSE(apm_->echo_control_mobile()->is_enabled());
1550   EXPECT_FALSE(apm_->gain_control()->is_enabled());
1551   EXPECT_FALSE(apm_->high_pass_filter()->is_enabled());
1552   EXPECT_FALSE(apm_->level_estimator()->is_enabled());
1553   EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1554   EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1555 }
1556 
TEST_F(ApmTest,NoProcessingWhenAllComponentsDisabled)1557 TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabled) {
1558   for (size_t i = 0; i < arraysize(kSampleRates); i++) {
1559     Init(kSampleRates[i], kSampleRates[i], kSampleRates[i], 2, 2, 2, false);
1560     SetFrameTo(frame_, 1000, 2000);
1561     AudioFrame frame_copy;
1562     frame_copy.CopyFrom(*frame_);
1563     for (int j = 0; j < 1000; j++) {
1564       EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1565       EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1566       EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(frame_));
1567       EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1568     }
1569   }
1570 }
1571 
TEST_F(ApmTest,NoProcessingWhenAllComponentsDisabledFloat)1572 TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabledFloat) {
1573   // Test that ProcessStream copies input to output even with no processing.
1574   const size_t kSamples = 80;
1575   const int sample_rate = 8000;
1576   const float src[kSamples] = {
1577     -1.0f, 0.0f, 1.0f
1578   };
1579   float dest[kSamples] = {};
1580 
1581   auto src_channels = &src[0];
1582   auto dest_channels = &dest[0];
1583 
1584   apm_.reset(AudioProcessing::Create());
1585   EXPECT_NOERR(apm_->ProcessStream(
1586       &src_channels, kSamples, sample_rate, LayoutFromChannels(1),
1587       sample_rate, LayoutFromChannels(1), &dest_channels));
1588 
1589   for (size_t i = 0; i < kSamples; ++i) {
1590     EXPECT_EQ(src[i], dest[i]);
1591   }
1592 
1593   // Same for ProcessReverseStream.
1594   float rev_dest[kSamples] = {};
1595   auto rev_dest_channels = &rev_dest[0];
1596 
1597   StreamConfig input_stream = {sample_rate, 1};
1598   StreamConfig output_stream = {sample_rate, 1};
1599   EXPECT_NOERR(apm_->ProcessReverseStream(&src_channels, input_stream,
1600                                           output_stream, &rev_dest_channels));
1601 
1602   for (size_t i = 0; i < kSamples; ++i) {
1603     EXPECT_EQ(src[i], rev_dest[i]);
1604   }
1605 }
1606 
TEST_F(ApmTest,IdenticalInputChannelsResultInIdenticalOutputChannels)1607 TEST_F(ApmTest, IdenticalInputChannelsResultInIdenticalOutputChannels) {
1608   EnableAllComponents();
1609 
1610   for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
1611     Init(kProcessSampleRates[i],
1612          kProcessSampleRates[i],
1613          kProcessSampleRates[i],
1614          2,
1615          2,
1616          2,
1617          false);
1618     int analog_level = 127;
1619     ASSERT_EQ(0, feof(far_file_));
1620     ASSERT_EQ(0, feof(near_file_));
1621     while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
1622       CopyLeftToRightChannel(revframe_->mutable_data(),
1623                              revframe_->samples_per_channel_);
1624 
1625       ASSERT_EQ(kNoErr, apm_->ProcessReverseStream(revframe_));
1626 
1627       CopyLeftToRightChannel(frame_->mutable_data(),
1628                              frame_->samples_per_channel_);
1629       frame_->vad_activity_ = AudioFrame::kVadUnknown;
1630 
1631       ASSERT_EQ(kNoErr, apm_->set_stream_delay_ms(0));
1632       apm_->echo_cancellation()->set_stream_drift_samples(0);
1633       ASSERT_EQ(kNoErr,
1634           apm_->gain_control()->set_stream_analog_level(analog_level));
1635       ASSERT_EQ(kNoErr, apm_->ProcessStream(frame_));
1636       analog_level = apm_->gain_control()->stream_analog_level();
1637 
1638       VerifyChannelsAreEqual(frame_->data(), frame_->samples_per_channel_);
1639     }
1640     rewind(far_file_);
1641     rewind(near_file_);
1642   }
1643 }
1644 
TEST_F(ApmTest,SplittingFilter)1645 TEST_F(ApmTest, SplittingFilter) {
1646   // Verify the filter is not active through undistorted audio when:
1647   // 1. No components are enabled...
1648   SetFrameTo(frame_, 1000);
1649   AudioFrame frame_copy;
1650   frame_copy.CopyFrom(*frame_);
1651   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1652   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1653   EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1654 
1655   // 2. Only the level estimator is enabled...
1656   SetFrameTo(frame_, 1000);
1657   frame_copy.CopyFrom(*frame_);
1658   EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1659   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1660   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1661   EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1662   EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1663 
1664   // 3. Only VAD is enabled...
1665   SetFrameTo(frame_, 1000);
1666   frame_copy.CopyFrom(*frame_);
1667   EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1668   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1669   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1670   EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1671   EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1672 
1673   // 4. Both VAD and the level estimator are enabled...
1674   SetFrameTo(frame_, 1000);
1675   frame_copy.CopyFrom(*frame_);
1676   EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1677   EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1678   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1679   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1680   EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1681   EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1682   EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1683 
1684   // 5. Not using super-wb.
1685   frame_->samples_per_channel_ = 160;
1686   frame_->num_channels_ = 2;
1687   frame_->sample_rate_hz_ = 16000;
1688   // Enable AEC, which would require the filter in super-wb. We rely on the
1689   // first few frames of data being unaffected by the AEC.
1690   // TODO(andrew): This test, and the one below, rely rather tenuously on the
1691   // behavior of the AEC. Think of something more robust.
1692   EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
1693   // Make sure we have extended filter enabled. This makes sure nothing is
1694   // touched until we have a farend frame.
1695   Config config;
1696   config.Set<ExtendedFilter>(new ExtendedFilter(true));
1697   apm_->SetExtraOptions(config);
1698   SetFrameTo(frame_, 1000);
1699   frame_copy.CopyFrom(*frame_);
1700   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
1701   apm_->echo_cancellation()->set_stream_drift_samples(0);
1702   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1703   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
1704   apm_->echo_cancellation()->set_stream_drift_samples(0);
1705   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1706   EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1707 
1708   // Check the test is valid. We should have distortion from the filter
1709   // when AEC is enabled (which won't affect the audio).
1710   frame_->samples_per_channel_ = 320;
1711   frame_->num_channels_ = 2;
1712   frame_->sample_rate_hz_ = 32000;
1713   SetFrameTo(frame_, 1000);
1714   frame_copy.CopyFrom(*frame_);
1715   EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
1716   apm_->echo_cancellation()->set_stream_drift_samples(0);
1717   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1718   EXPECT_FALSE(FrameDataAreEqual(*frame_, frame_copy));
1719 }
1720 
1721 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ProcessDebugDump(const std::string & in_filename,const std::string & out_filename,Format format,int max_size_bytes)1722 void ApmTest::ProcessDebugDump(const std::string& in_filename,
1723                                const std::string& out_filename,
1724                                Format format,
1725                                int max_size_bytes) {
1726   rtc::TaskQueue worker_queue("ApmTest_worker_queue");
1727   FILE* in_file = fopen(in_filename.c_str(), "rb");
1728   ASSERT_TRUE(in_file != NULL);
1729   audioproc::Event event_msg;
1730   bool first_init = true;
1731 
1732   while (ReadMessageFromFile(in_file, &event_msg)) {
1733     if (event_msg.type() == audioproc::Event::INIT) {
1734       const audioproc::Init msg = event_msg.init();
1735       int reverse_sample_rate = msg.sample_rate();
1736       if (msg.has_reverse_sample_rate()) {
1737         reverse_sample_rate = msg.reverse_sample_rate();
1738       }
1739       int output_sample_rate = msg.sample_rate();
1740       if (msg.has_output_sample_rate()) {
1741         output_sample_rate = msg.output_sample_rate();
1742       }
1743 
1744       Init(msg.sample_rate(),
1745            output_sample_rate,
1746            reverse_sample_rate,
1747            msg.num_input_channels(),
1748            msg.num_output_channels(),
1749            msg.num_reverse_channels(),
1750            false);
1751       if (first_init) {
1752         // AttachAecDump() writes an additional init message. Don't start
1753         // recording until after the first init to avoid the extra message.
1754         auto aec_dump =
1755             AecDumpFactory::Create(out_filename, max_size_bytes, &worker_queue);
1756         EXPECT_TRUE(aec_dump);
1757         apm_->AttachAecDump(std::move(aec_dump));
1758         first_init = false;
1759       }
1760 
1761     } else if (event_msg.type() == audioproc::Event::REVERSE_STREAM) {
1762       const audioproc::ReverseStream msg = event_msg.reverse_stream();
1763 
1764       if (msg.channel_size() > 0) {
1765         ASSERT_EQ(revframe_->num_channels_,
1766                   static_cast<size_t>(msg.channel_size()));
1767         for (int i = 0; i < msg.channel_size(); ++i) {
1768            memcpy(revfloat_cb_->channels()[i],
1769                   msg.channel(i).data(),
1770                   msg.channel(i).size());
1771         }
1772       } else {
1773         memcpy(revframe_->mutable_data(), msg.data().data(), msg.data().size());
1774         if (format == kFloatFormat) {
1775           // We're using an int16 input file; convert to float.
1776           ConvertToFloat(*revframe_, revfloat_cb_.get());
1777         }
1778       }
1779       AnalyzeReverseStreamChooser(format);
1780 
1781     } else if (event_msg.type() == audioproc::Event::STREAM) {
1782       const audioproc::Stream msg = event_msg.stream();
1783       // ProcessStream could have changed this for the output frame.
1784       frame_->num_channels_ = apm_->num_input_channels();
1785 
1786       EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(msg.level()));
1787       EXPECT_NOERR(apm_->set_stream_delay_ms(msg.delay()));
1788       apm_->echo_cancellation()->set_stream_drift_samples(msg.drift());
1789       if (msg.has_keypress()) {
1790         apm_->set_stream_key_pressed(msg.keypress());
1791       } else {
1792         apm_->set_stream_key_pressed(true);
1793       }
1794 
1795       if (msg.input_channel_size() > 0) {
1796         ASSERT_EQ(frame_->num_channels_,
1797                   static_cast<size_t>(msg.input_channel_size()));
1798         for (int i = 0; i < msg.input_channel_size(); ++i) {
1799            memcpy(float_cb_->channels()[i],
1800                   msg.input_channel(i).data(),
1801                   msg.input_channel(i).size());
1802         }
1803       } else {
1804         memcpy(frame_->mutable_data(), msg.input_data().data(),
1805                msg.input_data().size());
1806         if (format == kFloatFormat) {
1807           // We're using an int16 input file; convert to float.
1808           ConvertToFloat(*frame_, float_cb_.get());
1809         }
1810       }
1811       ProcessStreamChooser(format);
1812     }
1813   }
1814   apm_->DetachAecDump();
1815   fclose(in_file);
1816 }
1817 
VerifyDebugDumpTest(Format format)1818 void ApmTest::VerifyDebugDumpTest(Format format) {
1819   const std::string in_filename = test::ResourcePath("ref03", "aecdump");
1820   std::string format_string;
1821   switch (format) {
1822     case kIntFormat:
1823       format_string = "_int";
1824       break;
1825     case kFloatFormat:
1826       format_string = "_float";
1827       break;
1828   }
1829   const std::string ref_filename = test::TempFilename(
1830       test::OutputPath(), std::string("ref") + format_string + "_aecdump");
1831   const std::string out_filename = test::TempFilename(
1832       test::OutputPath(), std::string("out") + format_string + "_aecdump");
1833   const std::string limited_filename = test::TempFilename(
1834       test::OutputPath(), std::string("limited") + format_string + "_aecdump");
1835   const size_t logging_limit_bytes = 100000;
1836   // We expect at least this many bytes in the created logfile.
1837   const size_t logging_expected_bytes = 95000;
1838   EnableAllComponents();
1839   ProcessDebugDump(in_filename, ref_filename, format, -1);
1840   ProcessDebugDump(ref_filename, out_filename, format, -1);
1841   ProcessDebugDump(ref_filename, limited_filename, format, logging_limit_bytes);
1842 
1843   FILE* ref_file = fopen(ref_filename.c_str(), "rb");
1844   FILE* out_file = fopen(out_filename.c_str(), "rb");
1845   FILE* limited_file = fopen(limited_filename.c_str(), "rb");
1846   ASSERT_TRUE(ref_file != NULL);
1847   ASSERT_TRUE(out_file != NULL);
1848   ASSERT_TRUE(limited_file != NULL);
1849   std::unique_ptr<uint8_t[]> ref_bytes;
1850   std::unique_ptr<uint8_t[]> out_bytes;
1851   std::unique_ptr<uint8_t[]> limited_bytes;
1852 
1853   size_t ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1854   size_t out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
1855   size_t limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
1856   size_t bytes_read = 0;
1857   size_t bytes_read_limited = 0;
1858   while (ref_size > 0 && out_size > 0) {
1859     bytes_read += ref_size;
1860     bytes_read_limited += limited_size;
1861     EXPECT_EQ(ref_size, out_size);
1862     EXPECT_GE(ref_size, limited_size);
1863     EXPECT_EQ(0, memcmp(ref_bytes.get(), out_bytes.get(), ref_size));
1864     EXPECT_EQ(0, memcmp(ref_bytes.get(), limited_bytes.get(), limited_size));
1865     ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1866     out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
1867     limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
1868   }
1869   EXPECT_GT(bytes_read, 0u);
1870   EXPECT_GT(bytes_read_limited, logging_expected_bytes);
1871   EXPECT_LE(bytes_read_limited, logging_limit_bytes);
1872   EXPECT_NE(0, feof(ref_file));
1873   EXPECT_NE(0, feof(out_file));
1874   EXPECT_NE(0, feof(limited_file));
1875   ASSERT_EQ(0, fclose(ref_file));
1876   ASSERT_EQ(0, fclose(out_file));
1877   ASSERT_EQ(0, fclose(limited_file));
1878   remove(ref_filename.c_str());
1879   remove(out_filename.c_str());
1880   remove(limited_filename.c_str());
1881 }
1882 
TEST_F(ApmTest,VerifyDebugDumpInt)1883 TEST_F(ApmTest, VerifyDebugDumpInt) {
1884   VerifyDebugDumpTest(kIntFormat);
1885 }
1886 
TEST_F(ApmTest,VerifyDebugDumpFloat)1887 TEST_F(ApmTest, VerifyDebugDumpFloat) {
1888   VerifyDebugDumpTest(kFloatFormat);
1889 }
1890 #endif
1891 
1892 // TODO(andrew): expand test to verify output.
TEST_F(ApmTest,DebugDump)1893 TEST_F(ApmTest, DebugDump) {
1894   rtc::TaskQueue worker_queue("ApmTest_worker_queue");
1895   const std::string filename =
1896       test::TempFilename(test::OutputPath(), "debug_aec");
1897   {
1898     auto aec_dump = AecDumpFactory::Create("", -1, &worker_queue);
1899     EXPECT_FALSE(aec_dump);
1900   }
1901 
1902 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1903   // Stopping without having started should be OK.
1904   apm_->DetachAecDump();
1905 
1906   auto aec_dump = AecDumpFactory::Create(filename, -1, &worker_queue);
1907   EXPECT_TRUE(aec_dump);
1908   apm_->AttachAecDump(std::move(aec_dump));
1909   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1910   EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
1911   apm_->DetachAecDump();
1912 
1913   // Verify the file has been written.
1914   FILE* fid = fopen(filename.c_str(), "r");
1915   ASSERT_TRUE(fid != NULL);
1916 
1917   // Clean it up.
1918   ASSERT_EQ(0, fclose(fid));
1919   ASSERT_EQ(0, remove(filename.c_str()));
1920 #else
1921   // Verify the file has NOT been written.
1922   ASSERT_TRUE(fopen(filename.c_str(), "r") == NULL);
1923 #endif  // WEBRTC_AUDIOPROC_DEBUG_DUMP
1924 }
1925 
1926 // TODO(andrew): expand test to verify output.
TEST_F(ApmTest,DebugDumpFromFileHandle)1927 TEST_F(ApmTest, DebugDumpFromFileHandle) {
1928   rtc::TaskQueue worker_queue("ApmTest_worker_queue");
1929 
1930   const std::string filename =
1931       test::TempFilename(test::OutputPath(), "debug_aec");
1932   FILE* fid = fopen(filename.c_str(), "w");
1933   ASSERT_TRUE(fid);
1934 
1935 #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1936   // Stopping without having started should be OK.
1937   apm_->DetachAecDump();
1938 
1939   auto aec_dump = AecDumpFactory::Create(fid, -1, &worker_queue);
1940   EXPECT_TRUE(aec_dump);
1941   apm_->AttachAecDump(std::move(aec_dump));
1942   EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
1943   EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1944   apm_->DetachAecDump();
1945 
1946   // Verify the file has been written.
1947   fid = fopen(filename.c_str(), "r");
1948   ASSERT_TRUE(fid != NULL);
1949 
1950   // Clean it up.
1951   ASSERT_EQ(0, fclose(fid));
1952   ASSERT_EQ(0, remove(filename.c_str()));
1953 #else
1954   ASSERT_EQ(0, fclose(fid));
1955 #endif  // WEBRTC_AUDIOPROC_DEBUG_DUMP
1956 }
1957 
TEST_F(ApmTest,FloatAndIntInterfacesGiveSimilarResults)1958 TEST_F(ApmTest, FloatAndIntInterfacesGiveSimilarResults) {
1959   audioproc::OutputData ref_data;
1960   OpenFileAndReadMessage(ref_filename_, &ref_data);
1961 
1962   Config config;
1963   config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
1964   std::unique_ptr<AudioProcessing> fapm(AudioProcessing::Create(config));
1965   EnableAllComponents();
1966   EnableAllAPComponents(fapm.get());
1967   for (int i = 0; i < ref_data.test_size(); i++) {
1968     printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
1969 
1970     audioproc::Test* test = ref_data.mutable_test(i);
1971     // TODO(ajm): Restore downmixing test cases.
1972     if (test->num_input_channels() != test->num_output_channels())
1973       continue;
1974 
1975     const size_t num_render_channels =
1976         static_cast<size_t>(test->num_reverse_channels());
1977     const size_t num_input_channels =
1978         static_cast<size_t>(test->num_input_channels());
1979     const size_t num_output_channels =
1980         static_cast<size_t>(test->num_output_channels());
1981     const size_t samples_per_channel = static_cast<size_t>(
1982         test->sample_rate() * AudioProcessing::kChunkSizeMs / 1000);
1983 
1984     Init(test->sample_rate(), test->sample_rate(), test->sample_rate(),
1985          num_input_channels, num_output_channels, num_render_channels, true);
1986     Init(fapm.get());
1987 
1988     ChannelBuffer<int16_t> output_cb(samples_per_channel, num_input_channels);
1989     ChannelBuffer<int16_t> output_int16(samples_per_channel,
1990                                         num_input_channels);
1991 
1992     int analog_level = 127;
1993     size_t num_bad_chunks = 0;
1994     while (ReadFrame(far_file_, revframe_, revfloat_cb_.get()) &&
1995            ReadFrame(near_file_, frame_, float_cb_.get())) {
1996       frame_->vad_activity_ = AudioFrame::kVadUnknown;
1997 
1998       EXPECT_NOERR(apm_->ProcessReverseStream(revframe_));
1999       EXPECT_NOERR(fapm->AnalyzeReverseStream(
2000           revfloat_cb_->channels(),
2001           samples_per_channel,
2002           test->sample_rate(),
2003           LayoutFromChannels(num_render_channels)));
2004 
2005       EXPECT_NOERR(apm_->set_stream_delay_ms(0));
2006       EXPECT_NOERR(fapm->set_stream_delay_ms(0));
2007       apm_->echo_cancellation()->set_stream_drift_samples(0);
2008       fapm->echo_cancellation()->set_stream_drift_samples(0);
2009       EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(analog_level));
2010       EXPECT_NOERR(fapm->gain_control()->set_stream_analog_level(analog_level));
2011 
2012       EXPECT_NOERR(apm_->ProcessStream(frame_));
2013       Deinterleave(frame_->data(), samples_per_channel, num_output_channels,
2014                    output_int16.channels());
2015 
2016       EXPECT_NOERR(fapm->ProcessStream(
2017           float_cb_->channels(),
2018           samples_per_channel,
2019           test->sample_rate(),
2020           LayoutFromChannels(num_input_channels),
2021           test->sample_rate(),
2022           LayoutFromChannels(num_output_channels),
2023           float_cb_->channels()));
2024       for (size_t j = 0; j < num_output_channels; ++j) {
2025         FloatToS16(float_cb_->channels()[j],
2026                    samples_per_channel,
2027                    output_cb.channels()[j]);
2028         float variance = 0;
2029         float snr = ComputeSNR(output_int16.channels()[j],
2030                                output_cb.channels()[j],
2031                                samples_per_channel, &variance);
2032 
2033         const float kVarianceThreshold = 20;
2034         const float kSNRThreshold = 20;
2035 
2036         // Skip frames with low energy.
2037         if (sqrt(variance) > kVarianceThreshold && snr < kSNRThreshold) {
2038           ++num_bad_chunks;
2039         }
2040       }
2041 
2042       analog_level = fapm->gain_control()->stream_analog_level();
2043       EXPECT_EQ(apm_->gain_control()->stream_analog_level(),
2044                 fapm->gain_control()->stream_analog_level());
2045       EXPECT_EQ(apm_->echo_cancellation()->stream_has_echo(),
2046                 fapm->echo_cancellation()->stream_has_echo());
2047       EXPECT_NEAR(apm_->noise_suppression()->speech_probability(),
2048                   fapm->noise_suppression()->speech_probability(),
2049                   0.01);
2050 
2051       // Reset in case of downmixing.
2052       frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
2053     }
2054 
2055 #if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2056     const size_t kMaxNumBadChunks = 0;
2057 #elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
2058     // There are a few chunks in the fixed-point profile that give low SNR.
2059     // Listening confirmed the difference is acceptable.
2060     const size_t kMaxNumBadChunks = 60;
2061 #endif
2062     EXPECT_LE(num_bad_chunks, kMaxNumBadChunks);
2063 
2064     rewind(far_file_);
2065     rewind(near_file_);
2066   }
2067 }
2068 
2069 // TODO(andrew): Add a test to process a few frames with different combinations
2070 // of enabled components.
2071 
TEST_F(ApmTest,Process)2072 TEST_F(ApmTest, Process) {
2073   GOOGLE_PROTOBUF_VERIFY_VERSION;
2074   audioproc::OutputData ref_data;
2075 
2076   if (!write_ref_data) {
2077     OpenFileAndReadMessage(ref_filename_, &ref_data);
2078   } else {
2079     // Write the desired tests to the protobuf reference file.
2080     for (size_t i = 0; i < arraysize(kChannels); i++) {
2081       for (size_t j = 0; j < arraysize(kChannels); j++) {
2082         for (size_t l = 0; l < arraysize(kProcessSampleRates); l++) {
2083           audioproc::Test* test = ref_data.add_test();
2084           test->set_num_reverse_channels(kChannels[i]);
2085           test->set_num_input_channels(kChannels[j]);
2086           test->set_num_output_channels(kChannels[j]);
2087           test->set_sample_rate(kProcessSampleRates[l]);
2088           test->set_use_aec_extended_filter(false);
2089         }
2090       }
2091     }
2092 #if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2093     // To test the extended filter mode.
2094     audioproc::Test* test = ref_data.add_test();
2095     test->set_num_reverse_channels(2);
2096     test->set_num_input_channels(2);
2097     test->set_num_output_channels(2);
2098     test->set_sample_rate(AudioProcessing::kSampleRate32kHz);
2099     test->set_use_aec_extended_filter(true);
2100 #endif
2101   }
2102 
2103   for (int i = 0; i < ref_data.test_size(); i++) {
2104     printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
2105 
2106     audioproc::Test* test = ref_data.mutable_test(i);
2107     // TODO(ajm): We no longer allow different input and output channels. Skip
2108     // these tests for now, but they should be removed from the set.
2109     if (test->num_input_channels() != test->num_output_channels())
2110       continue;
2111 
2112     Config config;
2113     config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
2114     config.Set<ExtendedFilter>(
2115         new ExtendedFilter(test->use_aec_extended_filter()));
2116     apm_.reset(AudioProcessing::Create(config));
2117 
2118     EnableAllComponents();
2119 
2120     Init(test->sample_rate(),
2121          test->sample_rate(),
2122          test->sample_rate(),
2123          static_cast<size_t>(test->num_input_channels()),
2124          static_cast<size_t>(test->num_output_channels()),
2125          static_cast<size_t>(test->num_reverse_channels()),
2126          true);
2127 
2128     int frame_count = 0;
2129     int has_echo_count = 0;
2130     int has_voice_count = 0;
2131     int is_saturated_count = 0;
2132     int analog_level = 127;
2133     int analog_level_average = 0;
2134     int max_output_average = 0;
2135     float ns_speech_prob_average = 0.0f;
2136 #if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2137   int stats_index = 0;
2138 #endif
2139 
2140     while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
2141       EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
2142 
2143       frame_->vad_activity_ = AudioFrame::kVadUnknown;
2144 
2145       EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
2146       apm_->echo_cancellation()->set_stream_drift_samples(0);
2147       EXPECT_EQ(apm_->kNoError,
2148           apm_->gain_control()->set_stream_analog_level(analog_level));
2149 
2150       EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
2151 
2152       // Ensure the frame was downmixed properly.
2153       EXPECT_EQ(static_cast<size_t>(test->num_output_channels()),
2154                 frame_->num_channels_);
2155 
2156       max_output_average += MaxAudioFrame(*frame_);
2157 
2158       if (apm_->echo_cancellation()->stream_has_echo()) {
2159         has_echo_count++;
2160       }
2161 
2162       analog_level = apm_->gain_control()->stream_analog_level();
2163       analog_level_average += analog_level;
2164       if (apm_->gain_control()->stream_is_saturated()) {
2165         is_saturated_count++;
2166       }
2167       if (apm_->voice_detection()->stream_has_voice()) {
2168         has_voice_count++;
2169         EXPECT_EQ(AudioFrame::kVadActive, frame_->vad_activity_);
2170       } else {
2171         EXPECT_EQ(AudioFrame::kVadPassive, frame_->vad_activity_);
2172       }
2173 
2174       ns_speech_prob_average += apm_->noise_suppression()->speech_probability();
2175 
2176       size_t frame_size = frame_->samples_per_channel_ * frame_->num_channels_;
2177       size_t write_count = fwrite(frame_->data(),
2178                                   sizeof(int16_t),
2179                                   frame_size,
2180                                   out_file_);
2181       ASSERT_EQ(frame_size, write_count);
2182 
2183       // Reset in case of downmixing.
2184       frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
2185       frame_count++;
2186 
2187 #if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2188       const int kStatsAggregationFrameNum = 100;  // 1 second.
2189       if (frame_count % kStatsAggregationFrameNum == 0) {
2190         // Get echo metrics.
2191         EchoCancellation::Metrics echo_metrics;
2192         EXPECT_EQ(apm_->kNoError,
2193                   apm_->echo_cancellation()->GetMetrics(&echo_metrics));
2194 
2195         // Get delay metrics.
2196         int median = 0;
2197         int std = 0;
2198         float fraction_poor_delays = 0;
2199         EXPECT_EQ(apm_->kNoError,
2200                   apm_->echo_cancellation()->GetDelayMetrics(
2201                       &median, &std, &fraction_poor_delays));
2202 
2203         // Get RMS.
2204         int rms_level = apm_->level_estimator()->RMS();
2205         EXPECT_LE(0, rms_level);
2206         EXPECT_GE(127, rms_level);
2207 
2208         if (!write_ref_data) {
2209           const audioproc::Test::EchoMetrics& reference =
2210               test->echo_metrics(stats_index);
2211           TestStats(echo_metrics.residual_echo_return_loss,
2212                     reference.residual_echo_return_loss());
2213           TestStats(echo_metrics.echo_return_loss,
2214                     reference.echo_return_loss());
2215           TestStats(echo_metrics.echo_return_loss_enhancement,
2216                     reference.echo_return_loss_enhancement());
2217           TestStats(echo_metrics.a_nlp,
2218                     reference.a_nlp());
2219           EXPECT_EQ(echo_metrics.divergent_filter_fraction,
2220                     reference.divergent_filter_fraction());
2221 
2222           const audioproc::Test::DelayMetrics& reference_delay =
2223               test->delay_metrics(stats_index);
2224           EXPECT_EQ(reference_delay.median(), median);
2225           EXPECT_EQ(reference_delay.std(), std);
2226           EXPECT_EQ(reference_delay.fraction_poor_delays(),
2227                     fraction_poor_delays);
2228 
2229           EXPECT_EQ(test->rms_level(stats_index), rms_level);
2230 
2231           ++stats_index;
2232         } else {
2233           audioproc::Test::EchoMetrics* message =
2234               test->add_echo_metrics();
2235           WriteStatsMessage(echo_metrics.residual_echo_return_loss,
2236                             message->mutable_residual_echo_return_loss());
2237           WriteStatsMessage(echo_metrics.echo_return_loss,
2238                             message->mutable_echo_return_loss());
2239           WriteStatsMessage(echo_metrics.echo_return_loss_enhancement,
2240                             message->mutable_echo_return_loss_enhancement());
2241           WriteStatsMessage(echo_metrics.a_nlp,
2242                             message->mutable_a_nlp());
2243           message->set_divergent_filter_fraction(
2244               echo_metrics.divergent_filter_fraction);
2245 
2246           audioproc::Test::DelayMetrics* message_delay =
2247               test->add_delay_metrics();
2248           message_delay->set_median(median);
2249           message_delay->set_std(std);
2250           message_delay->set_fraction_poor_delays(fraction_poor_delays);
2251 
2252           test->add_rms_level(rms_level);
2253         }
2254       }
2255 #endif  // defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE).
2256     }
2257     max_output_average /= frame_count;
2258     analog_level_average /= frame_count;
2259     ns_speech_prob_average /= frame_count;
2260 
2261     if (!write_ref_data) {
2262       const int kIntNear = 1;
2263       // When running the test on a N7 we get a {2, 6} difference of
2264       // |has_voice_count| and |max_output_average| is up to 18 higher.
2265       // All numbers being consistently higher on N7 compare to ref_data.
2266       // TODO(bjornv): If we start getting more of these offsets on Android we
2267       // should consider a different approach. Either using one slack for all,
2268       // or generate a separate android reference.
2269 #if defined(WEBRTC_ANDROID)
2270       const int kHasVoiceCountOffset = 3;
2271       const int kHasVoiceCountNear = 4;
2272       const int kMaxOutputAverageOffset = 9;
2273       const int kMaxOutputAverageNear = 9;
2274 #else
2275       const int kHasVoiceCountOffset = 0;
2276       const int kHasVoiceCountNear = kIntNear;
2277       const int kMaxOutputAverageOffset = 0;
2278       const int kMaxOutputAverageNear = kIntNear;
2279 #endif
2280       EXPECT_NEAR(test->has_echo_count(), has_echo_count, kIntNear);
2281       EXPECT_NEAR(test->has_voice_count(),
2282                   has_voice_count - kHasVoiceCountOffset,
2283                   kHasVoiceCountNear);
2284       EXPECT_NEAR(test->is_saturated_count(), is_saturated_count, kIntNear);
2285 
2286       EXPECT_NEAR(test->analog_level_average(), analog_level_average, kIntNear);
2287       EXPECT_NEAR(test->max_output_average(),
2288                   max_output_average - kMaxOutputAverageOffset,
2289                   kMaxOutputAverageNear);
2290 #if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2291       const double kFloatNear = 0.0005;
2292       EXPECT_NEAR(test->ns_speech_probability_average(),
2293                   ns_speech_prob_average,
2294                   kFloatNear);
2295 #endif
2296     } else {
2297       test->set_has_echo_count(has_echo_count);
2298       test->set_has_voice_count(has_voice_count);
2299       test->set_is_saturated_count(is_saturated_count);
2300 
2301       test->set_analog_level_average(analog_level_average);
2302       test->set_max_output_average(max_output_average);
2303 
2304 #if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2305       EXPECT_LE(0.0f, ns_speech_prob_average);
2306       EXPECT_GE(1.0f, ns_speech_prob_average);
2307       test->set_ns_speech_probability_average(ns_speech_prob_average);
2308 #endif
2309     }
2310 
2311     rewind(far_file_);
2312     rewind(near_file_);
2313   }
2314 
2315   if (write_ref_data) {
2316     OpenFileAndWriteMessage(ref_filename_, ref_data);
2317   }
2318 }
2319 
TEST_F(ApmTest,NoErrorsWithKeyboardChannel)2320 TEST_F(ApmTest, NoErrorsWithKeyboardChannel) {
2321   struct ChannelFormat {
2322     AudioProcessing::ChannelLayout in_layout;
2323     AudioProcessing::ChannelLayout out_layout;
2324   };
2325   ChannelFormat cf[] = {
2326     {AudioProcessing::kMonoAndKeyboard, AudioProcessing::kMono},
2327     {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kMono},
2328     {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kStereo},
2329   };
2330 
2331   std::unique_ptr<AudioProcessing> ap(AudioProcessing::Create());
2332   // Enable one component just to ensure some processing takes place.
2333   ap->noise_suppression()->Enable(true);
2334   for (size_t i = 0; i < arraysize(cf); ++i) {
2335     const int in_rate = 44100;
2336     const int out_rate = 48000;
2337     ChannelBuffer<float> in_cb(SamplesFromRate(in_rate),
2338                                TotalChannelsFromLayout(cf[i].in_layout));
2339     ChannelBuffer<float> out_cb(SamplesFromRate(out_rate),
2340                                 ChannelsFromLayout(cf[i].out_layout));
2341 
2342     // Run over a few chunks.
2343     for (int j = 0; j < 10; ++j) {
2344       EXPECT_NOERR(ap->ProcessStream(
2345           in_cb.channels(),
2346           in_cb.num_frames(),
2347           in_rate,
2348           cf[i].in_layout,
2349           out_rate,
2350           cf[i].out_layout,
2351           out_cb.channels()));
2352     }
2353   }
2354 }
2355 
2356 // Compares the reference and test arrays over a region around the expected
2357 // delay. Finds the highest SNR in that region and adds the variance and squared
2358 // error results to the supplied accumulators.
UpdateBestSNR(const float * ref,const float * test,size_t length,int expected_delay,double * variance_acc,double * sq_error_acc)2359 void UpdateBestSNR(const float* ref,
2360                    const float* test,
2361                    size_t length,
2362                    int expected_delay,
2363                    double* variance_acc,
2364                    double* sq_error_acc) {
2365   double best_snr = std::numeric_limits<double>::min();
2366   double best_variance = 0;
2367   double best_sq_error = 0;
2368   // Search over a region of eight samples around the expected delay.
2369   for (int delay = std::max(expected_delay - 4, 0); delay <= expected_delay + 4;
2370        ++delay) {
2371     double sq_error = 0;
2372     double variance = 0;
2373     for (size_t i = 0; i < length - delay; ++i) {
2374       double error = test[i + delay] - ref[i];
2375       sq_error += error * error;
2376       variance += ref[i] * ref[i];
2377     }
2378 
2379     if (sq_error == 0) {
2380       *variance_acc += variance;
2381       return;
2382     }
2383     double snr = variance / sq_error;
2384     if (snr > best_snr) {
2385       best_snr = snr;
2386       best_variance = variance;
2387       best_sq_error = sq_error;
2388     }
2389   }
2390 
2391   *variance_acc += best_variance;
2392   *sq_error_acc += best_sq_error;
2393 }
2394 
2395 // Used to test a multitude of sample rate and channel combinations. It works
2396 // by first producing a set of reference files (in SetUpTestCase) that are
2397 // assumed to be correct, as the used parameters are verified by other tests
2398 // in this collection. Primarily the reference files are all produced at
2399 // "native" rates which do not involve any resampling.
2400 
2401 // Each test pass produces an output file with a particular format. The output
2402 // is matched against the reference file closest to its internal processing
2403 // format. If necessary the output is resampled back to its process format.
2404 // Due to the resampling distortion, we don't expect identical results, but
2405 // enforce SNR thresholds which vary depending on the format. 0 is a special
2406 // case SNR which corresponds to inf, or zero error.
2407 typedef std::tuple<int, int, int, int, double, double> AudioProcessingTestData;
2408 class AudioProcessingTest
2409     : public testing::TestWithParam<AudioProcessingTestData> {
2410  public:
AudioProcessingTest()2411   AudioProcessingTest()
2412       : input_rate_(std::get<0>(GetParam())),
2413         output_rate_(std::get<1>(GetParam())),
2414         reverse_input_rate_(std::get<2>(GetParam())),
2415         reverse_output_rate_(std::get<3>(GetParam())),
2416         expected_snr_(std::get<4>(GetParam())),
2417         expected_reverse_snr_(std::get<5>(GetParam())) {}
2418 
~AudioProcessingTest()2419   virtual ~AudioProcessingTest() {}
2420 
SetUpTestCase()2421   static void SetUpTestCase() {
2422     // Create all needed output reference files.
2423     const int kNativeRates[] = {8000, 16000, 32000, 48000};
2424     const size_t kNumChannels[] = {1, 2};
2425     for (size_t i = 0; i < arraysize(kNativeRates); ++i) {
2426       for (size_t j = 0; j < arraysize(kNumChannels); ++j) {
2427         for (size_t k = 0; k < arraysize(kNumChannels); ++k) {
2428           // The reference files always have matching input and output channels.
2429           ProcessFormat(kNativeRates[i], kNativeRates[i], kNativeRates[i],
2430                         kNativeRates[i], kNumChannels[j], kNumChannels[j],
2431                         kNumChannels[k], kNumChannels[k], "ref");
2432         }
2433       }
2434     }
2435   }
2436 
TearDown()2437   void TearDown() {
2438     // Remove "out" files after each test.
2439     ClearTempOutFiles();
2440   }
2441 
TearDownTestCase()2442   static void TearDownTestCase() {
2443     ClearTempFiles();
2444   }
2445 
2446   // Runs a process pass on files with the given parameters and dumps the output
2447   // to a file specified with |output_file_prefix|. Both forward and reverse
2448   // output streams are dumped.
ProcessFormat(int input_rate,int output_rate,int reverse_input_rate,int reverse_output_rate,size_t num_input_channels,size_t num_output_channels,size_t num_reverse_input_channels,size_t num_reverse_output_channels,const std::string & output_file_prefix)2449   static void ProcessFormat(int input_rate,
2450                             int output_rate,
2451                             int reverse_input_rate,
2452                             int reverse_output_rate,
2453                             size_t num_input_channels,
2454                             size_t num_output_channels,
2455                             size_t num_reverse_input_channels,
2456                             size_t num_reverse_output_channels,
2457                             const std::string& output_file_prefix) {
2458     Config config;
2459     config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
2460     std::unique_ptr<AudioProcessing> ap(AudioProcessing::Create(config));
2461     EnableAllAPComponents(ap.get());
2462 
2463     ProcessingConfig processing_config = {
2464         {{input_rate, num_input_channels},
2465          {output_rate, num_output_channels},
2466          {reverse_input_rate, num_reverse_input_channels},
2467          {reverse_output_rate, num_reverse_output_channels}}};
2468     ap->Initialize(processing_config);
2469 
2470     FILE* far_file =
2471         fopen(ResourceFilePath("far", reverse_input_rate).c_str(), "rb");
2472     FILE* near_file = fopen(ResourceFilePath("near", input_rate).c_str(), "rb");
2473     FILE* out_file =
2474         fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2475                              reverse_input_rate, reverse_output_rate,
2476                              num_input_channels, num_output_channels,
2477                              num_reverse_input_channels,
2478                              num_reverse_output_channels, kForward).c_str(),
2479               "wb");
2480     FILE* rev_out_file =
2481         fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2482                              reverse_input_rate, reverse_output_rate,
2483                              num_input_channels, num_output_channels,
2484                              num_reverse_input_channels,
2485                              num_reverse_output_channels, kReverse).c_str(),
2486               "wb");
2487     ASSERT_TRUE(far_file != NULL);
2488     ASSERT_TRUE(near_file != NULL);
2489     ASSERT_TRUE(out_file != NULL);
2490     ASSERT_TRUE(rev_out_file != NULL);
2491 
2492     ChannelBuffer<float> fwd_cb(SamplesFromRate(input_rate),
2493                                 num_input_channels);
2494     ChannelBuffer<float> rev_cb(SamplesFromRate(reverse_input_rate),
2495                                 num_reverse_input_channels);
2496     ChannelBuffer<float> out_cb(SamplesFromRate(output_rate),
2497                                 num_output_channels);
2498     ChannelBuffer<float> rev_out_cb(SamplesFromRate(reverse_output_rate),
2499                                     num_reverse_output_channels);
2500 
2501     // Temporary buffers.
2502     const int max_length =
2503         2 * std::max(std::max(out_cb.num_frames(), rev_out_cb.num_frames()),
2504                      std::max(fwd_cb.num_frames(), rev_cb.num_frames()));
2505     std::unique_ptr<float[]> float_data(new float[max_length]);
2506     std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
2507 
2508     int analog_level = 127;
2509     while (ReadChunk(far_file, int_data.get(), float_data.get(), &rev_cb) &&
2510            ReadChunk(near_file, int_data.get(), float_data.get(), &fwd_cb)) {
2511       EXPECT_NOERR(ap->ProcessReverseStream(
2512           rev_cb.channels(), processing_config.reverse_input_stream(),
2513           processing_config.reverse_output_stream(), rev_out_cb.channels()));
2514 
2515       EXPECT_NOERR(ap->set_stream_delay_ms(0));
2516       ap->echo_cancellation()->set_stream_drift_samples(0);
2517       EXPECT_NOERR(ap->gain_control()->set_stream_analog_level(analog_level));
2518 
2519       EXPECT_NOERR(ap->ProcessStream(
2520           fwd_cb.channels(),
2521           fwd_cb.num_frames(),
2522           input_rate,
2523           LayoutFromChannels(num_input_channels),
2524           output_rate,
2525           LayoutFromChannels(num_output_channels),
2526           out_cb.channels()));
2527 
2528       // Dump forward output to file.
2529       Interleave(out_cb.channels(), out_cb.num_frames(), out_cb.num_channels(),
2530                  float_data.get());
2531       size_t out_length = out_cb.num_channels() * out_cb.num_frames();
2532 
2533       ASSERT_EQ(out_length,
2534                 fwrite(float_data.get(), sizeof(float_data[0]),
2535                        out_length, out_file));
2536 
2537       // Dump reverse output to file.
2538       Interleave(rev_out_cb.channels(), rev_out_cb.num_frames(),
2539                  rev_out_cb.num_channels(), float_data.get());
2540       size_t rev_out_length =
2541           rev_out_cb.num_channels() * rev_out_cb.num_frames();
2542 
2543       ASSERT_EQ(rev_out_length,
2544                 fwrite(float_data.get(), sizeof(float_data[0]), rev_out_length,
2545                        rev_out_file));
2546 
2547       analog_level = ap->gain_control()->stream_analog_level();
2548     }
2549     fclose(far_file);
2550     fclose(near_file);
2551     fclose(out_file);
2552     fclose(rev_out_file);
2553   }
2554 
2555  protected:
2556   int input_rate_;
2557   int output_rate_;
2558   int reverse_input_rate_;
2559   int reverse_output_rate_;
2560   double expected_snr_;
2561   double expected_reverse_snr_;
2562 };
2563 
TEST_P(AudioProcessingTest,Formats)2564 TEST_P(AudioProcessingTest, Formats) {
2565   struct ChannelFormat {
2566     int num_input;
2567     int num_output;
2568     int num_reverse_input;
2569     int num_reverse_output;
2570   };
2571   ChannelFormat cf[] = {
2572       {1, 1, 1, 1},
2573       {1, 1, 2, 1},
2574       {2, 1, 1, 1},
2575       {2, 1, 2, 1},
2576       {2, 2, 1, 1},
2577       {2, 2, 2, 2},
2578   };
2579 
2580   for (size_t i = 0; i < arraysize(cf); ++i) {
2581     ProcessFormat(input_rate_, output_rate_, reverse_input_rate_,
2582                   reverse_output_rate_, cf[i].num_input, cf[i].num_output,
2583                   cf[i].num_reverse_input, cf[i].num_reverse_output, "out");
2584 
2585     // Verify output for both directions.
2586     std::vector<StreamDirection> stream_directions;
2587     stream_directions.push_back(kForward);
2588     stream_directions.push_back(kReverse);
2589     for (StreamDirection file_direction : stream_directions) {
2590       const int in_rate = file_direction ? reverse_input_rate_ : input_rate_;
2591       const int out_rate = file_direction ? reverse_output_rate_ : output_rate_;
2592       const int out_num =
2593           file_direction ? cf[i].num_reverse_output : cf[i].num_output;
2594       const double expected_snr =
2595           file_direction ? expected_reverse_snr_ : expected_snr_;
2596 
2597       const int min_ref_rate = std::min(in_rate, out_rate);
2598       int ref_rate;
2599 
2600       if (min_ref_rate > 32000) {
2601         ref_rate = 48000;
2602       } else if (min_ref_rate > 16000) {
2603         ref_rate = 32000;
2604       } else if (min_ref_rate > 8000) {
2605         ref_rate = 16000;
2606       } else {
2607         ref_rate = 8000;
2608       }
2609 #ifdef WEBRTC_ARCH_ARM_FAMILY
2610       if (file_direction == kForward) {
2611         ref_rate = std::min(ref_rate, 32000);
2612       }
2613 #endif
2614       FILE* out_file = fopen(
2615           OutputFilePath("out", input_rate_, output_rate_, reverse_input_rate_,
2616                          reverse_output_rate_, cf[i].num_input,
2617                          cf[i].num_output, cf[i].num_reverse_input,
2618                          cf[i].num_reverse_output, file_direction).c_str(),
2619           "rb");
2620       // The reference files always have matching input and output channels.
2621       FILE* ref_file = fopen(
2622           OutputFilePath("ref", ref_rate, ref_rate, ref_rate, ref_rate,
2623                          cf[i].num_output, cf[i].num_output,
2624                          cf[i].num_reverse_output, cf[i].num_reverse_output,
2625                          file_direction).c_str(),
2626           "rb");
2627       ASSERT_TRUE(out_file != NULL);
2628       ASSERT_TRUE(ref_file != NULL);
2629 
2630       const size_t ref_length = SamplesFromRate(ref_rate) * out_num;
2631       const size_t out_length = SamplesFromRate(out_rate) * out_num;
2632       // Data from the reference file.
2633       std::unique_ptr<float[]> ref_data(new float[ref_length]);
2634       // Data from the output file.
2635       std::unique_ptr<float[]> out_data(new float[out_length]);
2636       // Data from the resampled output, in case the reference and output rates
2637       // don't match.
2638       std::unique_ptr<float[]> cmp_data(new float[ref_length]);
2639 
2640       PushResampler<float> resampler;
2641       resampler.InitializeIfNeeded(out_rate, ref_rate, out_num);
2642 
2643       // Compute the resampling delay of the output relative to the reference,
2644       // to find the region over which we should search for the best SNR.
2645       float expected_delay_sec = 0;
2646       if (in_rate != ref_rate) {
2647         // Input resampling delay.
2648         expected_delay_sec +=
2649             PushSincResampler::AlgorithmicDelaySeconds(in_rate);
2650       }
2651       if (out_rate != ref_rate) {
2652         // Output resampling delay.
2653         expected_delay_sec +=
2654             PushSincResampler::AlgorithmicDelaySeconds(ref_rate);
2655         // Delay of converting the output back to its processing rate for
2656         // testing.
2657         expected_delay_sec +=
2658             PushSincResampler::AlgorithmicDelaySeconds(out_rate);
2659       }
2660       int expected_delay =
2661           floor(expected_delay_sec * ref_rate + 0.5f) * out_num;
2662 
2663       double variance = 0;
2664       double sq_error = 0;
2665       while (fread(out_data.get(), sizeof(out_data[0]), out_length, out_file) &&
2666              fread(ref_data.get(), sizeof(ref_data[0]), ref_length, ref_file)) {
2667         float* out_ptr = out_data.get();
2668         if (out_rate != ref_rate) {
2669           // Resample the output back to its internal processing rate if
2670           // necssary.
2671           ASSERT_EQ(ref_length,
2672                     static_cast<size_t>(resampler.Resample(
2673                         out_ptr, out_length, cmp_data.get(), ref_length)));
2674           out_ptr = cmp_data.get();
2675         }
2676 
2677         // Update the |sq_error| and |variance| accumulators with the highest
2678         // SNR of reference vs output.
2679         UpdateBestSNR(ref_data.get(), out_ptr, ref_length, expected_delay,
2680                       &variance, &sq_error);
2681       }
2682 
2683       std::cout << "(" << input_rate_ << ", " << output_rate_ << ", "
2684                 << reverse_input_rate_ << ", " << reverse_output_rate_ << ", "
2685                 << cf[i].num_input << ", " << cf[i].num_output << ", "
2686                 << cf[i].num_reverse_input << ", " << cf[i].num_reverse_output
2687                 << ", " << file_direction << "): ";
2688       if (sq_error > 0) {
2689         double snr = 10 * log10(variance / sq_error);
2690         EXPECT_GE(snr, expected_snr);
2691         EXPECT_NE(0, expected_snr);
2692         std::cout << "SNR=" << snr << " dB" << std::endl;
2693       } else {
2694         std::cout << "SNR=inf dB" << std::endl;
2695       }
2696 
2697       fclose(out_file);
2698       fclose(ref_file);
2699     }
2700   }
2701 }
2702 
2703 #if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2704 INSTANTIATE_TEST_CASE_P(
2705     CommonFormats,
2706     AudioProcessingTest,
2707     testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 0, 0),
2708                     std::make_tuple(48000, 48000, 32000, 48000, 40, 30),
2709                     std::make_tuple(48000, 48000, 16000, 48000, 40, 20),
2710                     std::make_tuple(48000, 44100, 48000, 44100, 20, 20),
2711                     std::make_tuple(48000, 44100, 32000, 44100, 20, 15),
2712                     std::make_tuple(48000, 44100, 16000, 44100, 20, 15),
2713                     std::make_tuple(48000, 32000, 48000, 32000, 30, 35),
2714                     std::make_tuple(48000, 32000, 32000, 32000, 30, 0),
2715                     std::make_tuple(48000, 32000, 16000, 32000, 30, 20),
2716                     std::make_tuple(48000, 16000, 48000, 16000, 25, 20),
2717                     std::make_tuple(48000, 16000, 32000, 16000, 25, 20),
2718                     std::make_tuple(48000, 16000, 16000, 16000, 25, 0),
2719 
2720                     std::make_tuple(44100, 48000, 48000, 48000, 30, 0),
2721                     std::make_tuple(44100, 48000, 32000, 48000, 30, 30),
2722                     std::make_tuple(44100, 48000, 16000, 48000, 30, 20),
2723                     std::make_tuple(44100, 44100, 48000, 44100, 20, 20),
2724                     std::make_tuple(44100, 44100, 32000, 44100, 20, 15),
2725                     std::make_tuple(44100, 44100, 16000, 44100, 20, 15),
2726                     std::make_tuple(44100, 32000, 48000, 32000, 30, 35),
2727                     std::make_tuple(44100, 32000, 32000, 32000, 30, 0),
2728                     std::make_tuple(44100, 32000, 16000, 32000, 30, 20),
2729                     std::make_tuple(44100, 16000, 48000, 16000, 25, 20),
2730                     std::make_tuple(44100, 16000, 32000, 16000, 25, 20),
2731                     std::make_tuple(44100, 16000, 16000, 16000, 25, 0),
2732 
2733                     std::make_tuple(32000, 48000, 48000, 48000, 30, 0),
2734                     std::make_tuple(32000, 48000, 32000, 48000, 35, 30),
2735                     std::make_tuple(32000, 48000, 16000, 48000, 30, 20),
2736                     std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2737                     std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2738                     std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2739                     std::make_tuple(32000, 32000, 48000, 32000, 40, 35),
2740                     std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2741                     std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2742                     std::make_tuple(32000, 16000, 48000, 16000, 25, 20),
2743                     std::make_tuple(32000, 16000, 32000, 16000, 25, 20),
2744                     std::make_tuple(32000, 16000, 16000, 16000, 25, 0),
2745 
2746                     std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2747                     std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2748                     std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2749                     std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2750                     std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2751                     std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2752                     std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2753                     std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2754                     std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2755                     std::make_tuple(16000, 16000, 48000, 16000, 40, 20),
2756                     std::make_tuple(16000, 16000, 32000, 16000, 40, 20),
2757                     std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
2758 
2759 #elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
2760 INSTANTIATE_TEST_CASE_P(
2761     CommonFormats,
2762     AudioProcessingTest,
2763     testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 20, 0),
2764                     std::make_tuple(48000, 48000, 32000, 48000, 20, 30),
2765                     std::make_tuple(48000, 48000, 16000, 48000, 20, 20),
2766                     std::make_tuple(48000, 44100, 48000, 44100, 15, 20),
2767                     std::make_tuple(48000, 44100, 32000, 44100, 15, 15),
2768                     std::make_tuple(48000, 44100, 16000, 44100, 15, 15),
2769                     std::make_tuple(48000, 32000, 48000, 32000, 20, 35),
2770                     std::make_tuple(48000, 32000, 32000, 32000, 20, 0),
2771                     std::make_tuple(48000, 32000, 16000, 32000, 20, 20),
2772                     std::make_tuple(48000, 16000, 48000, 16000, 20, 20),
2773                     std::make_tuple(48000, 16000, 32000, 16000, 20, 20),
2774                     std::make_tuple(48000, 16000, 16000, 16000, 20, 0),
2775 
2776                     std::make_tuple(44100, 48000, 48000, 48000, 15, 0),
2777                     std::make_tuple(44100, 48000, 32000, 48000, 15, 30),
2778                     std::make_tuple(44100, 48000, 16000, 48000, 15, 20),
2779                     std::make_tuple(44100, 44100, 48000, 44100, 15, 20),
2780                     std::make_tuple(44100, 44100, 32000, 44100, 15, 15),
2781                     std::make_tuple(44100, 44100, 16000, 44100, 15, 15),
2782                     std::make_tuple(44100, 32000, 48000, 32000, 20, 35),
2783                     std::make_tuple(44100, 32000, 32000, 32000, 20, 0),
2784                     std::make_tuple(44100, 32000, 16000, 32000, 20, 20),
2785                     std::make_tuple(44100, 16000, 48000, 16000, 20, 20),
2786                     std::make_tuple(44100, 16000, 32000, 16000, 20, 20),
2787                     std::make_tuple(44100, 16000, 16000, 16000, 20, 0),
2788 
2789                     std::make_tuple(32000, 48000, 48000, 48000, 35, 0),
2790                     std::make_tuple(32000, 48000, 32000, 48000, 65, 30),
2791                     std::make_tuple(32000, 48000, 16000, 48000, 40, 20),
2792                     std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2793                     std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2794                     std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2795                     std::make_tuple(32000, 32000, 48000, 32000, 35, 35),
2796                     std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2797                     std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2798                     std::make_tuple(32000, 16000, 48000, 16000, 20, 20),
2799                     std::make_tuple(32000, 16000, 32000, 16000, 20, 20),
2800                     std::make_tuple(32000, 16000, 16000, 16000, 20, 0),
2801 
2802                     std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2803                     std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2804                     std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2805                     std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2806                     std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2807                     std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2808                     std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2809                     std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2810                     std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2811                     std::make_tuple(16000, 16000, 48000, 16000, 35, 20),
2812                     std::make_tuple(16000, 16000, 32000, 16000, 35, 20),
2813                     std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
2814 #endif
2815 
2816 }  // namespace
2817 
TEST(ApmConfiguration,DefaultBehavior)2818 TEST(ApmConfiguration, DefaultBehavior) {
2819   // Verify that the level controller is default off, it can be activated using
2820   // the config, and that the default initial level is maintained after the
2821   // config has been applied.
2822   std::unique_ptr<AudioProcessingImpl> apm(
2823       new rtc::RefCountedObject<AudioProcessingImpl>(webrtc::Config()));
2824   AudioProcessing::Config config;
2825   EXPECT_FALSE(apm->config_.level_controller.enabled);
2826   // TODO(peah): Add test for the existence of the level controller object once
2827   // that is created only when that is specified in the config.
2828   // TODO(peah): Remove the testing for
2829   // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2830   // is instead used to activate the level controller.
2831   EXPECT_FALSE(apm->capture_nonlocked_.level_controller_enabled);
2832   EXPECT_NEAR(kTargetLcPeakLeveldBFS,
2833               apm->config_.level_controller.initial_peak_level_dbfs,
2834               std::numeric_limits<float>::epsilon());
2835   config.level_controller.enabled = true;
2836   apm->ApplyConfig(config);
2837   EXPECT_TRUE(apm->config_.level_controller.enabled);
2838   // TODO(peah): Add test for the existence of the level controller object once
2839   // that is created only when the that is specified in the config.
2840   // TODO(peah): Remove the testing for
2841   // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2842   // is instead used to activate the level controller.
2843   EXPECT_TRUE(apm->capture_nonlocked_.level_controller_enabled);
2844   EXPECT_NEAR(kTargetLcPeakLeveldBFS,
2845               apm->config_.level_controller.initial_peak_level_dbfs,
2846               std::numeric_limits<float>::epsilon());
2847 }
2848 
TEST(ApmConfiguration,ValidConfigBehavior)2849 TEST(ApmConfiguration, ValidConfigBehavior) {
2850   // Verify that the initial level can be specified and is retained after the
2851   // config has been applied.
2852   std::unique_ptr<AudioProcessingImpl> apm(
2853       new rtc::RefCountedObject<AudioProcessingImpl>(webrtc::Config()));
2854   AudioProcessing::Config config;
2855   config.level_controller.initial_peak_level_dbfs = -50.f;
2856   apm->ApplyConfig(config);
2857   EXPECT_FALSE(apm->config_.level_controller.enabled);
2858   // TODO(peah): Add test for the existence of the level controller object once
2859   // that is created only when the that is specified in the config.
2860   // TODO(peah): Remove the testing for
2861   // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2862   // is instead used to activate the level controller.
2863   EXPECT_FALSE(apm->capture_nonlocked_.level_controller_enabled);
2864   EXPECT_NEAR(-50.f, apm->config_.level_controller.initial_peak_level_dbfs,
2865               std::numeric_limits<float>::epsilon());
2866 }
2867 
TEST(ApmConfiguration,InValidConfigBehavior)2868 TEST(ApmConfiguration, InValidConfigBehavior) {
2869   // Verify that the config is properly reset when nonproper values are applied
2870   // for the initial level.
2871 
2872   // Verify that the config is properly reset when the specified initial peak
2873   // level is too low.
2874   std::unique_ptr<AudioProcessingImpl> apm(
2875       new rtc::RefCountedObject<AudioProcessingImpl>(webrtc::Config()));
2876   AudioProcessing::Config config;
2877   config.level_controller.enabled = true;
2878   config.level_controller.initial_peak_level_dbfs = -101.f;
2879   apm->ApplyConfig(config);
2880   EXPECT_FALSE(apm->config_.level_controller.enabled);
2881   // TODO(peah): Add test for the existence of the level controller object once
2882   // that is created only when the that is specified in the config.
2883   // TODO(peah): Remove the testing for
2884   // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2885   // is instead used to activate the level controller.
2886   EXPECT_FALSE(apm->capture_nonlocked_.level_controller_enabled);
2887   EXPECT_NEAR(kTargetLcPeakLeveldBFS,
2888               apm->config_.level_controller.initial_peak_level_dbfs,
2889               std::numeric_limits<float>::epsilon());
2890 
2891   // Verify that the config is properly reset when the specified initial peak
2892   // level is too high.
2893   apm.reset(new rtc::RefCountedObject<AudioProcessingImpl>(webrtc::Config()));
2894   config = AudioProcessing::Config();
2895   config.level_controller.enabled = true;
2896   config.level_controller.initial_peak_level_dbfs = 1.f;
2897   apm->ApplyConfig(config);
2898   EXPECT_FALSE(apm->config_.level_controller.enabled);
2899   // TODO(peah): Add test for the existence of the level controller object once
2900   // that is created only when that is specified in the config.
2901   // TODO(peah): Remove the testing for
2902   // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2903   // is instead used to activate the level controller.
2904   EXPECT_FALSE(apm->capture_nonlocked_.level_controller_enabled);
2905   EXPECT_NEAR(kTargetLcPeakLeveldBFS,
2906               apm->config_.level_controller.initial_peak_level_dbfs,
2907               std::numeric_limits<float>::epsilon());
2908 }
2909 
TEST(ApmConfiguration,EnablePostProcessing)2910 TEST(ApmConfiguration, EnablePostProcessing) {
2911   // Verify that apm uses a capture post processing module if one is provided.
2912   webrtc::Config webrtc_config;
2913   auto mock_post_processor_ptr =
2914       new testing::NiceMock<test::MockPostProcessing>();
2915   auto mock_post_processor =
2916       std::unique_ptr<PostProcessing>(mock_post_processor_ptr);
2917   rtc::scoped_refptr<AudioProcessing> apm = AudioProcessing::Create(
2918       webrtc_config, std::move(mock_post_processor), nullptr, nullptr);
2919 
2920   AudioFrame audio;
2921   audio.num_channels_ = 1;
2922   SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2923 
2924   EXPECT_CALL(*mock_post_processor_ptr, Process(testing::_)).Times(1);
2925   apm->ProcessStream(&audio);
2926 }
2927 
2928 class MyEchoControlFactory : public EchoControlFactory {
2929  public:
Create(int sample_rate_hz)2930   std::unique_ptr<EchoControl> Create(int sample_rate_hz) {
2931     auto ec = new test::MockEchoControl();
2932     EXPECT_CALL(*ec, AnalyzeRender(testing::_)).Times(1);
2933     EXPECT_CALL(*ec, AnalyzeCapture(testing::_)).Times(2);
2934     EXPECT_CALL(*ec, ProcessCapture(testing::_, testing::_)).Times(2);
2935     return std::unique_ptr<EchoControl>(ec);
2936   }
2937 };
2938 
TEST(ApmConfiguration,EchoControlInjection)2939 TEST(ApmConfiguration, EchoControlInjection) {
2940   // Verify that apm uses an injected echo controller if one is provided.
2941   webrtc::Config webrtc_config;
2942   std::unique_ptr<EchoControlFactory> echo_control_factory(
2943       new MyEchoControlFactory());
2944 
2945   rtc::scoped_refptr<AudioProcessing> apm = AudioProcessing::Create(
2946       webrtc_config, nullptr, std::move(echo_control_factory), nullptr);
2947 
2948   AudioFrame audio;
2949   audio.num_channels_ = 1;
2950   SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2951   apm->ProcessStream(&audio);
2952   apm->ProcessReverseStream(&audio);
2953   apm->ProcessStream(&audio);
2954 }
2955 
CreateApm(bool use_AEC2)2956 std::unique_ptr<AudioProcessing> CreateApm(bool use_AEC2) {
2957   Config old_config;
2958   if (use_AEC2) {
2959     old_config.Set<ExtendedFilter>(new ExtendedFilter(true));
2960     old_config.Set<DelayAgnostic>(new DelayAgnostic(true));
2961   }
2962   std::unique_ptr<AudioProcessing> apm(AudioProcessing::Create(old_config));
2963   if (!apm) {
2964     return apm;
2965   }
2966 
2967   ProcessingConfig processing_config = {
2968       {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2969 
2970   if (apm->Initialize(processing_config) != 0) {
2971     return nullptr;
2972   }
2973 
2974   // Disable all components except for an AEC and the residual echo detector.
2975   AudioProcessing::Config config;
2976   config.residual_echo_detector.enabled = true;
2977   config.echo_canceller3.enabled = false;
2978   config.high_pass_filter.enabled = false;
2979   config.gain_controller2.enabled = false;
2980   config.level_controller.enabled = false;
2981   apm->ApplyConfig(config);
2982   EXPECT_EQ(apm->gain_control()->Enable(false), 0);
2983   EXPECT_EQ(apm->level_estimator()->Enable(false), 0);
2984   EXPECT_EQ(apm->noise_suppression()->Enable(false), 0);
2985   EXPECT_EQ(apm->voice_detection()->Enable(false), 0);
2986 
2987   if (use_AEC2) {
2988     EXPECT_EQ(apm->echo_control_mobile()->Enable(false), 0);
2989     EXPECT_EQ(apm->echo_cancellation()->enable_metrics(true), 0);
2990     EXPECT_EQ(apm->echo_cancellation()->enable_delay_logging(true), 0);
2991     EXPECT_EQ(apm->echo_cancellation()->Enable(true), 0);
2992   } else {
2993     EXPECT_EQ(apm->echo_cancellation()->Enable(false), 0);
2994     EXPECT_EQ(apm->echo_control_mobile()->Enable(true), 0);
2995   }
2996   return apm;
2997 }
2998 
2999 #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) || defined(WEBRTC_MAC)
3000 #define MAYBE_ApmStatistics DISABLED_ApmStatistics
3001 #else
3002 #define MAYBE_ApmStatistics ApmStatistics
3003 #endif
3004 
TEST(MAYBE_ApmStatistics,AEC2EnabledTest)3005 TEST(MAYBE_ApmStatistics, AEC2EnabledTest) {
3006   // Set up APM with AEC2 and process some audio.
3007   std::unique_ptr<AudioProcessing> apm = CreateApm(true);
3008   ASSERT_TRUE(apm);
3009 
3010   // Set up an audioframe.
3011   AudioFrame frame;
3012   frame.num_channels_ = 1;
3013   SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
3014 
3015   // Fill the audio frame with a sawtooth pattern.
3016   int16_t* ptr = frame.mutable_data();
3017   for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
3018     ptr[i] = 10000 * ((i % 3) - 1);
3019   }
3020 
3021   // Do some processing.
3022   for (int i = 0; i < 200; i++) {
3023     EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
3024     EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
3025     EXPECT_EQ(apm->ProcessStream(&frame), 0);
3026   }
3027 
3028   // Test statistics interface.
3029   AudioProcessingStats stats = apm->GetStatistics(true);
3030   // We expect all statistics to be set and have a sensible value.
3031   ASSERT_TRUE(stats.residual_echo_likelihood);
3032   EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
3033   EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
3034   ASSERT_TRUE(stats.residual_echo_likelihood_recent_max);
3035   EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
3036   EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
3037   ASSERT_TRUE(stats.echo_return_loss);
3038   EXPECT_NE(*stats.echo_return_loss, -100.0);
3039   ASSERT_TRUE(stats.echo_return_loss_enhancement);
3040   EXPECT_NE(*stats.echo_return_loss_enhancement, -100.0);
3041   ASSERT_TRUE(stats.divergent_filter_fraction);
3042   EXPECT_NE(*stats.divergent_filter_fraction, -1.0);
3043   ASSERT_TRUE(stats.delay_standard_deviation_ms);
3044   EXPECT_GE(*stats.delay_standard_deviation_ms, 0);
3045   // We don't check stats.delay_median_ms since it takes too long to settle to a
3046   // value. At least 20 seconds of data need to be processed before it will get
3047   // a value, which would make this test take too much time.
3048 
3049   // If there are no receive streams, we expect the stats not to be set. The
3050   // 'false' argument signals to APM that no receive streams are currently
3051   // active. In that situation the statistics would get stuck at their last
3052   // calculated value (AEC and echo detection need at least one stream in each
3053   // direction), so to avoid that, they should not be set by APM.
3054   stats = apm->GetStatistics(false);
3055   EXPECT_FALSE(stats.residual_echo_likelihood);
3056   EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
3057   EXPECT_FALSE(stats.echo_return_loss);
3058   EXPECT_FALSE(stats.echo_return_loss_enhancement);
3059   EXPECT_FALSE(stats.divergent_filter_fraction);
3060   EXPECT_FALSE(stats.delay_median_ms);
3061   EXPECT_FALSE(stats.delay_standard_deviation_ms);
3062 }
3063 
TEST(MAYBE_ApmStatistics,AECMEnabledTest)3064 TEST(MAYBE_ApmStatistics, AECMEnabledTest) {
3065   // Set up APM with AECM and process some audio.
3066   std::unique_ptr<AudioProcessing> apm = CreateApm(false);
3067   ASSERT_TRUE(apm);
3068 
3069   // Set up an audioframe.
3070   AudioFrame frame;
3071   frame.num_channels_ = 1;
3072   SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
3073 
3074   // Fill the audio frame with a sawtooth pattern.
3075   int16_t* ptr = frame.mutable_data();
3076   for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
3077     ptr[i] = 10000 * ((i % 3) - 1);
3078   }
3079 
3080   // Do some processing.
3081   for (int i = 0; i < 200; i++) {
3082     EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
3083     EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
3084     EXPECT_EQ(apm->ProcessStream(&frame), 0);
3085   }
3086 
3087   // Test statistics interface.
3088   AudioProcessingStats stats = apm->GetStatistics(true);
3089   // We expect only the residual echo detector statistics to be set and have a
3090   // sensible value.
3091   EXPECT_TRUE(stats.residual_echo_likelihood);
3092   if (stats.residual_echo_likelihood) {
3093     EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
3094     EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
3095   }
3096   EXPECT_TRUE(stats.residual_echo_likelihood_recent_max);
3097   if (stats.residual_echo_likelihood_recent_max) {
3098     EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
3099     EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
3100   }
3101   EXPECT_FALSE(stats.echo_return_loss);
3102   EXPECT_FALSE(stats.echo_return_loss_enhancement);
3103   EXPECT_FALSE(stats.divergent_filter_fraction);
3104   EXPECT_FALSE(stats.delay_median_ms);
3105   EXPECT_FALSE(stats.delay_standard_deviation_ms);
3106 
3107   // If there are no receive streams, we expect the stats not to be set.
3108   stats = apm->GetStatistics(false);
3109   EXPECT_FALSE(stats.residual_echo_likelihood);
3110   EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
3111   EXPECT_FALSE(stats.echo_return_loss);
3112   EXPECT_FALSE(stats.echo_return_loss_enhancement);
3113   EXPECT_FALSE(stats.divergent_filter_fraction);
3114   EXPECT_FALSE(stats.delay_median_ms);
3115   EXPECT_FALSE(stats.delay_standard_deviation_ms);
3116 }
3117 }  // namespace webrtc
3118