xref: /aosp_15_r20/external/webrtc/modules/audio_coding/neteq/neteq_unittest.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2011 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 
11 #include "api/neteq/neteq.h"
12 
13 #include <math.h>
14 #include <stdlib.h>
15 #include <string.h>  // memset
16 
17 #include <algorithm>
18 #include <memory>
19 #include <set>
20 #include <string>
21 #include <vector>
22 
23 #include "absl/flags/flag.h"
24 #include "api/audio/audio_frame.h"
25 #include "api/audio_codecs/builtin_audio_decoder_factory.h"
26 #include "modules/audio_coding/codecs/pcm16b/pcm16b.h"
27 #include "modules/audio_coding/neteq/test/neteq_decoding_test.h"
28 #include "modules/audio_coding/neteq/tools/audio_loop.h"
29 #include "modules/audio_coding/neteq/tools/neteq_packet_source_input.h"
30 #include "modules/audio_coding/neteq/tools/neteq_test.h"
31 #include "modules/include/module_common_types_public.h"
32 #include "modules/rtp_rtcp/include/rtcp_statistics.h"
33 #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
34 #include "rtc_base/ignore_wundef.h"
35 #include "rtc_base/message_digest.h"
36 #include "rtc_base/numerics/safe_conversions.h"
37 #include "rtc_base/strings/string_builder.h"
38 #include "rtc_base/system/arch.h"
39 #include "test/field_trial.h"
40 #include "test/gtest.h"
41 #include "test/testsupport/file_utils.h"
42 
43 ABSL_FLAG(bool, gen_ref, false, "Generate reference files.");
44 
45 namespace webrtc {
46 
47 #if defined(WEBRTC_LINUX) && defined(WEBRTC_ARCH_X86_64) &&         \
48     defined(WEBRTC_NETEQ_UNITTEST_BITEXACT) &&                      \
49     (defined(WEBRTC_CODEC_ISAC) || defined(WEBRTC_CODEC_ISACFX)) && \
50     defined(WEBRTC_CODEC_ILBC)
51 #define MAYBE_TestBitExactness TestBitExactness
52 #else
53 #define MAYBE_TestBitExactness DISABLED_TestBitExactness
54 #endif
TEST_F(NetEqDecodingTest,MAYBE_TestBitExactness)55 TEST_F(NetEqDecodingTest, MAYBE_TestBitExactness) {
56   const std::string input_rtp_file =
57       webrtc::test::ResourcePath("audio_coding/neteq_universal_new", "rtp");
58 
59   const std::string output_checksum =
60       "dee7a10ab92526876a70a85bc48a4906901af3df";
61 
62   const std::string network_stats_checksum =
63       "911dbf5fd97f48d25b8f0967286eb73c9d6f6158";
64 
65   DecodeAndCompare(input_rtp_file, output_checksum, network_stats_checksum,
66                    absl::GetFlag(FLAGS_gen_ref));
67 }
68 
69 #if defined(WEBRTC_LINUX) && defined(WEBRTC_ARCH_X86_64) && \
70     defined(WEBRTC_NETEQ_UNITTEST_BITEXACT) && defined(WEBRTC_CODEC_OPUS)
71 #define MAYBE_TestOpusBitExactness TestOpusBitExactness
72 #else
73 #define MAYBE_TestOpusBitExactness DISABLED_TestOpusBitExactness
74 #endif
TEST_F(NetEqDecodingTest,MAYBE_TestOpusBitExactness)75 TEST_F(NetEqDecodingTest, MAYBE_TestOpusBitExactness) {
76   const std::string input_rtp_file =
77       webrtc::test::ResourcePath("audio_coding/neteq_opus", "rtp");
78 
79   const std::string output_checksum =
80       "fec6827bb9ee0b21770bbbb4a3a6f8823bf537dc|"
81       "3610cc7be4b3407b9c273b1299ab7f8f47cca96b";
82 
83   const std::string network_stats_checksum =
84       "3d043e47e5f4bb81d37e7bce8c44bf802965c853|"
85       "076662525572dba753b11578330bd491923f7f5e";
86 
87   DecodeAndCompare(input_rtp_file, output_checksum, network_stats_checksum,
88                    absl::GetFlag(FLAGS_gen_ref));
89 }
90 
91 #if defined(WEBRTC_LINUX) && defined(WEBRTC_ARCH_X86_64) && \
92     defined(WEBRTC_NETEQ_UNITTEST_BITEXACT) && defined(WEBRTC_CODEC_OPUS)
93 #define MAYBE_TestOpusDtxBitExactness TestOpusDtxBitExactness
94 #else
95 #define MAYBE_TestOpusDtxBitExactness DISABLED_TestOpusDtxBitExactness
96 #endif
TEST_F(NetEqDecodingTest,MAYBE_TestOpusDtxBitExactness)97 TEST_F(NetEqDecodingTest, MAYBE_TestOpusDtxBitExactness) {
98   const std::string input_rtp_file =
99       webrtc::test::ResourcePath("audio_coding/neteq_opus_dtx", "rtp");
100 
101   const std::string output_checksum =
102       "b3c4899eab5378ef5e54f2302948872149f6ad5e|"
103       "589e975ec31ea13f302457fea1425be9380ffb96";
104 
105   const std::string network_stats_checksum =
106       "dc8447b9fee1a21fd5d1f4045d62b982a3fb0215";
107 
108   DecodeAndCompare(input_rtp_file, output_checksum, network_stats_checksum,
109                    absl::GetFlag(FLAGS_gen_ref));
110 }
111 
112 // Use fax mode to avoid time-scaling. This is to simplify the testing of
113 // packet waiting times in the packet buffer.
114 class NetEqDecodingTestFaxMode : public NetEqDecodingTest {
115  protected:
NetEqDecodingTestFaxMode()116   NetEqDecodingTestFaxMode() : NetEqDecodingTest() {
117     config_.for_test_no_time_stretching = true;
118   }
119   void TestJitterBufferDelay(bool apply_packet_loss);
120 };
121 
TEST_F(NetEqDecodingTestFaxMode,TestFrameWaitingTimeStatistics)122 TEST_F(NetEqDecodingTestFaxMode, TestFrameWaitingTimeStatistics) {
123   // Insert 30 dummy packets at once. Each packet contains 10 ms 16 kHz audio.
124   size_t num_frames = 30;
125   const size_t kSamples = 10 * 16;
126   const size_t kPayloadBytes = kSamples * 2;
127   for (size_t i = 0; i < num_frames; ++i) {
128     const uint8_t payload[kPayloadBytes] = {0};
129     RTPHeader rtp_info;
130     rtp_info.sequenceNumber = rtc::checked_cast<uint16_t>(i);
131     rtp_info.timestamp = rtc::checked_cast<uint32_t>(i * kSamples);
132     rtp_info.ssrc = 0x1234;     // Just an arbitrary SSRC.
133     rtp_info.payloadType = 94;  // PCM16b WB codec.
134     rtp_info.markerBit = 0;
135     ASSERT_EQ(0, neteq_->InsertPacket(rtp_info, payload));
136   }
137   // Pull out all data.
138   for (size_t i = 0; i < num_frames; ++i) {
139     bool muted;
140     ASSERT_EQ(0, neteq_->GetAudio(&out_frame_, &muted));
141     ASSERT_EQ(kBlockSize16kHz, out_frame_.samples_per_channel_);
142   }
143 
144   NetEqNetworkStatistics stats;
145   EXPECT_EQ(0, neteq_->NetworkStatistics(&stats));
146   // Since all frames are dumped into NetEQ at once, but pulled out with 10 ms
147   // spacing (per definition), we expect the delay to increase with 10 ms for
148   // each packet. Thus, we are calculating the statistics for a series from 10
149   // to 300, in steps of 10 ms.
150   EXPECT_EQ(155, stats.mean_waiting_time_ms);
151   EXPECT_EQ(155, stats.median_waiting_time_ms);
152   EXPECT_EQ(10, stats.min_waiting_time_ms);
153   EXPECT_EQ(300, stats.max_waiting_time_ms);
154 
155   // Check statistics again and make sure it's been reset.
156   EXPECT_EQ(0, neteq_->NetworkStatistics(&stats));
157   EXPECT_EQ(-1, stats.mean_waiting_time_ms);
158   EXPECT_EQ(-1, stats.median_waiting_time_ms);
159   EXPECT_EQ(-1, stats.min_waiting_time_ms);
160   EXPECT_EQ(-1, stats.max_waiting_time_ms);
161 }
162 
163 
TEST_F(NetEqDecodingTest,LongCngWithNegativeClockDrift)164 TEST_F(NetEqDecodingTest, LongCngWithNegativeClockDrift) {
165   // Apply a clock drift of -25 ms / s (sender faster than receiver).
166   const double kDriftFactor = 1000.0 / (1000.0 + 25.0);
167   const double kNetworkFreezeTimeMs = 0.0;
168   const bool kGetAudioDuringFreezeRecovery = false;
169   const int kDelayToleranceMs = 20;
170   const int kMaxTimeToSpeechMs = 100;
171   LongCngWithClockDrift(kDriftFactor, kNetworkFreezeTimeMs,
172                         kGetAudioDuringFreezeRecovery, kDelayToleranceMs,
173                         kMaxTimeToSpeechMs);
174 }
175 
TEST_F(NetEqDecodingTest,LongCngWithPositiveClockDrift)176 TEST_F(NetEqDecodingTest, LongCngWithPositiveClockDrift) {
177   // Apply a clock drift of +25 ms / s (sender slower than receiver).
178   const double kDriftFactor = 1000.0 / (1000.0 - 25.0);
179   const double kNetworkFreezeTimeMs = 0.0;
180   const bool kGetAudioDuringFreezeRecovery = false;
181   const int kDelayToleranceMs = 40;
182   const int kMaxTimeToSpeechMs = 100;
183   LongCngWithClockDrift(kDriftFactor, kNetworkFreezeTimeMs,
184                         kGetAudioDuringFreezeRecovery, kDelayToleranceMs,
185                         kMaxTimeToSpeechMs);
186 }
187 
TEST_F(NetEqDecodingTest,LongCngWithNegativeClockDriftNetworkFreeze)188 TEST_F(NetEqDecodingTest, LongCngWithNegativeClockDriftNetworkFreeze) {
189   // Apply a clock drift of -25 ms / s (sender faster than receiver).
190   const double kDriftFactor = 1000.0 / (1000.0 + 25.0);
191   const double kNetworkFreezeTimeMs = 5000.0;
192   const bool kGetAudioDuringFreezeRecovery = false;
193   const int kDelayToleranceMs = 60;
194   const int kMaxTimeToSpeechMs = 200;
195   LongCngWithClockDrift(kDriftFactor, kNetworkFreezeTimeMs,
196                         kGetAudioDuringFreezeRecovery, kDelayToleranceMs,
197                         kMaxTimeToSpeechMs);
198 }
199 
TEST_F(NetEqDecodingTest,LongCngWithPositiveClockDriftNetworkFreeze)200 TEST_F(NetEqDecodingTest, LongCngWithPositiveClockDriftNetworkFreeze) {
201   // Apply a clock drift of +25 ms / s (sender slower than receiver).
202   const double kDriftFactor = 1000.0 / (1000.0 - 25.0);
203   const double kNetworkFreezeTimeMs = 5000.0;
204   const bool kGetAudioDuringFreezeRecovery = false;
205   const int kDelayToleranceMs = 40;
206   const int kMaxTimeToSpeechMs = 100;
207   LongCngWithClockDrift(kDriftFactor, kNetworkFreezeTimeMs,
208                         kGetAudioDuringFreezeRecovery, kDelayToleranceMs,
209                         kMaxTimeToSpeechMs);
210 }
211 
TEST_F(NetEqDecodingTest,LongCngWithPositiveClockDriftNetworkFreezeExtraPull)212 TEST_F(NetEqDecodingTest, LongCngWithPositiveClockDriftNetworkFreezeExtraPull) {
213   // Apply a clock drift of +25 ms / s (sender slower than receiver).
214   const double kDriftFactor = 1000.0 / (1000.0 - 25.0);
215   const double kNetworkFreezeTimeMs = 5000.0;
216   const bool kGetAudioDuringFreezeRecovery = true;
217   const int kDelayToleranceMs = 40;
218   const int kMaxTimeToSpeechMs = 100;
219   LongCngWithClockDrift(kDriftFactor, kNetworkFreezeTimeMs,
220                         kGetAudioDuringFreezeRecovery, kDelayToleranceMs,
221                         kMaxTimeToSpeechMs);
222 }
223 
TEST_F(NetEqDecodingTest,LongCngWithoutClockDrift)224 TEST_F(NetEqDecodingTest, LongCngWithoutClockDrift) {
225   const double kDriftFactor = 1.0;  // No drift.
226   const double kNetworkFreezeTimeMs = 0.0;
227   const bool kGetAudioDuringFreezeRecovery = false;
228   const int kDelayToleranceMs = 10;
229   const int kMaxTimeToSpeechMs = 50;
230   LongCngWithClockDrift(kDriftFactor, kNetworkFreezeTimeMs,
231                         kGetAudioDuringFreezeRecovery, kDelayToleranceMs,
232                         kMaxTimeToSpeechMs);
233 }
234 
TEST_F(NetEqDecodingTest,UnknownPayloadType)235 TEST_F(NetEqDecodingTest, UnknownPayloadType) {
236   const size_t kPayloadBytes = 100;
237   uint8_t payload[kPayloadBytes] = {0};
238   RTPHeader rtp_info;
239   PopulateRtpInfo(0, 0, &rtp_info);
240   rtp_info.payloadType = 1;  // Not registered as a decoder.
241   EXPECT_EQ(NetEq::kFail, neteq_->InsertPacket(rtp_info, payload));
242 }
243 
244 #if defined(WEBRTC_CODEC_ISAC) || defined(WEBRTC_CODEC_ISACFX)
245 #define MAYBE_DecoderError DecoderError
246 #else
247 #define MAYBE_DecoderError DISABLED_DecoderError
248 #endif
249 
TEST_F(NetEqDecodingTest,MAYBE_DecoderError)250 TEST_F(NetEqDecodingTest, MAYBE_DecoderError) {
251   const size_t kPayloadBytes = 100;
252   uint8_t payload[kPayloadBytes] = {0};
253   RTPHeader rtp_info;
254   PopulateRtpInfo(0, 0, &rtp_info);
255   rtp_info.payloadType = 103;  // iSAC, but the payload is invalid.
256   EXPECT_EQ(0, neteq_->InsertPacket(rtp_info, payload));
257   // Set all of `out_data_` to 1, and verify that it was set to 0 by the call
258   // to GetAudio.
259   int16_t* out_frame_data = out_frame_.mutable_data();
260   for (size_t i = 0; i < AudioFrame::kMaxDataSizeSamples; ++i) {
261     out_frame_data[i] = 1;
262   }
263   bool muted;
264   EXPECT_EQ(NetEq::kFail, neteq_->GetAudio(&out_frame_, &muted));
265   ASSERT_FALSE(muted);
266 
267   // Verify that the first 160 samples are set to 0.
268   static const int kExpectedOutputLength = 160;  // 10 ms at 16 kHz sample rate.
269   const int16_t* const_out_frame_data = out_frame_.data();
270   for (int i = 0; i < kExpectedOutputLength; ++i) {
271     rtc::StringBuilder ss;
272     ss << "i = " << i;
273     SCOPED_TRACE(ss.str());  // Print out the parameter values on failure.
274     EXPECT_EQ(0, const_out_frame_data[i]);
275   }
276 }
277 
TEST_F(NetEqDecodingTest,GetAudioBeforeInsertPacket)278 TEST_F(NetEqDecodingTest, GetAudioBeforeInsertPacket) {
279   // Set all of `out_data_` to 1, and verify that it was set to 0 by the call
280   // to GetAudio.
281   int16_t* out_frame_data = out_frame_.mutable_data();
282   for (size_t i = 0; i < AudioFrame::kMaxDataSizeSamples; ++i) {
283     out_frame_data[i] = 1;
284   }
285   bool muted;
286   EXPECT_EQ(0, neteq_->GetAudio(&out_frame_, &muted));
287   ASSERT_FALSE(muted);
288   // Verify that the first block of samples is set to 0.
289   static const int kExpectedOutputLength =
290       kInitSampleRateHz / 100;  // 10 ms at initial sample rate.
291   const int16_t* const_out_frame_data = out_frame_.data();
292   for (int i = 0; i < kExpectedOutputLength; ++i) {
293     rtc::StringBuilder ss;
294     ss << "i = " << i;
295     SCOPED_TRACE(ss.str());  // Print out the parameter values on failure.
296     EXPECT_EQ(0, const_out_frame_data[i]);
297   }
298   // Verify that the sample rate did not change from the initial configuration.
299   EXPECT_EQ(config_.sample_rate_hz, neteq_->last_output_sample_rate_hz());
300 }
301 
302 class NetEqBgnTest : public NetEqDecodingTest {
303  protected:
CheckBgn(int sampling_rate_hz)304   void CheckBgn(int sampling_rate_hz) {
305     size_t expected_samples_per_channel = 0;
306     uint8_t payload_type = 0xFF;  // Invalid.
307     if (sampling_rate_hz == 8000) {
308       expected_samples_per_channel = kBlockSize8kHz;
309       payload_type = 93;  // PCM 16, 8 kHz.
310     } else if (sampling_rate_hz == 16000) {
311       expected_samples_per_channel = kBlockSize16kHz;
312       payload_type = 94;  // PCM 16, 16 kHZ.
313     } else if (sampling_rate_hz == 32000) {
314       expected_samples_per_channel = kBlockSize32kHz;
315       payload_type = 95;  // PCM 16, 32 kHz.
316     } else {
317       ASSERT_TRUE(false);  // Unsupported test case.
318     }
319 
320     AudioFrame output;
321     test::AudioLoop input;
322     // We are using the same 32 kHz input file for all tests, regardless of
323     // `sampling_rate_hz`. The output may sound weird, but the test is still
324     // valid.
325     ASSERT_TRUE(input.Init(
326         webrtc::test::ResourcePath("audio_coding/testfile32kHz", "pcm"),
327         10 * sampling_rate_hz,  // Max 10 seconds loop length.
328         expected_samples_per_channel));
329 
330     // Payload of 10 ms of PCM16 32 kHz.
331     uint8_t payload[kBlockSize32kHz * sizeof(int16_t)];
332     RTPHeader rtp_info;
333     PopulateRtpInfo(0, 0, &rtp_info);
334     rtp_info.payloadType = payload_type;
335 
336     bool muted;
337     for (int n = 0; n < 10; ++n) {  // Insert few packets and get audio.
338       auto block = input.GetNextBlock();
339       ASSERT_EQ(expected_samples_per_channel, block.size());
340       size_t enc_len_bytes =
341           WebRtcPcm16b_Encode(block.data(), block.size(), payload);
342       ASSERT_EQ(enc_len_bytes, expected_samples_per_channel * 2);
343 
344       ASSERT_EQ(0, neteq_->InsertPacket(rtp_info, rtc::ArrayView<const uint8_t>(
345                                                       payload, enc_len_bytes)));
346       output.Reset();
347       ASSERT_EQ(0, neteq_->GetAudio(&output, &muted));
348       ASSERT_EQ(1u, output.num_channels_);
349       ASSERT_EQ(expected_samples_per_channel, output.samples_per_channel_);
350       ASSERT_EQ(AudioFrame::kNormalSpeech, output.speech_type_);
351 
352       // Next packet.
353       rtp_info.timestamp +=
354           rtc::checked_cast<uint32_t>(expected_samples_per_channel);
355       rtp_info.sequenceNumber++;
356     }
357 
358     output.Reset();
359 
360     // Get audio without inserting packets, expecting PLC and PLC-to-CNG. Pull
361     // one frame without checking speech-type. This is the first frame pulled
362     // without inserting any packet, and might not be labeled as PLC.
363     ASSERT_EQ(0, neteq_->GetAudio(&output, &muted));
364     ASSERT_EQ(1u, output.num_channels_);
365     ASSERT_EQ(expected_samples_per_channel, output.samples_per_channel_);
366 
367     // To be able to test the fading of background noise we need at lease to
368     // pull 611 frames.
369     const int kFadingThreshold = 611;
370 
371     // Test several CNG-to-PLC packet for the expected behavior. The number 20
372     // is arbitrary, but sufficiently large to test enough number of frames.
373     const int kNumPlcToCngTestFrames = 20;
374     bool plc_to_cng = false;
375     for (int n = 0; n < kFadingThreshold + kNumPlcToCngTestFrames; ++n) {
376       output.Reset();
377       // Set to non-zero.
378       memset(output.mutable_data(), 1, AudioFrame::kMaxDataSizeBytes);
379       ASSERT_EQ(0, neteq_->GetAudio(&output, &muted));
380       ASSERT_FALSE(muted);
381       ASSERT_EQ(1u, output.num_channels_);
382       ASSERT_EQ(expected_samples_per_channel, output.samples_per_channel_);
383       if (output.speech_type_ == AudioFrame::kPLCCNG) {
384         plc_to_cng = true;
385         double sum_squared = 0;
386         const int16_t* output_data = output.data();
387         for (size_t k = 0;
388              k < output.num_channels_ * output.samples_per_channel_; ++k)
389           sum_squared += output_data[k] * output_data[k];
390         EXPECT_EQ(0, sum_squared);
391       } else {
392         EXPECT_EQ(AudioFrame::kPLC, output.speech_type_);
393       }
394     }
395     EXPECT_TRUE(plc_to_cng);  // Just to be sure that PLC-to-CNG has occurred.
396   }
397 };
398 
TEST_F(NetEqBgnTest,RunTest)399 TEST_F(NetEqBgnTest, RunTest) {
400   CheckBgn(8000);
401   CheckBgn(16000);
402   CheckBgn(32000);
403 }
404 
TEST_F(NetEqDecodingTest,SequenceNumberWrap)405 TEST_F(NetEqDecodingTest, SequenceNumberWrap) {
406   // Start with a sequence number that will soon wrap.
407   std::set<uint16_t> drop_seq_numbers;  // Don't drop any packets.
408   WrapTest(0xFFFF - 10, 0, drop_seq_numbers, true, false);
409 }
410 
TEST_F(NetEqDecodingTest,SequenceNumberWrapAndDrop)411 TEST_F(NetEqDecodingTest, SequenceNumberWrapAndDrop) {
412   // Start with a sequence number that will soon wrap.
413   std::set<uint16_t> drop_seq_numbers;
414   drop_seq_numbers.insert(0xFFFF);
415   drop_seq_numbers.insert(0x0);
416   WrapTest(0xFFFF - 10, 0, drop_seq_numbers, true, false);
417 }
418 
TEST_F(NetEqDecodingTest,TimestampWrap)419 TEST_F(NetEqDecodingTest, TimestampWrap) {
420   // Start with a timestamp that will soon wrap.
421   std::set<uint16_t> drop_seq_numbers;
422   WrapTest(0, 0xFFFFFFFF - 3000, drop_seq_numbers, false, true);
423 }
424 
TEST_F(NetEqDecodingTest,TimestampAndSequenceNumberWrap)425 TEST_F(NetEqDecodingTest, TimestampAndSequenceNumberWrap) {
426   // Start with a timestamp and a sequence number that will wrap at the same
427   // time.
428   std::set<uint16_t> drop_seq_numbers;
429   WrapTest(0xFFFF - 10, 0xFFFFFFFF - 5000, drop_seq_numbers, true, true);
430 }
431 
TEST_F(NetEqDecodingTest,DiscardDuplicateCng)432 TEST_F(NetEqDecodingTest, DiscardDuplicateCng) {
433   uint16_t seq_no = 0;
434   uint32_t timestamp = 0;
435   const int kFrameSizeMs = 10;
436   const int kSampleRateKhz = 16;
437   const int kSamples = kFrameSizeMs * kSampleRateKhz;
438   const size_t kPayloadBytes = kSamples * 2;
439 
440   const int algorithmic_delay_samples =
441       std::max(algorithmic_delay_ms_ * kSampleRateKhz, 5 * kSampleRateKhz / 8);
442   // Insert three speech packets. Three are needed to get the frame length
443   // correct.
444   uint8_t payload[kPayloadBytes] = {0};
445   RTPHeader rtp_info;
446   bool muted;
447   for (int i = 0; i < 3; ++i) {
448     PopulateRtpInfo(seq_no, timestamp, &rtp_info);
449     ASSERT_EQ(0, neteq_->InsertPacket(rtp_info, payload));
450     ++seq_no;
451     timestamp += kSamples;
452 
453     // Pull audio once.
454     ASSERT_EQ(0, neteq_->GetAudio(&out_frame_, &muted));
455     ASSERT_EQ(kBlockSize16kHz, out_frame_.samples_per_channel_);
456   }
457   // Verify speech output.
458   EXPECT_EQ(AudioFrame::kNormalSpeech, out_frame_.speech_type_);
459 
460   // Insert same CNG packet twice.
461   const int kCngPeriodMs = 100;
462   const int kCngPeriodSamples = kCngPeriodMs * kSampleRateKhz;
463   size_t payload_len;
464   PopulateCng(seq_no, timestamp, &rtp_info, payload, &payload_len);
465   // This is the first time this CNG packet is inserted.
466   ASSERT_EQ(0, neteq_->InsertPacket(rtp_info, rtc::ArrayView<const uint8_t>(
467                                                   payload, payload_len)));
468 
469   // Pull audio once and make sure CNG is played.
470   ASSERT_EQ(0, neteq_->GetAudio(&out_frame_, &muted));
471   ASSERT_EQ(kBlockSize16kHz, out_frame_.samples_per_channel_);
472   EXPECT_EQ(AudioFrame::kCNG, out_frame_.speech_type_);
473   EXPECT_FALSE(
474       neteq_->GetPlayoutTimestamp());  // Returns empty value during CNG.
475   EXPECT_EQ(timestamp - algorithmic_delay_samples,
476             out_frame_.timestamp_ + out_frame_.samples_per_channel_);
477 
478   // Insert the same CNG packet again. Note that at this point it is old, since
479   // we have already decoded the first copy of it.
480   ASSERT_EQ(0, neteq_->InsertPacket(rtp_info, rtc::ArrayView<const uint8_t>(
481                                                   payload, payload_len)));
482 
483   // Pull audio until we have played `kCngPeriodMs` of CNG. Start at 10 ms since
484   // we have already pulled out CNG once.
485   for (int cng_time_ms = 10; cng_time_ms < kCngPeriodMs; cng_time_ms += 10) {
486     ASSERT_EQ(0, neteq_->GetAudio(&out_frame_, &muted));
487     ASSERT_EQ(kBlockSize16kHz, out_frame_.samples_per_channel_);
488     EXPECT_EQ(AudioFrame::kCNG, out_frame_.speech_type_);
489     EXPECT_FALSE(
490         neteq_->GetPlayoutTimestamp());  // Returns empty value during CNG.
491     EXPECT_EQ(timestamp - algorithmic_delay_samples,
492               out_frame_.timestamp_ + out_frame_.samples_per_channel_);
493   }
494 
495   ++seq_no;
496   timestamp += kCngPeriodSamples;
497   uint32_t first_speech_timestamp = timestamp;
498   // Insert speech again.
499   for (int i = 0; i < 3; ++i) {
500     PopulateRtpInfo(seq_no, timestamp, &rtp_info);
501     ASSERT_EQ(0, neteq_->InsertPacket(rtp_info, payload));
502     ++seq_no;
503     timestamp += kSamples;
504   }
505 
506   // Pull audio once and verify that the output is speech again.
507   ASSERT_EQ(0, neteq_->GetAudio(&out_frame_, &muted));
508   ASSERT_EQ(kBlockSize16kHz, out_frame_.samples_per_channel_);
509   EXPECT_EQ(AudioFrame::kNormalSpeech, out_frame_.speech_type_);
510   absl::optional<uint32_t> playout_timestamp = neteq_->GetPlayoutTimestamp();
511   ASSERT_TRUE(playout_timestamp);
512   EXPECT_EQ(first_speech_timestamp + kSamples - algorithmic_delay_samples,
513             *playout_timestamp);
514 }
515 
TEST_F(NetEqDecodingTest,CngFirst)516 TEST_F(NetEqDecodingTest, CngFirst) {
517   uint16_t seq_no = 0;
518   uint32_t timestamp = 0;
519   const int kFrameSizeMs = 10;
520   const int kSampleRateKhz = 16;
521   const int kSamples = kFrameSizeMs * kSampleRateKhz;
522   const int kPayloadBytes = kSamples * 2;
523   const int kCngPeriodMs = 100;
524   const int kCngPeriodSamples = kCngPeriodMs * kSampleRateKhz;
525   size_t payload_len;
526 
527   uint8_t payload[kPayloadBytes] = {0};
528   RTPHeader rtp_info;
529 
530   PopulateCng(seq_no, timestamp, &rtp_info, payload, &payload_len);
531   ASSERT_EQ(NetEq::kOK,
532             neteq_->InsertPacket(
533                 rtp_info, rtc::ArrayView<const uint8_t>(payload, payload_len)));
534   ++seq_no;
535   timestamp += kCngPeriodSamples;
536 
537   // Pull audio once and make sure CNG is played.
538   bool muted;
539   ASSERT_EQ(0, neteq_->GetAudio(&out_frame_, &muted));
540   ASSERT_EQ(kBlockSize16kHz, out_frame_.samples_per_channel_);
541   EXPECT_EQ(AudioFrame::kCNG, out_frame_.speech_type_);
542 
543   // Insert some speech packets.
544   const uint32_t first_speech_timestamp = timestamp;
545   int timeout_counter = 0;
546   do {
547     ASSERT_LT(timeout_counter++, 20) << "Test timed out";
548     PopulateRtpInfo(seq_no, timestamp, &rtp_info);
549     ASSERT_EQ(0, neteq_->InsertPacket(rtp_info, payload));
550     ++seq_no;
551     timestamp += kSamples;
552 
553     // Pull audio once.
554     ASSERT_EQ(0, neteq_->GetAudio(&out_frame_, &muted));
555     ASSERT_EQ(kBlockSize16kHz, out_frame_.samples_per_channel_);
556   } while (!IsNewerTimestamp(out_frame_.timestamp_, first_speech_timestamp));
557   // Verify speech output.
558   EXPECT_EQ(AudioFrame::kNormalSpeech, out_frame_.speech_type_);
559 }
560 
561 class NetEqDecodingTestWithMutedState : public NetEqDecodingTest {
562  public:
NetEqDecodingTestWithMutedState()563   NetEqDecodingTestWithMutedState() : NetEqDecodingTest() {
564     config_.enable_muted_state = true;
565   }
566 
567  protected:
568   static constexpr size_t kSamples = 10 * 16;
569   static constexpr size_t kPayloadBytes = kSamples * 2;
570 
InsertPacket(uint32_t rtp_timestamp)571   void InsertPacket(uint32_t rtp_timestamp) {
572     uint8_t payload[kPayloadBytes] = {0};
573     RTPHeader rtp_info;
574     PopulateRtpInfo(0, rtp_timestamp, &rtp_info);
575     EXPECT_EQ(0, neteq_->InsertPacket(rtp_info, payload));
576   }
577 
InsertCngPacket(uint32_t rtp_timestamp)578   void InsertCngPacket(uint32_t rtp_timestamp) {
579     uint8_t payload[kPayloadBytes] = {0};
580     RTPHeader rtp_info;
581     size_t payload_len;
582     PopulateCng(0, rtp_timestamp, &rtp_info, payload, &payload_len);
583     EXPECT_EQ(NetEq::kOK,
584               neteq_->InsertPacket(rtp_info, rtc::ArrayView<const uint8_t>(
585                                                  payload, payload_len)));
586   }
587 
GetAudioReturnMuted()588   bool GetAudioReturnMuted() {
589     bool muted;
590     EXPECT_EQ(0, neteq_->GetAudio(&out_frame_, &muted));
591     return muted;
592   }
593 
GetAudioUntilMuted()594   void GetAudioUntilMuted() {
595     while (!GetAudioReturnMuted()) {
596       ASSERT_LT(counter_++, 1000) << "Test timed out";
597     }
598   }
599 
GetAudioUntilNormal()600   void GetAudioUntilNormal() {
601     bool muted = false;
602     while (out_frame_.speech_type_ != AudioFrame::kNormalSpeech) {
603       EXPECT_EQ(0, neteq_->GetAudio(&out_frame_, &muted));
604       ASSERT_LT(counter_++, 1000) << "Test timed out";
605     }
606     EXPECT_FALSE(muted);
607   }
608 
609   int counter_ = 0;
610 };
611 
612 // Verifies that NetEq goes in and out of muted state as expected.
TEST_F(NetEqDecodingTestWithMutedState,MutedState)613 TEST_F(NetEqDecodingTestWithMutedState, MutedState) {
614   // Insert one speech packet.
615   InsertPacket(0);
616   // Pull out audio once and expect it not to be muted.
617   EXPECT_FALSE(GetAudioReturnMuted());
618   // Pull data until faded out.
619   GetAudioUntilMuted();
620   EXPECT_TRUE(out_frame_.muted());
621 
622   // Verify that output audio is not written during muted mode. Other parameters
623   // should be correct, though.
624   AudioFrame new_frame;
625   int16_t* frame_data = new_frame.mutable_data();
626   for (size_t i = 0; i < AudioFrame::kMaxDataSizeSamples; i++) {
627     frame_data[i] = 17;
628   }
629   bool muted;
630   EXPECT_EQ(0, neteq_->GetAudio(&new_frame, &muted));
631   EXPECT_TRUE(muted);
632   EXPECT_TRUE(out_frame_.muted());
633   for (size_t i = 0; i < AudioFrame::kMaxDataSizeSamples; i++) {
634     EXPECT_EQ(17, frame_data[i]);
635   }
636   EXPECT_EQ(out_frame_.timestamp_ + out_frame_.samples_per_channel_,
637             new_frame.timestamp_);
638   EXPECT_EQ(out_frame_.samples_per_channel_, new_frame.samples_per_channel_);
639   EXPECT_EQ(out_frame_.sample_rate_hz_, new_frame.sample_rate_hz_);
640   EXPECT_EQ(out_frame_.num_channels_, new_frame.num_channels_);
641   EXPECT_EQ(out_frame_.speech_type_, new_frame.speech_type_);
642   EXPECT_EQ(out_frame_.vad_activity_, new_frame.vad_activity_);
643 
644   // Insert new data. Timestamp is corrected for the time elapsed since the last
645   // packet. Verify that normal operation resumes.
646   InsertPacket(kSamples * counter_);
647   GetAudioUntilNormal();
648   EXPECT_FALSE(out_frame_.muted());
649 
650   NetEqNetworkStatistics stats;
651   EXPECT_EQ(0, neteq_->NetworkStatistics(&stats));
652   // NetEqNetworkStatistics::expand_rate tells the fraction of samples that were
653   // concealment samples, in Q14 (16384 = 100%) .The vast majority should be
654   // concealment samples in this test.
655   EXPECT_GT(stats.expand_rate, 14000);
656   // And, it should be greater than the speech_expand_rate.
657   EXPECT_GT(stats.expand_rate, stats.speech_expand_rate);
658 }
659 
660 // Verifies that NetEq goes out of muted state when given a delayed packet.
TEST_F(NetEqDecodingTestWithMutedState,MutedStateDelayedPacket)661 TEST_F(NetEqDecodingTestWithMutedState, MutedStateDelayedPacket) {
662   // Insert one speech packet.
663   InsertPacket(0);
664   // Pull out audio once and expect it not to be muted.
665   EXPECT_FALSE(GetAudioReturnMuted());
666   // Pull data until faded out.
667   GetAudioUntilMuted();
668   // Insert new data. Timestamp is only corrected for the half of the time
669   // elapsed since the last packet. That is, the new packet is delayed. Verify
670   // that normal operation resumes.
671   InsertPacket(kSamples * counter_ / 2);
672   GetAudioUntilNormal();
673 }
674 
675 // Verifies that NetEq goes out of muted state when given a future packet.
TEST_F(NetEqDecodingTestWithMutedState,MutedStateFuturePacket)676 TEST_F(NetEqDecodingTestWithMutedState, MutedStateFuturePacket) {
677   // Insert one speech packet.
678   InsertPacket(0);
679   // Pull out audio once and expect it not to be muted.
680   EXPECT_FALSE(GetAudioReturnMuted());
681   // Pull data until faded out.
682   GetAudioUntilMuted();
683   // Insert new data. Timestamp is over-corrected for the time elapsed since the
684   // last packet. That is, the new packet is too early. Verify that normal
685   // operation resumes.
686   InsertPacket(kSamples * counter_ * 2);
687   GetAudioUntilNormal();
688 }
689 
690 // Verifies that NetEq goes out of muted state when given an old packet.
TEST_F(NetEqDecodingTestWithMutedState,MutedStateOldPacket)691 TEST_F(NetEqDecodingTestWithMutedState, MutedStateOldPacket) {
692   // Insert one speech packet.
693   InsertPacket(0);
694   // Pull out audio once and expect it not to be muted.
695   EXPECT_FALSE(GetAudioReturnMuted());
696   // Pull data until faded out.
697   GetAudioUntilMuted();
698 
699   EXPECT_NE(AudioFrame::kNormalSpeech, out_frame_.speech_type_);
700   // Insert a few packets which are older than the first packet.
701   for (int i = 0; i < 5; ++i) {
702     InsertPacket(kSamples * (i - 1000));
703   }
704   EXPECT_FALSE(GetAudioReturnMuted());
705   EXPECT_EQ(AudioFrame::kNormalSpeech, out_frame_.speech_type_);
706 }
707 
708 // Verifies that NetEq doesn't enter muted state when CNG mode is active and the
709 // packet stream is suspended for a long time.
TEST_F(NetEqDecodingTestWithMutedState,DoNotMuteExtendedCngWithoutPackets)710 TEST_F(NetEqDecodingTestWithMutedState, DoNotMuteExtendedCngWithoutPackets) {
711   // Insert one CNG packet.
712   InsertCngPacket(0);
713 
714   // Pull 10 seconds of audio (10 ms audio generated per lap).
715   for (int i = 0; i < 1000; ++i) {
716     bool muted;
717     EXPECT_EQ(0, neteq_->GetAudio(&out_frame_, &muted));
718     ASSERT_FALSE(muted);
719   }
720   EXPECT_EQ(AudioFrame::kCNG, out_frame_.speech_type_);
721 }
722 
723 // Verifies that NetEq goes back to normal after a long CNG period with the
724 // packet stream suspended.
TEST_F(NetEqDecodingTestWithMutedState,RecoverAfterExtendedCngWithoutPackets)725 TEST_F(NetEqDecodingTestWithMutedState, RecoverAfterExtendedCngWithoutPackets) {
726   // Insert one CNG packet.
727   InsertCngPacket(0);
728 
729   // Pull 10 seconds of audio (10 ms audio generated per lap).
730   for (int i = 0; i < 1000; ++i) {
731     bool muted;
732     EXPECT_EQ(0, neteq_->GetAudio(&out_frame_, &muted));
733   }
734 
735   // Insert new data. Timestamp is corrected for the time elapsed since the last
736   // packet. Verify that normal operation resumes.
737   InsertPacket(kSamples * counter_);
738   GetAudioUntilNormal();
739 }
740 
741 namespace {
AudioFramesEqualExceptData(const AudioFrame & a,const AudioFrame & b)742 ::testing::AssertionResult AudioFramesEqualExceptData(const AudioFrame& a,
743                                                       const AudioFrame& b) {
744   if (a.timestamp_ != b.timestamp_)
745     return ::testing::AssertionFailure() << "timestamp_ diff (" << a.timestamp_
746                                          << " != " << b.timestamp_ << ")";
747   if (a.sample_rate_hz_ != b.sample_rate_hz_)
748     return ::testing::AssertionFailure()
749            << "sample_rate_hz_ diff (" << a.sample_rate_hz_
750            << " != " << b.sample_rate_hz_ << ")";
751   if (a.samples_per_channel_ != b.samples_per_channel_)
752     return ::testing::AssertionFailure()
753            << "samples_per_channel_ diff (" << a.samples_per_channel_
754            << " != " << b.samples_per_channel_ << ")";
755   if (a.num_channels_ != b.num_channels_)
756     return ::testing::AssertionFailure()
757            << "num_channels_ diff (" << a.num_channels_
758            << " != " << b.num_channels_ << ")";
759   if (a.speech_type_ != b.speech_type_)
760     return ::testing::AssertionFailure()
761            << "speech_type_ diff (" << a.speech_type_
762            << " != " << b.speech_type_ << ")";
763   if (a.vad_activity_ != b.vad_activity_)
764     return ::testing::AssertionFailure()
765            << "vad_activity_ diff (" << a.vad_activity_
766            << " != " << b.vad_activity_ << ")";
767   return ::testing::AssertionSuccess();
768 }
769 
AudioFramesEqual(const AudioFrame & a,const AudioFrame & b)770 ::testing::AssertionResult AudioFramesEqual(const AudioFrame& a,
771                                             const AudioFrame& b) {
772   ::testing::AssertionResult res = AudioFramesEqualExceptData(a, b);
773   if (!res)
774     return res;
775   if (memcmp(a.data(), b.data(),
776              a.samples_per_channel_ * a.num_channels_ * sizeof(*a.data())) !=
777       0) {
778     return ::testing::AssertionFailure() << "data_ diff";
779   }
780   return ::testing::AssertionSuccess();
781 }
782 
783 }  // namespace
784 
TEST_F(NetEqDecodingTestTwoInstances,CompareMutedStateOnOff)785 TEST_F(NetEqDecodingTestTwoInstances, CompareMutedStateOnOff) {
786   ASSERT_FALSE(config_.enable_muted_state);
787   config2_.enable_muted_state = true;
788   CreateSecondInstance();
789 
790   // Insert one speech packet into both NetEqs.
791   const size_t kSamples = 10 * 16;
792   const size_t kPayloadBytes = kSamples * 2;
793   uint8_t payload[kPayloadBytes] = {0};
794   RTPHeader rtp_info;
795   PopulateRtpInfo(0, 0, &rtp_info);
796   EXPECT_EQ(0, neteq_->InsertPacket(rtp_info, payload));
797   EXPECT_EQ(0, neteq2_->InsertPacket(rtp_info, payload));
798 
799   AudioFrame out_frame1, out_frame2;
800   bool muted;
801   for (int i = 0; i < 1000; ++i) {
802     rtc::StringBuilder ss;
803     ss << "i = " << i;
804     SCOPED_TRACE(ss.str());  // Print out the loop iterator on failure.
805     EXPECT_EQ(0, neteq_->GetAudio(&out_frame1, &muted));
806     EXPECT_FALSE(muted);
807     EXPECT_EQ(0, neteq2_->GetAudio(&out_frame2, &muted));
808     if (muted) {
809       EXPECT_TRUE(AudioFramesEqualExceptData(out_frame1, out_frame2));
810     } else {
811       EXPECT_TRUE(AudioFramesEqual(out_frame1, out_frame2));
812     }
813   }
814   EXPECT_TRUE(muted);
815 
816   // Insert new data. Timestamp is corrected for the time elapsed since the last
817   // packet.
818   for (int i = 0; i < 5; ++i) {
819     PopulateRtpInfo(0, kSamples * 1000 + kSamples * i, &rtp_info);
820     EXPECT_EQ(0, neteq_->InsertPacket(rtp_info, payload));
821     EXPECT_EQ(0, neteq2_->InsertPacket(rtp_info, payload));
822   }
823 
824   int counter = 0;
825   while (out_frame1.speech_type_ != AudioFrame::kNormalSpeech) {
826     ASSERT_LT(counter++, 1000) << "Test timed out";
827     rtc::StringBuilder ss;
828     ss << "counter = " << counter;
829     SCOPED_TRACE(ss.str());  // Print out the loop iterator on failure.
830     EXPECT_EQ(0, neteq_->GetAudio(&out_frame1, &muted));
831     EXPECT_FALSE(muted);
832     EXPECT_EQ(0, neteq2_->GetAudio(&out_frame2, &muted));
833     if (muted) {
834       EXPECT_TRUE(AudioFramesEqualExceptData(out_frame1, out_frame2));
835     } else {
836       EXPECT_TRUE(AudioFramesEqual(out_frame1, out_frame2));
837     }
838   }
839   EXPECT_FALSE(muted);
840 }
841 
TEST_F(NetEqDecodingTest,TestConcealmentEvents)842 TEST_F(NetEqDecodingTest, TestConcealmentEvents) {
843   const int kNumConcealmentEvents = 19;
844   const size_t kSamples = 10 * 16;
845   const size_t kPayloadBytes = kSamples * 2;
846   int seq_no = 0;
847   RTPHeader rtp_info;
848   rtp_info.ssrc = 0x1234;     // Just an arbitrary SSRC.
849   rtp_info.payloadType = 94;  // PCM16b WB codec.
850   rtp_info.markerBit = 0;
851   const uint8_t payload[kPayloadBytes] = {0};
852   bool muted;
853 
854   for (int i = 0; i < kNumConcealmentEvents; i++) {
855     // Insert some packets of 10 ms size.
856     for (int j = 0; j < 10; j++) {
857       rtp_info.sequenceNumber = seq_no++;
858       rtp_info.timestamp = rtp_info.sequenceNumber * kSamples;
859       neteq_->InsertPacket(rtp_info, payload);
860       neteq_->GetAudio(&out_frame_, &muted);
861     }
862 
863     // Lose a number of packets.
864     int num_lost = 1 + i;
865     for (int j = 0; j < num_lost; j++) {
866       seq_no++;
867       neteq_->GetAudio(&out_frame_, &muted);
868     }
869   }
870 
871   // Check number of concealment events.
872   NetEqLifetimeStatistics stats = neteq_->GetLifetimeStatistics();
873   EXPECT_EQ(kNumConcealmentEvents, static_cast<int>(stats.concealment_events));
874 }
875 
876 // Test that the jitter buffer delay stat is computed correctly.
TestJitterBufferDelay(bool apply_packet_loss)877 void NetEqDecodingTestFaxMode::TestJitterBufferDelay(bool apply_packet_loss) {
878   const int kNumPackets = 10;
879   const int kDelayInNumPackets = 2;
880   const int kPacketLenMs = 10;  // All packets are of 10 ms size.
881   const size_t kSamples = kPacketLenMs * 16;
882   const size_t kPayloadBytes = kSamples * 2;
883   RTPHeader rtp_info;
884   rtp_info.ssrc = 0x1234;     // Just an arbitrary SSRC.
885   rtp_info.payloadType = 94;  // PCM16b WB codec.
886   rtp_info.markerBit = 0;
887   const uint8_t payload[kPayloadBytes] = {0};
888   bool muted;
889   int packets_sent = 0;
890   int packets_received = 0;
891   int expected_delay = 0;
892   int expected_target_delay = 0;
893   uint64_t expected_emitted_count = 0;
894   while (packets_received < kNumPackets) {
895     // Insert packet.
896     if (packets_sent < kNumPackets) {
897       rtp_info.sequenceNumber = packets_sent++;
898       rtp_info.timestamp = rtp_info.sequenceNumber * kSamples;
899       neteq_->InsertPacket(rtp_info, payload);
900     }
901 
902     // Get packet.
903     if (packets_sent > kDelayInNumPackets) {
904       neteq_->GetAudio(&out_frame_, &muted);
905       packets_received++;
906 
907       // The delay reported by the jitter buffer never exceeds
908       // the number of samples previously fetched with GetAudio
909       // (hence the min()).
910       int packets_delay = std::min(packets_received, kDelayInNumPackets + 1);
911 
912       // The increase of the expected delay is the product of
913       // the current delay of the jitter buffer in ms * the
914       // number of samples that are sent for play out.
915       int current_delay_ms = packets_delay * kPacketLenMs;
916       expected_delay += current_delay_ms * kSamples;
917       expected_target_delay += neteq_->TargetDelayMs() * kSamples;
918       expected_emitted_count += kSamples;
919     }
920   }
921 
922   if (apply_packet_loss) {
923     // Extra call to GetAudio to cause concealment.
924     neteq_->GetAudio(&out_frame_, &muted);
925   }
926 
927   // Check jitter buffer delay.
928   NetEqLifetimeStatistics stats = neteq_->GetLifetimeStatistics();
929   EXPECT_EQ(expected_delay,
930             rtc::checked_cast<int>(stats.jitter_buffer_delay_ms));
931   EXPECT_EQ(expected_emitted_count, stats.jitter_buffer_emitted_count);
932   EXPECT_EQ(expected_target_delay,
933             rtc::checked_cast<int>(stats.jitter_buffer_target_delay_ms));
934 }
935 
TEST_F(NetEqDecodingTestFaxMode,TestJitterBufferDelayWithoutLoss)936 TEST_F(NetEqDecodingTestFaxMode, TestJitterBufferDelayWithoutLoss) {
937   TestJitterBufferDelay(false);
938 }
939 
TEST_F(NetEqDecodingTestFaxMode,TestJitterBufferDelayWithLoss)940 TEST_F(NetEqDecodingTestFaxMode, TestJitterBufferDelayWithLoss) {
941   TestJitterBufferDelay(true);
942 }
943 
TEST_F(NetEqDecodingTestFaxMode,TestJitterBufferDelayWithAcceleration)944 TEST_F(NetEqDecodingTestFaxMode, TestJitterBufferDelayWithAcceleration) {
945   const int kPacketLenMs = 10;  // All packets are of 10 ms size.
946   const size_t kSamples = kPacketLenMs * 16;
947   const size_t kPayloadBytes = kSamples * 2;
948   RTPHeader rtp_info;
949   rtp_info.ssrc = 0x1234;     // Just an arbitrary SSRC.
950   rtp_info.payloadType = 94;  // PCM16b WB codec.
951   rtp_info.markerBit = 0;
952   const uint8_t payload[kPayloadBytes] = {0};
953 
954   int expected_target_delay = neteq_->TargetDelayMs() * kSamples;
955   neteq_->InsertPacket(rtp_info, payload);
956 
957   bool muted;
958   neteq_->GetAudio(&out_frame_, &muted);
959 
960   rtp_info.sequenceNumber += 1;
961   rtp_info.timestamp += kSamples;
962   neteq_->InsertPacket(rtp_info, payload);
963   rtp_info.sequenceNumber += 1;
964   rtp_info.timestamp += kSamples;
965   neteq_->InsertPacket(rtp_info, payload);
966 
967   expected_target_delay += neteq_->TargetDelayMs() * 2 * kSamples;
968   // We have two packets in the buffer and kAccelerate operation will
969   // extract 20 ms of data.
970   neteq_->GetAudio(&out_frame_, &muted, nullptr, NetEq::Operation::kAccelerate);
971 
972   // Check jitter buffer delay.
973   NetEqLifetimeStatistics stats = neteq_->GetLifetimeStatistics();
974   EXPECT_EQ(10 * kSamples * 3, stats.jitter_buffer_delay_ms);
975   EXPECT_EQ(kSamples * 3, stats.jitter_buffer_emitted_count);
976   EXPECT_EQ(expected_target_delay,
977             rtc::checked_cast<int>(stats.jitter_buffer_target_delay_ms));
978 }
979 
980 namespace test {
TEST(NetEqNoTimeStretchingMode,RunTest)981 TEST(NetEqNoTimeStretchingMode, RunTest) {
982   NetEq::Config config;
983   config.for_test_no_time_stretching = true;
984   auto codecs = NetEqTest::StandardDecoderMap();
985   NetEqPacketSourceInput::RtpHeaderExtensionMap rtp_ext_map = {
986       {1, kRtpExtensionAudioLevel},
987       {3, kRtpExtensionAbsoluteSendTime},
988       {5, kRtpExtensionTransportSequenceNumber},
989       {7, kRtpExtensionVideoContentType},
990       {8, kRtpExtensionVideoTiming}};
991   std::unique_ptr<NetEqInput> input(new NetEqRtpDumpInput(
992       webrtc::test::ResourcePath("audio_coding/neteq_universal_new", "rtp"),
993       rtp_ext_map, absl::nullopt /*No SSRC filter*/));
994   std::unique_ptr<TimeLimitedNetEqInput> input_time_limit(
995       new TimeLimitedNetEqInput(std::move(input), 20000));
996   std::unique_ptr<AudioSink> output(new VoidAudioSink);
997   NetEqTest::Callbacks callbacks;
998   NetEqTest test(config, CreateBuiltinAudioDecoderFactory(), codecs,
999                  /*text_log=*/nullptr, /*neteq_factory=*/nullptr,
1000                  /*input=*/std::move(input_time_limit), std::move(output),
1001                  callbacks);
1002   test.Run();
1003   const auto stats = test.SimulationStats();
1004   EXPECT_EQ(0, stats.accelerate_rate);
1005   EXPECT_EQ(0, stats.preemptive_rate);
1006 }
1007 
1008 }  // namespace test
1009 }  // namespace webrtc
1010