• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "audio/audio_receive_stream.h"
12 
13 #include <string>
14 #include <utility>
15 
16 #include "absl/memory/memory.h"
17 #include "api/array_view.h"
18 #include "api/audio_codecs/audio_format.h"
19 #include "api/call/audio_sink.h"
20 #include "api/rtp_parameters.h"
21 #include "audio/audio_send_stream.h"
22 #include "audio/audio_state.h"
23 #include "audio/channel_receive.h"
24 #include "audio/conversion.h"
25 #include "call/rtp_config.h"
26 #include "call/rtp_stream_receiver_controller_interface.h"
27 #include "rtc_base/checks.h"
28 #include "rtc_base/logging.h"
29 #include "rtc_base/strings/string_builder.h"
30 #include "rtc_base/time_utils.h"
31 
32 namespace webrtc {
33 
ToString() const34 std::string AudioReceiveStream::Config::Rtp::ToString() const {
35   char ss_buf[1024];
36   rtc::SimpleStringBuilder ss(ss_buf);
37   ss << "{remote_ssrc: " << remote_ssrc;
38   ss << ", local_ssrc: " << local_ssrc;
39   ss << ", transport_cc: " << (transport_cc ? "on" : "off");
40   ss << ", nack: " << nack.ToString();
41   ss << ", extensions: [";
42   for (size_t i = 0; i < extensions.size(); ++i) {
43     ss << extensions[i].ToString();
44     if (i != extensions.size() - 1) {
45       ss << ", ";
46     }
47   }
48   ss << ']';
49   ss << '}';
50   return ss.str();
51 }
52 
ToString() const53 std::string AudioReceiveStream::Config::ToString() const {
54   char ss_buf[1024];
55   rtc::SimpleStringBuilder ss(ss_buf);
56   ss << "{rtp: " << rtp.ToString();
57   ss << ", rtcp_send_transport: "
58      << (rtcp_send_transport ? "(Transport)" : "null");
59   if (!sync_group.empty()) {
60     ss << ", sync_group: " << sync_group;
61   }
62   ss << '}';
63   return ss.str();
64 }
65 
66 namespace internal {
67 namespace {
CreateChannelReceive(Clock * clock,webrtc::AudioState * audio_state,ProcessThread * module_process_thread,NetEqFactory * neteq_factory,const webrtc::AudioReceiveStream::Config & config,RtcEventLog * event_log)68 std::unique_ptr<voe::ChannelReceiveInterface> CreateChannelReceive(
69     Clock* clock,
70     webrtc::AudioState* audio_state,
71     ProcessThread* module_process_thread,
72     NetEqFactory* neteq_factory,
73     const webrtc::AudioReceiveStream::Config& config,
74     RtcEventLog* event_log) {
75   RTC_DCHECK(audio_state);
76   internal::AudioState* internal_audio_state =
77       static_cast<internal::AudioState*>(audio_state);
78   return voe::CreateChannelReceive(
79       clock, module_process_thread, neteq_factory,
80       internal_audio_state->audio_device_module(), config.rtcp_send_transport,
81       event_log, config.rtp.local_ssrc, config.rtp.remote_ssrc,
82       config.jitter_buffer_max_packets, config.jitter_buffer_fast_accelerate,
83       config.jitter_buffer_min_delay_ms,
84       config.jitter_buffer_enable_rtx_handling, config.decoder_factory,
85       config.codec_pair_id, config.frame_decryptor, config.crypto_options,
86       std::move(config.frame_transformer));
87 }
88 }  // namespace
89 
AudioReceiveStream(Clock * clock,RtpStreamReceiverControllerInterface * receiver_controller,PacketRouter * packet_router,ProcessThread * module_process_thread,NetEqFactory * neteq_factory,const webrtc::AudioReceiveStream::Config & config,const rtc::scoped_refptr<webrtc::AudioState> & audio_state,webrtc::RtcEventLog * event_log)90 AudioReceiveStream::AudioReceiveStream(
91     Clock* clock,
92     RtpStreamReceiverControllerInterface* receiver_controller,
93     PacketRouter* packet_router,
94     ProcessThread* module_process_thread,
95     NetEqFactory* neteq_factory,
96     const webrtc::AudioReceiveStream::Config& config,
97     const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
98     webrtc::RtcEventLog* event_log)
99     : AudioReceiveStream(clock,
100                          receiver_controller,
101                          packet_router,
102                          config,
103                          audio_state,
104                          event_log,
105                          CreateChannelReceive(clock,
106                                               audio_state.get(),
107                                               module_process_thread,
108                                               neteq_factory,
109                                               config,
110                                               event_log)) {}
111 
AudioReceiveStream(Clock * clock,RtpStreamReceiverControllerInterface * receiver_controller,PacketRouter * packet_router,const webrtc::AudioReceiveStream::Config & config,const rtc::scoped_refptr<webrtc::AudioState> & audio_state,webrtc::RtcEventLog * event_log,std::unique_ptr<voe::ChannelReceiveInterface> channel_receive)112 AudioReceiveStream::AudioReceiveStream(
113     Clock* clock,
114     RtpStreamReceiverControllerInterface* receiver_controller,
115     PacketRouter* packet_router,
116     const webrtc::AudioReceiveStream::Config& config,
117     const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
118     webrtc::RtcEventLog* event_log,
119     std::unique_ptr<voe::ChannelReceiveInterface> channel_receive)
120     : audio_state_(audio_state),
121       channel_receive_(std::move(channel_receive)),
122       source_tracker_(clock) {
123   RTC_LOG(LS_INFO) << "AudioReceiveStream: " << config.rtp.remote_ssrc;
124   RTC_DCHECK(config.decoder_factory);
125   RTC_DCHECK(config.rtcp_send_transport);
126   RTC_DCHECK(audio_state_);
127   RTC_DCHECK(channel_receive_);
128 
129   module_process_thread_checker_.Detach();
130 
131   RTC_DCHECK(receiver_controller);
132   RTC_DCHECK(packet_router);
133   // Configure bandwidth estimation.
134   channel_receive_->RegisterReceiverCongestionControlObjects(packet_router);
135 
136   // Register with transport.
137   rtp_stream_receiver_ = receiver_controller->CreateReceiver(
138       config.rtp.remote_ssrc, channel_receive_.get());
139   ConfigureStream(this, config, true);
140 }
141 
~AudioReceiveStream()142 AudioReceiveStream::~AudioReceiveStream() {
143   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
144   RTC_LOG(LS_INFO) << "~AudioReceiveStream: " << config_.rtp.remote_ssrc;
145   Stop();
146   channel_receive_->SetAssociatedSendChannel(nullptr);
147   channel_receive_->ResetReceiverCongestionControlObjects();
148 }
149 
Reconfigure(const webrtc::AudioReceiveStream::Config & config)150 void AudioReceiveStream::Reconfigure(
151     const webrtc::AudioReceiveStream::Config& config) {
152   RTC_DCHECK(worker_thread_checker_.IsCurrent());
153   ConfigureStream(this, config, false);
154 }
155 
Start()156 void AudioReceiveStream::Start() {
157   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
158   if (playing_) {
159     return;
160   }
161   channel_receive_->StartPlayout();
162   playing_ = true;
163   audio_state()->AddReceivingStream(this);
164 }
165 
Stop()166 void AudioReceiveStream::Stop() {
167   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
168   if (!playing_) {
169     return;
170   }
171   channel_receive_->StopPlayout();
172   playing_ = false;
173   audio_state()->RemoveReceivingStream(this);
174 }
175 
GetStats() const176 webrtc::AudioReceiveStream::Stats AudioReceiveStream::GetStats() const {
177   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
178   webrtc::AudioReceiveStream::Stats stats;
179   stats.remote_ssrc = config_.rtp.remote_ssrc;
180 
181   webrtc::CallReceiveStatistics call_stats =
182       channel_receive_->GetRTCPStatistics();
183   // TODO(solenberg): Don't return here if we can't get the codec - return the
184   //                  stats we *can* get.
185   auto receive_codec = channel_receive_->GetReceiveCodec();
186   if (!receive_codec) {
187     return stats;
188   }
189 
190   stats.payload_bytes_rcvd = call_stats.payload_bytes_rcvd;
191   stats.header_and_padding_bytes_rcvd =
192       call_stats.header_and_padding_bytes_rcvd;
193   stats.packets_rcvd = call_stats.packetsReceived;
194   stats.packets_lost = call_stats.cumulativeLost;
195   stats.capture_start_ntp_time_ms = call_stats.capture_start_ntp_time_ms_;
196   stats.last_packet_received_timestamp_ms =
197       call_stats.last_packet_received_timestamp_ms;
198   stats.codec_name = receive_codec->second.name;
199   stats.codec_payload_type = receive_codec->first;
200   int clockrate_khz = receive_codec->second.clockrate_hz / 1000;
201   if (clockrate_khz > 0) {
202     stats.jitter_ms = call_stats.jitterSamples / clockrate_khz;
203   }
204   stats.delay_estimate_ms = channel_receive_->GetDelayEstimate();
205   stats.audio_level = channel_receive_->GetSpeechOutputLevelFullRange();
206   stats.total_output_energy = channel_receive_->GetTotalOutputEnergy();
207   stats.total_output_duration = channel_receive_->GetTotalOutputDuration();
208   stats.estimated_playout_ntp_timestamp_ms =
209       channel_receive_->GetCurrentEstimatedPlayoutNtpTimestampMs(
210           rtc::TimeMillis());
211 
212   // Get jitter buffer and total delay (alg + jitter + playout) stats.
213   auto ns = channel_receive_->GetNetworkStatistics();
214   stats.fec_packets_received = ns.fecPacketsReceived;
215   stats.fec_packets_discarded = ns.fecPacketsDiscarded;
216   stats.jitter_buffer_ms = ns.currentBufferSize;
217   stats.jitter_buffer_preferred_ms = ns.preferredBufferSize;
218   stats.total_samples_received = ns.totalSamplesReceived;
219   stats.concealed_samples = ns.concealedSamples;
220   stats.silent_concealed_samples = ns.silentConcealedSamples;
221   stats.concealment_events = ns.concealmentEvents;
222   stats.jitter_buffer_delay_seconds =
223       static_cast<double>(ns.jitterBufferDelayMs) /
224       static_cast<double>(rtc::kNumMillisecsPerSec);
225   stats.jitter_buffer_emitted_count = ns.jitterBufferEmittedCount;
226   stats.jitter_buffer_target_delay_seconds =
227       static_cast<double>(ns.jitterBufferTargetDelayMs) /
228       static_cast<double>(rtc::kNumMillisecsPerSec);
229   stats.inserted_samples_for_deceleration = ns.insertedSamplesForDeceleration;
230   stats.removed_samples_for_acceleration = ns.removedSamplesForAcceleration;
231   stats.expand_rate = Q14ToFloat(ns.currentExpandRate);
232   stats.speech_expand_rate = Q14ToFloat(ns.currentSpeechExpandRate);
233   stats.secondary_decoded_rate = Q14ToFloat(ns.currentSecondaryDecodedRate);
234   stats.secondary_discarded_rate = Q14ToFloat(ns.currentSecondaryDiscardedRate);
235   stats.accelerate_rate = Q14ToFloat(ns.currentAccelerateRate);
236   stats.preemptive_expand_rate = Q14ToFloat(ns.currentPreemptiveRate);
237   stats.jitter_buffer_flushes = ns.packetBufferFlushes;
238   stats.delayed_packet_outage_samples = ns.delayedPacketOutageSamples;
239   stats.relative_packet_arrival_delay_seconds =
240       static_cast<double>(ns.relativePacketArrivalDelayMs) /
241       static_cast<double>(rtc::kNumMillisecsPerSec);
242   stats.interruption_count = ns.interruptionCount;
243   stats.total_interruption_duration_ms = ns.totalInterruptionDurationMs;
244 
245   auto ds = channel_receive_->GetDecodingCallStatistics();
246   stats.decoding_calls_to_silence_generator = ds.calls_to_silence_generator;
247   stats.decoding_calls_to_neteq = ds.calls_to_neteq;
248   stats.decoding_normal = ds.decoded_normal;
249   stats.decoding_plc = ds.decoded_neteq_plc;
250   stats.decoding_codec_plc = ds.decoded_codec_plc;
251   stats.decoding_cng = ds.decoded_cng;
252   stats.decoding_plc_cng = ds.decoded_plc_cng;
253   stats.decoding_muted_output = ds.decoded_muted_output;
254 
255   return stats;
256 }
257 
SetSink(AudioSinkInterface * sink)258 void AudioReceiveStream::SetSink(AudioSinkInterface* sink) {
259   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
260   channel_receive_->SetSink(sink);
261 }
262 
SetGain(float gain)263 void AudioReceiveStream::SetGain(float gain) {
264   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
265   channel_receive_->SetChannelOutputVolumeScaling(gain);
266 }
267 
SetBaseMinimumPlayoutDelayMs(int delay_ms)268 bool AudioReceiveStream::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
269   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
270   return channel_receive_->SetBaseMinimumPlayoutDelayMs(delay_ms);
271 }
272 
GetBaseMinimumPlayoutDelayMs() const273 int AudioReceiveStream::GetBaseMinimumPlayoutDelayMs() const {
274   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
275   return channel_receive_->GetBaseMinimumPlayoutDelayMs();
276 }
277 
GetSources() const278 std::vector<RtpSource> AudioReceiveStream::GetSources() const {
279   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
280   return source_tracker_.GetSources();
281 }
282 
GetAudioFrameWithInfo(int sample_rate_hz,AudioFrame * audio_frame)283 AudioMixer::Source::AudioFrameInfo AudioReceiveStream::GetAudioFrameWithInfo(
284     int sample_rate_hz,
285     AudioFrame* audio_frame) {
286   AudioMixer::Source::AudioFrameInfo audio_frame_info =
287       channel_receive_->GetAudioFrameWithInfo(sample_rate_hz, audio_frame);
288   if (audio_frame_info != AudioMixer::Source::AudioFrameInfo::kError) {
289     source_tracker_.OnFrameDelivered(audio_frame->packet_infos_);
290   }
291   return audio_frame_info;
292 }
293 
Ssrc() const294 int AudioReceiveStream::Ssrc() const {
295   return config_.rtp.remote_ssrc;
296 }
297 
PreferredSampleRate() const298 int AudioReceiveStream::PreferredSampleRate() const {
299   return channel_receive_->PreferredSampleRate();
300 }
301 
id() const302 uint32_t AudioReceiveStream::id() const {
303   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
304   return config_.rtp.remote_ssrc;
305 }
306 
GetInfo() const307 absl::optional<Syncable::Info> AudioReceiveStream::GetInfo() const {
308   RTC_DCHECK_RUN_ON(&module_process_thread_checker_);
309   absl::optional<Syncable::Info> info = channel_receive_->GetSyncInfo();
310 
311   if (!info)
312     return absl::nullopt;
313 
314   info->current_delay_ms = channel_receive_->GetDelayEstimate();
315   return info;
316 }
317 
GetPlayoutRtpTimestamp(uint32_t * rtp_timestamp,int64_t * time_ms) const318 bool AudioReceiveStream::GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp,
319                                                 int64_t* time_ms) const {
320   // Called on video capture thread.
321   return channel_receive_->GetPlayoutRtpTimestamp(rtp_timestamp, time_ms);
322 }
323 
SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,int64_t time_ms)324 void AudioReceiveStream::SetEstimatedPlayoutNtpTimestampMs(
325     int64_t ntp_timestamp_ms,
326     int64_t time_ms) {
327   // Called on video capture thread.
328   channel_receive_->SetEstimatedPlayoutNtpTimestampMs(ntp_timestamp_ms,
329                                                       time_ms);
330 }
331 
SetMinimumPlayoutDelay(int delay_ms)332 void AudioReceiveStream::SetMinimumPlayoutDelay(int delay_ms) {
333   RTC_DCHECK_RUN_ON(&module_process_thread_checker_);
334   return channel_receive_->SetMinimumPlayoutDelay(delay_ms);
335 }
336 
AssociateSendStream(AudioSendStream * send_stream)337 void AudioReceiveStream::AssociateSendStream(AudioSendStream* send_stream) {
338   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
339   channel_receive_->SetAssociatedSendChannel(
340       send_stream ? send_stream->GetChannel() : nullptr);
341   associated_send_stream_ = send_stream;
342 }
343 
DeliverRtcp(const uint8_t * packet,size_t length)344 void AudioReceiveStream::DeliverRtcp(const uint8_t* packet, size_t length) {
345   // TODO(solenberg): Tests call this function on a network thread, libjingle
346   // calls on the worker thread. We should move towards always using a network
347   // thread. Then this check can be enabled.
348   // RTC_DCHECK(!thread_checker_.IsCurrent());
349   channel_receive_->ReceivedRTCPPacket(packet, length);
350 }
351 
OnRtpPacket(const RtpPacketReceived & packet)352 void AudioReceiveStream::OnRtpPacket(const RtpPacketReceived& packet) {
353   // TODO(solenberg): Tests call this function on a network thread, libjingle
354   // calls on the worker thread. We should move towards always using a network
355   // thread. Then this check can be enabled.
356   // RTC_DCHECK(!thread_checker_.IsCurrent());
357   channel_receive_->OnRtpPacket(packet);
358 }
359 
config() const360 const webrtc::AudioReceiveStream::Config& AudioReceiveStream::config() const {
361   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
362   return config_;
363 }
364 
GetAssociatedSendStreamForTesting() const365 const AudioSendStream* AudioReceiveStream::GetAssociatedSendStreamForTesting()
366     const {
367   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
368   return associated_send_stream_;
369 }
370 
audio_state() const371 internal::AudioState* AudioReceiveStream::audio_state() const {
372   auto* audio_state = static_cast<internal::AudioState*>(audio_state_.get());
373   RTC_DCHECK(audio_state);
374   return audio_state;
375 }
376 
ConfigureStream(AudioReceiveStream * stream,const Config & new_config,bool first_time)377 void AudioReceiveStream::ConfigureStream(AudioReceiveStream* stream,
378                                          const Config& new_config,
379                                          bool first_time) {
380   RTC_LOG(LS_INFO) << "AudioReceiveStream::ConfigureStream: "
381                    << new_config.ToString();
382   RTC_DCHECK(stream);
383   const auto& channel_receive = stream->channel_receive_;
384   const auto& old_config = stream->config_;
385 
386   // Configuration parameters which cannot be changed.
387   RTC_DCHECK(first_time ||
388              old_config.rtp.remote_ssrc == new_config.rtp.remote_ssrc);
389   RTC_DCHECK(first_time ||
390              old_config.rtcp_send_transport == new_config.rtcp_send_transport);
391   // Decoder factory cannot be changed because it is configured at
392   // voe::Channel construction time.
393   RTC_DCHECK(first_time ||
394              old_config.decoder_factory == new_config.decoder_factory);
395 
396   if (!first_time) {
397     // SSRC can't be changed mid-stream.
398     RTC_DCHECK_EQ(old_config.rtp.local_ssrc, new_config.rtp.local_ssrc);
399     RTC_DCHECK_EQ(old_config.rtp.remote_ssrc, new_config.rtp.remote_ssrc);
400   }
401 
402   // TODO(solenberg): Config NACK history window (which is a packet count),
403   // using the actual packet size for the configured codec.
404   if (first_time || old_config.rtp.nack.rtp_history_ms !=
405                         new_config.rtp.nack.rtp_history_ms) {
406     channel_receive->SetNACKStatus(new_config.rtp.nack.rtp_history_ms != 0,
407                                    new_config.rtp.nack.rtp_history_ms / 20);
408   }
409   if (first_time || old_config.decoder_map != new_config.decoder_map) {
410     channel_receive->SetReceiveCodecs(new_config.decoder_map);
411   }
412 
413   if (first_time ||
414       old_config.frame_transformer != new_config.frame_transformer) {
415     channel_receive->SetDepacketizerToDecoderFrameTransformer(
416         new_config.frame_transformer);
417   }
418 
419   stream->config_ = new_config;
420 }
421 }  // namespace internal
422 }  // namespace webrtc
423