1/*
2 *  Copyright (c) 2015 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 <string>
12#include <vector>
13
14#include "testing/gtest/include/gtest/gtest.h"
15
16#include "webrtc/audio/audio_send_stream.h"
17#include "webrtc/audio/audio_state.h"
18#include "webrtc/audio/conversion.h"
19#include "webrtc/call/congestion_controller.h"
20#include "webrtc/modules/bitrate_controller/include/mock/mock_bitrate_controller.h"
21#include "webrtc/modules/pacing/paced_sender.h"
22#include "webrtc/test/mock_voe_channel_proxy.h"
23#include "webrtc/test/mock_voice_engine.h"
24#include "webrtc/video/call_stats.h"
25
26namespace webrtc {
27namespace test {
28namespace {
29
30using testing::_;
31using testing::Return;
32
33const int kChannelId = 1;
34const uint32_t kSsrc = 1234;
35const char* kCName = "foo_name";
36const int kAudioLevelId = 2;
37const int kAbsSendTimeId = 3;
38const int kTransportSequenceNumberId = 4;
39const int kEchoDelayMedian = 254;
40const int kEchoDelayStdDev = -3;
41const int kEchoReturnLoss = -65;
42const int kEchoReturnLossEnhancement = 101;
43const unsigned int kSpeechInputLevel = 96;
44const CallStatistics kCallStats = {
45    1345,  1678,  1901, 1234,  112, 13456, 17890, 1567, -1890, -1123};
46const CodecInst kCodecInst = {-121, "codec_name_send", 48000, -231, 0, -671};
47const ReportBlock kReportBlock = {456, 780, 123, 567, 890, 132, 143, 13354};
48const int kTelephoneEventPayloadType = 123;
49const uint8_t kTelephoneEventCode = 45;
50const uint32_t kTelephoneEventDuration = 6789;
51
52struct ConfigHelper {
53  ConfigHelper()
54      : stream_config_(nullptr),
55        call_stats_(Clock::GetRealTimeClock()),
56        process_thread_(ProcessThread::Create("AudioTestThread")),
57        congestion_controller_(process_thread_.get(),
58                               &call_stats_,
59                               &bitrate_observer_) {
60    using testing::Invoke;
61    using testing::StrEq;
62
63    EXPECT_CALL(voice_engine_,
64        RegisterVoiceEngineObserver(_)).WillOnce(Return(0));
65    EXPECT_CALL(voice_engine_,
66        DeRegisterVoiceEngineObserver()).WillOnce(Return(0));
67    AudioState::Config config;
68    config.voice_engine = &voice_engine_;
69    audio_state_ = AudioState::Create(config);
70
71    EXPECT_CALL(voice_engine_, ChannelProxyFactory(kChannelId))
72        .WillOnce(Invoke([this](int channel_id) {
73          EXPECT_FALSE(channel_proxy_);
74          channel_proxy_ = new testing::StrictMock<MockVoEChannelProxy>();
75          EXPECT_CALL(*channel_proxy_, SetRTCPStatus(true)).Times(1);
76          EXPECT_CALL(*channel_proxy_, SetLocalSSRC(kSsrc)).Times(1);
77          EXPECT_CALL(*channel_proxy_, SetRTCP_CNAME(StrEq(kCName))).Times(1);
78          EXPECT_CALL(*channel_proxy_,
79              SetSendAbsoluteSenderTimeStatus(true, kAbsSendTimeId)).Times(1);
80          EXPECT_CALL(*channel_proxy_,
81              SetSendAudioLevelIndicationStatus(true, kAudioLevelId)).Times(1);
82          EXPECT_CALL(*channel_proxy_, EnableSendTransportSequenceNumber(
83                                           kTransportSequenceNumberId))
84              .Times(1);
85          EXPECT_CALL(*channel_proxy_,
86                      SetCongestionControlObjects(
87                          congestion_controller_.pacer(),
88                          congestion_controller_.GetTransportFeedbackObserver(),
89                          congestion_controller_.packet_router()))
90              .Times(1);
91          EXPECT_CALL(*channel_proxy_,
92                      SetCongestionControlObjects(nullptr, nullptr, nullptr))
93              .Times(1);
94          return channel_proxy_;
95        }));
96    stream_config_.voe_channel_id = kChannelId;
97    stream_config_.rtp.ssrc = kSsrc;
98    stream_config_.rtp.c_name = kCName;
99    stream_config_.rtp.extensions.push_back(
100        RtpExtension(RtpExtension::kAudioLevel, kAudioLevelId));
101    stream_config_.rtp.extensions.push_back(
102        RtpExtension(RtpExtension::kAbsSendTime, kAbsSendTimeId));
103    stream_config_.rtp.extensions.push_back(RtpExtension(
104        RtpExtension::kTransportSequenceNumber, kTransportSequenceNumberId));
105  }
106
107  AudioSendStream::Config& config() { return stream_config_; }
108  rtc::scoped_refptr<AudioState> audio_state() { return audio_state_; }
109  CongestionController* congestion_controller() {
110    return &congestion_controller_;
111  }
112
113  void SetupMockForSendTelephoneEvent() {
114    EXPECT_TRUE(channel_proxy_);
115    EXPECT_CALL(*channel_proxy_,
116        SetSendTelephoneEventPayloadType(kTelephoneEventPayloadType))
117            .WillOnce(Return(true));
118    EXPECT_CALL(*channel_proxy_,
119        SendTelephoneEventOutband(kTelephoneEventCode, kTelephoneEventDuration))
120            .WillOnce(Return(true));
121  }
122
123  void SetupMockForGetStats() {
124    using testing::DoAll;
125    using testing::SetArgReferee;
126
127    std::vector<ReportBlock> report_blocks;
128    webrtc::ReportBlock block = kReportBlock;
129    report_blocks.push_back(block);  // Has wrong SSRC.
130    block.source_SSRC = kSsrc;
131    report_blocks.push_back(block);  // Correct block.
132    block.fraction_lost = 0;
133    report_blocks.push_back(block);  // Duplicate SSRC, bad fraction_lost.
134
135    EXPECT_TRUE(channel_proxy_);
136    EXPECT_CALL(*channel_proxy_, GetRTCPStatistics())
137        .WillRepeatedly(Return(kCallStats));
138    EXPECT_CALL(*channel_proxy_, GetRemoteRTCPReportBlocks())
139        .WillRepeatedly(Return(report_blocks));
140
141    EXPECT_CALL(voice_engine_, GetSendCodec(kChannelId, _))
142        .WillRepeatedly(DoAll(SetArgReferee<1>(kCodecInst), Return(0)));
143    EXPECT_CALL(voice_engine_, GetSpeechInputLevelFullRange(_))
144        .WillRepeatedly(DoAll(SetArgReferee<0>(kSpeechInputLevel), Return(0)));
145    EXPECT_CALL(voice_engine_, GetEcMetricsStatus(_))
146        .WillRepeatedly(DoAll(SetArgReferee<0>(true), Return(0)));
147    EXPECT_CALL(voice_engine_, GetEchoMetrics(_, _, _, _))
148        .WillRepeatedly(DoAll(SetArgReferee<0>(kEchoReturnLoss),
149                        SetArgReferee<1>(kEchoReturnLossEnhancement),
150                        Return(0)));
151    EXPECT_CALL(voice_engine_, GetEcDelayMetrics(_, _, _))
152        .WillRepeatedly(DoAll(SetArgReferee<0>(kEchoDelayMedian),
153                        SetArgReferee<1>(kEchoDelayStdDev), Return(0)));
154  }
155
156 private:
157  testing::StrictMock<MockVoiceEngine> voice_engine_;
158  rtc::scoped_refptr<AudioState> audio_state_;
159  AudioSendStream::Config stream_config_;
160  testing::StrictMock<MockVoEChannelProxy>* channel_proxy_ = nullptr;
161  CallStats call_stats_;
162  testing::NiceMock<MockBitrateObserver> bitrate_observer_;
163  rtc::scoped_ptr<ProcessThread> process_thread_;
164  CongestionController congestion_controller_;
165};
166}  // namespace
167
168TEST(AudioSendStreamTest, ConfigToString) {
169  AudioSendStream::Config config(nullptr);
170  config.rtp.ssrc = kSsrc;
171  config.rtp.extensions.push_back(
172      RtpExtension(RtpExtension::kAbsSendTime, kAbsSendTimeId));
173  config.rtp.c_name = kCName;
174  config.voe_channel_id = kChannelId;
175  config.cng_payload_type = 42;
176  config.red_payload_type = 17;
177  EXPECT_EQ(
178      "{rtp: {ssrc: 1234, extensions: [{name: "
179      "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time, id: 3}], "
180      "c_name: foo_name}, voe_channel_id: 1, cng_payload_type: 42, "
181      "red_payload_type: 17}",
182      config.ToString());
183}
184
185TEST(AudioSendStreamTest, ConstructDestruct) {
186  ConfigHelper helper;
187  internal::AudioSendStream send_stream(helper.config(), helper.audio_state(),
188                                        helper.congestion_controller());
189}
190
191TEST(AudioSendStreamTest, SendTelephoneEvent) {
192  ConfigHelper helper;
193  internal::AudioSendStream send_stream(helper.config(), helper.audio_state(),
194                                        helper.congestion_controller());
195  helper.SetupMockForSendTelephoneEvent();
196  EXPECT_TRUE(send_stream.SendTelephoneEvent(kTelephoneEventPayloadType,
197      kTelephoneEventCode, kTelephoneEventDuration));
198}
199
200TEST(AudioSendStreamTest, GetStats) {
201  ConfigHelper helper;
202  internal::AudioSendStream send_stream(helper.config(), helper.audio_state(),
203                                        helper.congestion_controller());
204  helper.SetupMockForGetStats();
205  AudioSendStream::Stats stats = send_stream.GetStats();
206  EXPECT_EQ(kSsrc, stats.local_ssrc);
207  EXPECT_EQ(static_cast<int64_t>(kCallStats.bytesSent), stats.bytes_sent);
208  EXPECT_EQ(kCallStats.packetsSent, stats.packets_sent);
209  EXPECT_EQ(static_cast<int32_t>(kReportBlock.cumulative_num_packets_lost),
210            stats.packets_lost);
211  EXPECT_EQ(Q8ToFloat(kReportBlock.fraction_lost), stats.fraction_lost);
212  EXPECT_EQ(std::string(kCodecInst.plname), stats.codec_name);
213  EXPECT_EQ(static_cast<int32_t>(kReportBlock.extended_highest_sequence_number),
214            stats.ext_seqnum);
215  EXPECT_EQ(static_cast<int32_t>(kReportBlock.interarrival_jitter /
216                                 (kCodecInst.plfreq / 1000)),
217            stats.jitter_ms);
218  EXPECT_EQ(kCallStats.rttMs, stats.rtt_ms);
219  EXPECT_EQ(static_cast<int32_t>(kSpeechInputLevel), stats.audio_level);
220  EXPECT_EQ(-1, stats.aec_quality_min);
221  EXPECT_EQ(kEchoDelayMedian, stats.echo_delay_median_ms);
222  EXPECT_EQ(kEchoDelayStdDev, stats.echo_delay_std_ms);
223  EXPECT_EQ(kEchoReturnLoss, stats.echo_return_loss);
224  EXPECT_EQ(kEchoReturnLossEnhancement, stats.echo_return_loss_enhancement);
225  EXPECT_FALSE(stats.typing_noise_detected);
226}
227
228TEST(AudioSendStreamTest, GetStatsTypingNoiseDetected) {
229  ConfigHelper helper;
230  internal::AudioSendStream send_stream(helper.config(), helper.audio_state(),
231                                        helper.congestion_controller());
232  helper.SetupMockForGetStats();
233  EXPECT_FALSE(send_stream.GetStats().typing_noise_detected);
234
235  internal::AudioState* internal_audio_state =
236      static_cast<internal::AudioState*>(helper.audio_state().get());
237  VoiceEngineObserver* voe_observer =
238      static_cast<VoiceEngineObserver*>(internal_audio_state);
239  voe_observer->CallbackOnError(-1, VE_TYPING_NOISE_WARNING);
240  EXPECT_TRUE(send_stream.GetStats().typing_noise_detected);
241  voe_observer->CallbackOnError(-1, VE_TYPING_NOISE_OFF_WARNING);
242  EXPECT_FALSE(send_stream.GetStats().typing_noise_detected);
243}
244}  // namespace test
245}  // namespace webrtc
246