1 /*
2 * Copyright 2016 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 "pc/rtc_stats_collector.h"
12
13 #include <map>
14 #include <memory>
15 #include <string>
16 #include <utility>
17 #include <vector>
18
19 #include "api/candidate.h"
20 #include "api/media_stream_interface.h"
21 #include "api/peer_connection_interface.h"
22 #include "api/video/video_content_type.h"
23 #include "media/base/media_channel.h"
24 #include "p2p/base/p2p_constants.h"
25 #include "p2p/base/port.h"
26 #include "pc/peer_connection.h"
27 #include "pc/rtc_stats_traversal.h"
28 #include "pc/webrtc_sdp.h"
29 #include "rtc_base/checks.h"
30 #include "rtc_base/strings/string_builder.h"
31 #include "rtc_base/time_utils.h"
32 #include "rtc_base/trace_event.h"
33
34 namespace webrtc {
35
36 namespace {
37
38 // TODO(https://crbug.com/webrtc/10656): Consider making IDs less predictable.
RTCCertificateIDFromFingerprint(const std::string & fingerprint)39 std::string RTCCertificateIDFromFingerprint(const std::string& fingerprint) {
40 return "RTCCertificate_" + fingerprint;
41 }
42
RTCCodecStatsIDFromMidDirectionAndPayload(const std::string & mid,bool inbound,uint32_t payload_type)43 std::string RTCCodecStatsIDFromMidDirectionAndPayload(const std::string& mid,
44 bool inbound,
45 uint32_t payload_type) {
46 char buf[1024];
47 rtc::SimpleStringBuilder sb(buf);
48 sb << "RTCCodec_" << mid << (inbound ? "_Inbound_" : "_Outbound_")
49 << payload_type;
50 return sb.str();
51 }
52
RTCIceCandidatePairStatsIDFromConnectionInfo(const cricket::ConnectionInfo & info)53 std::string RTCIceCandidatePairStatsIDFromConnectionInfo(
54 const cricket::ConnectionInfo& info) {
55 char buf[4096];
56 rtc::SimpleStringBuilder sb(buf);
57 sb << "RTCIceCandidatePair_" << info.local_candidate.id() << "_"
58 << info.remote_candidate.id();
59 return sb.str();
60 }
61
62 const char kSender[] = "sender";
63 const char kReceiver[] = "receiver";
64
RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(const char * direction,int attachment_id)65 std::string RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
66 const char* direction,
67 int attachment_id) {
68 char buf[1024];
69 rtc::SimpleStringBuilder sb(buf);
70 sb << "RTCMediaStreamTrack_" << direction << "_" << attachment_id;
71 return sb.str();
72 }
73
RTCTransportStatsIDFromTransportChannel(const std::string & transport_name,int channel_component)74 std::string RTCTransportStatsIDFromTransportChannel(
75 const std::string& transport_name,
76 int channel_component) {
77 char buf[1024];
78 rtc::SimpleStringBuilder sb(buf);
79 sb << "RTCTransport_" << transport_name << "_" << channel_component;
80 return sb.str();
81 }
82
RTCInboundRTPStreamStatsIDFromSSRC(bool audio,uint32_t ssrc)83 std::string RTCInboundRTPStreamStatsIDFromSSRC(bool audio, uint32_t ssrc) {
84 char buf[1024];
85 rtc::SimpleStringBuilder sb(buf);
86 sb << "RTCInboundRTP" << (audio ? "Audio" : "Video") << "Stream_" << ssrc;
87 return sb.str();
88 }
89
RTCOutboundRTPStreamStatsIDFromSSRC(bool audio,uint32_t ssrc)90 std::string RTCOutboundRTPStreamStatsIDFromSSRC(bool audio, uint32_t ssrc) {
91 char buf[1024];
92 rtc::SimpleStringBuilder sb(buf);
93 sb << "RTCOutboundRTP" << (audio ? "Audio" : "Video") << "Stream_" << ssrc;
94 return sb.str();
95 }
96
RTCRemoteInboundRtpStreamStatsIdFromSourceSsrc(cricket::MediaType media_type,uint32_t source_ssrc)97 std::string RTCRemoteInboundRtpStreamStatsIdFromSourceSsrc(
98 cricket::MediaType media_type,
99 uint32_t source_ssrc) {
100 char buf[1024];
101 rtc::SimpleStringBuilder sb(buf);
102 sb << "RTCRemoteInboundRtp"
103 << (media_type == cricket::MEDIA_TYPE_AUDIO ? "Audio" : "Video")
104 << "Stream_" << source_ssrc;
105 return sb.str();
106 }
107
RTCMediaSourceStatsIDFromKindAndAttachment(cricket::MediaType media_type,int attachment_id)108 std::string RTCMediaSourceStatsIDFromKindAndAttachment(
109 cricket::MediaType media_type,
110 int attachment_id) {
111 char buf[1024];
112 rtc::SimpleStringBuilder sb(buf);
113 sb << "RTC" << (media_type == cricket::MEDIA_TYPE_AUDIO ? "Audio" : "Video")
114 << "Source_" << attachment_id;
115 return sb.str();
116 }
117
CandidateTypeToRTCIceCandidateType(const std::string & type)118 const char* CandidateTypeToRTCIceCandidateType(const std::string& type) {
119 if (type == cricket::LOCAL_PORT_TYPE)
120 return RTCIceCandidateType::kHost;
121 if (type == cricket::STUN_PORT_TYPE)
122 return RTCIceCandidateType::kSrflx;
123 if (type == cricket::PRFLX_PORT_TYPE)
124 return RTCIceCandidateType::kPrflx;
125 if (type == cricket::RELAY_PORT_TYPE)
126 return RTCIceCandidateType::kRelay;
127 RTC_NOTREACHED();
128 return nullptr;
129 }
130
DataStateToRTCDataChannelState(DataChannelInterface::DataState state)131 const char* DataStateToRTCDataChannelState(
132 DataChannelInterface::DataState state) {
133 switch (state) {
134 case DataChannelInterface::kConnecting:
135 return RTCDataChannelState::kConnecting;
136 case DataChannelInterface::kOpen:
137 return RTCDataChannelState::kOpen;
138 case DataChannelInterface::kClosing:
139 return RTCDataChannelState::kClosing;
140 case DataChannelInterface::kClosed:
141 return RTCDataChannelState::kClosed;
142 default:
143 RTC_NOTREACHED();
144 return nullptr;
145 }
146 }
147
IceCandidatePairStateToRTCStatsIceCandidatePairState(cricket::IceCandidatePairState state)148 const char* IceCandidatePairStateToRTCStatsIceCandidatePairState(
149 cricket::IceCandidatePairState state) {
150 switch (state) {
151 case cricket::IceCandidatePairState::WAITING:
152 return RTCStatsIceCandidatePairState::kWaiting;
153 case cricket::IceCandidatePairState::IN_PROGRESS:
154 return RTCStatsIceCandidatePairState::kInProgress;
155 case cricket::IceCandidatePairState::SUCCEEDED:
156 return RTCStatsIceCandidatePairState::kSucceeded;
157 case cricket::IceCandidatePairState::FAILED:
158 return RTCStatsIceCandidatePairState::kFailed;
159 default:
160 RTC_NOTREACHED();
161 return nullptr;
162 }
163 }
164
DtlsTransportStateToRTCDtlsTransportState(cricket::DtlsTransportState state)165 const char* DtlsTransportStateToRTCDtlsTransportState(
166 cricket::DtlsTransportState state) {
167 switch (state) {
168 case cricket::DTLS_TRANSPORT_NEW:
169 return RTCDtlsTransportState::kNew;
170 case cricket::DTLS_TRANSPORT_CONNECTING:
171 return RTCDtlsTransportState::kConnecting;
172 case cricket::DTLS_TRANSPORT_CONNECTED:
173 return RTCDtlsTransportState::kConnected;
174 case cricket::DTLS_TRANSPORT_CLOSED:
175 return RTCDtlsTransportState::kClosed;
176 case cricket::DTLS_TRANSPORT_FAILED:
177 return RTCDtlsTransportState::kFailed;
178 default:
179 RTC_NOTREACHED();
180 return nullptr;
181 }
182 }
183
NetworkAdapterTypeToStatsType(rtc::AdapterType type)184 const char* NetworkAdapterTypeToStatsType(rtc::AdapterType type) {
185 switch (type) {
186 case rtc::ADAPTER_TYPE_CELLULAR:
187 case rtc::ADAPTER_TYPE_CELLULAR_2G:
188 case rtc::ADAPTER_TYPE_CELLULAR_3G:
189 case rtc::ADAPTER_TYPE_CELLULAR_4G:
190 case rtc::ADAPTER_TYPE_CELLULAR_5G:
191 return RTCNetworkType::kCellular;
192 case rtc::ADAPTER_TYPE_ETHERNET:
193 return RTCNetworkType::kEthernet;
194 case rtc::ADAPTER_TYPE_WIFI:
195 return RTCNetworkType::kWifi;
196 case rtc::ADAPTER_TYPE_VPN:
197 return RTCNetworkType::kVpn;
198 case rtc::ADAPTER_TYPE_UNKNOWN:
199 case rtc::ADAPTER_TYPE_LOOPBACK:
200 case rtc::ADAPTER_TYPE_ANY:
201 return RTCNetworkType::kUnknown;
202 }
203 RTC_NOTREACHED();
204 return nullptr;
205 }
206
QualityLimitationReasonToRTCQualityLimitationReason(QualityLimitationReason reason)207 const char* QualityLimitationReasonToRTCQualityLimitationReason(
208 QualityLimitationReason reason) {
209 switch (reason) {
210 case QualityLimitationReason::kNone:
211 return RTCQualityLimitationReason::kNone;
212 case QualityLimitationReason::kCpu:
213 return RTCQualityLimitationReason::kCpu;
214 case QualityLimitationReason::kBandwidth:
215 return RTCQualityLimitationReason::kBandwidth;
216 case QualityLimitationReason::kOther:
217 return RTCQualityLimitationReason::kOther;
218 }
219 RTC_CHECK_NOTREACHED();
220 }
221
DoubleAudioLevelFromIntAudioLevel(int audio_level)222 double DoubleAudioLevelFromIntAudioLevel(int audio_level) {
223 RTC_DCHECK_GE(audio_level, 0);
224 RTC_DCHECK_LE(audio_level, 32767);
225 return audio_level / 32767.0;
226 }
227
CodecStatsFromRtpCodecParameters(uint64_t timestamp_us,const std::string & mid,bool inbound,const RtpCodecParameters & codec_params)228 std::unique_ptr<RTCCodecStats> CodecStatsFromRtpCodecParameters(
229 uint64_t timestamp_us,
230 const std::string& mid,
231 bool inbound,
232 const RtpCodecParameters& codec_params) {
233 RTC_DCHECK_GE(codec_params.payload_type, 0);
234 RTC_DCHECK_LE(codec_params.payload_type, 127);
235 RTC_DCHECK(codec_params.clock_rate);
236 uint32_t payload_type = static_cast<uint32_t>(codec_params.payload_type);
237 std::unique_ptr<RTCCodecStats> codec_stats(new RTCCodecStats(
238 RTCCodecStatsIDFromMidDirectionAndPayload(mid, inbound, payload_type),
239 timestamp_us));
240 codec_stats->payload_type = payload_type;
241 codec_stats->mime_type = codec_params.mime_type();
242 if (codec_params.clock_rate) {
243 codec_stats->clock_rate = static_cast<uint32_t>(*codec_params.clock_rate);
244 }
245 if (codec_params.num_channels) {
246 codec_stats->channels = *codec_params.num_channels;
247 }
248
249 rtc::StringBuilder fmtp;
250 if (WriteFmtpParameters(codec_params.parameters, &fmtp)) {
251 codec_stats->sdp_fmtp_line = fmtp.Release();
252 }
253 return codec_stats;
254 }
255
SetMediaStreamTrackStatsFromMediaStreamTrackInterface(const MediaStreamTrackInterface & track,RTCMediaStreamTrackStats * track_stats)256 void SetMediaStreamTrackStatsFromMediaStreamTrackInterface(
257 const MediaStreamTrackInterface& track,
258 RTCMediaStreamTrackStats* track_stats) {
259 track_stats->track_identifier = track.id();
260 track_stats->ended = (track.state() == MediaStreamTrackInterface::kEnded);
261 }
262
263 // Provides the media independent counters (both audio and video).
SetInboundRTPStreamStatsFromMediaReceiverInfo(const cricket::MediaReceiverInfo & media_receiver_info,RTCInboundRTPStreamStats * inbound_stats)264 void SetInboundRTPStreamStatsFromMediaReceiverInfo(
265 const cricket::MediaReceiverInfo& media_receiver_info,
266 RTCInboundRTPStreamStats* inbound_stats) {
267 RTC_DCHECK(inbound_stats);
268 inbound_stats->ssrc = media_receiver_info.ssrc();
269 // TODO(hbos): Support the remote case. https://crbug.com/657855
270 inbound_stats->is_remote = false;
271 inbound_stats->packets_received =
272 static_cast<uint32_t>(media_receiver_info.packets_rcvd);
273 inbound_stats->bytes_received =
274 static_cast<uint64_t>(media_receiver_info.payload_bytes_rcvd);
275 inbound_stats->header_bytes_received =
276 static_cast<uint64_t>(media_receiver_info.header_and_padding_bytes_rcvd);
277 inbound_stats->packets_lost =
278 static_cast<int32_t>(media_receiver_info.packets_lost);
279 }
280
SetInboundRTPStreamStatsFromVoiceReceiverInfo(const std::string & mid,const cricket::VoiceReceiverInfo & voice_receiver_info,RTCInboundRTPStreamStats * inbound_audio)281 void SetInboundRTPStreamStatsFromVoiceReceiverInfo(
282 const std::string& mid,
283 const cricket::VoiceReceiverInfo& voice_receiver_info,
284 RTCInboundRTPStreamStats* inbound_audio) {
285 SetInboundRTPStreamStatsFromMediaReceiverInfo(voice_receiver_info,
286 inbound_audio);
287 inbound_audio->media_type = "audio";
288 inbound_audio->kind = "audio";
289 if (voice_receiver_info.codec_payload_type) {
290 inbound_audio->codec_id = RTCCodecStatsIDFromMidDirectionAndPayload(
291 mid, true, *voice_receiver_info.codec_payload_type);
292 }
293 inbound_audio->jitter = static_cast<double>(voice_receiver_info.jitter_ms) /
294 rtc::kNumMillisecsPerSec;
295 inbound_audio->jitter_buffer_delay =
296 voice_receiver_info.jitter_buffer_delay_seconds;
297 inbound_audio->jitter_buffer_emitted_count =
298 voice_receiver_info.jitter_buffer_emitted_count;
299 inbound_audio->total_samples_received =
300 voice_receiver_info.total_samples_received;
301 inbound_audio->concealed_samples = voice_receiver_info.concealed_samples;
302 inbound_audio->silent_concealed_samples =
303 voice_receiver_info.silent_concealed_samples;
304 inbound_audio->concealment_events = voice_receiver_info.concealment_events;
305 inbound_audio->inserted_samples_for_deceleration =
306 voice_receiver_info.inserted_samples_for_deceleration;
307 inbound_audio->removed_samples_for_acceleration =
308 voice_receiver_info.removed_samples_for_acceleration;
309 if (voice_receiver_info.audio_level >= 0) {
310 inbound_audio->audio_level =
311 DoubleAudioLevelFromIntAudioLevel(voice_receiver_info.audio_level);
312 }
313 inbound_audio->total_audio_energy = voice_receiver_info.total_output_energy;
314 inbound_audio->total_samples_duration =
315 voice_receiver_info.total_output_duration;
316 // |fir_count|, |pli_count| and |sli_count| are only valid for video and are
317 // purposefully left undefined for audio.
318 if (voice_receiver_info.last_packet_received_timestamp_ms) {
319 inbound_audio->last_packet_received_timestamp =
320 static_cast<double>(
321 *voice_receiver_info.last_packet_received_timestamp_ms) /
322 rtc::kNumMillisecsPerSec;
323 }
324 if (voice_receiver_info.estimated_playout_ntp_timestamp_ms) {
325 inbound_audio->estimated_playout_timestamp = static_cast<double>(
326 *voice_receiver_info.estimated_playout_ntp_timestamp_ms);
327 }
328 inbound_audio->fec_packets_received =
329 voice_receiver_info.fec_packets_received;
330 inbound_audio->fec_packets_discarded =
331 voice_receiver_info.fec_packets_discarded;
332 }
333
SetInboundRTPStreamStatsFromVideoReceiverInfo(const std::string & mid,const cricket::VideoReceiverInfo & video_receiver_info,RTCInboundRTPStreamStats * inbound_video)334 void SetInboundRTPStreamStatsFromVideoReceiverInfo(
335 const std::string& mid,
336 const cricket::VideoReceiverInfo& video_receiver_info,
337 RTCInboundRTPStreamStats* inbound_video) {
338 SetInboundRTPStreamStatsFromMediaReceiverInfo(video_receiver_info,
339 inbound_video);
340 inbound_video->media_type = "video";
341 inbound_video->kind = "video";
342 if (video_receiver_info.codec_payload_type) {
343 inbound_video->codec_id = RTCCodecStatsIDFromMidDirectionAndPayload(
344 mid, true, *video_receiver_info.codec_payload_type);
345 }
346 inbound_video->fir_count =
347 static_cast<uint32_t>(video_receiver_info.firs_sent);
348 inbound_video->pli_count =
349 static_cast<uint32_t>(video_receiver_info.plis_sent);
350 inbound_video->nack_count =
351 static_cast<uint32_t>(video_receiver_info.nacks_sent);
352 inbound_video->frames_received = video_receiver_info.frames_received;
353 inbound_video->frames_decoded = video_receiver_info.frames_decoded;
354 inbound_video->frames_dropped = video_receiver_info.frames_dropped;
355 inbound_video->key_frames_decoded = video_receiver_info.key_frames_decoded;
356 if (video_receiver_info.frame_width > 0) {
357 inbound_video->frame_width =
358 static_cast<uint32_t>(video_receiver_info.frame_width);
359 }
360 if (video_receiver_info.frame_height > 0) {
361 inbound_video->frame_height =
362 static_cast<uint32_t>(video_receiver_info.frame_height);
363 }
364 if (video_receiver_info.framerate_rcvd > 0) {
365 inbound_video->frames_per_second = video_receiver_info.framerate_rcvd;
366 }
367 if (video_receiver_info.qp_sum)
368 inbound_video->qp_sum = *video_receiver_info.qp_sum;
369 inbound_video->total_decode_time =
370 static_cast<double>(video_receiver_info.total_decode_time_ms) /
371 rtc::kNumMillisecsPerSec;
372 inbound_video->total_inter_frame_delay =
373 video_receiver_info.total_inter_frame_delay;
374 inbound_video->total_squared_inter_frame_delay =
375 video_receiver_info.total_squared_inter_frame_delay;
376 if (video_receiver_info.last_packet_received_timestamp_ms) {
377 inbound_video->last_packet_received_timestamp =
378 static_cast<double>(
379 *video_receiver_info.last_packet_received_timestamp_ms) /
380 rtc::kNumMillisecsPerSec;
381 }
382 if (video_receiver_info.estimated_playout_ntp_timestamp_ms) {
383 inbound_video->estimated_playout_timestamp = static_cast<double>(
384 *video_receiver_info.estimated_playout_ntp_timestamp_ms);
385 }
386 // TODO(https://crbug.com/webrtc/10529): When info's |content_info| is
387 // optional, support the "unspecified" value.
388 if (video_receiver_info.content_type == VideoContentType::SCREENSHARE)
389 inbound_video->content_type = RTCContentType::kScreenshare;
390 if (!video_receiver_info.decoder_implementation_name.empty()) {
391 inbound_video->decoder_implementation =
392 video_receiver_info.decoder_implementation_name;
393 }
394 }
395
396 // Provides the media independent counters (both audio and video).
SetOutboundRTPStreamStatsFromMediaSenderInfo(const cricket::MediaSenderInfo & media_sender_info,RTCOutboundRTPStreamStats * outbound_stats)397 void SetOutboundRTPStreamStatsFromMediaSenderInfo(
398 const cricket::MediaSenderInfo& media_sender_info,
399 RTCOutboundRTPStreamStats* outbound_stats) {
400 RTC_DCHECK(outbound_stats);
401 outbound_stats->ssrc = media_sender_info.ssrc();
402 // TODO(hbos): Support the remote case. https://crbug.com/657856
403 outbound_stats->is_remote = false;
404 outbound_stats->packets_sent =
405 static_cast<uint32_t>(media_sender_info.packets_sent);
406 outbound_stats->retransmitted_packets_sent =
407 media_sender_info.retransmitted_packets_sent;
408 outbound_stats->bytes_sent =
409 static_cast<uint64_t>(media_sender_info.payload_bytes_sent);
410 outbound_stats->header_bytes_sent =
411 static_cast<uint64_t>(media_sender_info.header_and_padding_bytes_sent);
412 outbound_stats->retransmitted_bytes_sent =
413 media_sender_info.retransmitted_bytes_sent;
414 }
415
SetOutboundRTPStreamStatsFromVoiceSenderInfo(const std::string & mid,const cricket::VoiceSenderInfo & voice_sender_info,RTCOutboundRTPStreamStats * outbound_audio)416 void SetOutboundRTPStreamStatsFromVoiceSenderInfo(
417 const std::string& mid,
418 const cricket::VoiceSenderInfo& voice_sender_info,
419 RTCOutboundRTPStreamStats* outbound_audio) {
420 SetOutboundRTPStreamStatsFromMediaSenderInfo(voice_sender_info,
421 outbound_audio);
422 outbound_audio->media_type = "audio";
423 outbound_audio->kind = "audio";
424 if (voice_sender_info.codec_payload_type) {
425 outbound_audio->codec_id = RTCCodecStatsIDFromMidDirectionAndPayload(
426 mid, false, *voice_sender_info.codec_payload_type);
427 }
428 // |fir_count|, |pli_count| and |sli_count| are only valid for video and are
429 // purposefully left undefined for audio.
430 }
431
SetOutboundRTPStreamStatsFromVideoSenderInfo(const std::string & mid,const cricket::VideoSenderInfo & video_sender_info,RTCOutboundRTPStreamStats * outbound_video)432 void SetOutboundRTPStreamStatsFromVideoSenderInfo(
433 const std::string& mid,
434 const cricket::VideoSenderInfo& video_sender_info,
435 RTCOutboundRTPStreamStats* outbound_video) {
436 SetOutboundRTPStreamStatsFromMediaSenderInfo(video_sender_info,
437 outbound_video);
438 outbound_video->media_type = "video";
439 outbound_video->kind = "video";
440 if (video_sender_info.codec_payload_type) {
441 outbound_video->codec_id = RTCCodecStatsIDFromMidDirectionAndPayload(
442 mid, false, *video_sender_info.codec_payload_type);
443 }
444 outbound_video->fir_count =
445 static_cast<uint32_t>(video_sender_info.firs_rcvd);
446 outbound_video->pli_count =
447 static_cast<uint32_t>(video_sender_info.plis_rcvd);
448 outbound_video->nack_count =
449 static_cast<uint32_t>(video_sender_info.nacks_rcvd);
450 if (video_sender_info.qp_sum)
451 outbound_video->qp_sum = *video_sender_info.qp_sum;
452 outbound_video->frames_encoded = video_sender_info.frames_encoded;
453 outbound_video->key_frames_encoded = video_sender_info.key_frames_encoded;
454 outbound_video->total_encode_time =
455 static_cast<double>(video_sender_info.total_encode_time_ms) /
456 rtc::kNumMillisecsPerSec;
457 outbound_video->total_encoded_bytes_target =
458 video_sender_info.total_encoded_bytes_target;
459 if (video_sender_info.send_frame_width > 0) {
460 outbound_video->frame_width =
461 static_cast<uint32_t>(video_sender_info.send_frame_width);
462 }
463 if (video_sender_info.send_frame_height > 0) {
464 outbound_video->frame_height =
465 static_cast<uint32_t>(video_sender_info.send_frame_height);
466 }
467 if (video_sender_info.framerate_sent > 0) {
468 outbound_video->frames_per_second = video_sender_info.framerate_sent;
469 }
470 outbound_video->frames_sent = video_sender_info.frames_sent;
471 outbound_video->huge_frames_sent = video_sender_info.huge_frames_sent;
472 outbound_video->total_packet_send_delay =
473 static_cast<double>(video_sender_info.total_packet_send_delay_ms) /
474 rtc::kNumMillisecsPerSec;
475 outbound_video->quality_limitation_reason =
476 QualityLimitationReasonToRTCQualityLimitationReason(
477 video_sender_info.quality_limitation_reason);
478 outbound_video->quality_limitation_resolution_changes =
479 video_sender_info.quality_limitation_resolution_changes;
480 // TODO(https://crbug.com/webrtc/10529): When info's |content_info| is
481 // optional, support the "unspecified" value.
482 if (video_sender_info.content_type == VideoContentType::SCREENSHARE)
483 outbound_video->content_type = RTCContentType::kScreenshare;
484 if (!video_sender_info.encoder_implementation_name.empty()) {
485 outbound_video->encoder_implementation =
486 video_sender_info.encoder_implementation_name;
487 }
488 if (video_sender_info.rid) {
489 outbound_video->rid = *video_sender_info.rid;
490 }
491 }
492
493 std::unique_ptr<RTCRemoteInboundRtpStreamStats>
ProduceRemoteInboundRtpStreamStatsFromReportBlockData(const ReportBlockData & report_block_data,cricket::MediaType media_type,const std::map<std::string,RTCOutboundRTPStreamStats * > & outbound_rtps,const RTCStatsReport & report)494 ProduceRemoteInboundRtpStreamStatsFromReportBlockData(
495 const ReportBlockData& report_block_data,
496 cricket::MediaType media_type,
497 const std::map<std::string, RTCOutboundRTPStreamStats*>& outbound_rtps,
498 const RTCStatsReport& report) {
499 const auto& report_block = report_block_data.report_block();
500 // RTCStats' timestamp generally refers to when the metric was sampled, but
501 // for "remote-[outbound/inbound]-rtp" it refers to the local time when the
502 // Report Block was received.
503 auto remote_inbound = std::make_unique<RTCRemoteInboundRtpStreamStats>(
504 RTCRemoteInboundRtpStreamStatsIdFromSourceSsrc(media_type,
505 report_block.source_ssrc),
506 /*timestamp=*/report_block_data.report_block_timestamp_utc_us());
507 remote_inbound->ssrc = report_block.source_ssrc;
508 remote_inbound->kind =
509 media_type == cricket::MEDIA_TYPE_AUDIO ? "audio" : "video";
510 remote_inbound->packets_lost = report_block.packets_lost;
511 remote_inbound->round_trip_time =
512 static_cast<double>(report_block_data.last_rtt_ms()) /
513 rtc::kNumMillisecsPerSec;
514
515 std::string local_id = RTCOutboundRTPStreamStatsIDFromSSRC(
516 media_type == cricket::MEDIA_TYPE_AUDIO, report_block.source_ssrc);
517 // Look up local stat from |outbound_rtps| where the pointers are non-const.
518 auto local_id_it = outbound_rtps.find(local_id);
519 if (local_id_it != outbound_rtps.end()) {
520 remote_inbound->local_id = local_id;
521 auto& outbound_rtp = *local_id_it->second;
522 outbound_rtp.remote_id = remote_inbound->id();
523 // The RTP/RTCP transport is obtained from the
524 // RTCOutboundRtpStreamStats's transport.
525 const auto* transport_from_id = outbound_rtp.transport_id.is_defined()
526 ? report.Get(*outbound_rtp.transport_id)
527 : nullptr;
528 if (transport_from_id) {
529 const auto& transport = transport_from_id->cast_to<RTCTransportStats>();
530 // If RTP and RTCP are not multiplexed, there is a separate RTCP
531 // transport paired with the RTP transport, otherwise the same
532 // transport is used for RTCP and RTP.
533 remote_inbound->transport_id =
534 transport.rtcp_transport_stats_id.is_defined()
535 ? *transport.rtcp_transport_stats_id
536 : *outbound_rtp.transport_id;
537 }
538 // We're assuming the same codec is used on both ends. However if the
539 // codec is switched out on the fly we may have received a Report Block
540 // based on the previous codec and there is no way to tell which point in
541 // time the codec changed for the remote end.
542 const auto* codec_from_id = outbound_rtp.codec_id.is_defined()
543 ? report.Get(*outbound_rtp.codec_id)
544 : nullptr;
545 if (codec_from_id) {
546 remote_inbound->codec_id = *outbound_rtp.codec_id;
547 const auto& codec = codec_from_id->cast_to<RTCCodecStats>();
548 if (codec.clock_rate.is_defined()) {
549 // The Report Block jitter is expressed in RTP timestamp units
550 // (https://tools.ietf.org/html/rfc3550#section-6.4.1). To convert this
551 // to seconds we divide by the codec's clock rate.
552 remote_inbound->jitter =
553 static_cast<double>(report_block.jitter) / *codec.clock_rate;
554 }
555 }
556 }
557 return remote_inbound;
558 }
559
ProduceCertificateStatsFromSSLCertificateStats(int64_t timestamp_us,const rtc::SSLCertificateStats & certificate_stats,RTCStatsReport * report)560 void ProduceCertificateStatsFromSSLCertificateStats(
561 int64_t timestamp_us,
562 const rtc::SSLCertificateStats& certificate_stats,
563 RTCStatsReport* report) {
564 RTCCertificateStats* prev_certificate_stats = nullptr;
565 for (const rtc::SSLCertificateStats* s = &certificate_stats; s;
566 s = s->issuer.get()) {
567 std::string certificate_stats_id =
568 RTCCertificateIDFromFingerprint(s->fingerprint);
569 // It is possible for the same certificate to show up multiple times, e.g.
570 // if local and remote side use the same certificate in a loopback call.
571 // If the report already contains stats for this certificate, skip it.
572 if (report->Get(certificate_stats_id)) {
573 RTC_DCHECK_EQ(s, &certificate_stats);
574 break;
575 }
576 RTCCertificateStats* certificate_stats =
577 new RTCCertificateStats(certificate_stats_id, timestamp_us);
578 certificate_stats->fingerprint = s->fingerprint;
579 certificate_stats->fingerprint_algorithm = s->fingerprint_algorithm;
580 certificate_stats->base64_certificate = s->base64_certificate;
581 if (prev_certificate_stats)
582 prev_certificate_stats->issuer_certificate_id = certificate_stats->id();
583 report->AddStats(std::unique_ptr<RTCCertificateStats>(certificate_stats));
584 prev_certificate_stats = certificate_stats;
585 }
586 }
587
ProduceIceCandidateStats(int64_t timestamp_us,const cricket::Candidate & candidate,bool is_local,const std::string & transport_id,RTCStatsReport * report)588 const std::string& ProduceIceCandidateStats(int64_t timestamp_us,
589 const cricket::Candidate& candidate,
590 bool is_local,
591 const std::string& transport_id,
592 RTCStatsReport* report) {
593 const std::string& id = "RTCIceCandidate_" + candidate.id();
594 const RTCStats* stats = report->Get(id);
595 if (!stats) {
596 std::unique_ptr<RTCIceCandidateStats> candidate_stats;
597 if (is_local)
598 candidate_stats.reset(new RTCLocalIceCandidateStats(id, timestamp_us));
599 else
600 candidate_stats.reset(new RTCRemoteIceCandidateStats(id, timestamp_us));
601 candidate_stats->transport_id = transport_id;
602 if (is_local) {
603 candidate_stats->network_type =
604 NetworkAdapterTypeToStatsType(candidate.network_type());
605 if (candidate.type() == cricket::RELAY_PORT_TYPE) {
606 std::string relay_protocol = candidate.relay_protocol();
607 RTC_DCHECK(relay_protocol.compare("udp") == 0 ||
608 relay_protocol.compare("tcp") == 0 ||
609 relay_protocol.compare("tls") == 0);
610 candidate_stats->relay_protocol = relay_protocol;
611 }
612 } else {
613 // We don't expect to know the adapter type of remote candidates.
614 RTC_DCHECK_EQ(rtc::ADAPTER_TYPE_UNKNOWN, candidate.network_type());
615 }
616 candidate_stats->ip = candidate.address().ipaddr().ToString();
617 candidate_stats->port = static_cast<int32_t>(candidate.address().port());
618 candidate_stats->protocol = candidate.protocol();
619 candidate_stats->candidate_type =
620 CandidateTypeToRTCIceCandidateType(candidate.type());
621 candidate_stats->priority = static_cast<int32_t>(candidate.priority());
622
623 stats = candidate_stats.get();
624 report->AddStats(std::move(candidate_stats));
625 }
626 RTC_DCHECK_EQ(stats->type(), is_local ? RTCLocalIceCandidateStats::kType
627 : RTCRemoteIceCandidateStats::kType);
628 return stats->id();
629 }
630
631 std::unique_ptr<RTCMediaStreamTrackStats>
ProduceMediaStreamTrackStatsFromVoiceSenderInfo(int64_t timestamp_us,const AudioTrackInterface & audio_track,const cricket::VoiceSenderInfo & voice_sender_info,int attachment_id)632 ProduceMediaStreamTrackStatsFromVoiceSenderInfo(
633 int64_t timestamp_us,
634 const AudioTrackInterface& audio_track,
635 const cricket::VoiceSenderInfo& voice_sender_info,
636 int attachment_id) {
637 std::unique_ptr<RTCMediaStreamTrackStats> audio_track_stats(
638 new RTCMediaStreamTrackStats(
639 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(kSender,
640 attachment_id),
641 timestamp_us, RTCMediaStreamTrackKind::kAudio));
642 SetMediaStreamTrackStatsFromMediaStreamTrackInterface(
643 audio_track, audio_track_stats.get());
644 audio_track_stats->media_source_id =
645 RTCMediaSourceStatsIDFromKindAndAttachment(cricket::MEDIA_TYPE_AUDIO,
646 attachment_id);
647 audio_track_stats->remote_source = false;
648 audio_track_stats->detached = false;
649 if (voice_sender_info.apm_statistics.echo_return_loss) {
650 audio_track_stats->echo_return_loss =
651 *voice_sender_info.apm_statistics.echo_return_loss;
652 }
653 if (voice_sender_info.apm_statistics.echo_return_loss_enhancement) {
654 audio_track_stats->echo_return_loss_enhancement =
655 *voice_sender_info.apm_statistics.echo_return_loss_enhancement;
656 }
657 return audio_track_stats;
658 }
659
660 std::unique_ptr<RTCMediaStreamTrackStats>
ProduceMediaStreamTrackStatsFromVoiceReceiverInfo(int64_t timestamp_us,const AudioTrackInterface & audio_track,const cricket::VoiceReceiverInfo & voice_receiver_info,int attachment_id)661 ProduceMediaStreamTrackStatsFromVoiceReceiverInfo(
662 int64_t timestamp_us,
663 const AudioTrackInterface& audio_track,
664 const cricket::VoiceReceiverInfo& voice_receiver_info,
665 int attachment_id) {
666 // Since receiver tracks can't be reattached, we use the SSRC as
667 // an attachment identifier.
668 std::unique_ptr<RTCMediaStreamTrackStats> audio_track_stats(
669 new RTCMediaStreamTrackStats(
670 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(kReceiver,
671 attachment_id),
672 timestamp_us, RTCMediaStreamTrackKind::kAudio));
673 SetMediaStreamTrackStatsFromMediaStreamTrackInterface(
674 audio_track, audio_track_stats.get());
675 audio_track_stats->remote_source = true;
676 audio_track_stats->detached = false;
677 if (voice_receiver_info.audio_level >= 0) {
678 audio_track_stats->audio_level =
679 DoubleAudioLevelFromIntAudioLevel(voice_receiver_info.audio_level);
680 }
681 audio_track_stats->jitter_buffer_delay =
682 voice_receiver_info.jitter_buffer_delay_seconds;
683 audio_track_stats->jitter_buffer_emitted_count =
684 voice_receiver_info.jitter_buffer_emitted_count;
685 audio_track_stats->inserted_samples_for_deceleration =
686 voice_receiver_info.inserted_samples_for_deceleration;
687 audio_track_stats->removed_samples_for_acceleration =
688 voice_receiver_info.removed_samples_for_acceleration;
689 audio_track_stats->total_audio_energy =
690 voice_receiver_info.total_output_energy;
691 audio_track_stats->total_samples_received =
692 voice_receiver_info.total_samples_received;
693 audio_track_stats->total_samples_duration =
694 voice_receiver_info.total_output_duration;
695 audio_track_stats->concealed_samples = voice_receiver_info.concealed_samples;
696 audio_track_stats->silent_concealed_samples =
697 voice_receiver_info.silent_concealed_samples;
698 audio_track_stats->concealment_events =
699 voice_receiver_info.concealment_events;
700 audio_track_stats->jitter_buffer_flushes =
701 voice_receiver_info.jitter_buffer_flushes;
702 audio_track_stats->delayed_packet_outage_samples =
703 voice_receiver_info.delayed_packet_outage_samples;
704 audio_track_stats->relative_packet_arrival_delay =
705 voice_receiver_info.relative_packet_arrival_delay_seconds;
706 audio_track_stats->jitter_buffer_target_delay =
707 voice_receiver_info.jitter_buffer_target_delay_seconds;
708 audio_track_stats->interruption_count =
709 voice_receiver_info.interruption_count >= 0
710 ? voice_receiver_info.interruption_count
711 : 0;
712 audio_track_stats->total_interruption_duration =
713 static_cast<double>(voice_receiver_info.total_interruption_duration_ms) /
714 rtc::kNumMillisecsPerSec;
715 return audio_track_stats;
716 }
717
718 std::unique_ptr<RTCMediaStreamTrackStats>
ProduceMediaStreamTrackStatsFromVideoSenderInfo(int64_t timestamp_us,const VideoTrackInterface & video_track,const cricket::VideoSenderInfo & video_sender_info,int attachment_id)719 ProduceMediaStreamTrackStatsFromVideoSenderInfo(
720 int64_t timestamp_us,
721 const VideoTrackInterface& video_track,
722 const cricket::VideoSenderInfo& video_sender_info,
723 int attachment_id) {
724 std::unique_ptr<RTCMediaStreamTrackStats> video_track_stats(
725 new RTCMediaStreamTrackStats(
726 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(kSender,
727 attachment_id),
728 timestamp_us, RTCMediaStreamTrackKind::kVideo));
729 SetMediaStreamTrackStatsFromMediaStreamTrackInterface(
730 video_track, video_track_stats.get());
731 video_track_stats->media_source_id =
732 RTCMediaSourceStatsIDFromKindAndAttachment(cricket::MEDIA_TYPE_VIDEO,
733 attachment_id);
734 video_track_stats->remote_source = false;
735 video_track_stats->detached = false;
736 video_track_stats->frame_width =
737 static_cast<uint32_t>(video_sender_info.send_frame_width);
738 video_track_stats->frame_height =
739 static_cast<uint32_t>(video_sender_info.send_frame_height);
740 // TODO(hbos): Will reduce this by frames dropped due to congestion control
741 // when available. https://crbug.com/659137
742 video_track_stats->frames_sent = video_sender_info.frames_encoded;
743 video_track_stats->huge_frames_sent = video_sender_info.huge_frames_sent;
744 return video_track_stats;
745 }
746
747 std::unique_ptr<RTCMediaStreamTrackStats>
ProduceMediaStreamTrackStatsFromVideoReceiverInfo(int64_t timestamp_us,const VideoTrackInterface & video_track,const cricket::VideoReceiverInfo & video_receiver_info,int attachment_id)748 ProduceMediaStreamTrackStatsFromVideoReceiverInfo(
749 int64_t timestamp_us,
750 const VideoTrackInterface& video_track,
751 const cricket::VideoReceiverInfo& video_receiver_info,
752 int attachment_id) {
753 std::unique_ptr<RTCMediaStreamTrackStats> video_track_stats(
754 new RTCMediaStreamTrackStats(
755 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(kReceiver,
756
757 attachment_id),
758 timestamp_us, RTCMediaStreamTrackKind::kVideo));
759 SetMediaStreamTrackStatsFromMediaStreamTrackInterface(
760 video_track, video_track_stats.get());
761 video_track_stats->remote_source = true;
762 video_track_stats->detached = false;
763 if (video_receiver_info.frame_width > 0 &&
764 video_receiver_info.frame_height > 0) {
765 video_track_stats->frame_width =
766 static_cast<uint32_t>(video_receiver_info.frame_width);
767 video_track_stats->frame_height =
768 static_cast<uint32_t>(video_receiver_info.frame_height);
769 }
770 video_track_stats->jitter_buffer_delay =
771 video_receiver_info.jitter_buffer_delay_seconds;
772 video_track_stats->jitter_buffer_emitted_count =
773 video_receiver_info.jitter_buffer_emitted_count;
774 video_track_stats->frames_received = video_receiver_info.frames_received;
775 // TODO(hbos): When we support receiving simulcast, this should be the total
776 // number of frames correctly decoded, independent of which SSRC it was
777 // received from. Since we don't support that, this is correct and is the same
778 // value as "RTCInboundRTPStreamStats.framesDecoded". https://crbug.com/659137
779 video_track_stats->frames_decoded = video_receiver_info.frames_decoded;
780 video_track_stats->frames_dropped = video_receiver_info.frames_dropped;
781 video_track_stats->freeze_count = video_receiver_info.freeze_count;
782 video_track_stats->pause_count = video_receiver_info.pause_count;
783 video_track_stats->total_freezes_duration =
784 static_cast<double>(video_receiver_info.total_freezes_duration_ms) /
785 rtc::kNumMillisecsPerSec;
786 video_track_stats->total_pauses_duration =
787 static_cast<double>(video_receiver_info.total_pauses_duration_ms) /
788 rtc::kNumMillisecsPerSec;
789 video_track_stats->total_frames_duration =
790 static_cast<double>(video_receiver_info.total_frames_duration_ms) /
791 rtc::kNumMillisecsPerSec;
792 video_track_stats->sum_squared_frame_durations =
793 video_receiver_info.sum_squared_frame_durations;
794
795 return video_track_stats;
796 }
797
ProduceSenderMediaTrackStats(int64_t timestamp_us,const TrackMediaInfoMap & track_media_info_map,std::vector<rtc::scoped_refptr<RtpSenderInternal>> senders,RTCStatsReport * report)798 void ProduceSenderMediaTrackStats(
799 int64_t timestamp_us,
800 const TrackMediaInfoMap& track_media_info_map,
801 std::vector<rtc::scoped_refptr<RtpSenderInternal>> senders,
802 RTCStatsReport* report) {
803 // This function iterates over the senders to generate outgoing track stats.
804
805 // TODO(hbos): Return stats of detached tracks. We have to perform stats
806 // gathering at the time of detachment to get accurate stats and timestamps.
807 // https://crbug.com/659137
808 for (const auto& sender : senders) {
809 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
810 AudioTrackInterface* track =
811 static_cast<AudioTrackInterface*>(sender->track().get());
812 if (!track)
813 continue;
814 cricket::VoiceSenderInfo null_sender_info;
815 const cricket::VoiceSenderInfo* voice_sender_info = &null_sender_info;
816 // TODO(hta): Checking on ssrc is not proper. There should be a way
817 // to see from a sender whether it's connected or not.
818 // Related to https://crbug.com/8694 (using ssrc 0 to indicate "none")
819 if (sender->ssrc() != 0) {
820 // When pc.close is called, sender info is discarded, so
821 // we generate zeroes instead. Bug: It should be retained.
822 // https://crbug.com/807174
823 const cricket::VoiceSenderInfo* sender_info =
824 track_media_info_map.GetVoiceSenderInfoBySsrc(sender->ssrc());
825 if (sender_info) {
826 voice_sender_info = sender_info;
827 } else {
828 RTC_LOG(LS_INFO)
829 << "RTCStatsCollector: No voice sender info for sender with ssrc "
830 << sender->ssrc();
831 }
832 }
833 std::unique_ptr<RTCMediaStreamTrackStats> audio_track_stats =
834 ProduceMediaStreamTrackStatsFromVoiceSenderInfo(
835 timestamp_us, *track, *voice_sender_info, sender->AttachmentId());
836 report->AddStats(std::move(audio_track_stats));
837 } else if (sender->media_type() == cricket::MEDIA_TYPE_VIDEO) {
838 VideoTrackInterface* track =
839 static_cast<VideoTrackInterface*>(sender->track().get());
840 if (!track)
841 continue;
842 cricket::VideoSenderInfo null_sender_info;
843 const cricket::VideoSenderInfo* video_sender_info = &null_sender_info;
844 // TODO(hta): Check on state not ssrc when state is available
845 // Related to https://bugs.webrtc.org/8694 (using ssrc 0 to indicate
846 // "none")
847 if (sender->ssrc() != 0) {
848 // When pc.close is called, sender info is discarded, so
849 // we generate zeroes instead. Bug: It should be retained.
850 // https://crbug.com/807174
851 const cricket::VideoSenderInfo* sender_info =
852 track_media_info_map.GetVideoSenderInfoBySsrc(sender->ssrc());
853 if (sender_info) {
854 video_sender_info = sender_info;
855 } else {
856 RTC_LOG(LS_INFO) << "No video sender info for sender with ssrc "
857 << sender->ssrc();
858 }
859 }
860 std::unique_ptr<RTCMediaStreamTrackStats> video_track_stats =
861 ProduceMediaStreamTrackStatsFromVideoSenderInfo(
862 timestamp_us, *track, *video_sender_info, sender->AttachmentId());
863 report->AddStats(std::move(video_track_stats));
864 } else {
865 RTC_NOTREACHED();
866 }
867 }
868 }
869
ProduceReceiverMediaTrackStats(int64_t timestamp_us,const TrackMediaInfoMap & track_media_info_map,std::vector<rtc::scoped_refptr<RtpReceiverInternal>> receivers,RTCStatsReport * report)870 void ProduceReceiverMediaTrackStats(
871 int64_t timestamp_us,
872 const TrackMediaInfoMap& track_media_info_map,
873 std::vector<rtc::scoped_refptr<RtpReceiverInternal>> receivers,
874 RTCStatsReport* report) {
875 // This function iterates over the receivers to find the remote tracks.
876 for (const auto& receiver : receivers) {
877 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
878 AudioTrackInterface* track =
879 static_cast<AudioTrackInterface*>(receiver->track().get());
880 const cricket::VoiceReceiverInfo* voice_receiver_info =
881 track_media_info_map.GetVoiceReceiverInfo(*track);
882 if (!voice_receiver_info) {
883 continue;
884 }
885 std::unique_ptr<RTCMediaStreamTrackStats> audio_track_stats =
886 ProduceMediaStreamTrackStatsFromVoiceReceiverInfo(
887 timestamp_us, *track, *voice_receiver_info,
888 receiver->AttachmentId());
889 report->AddStats(std::move(audio_track_stats));
890 } else if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
891 VideoTrackInterface* track =
892 static_cast<VideoTrackInterface*>(receiver->track().get());
893 const cricket::VideoReceiverInfo* video_receiver_info =
894 track_media_info_map.GetVideoReceiverInfo(*track);
895 if (!video_receiver_info) {
896 continue;
897 }
898 std::unique_ptr<RTCMediaStreamTrackStats> video_track_stats =
899 ProduceMediaStreamTrackStatsFromVideoReceiverInfo(
900 timestamp_us, *track, *video_receiver_info,
901 receiver->AttachmentId());
902 report->AddStats(std::move(video_track_stats));
903 } else {
904 RTC_NOTREACHED();
905 }
906 }
907 }
908
CreateReportFilteredBySelector(bool filter_by_sender_selector,rtc::scoped_refptr<const RTCStatsReport> report,rtc::scoped_refptr<RtpSenderInternal> sender_selector,rtc::scoped_refptr<RtpReceiverInternal> receiver_selector)909 rtc::scoped_refptr<RTCStatsReport> CreateReportFilteredBySelector(
910 bool filter_by_sender_selector,
911 rtc::scoped_refptr<const RTCStatsReport> report,
912 rtc::scoped_refptr<RtpSenderInternal> sender_selector,
913 rtc::scoped_refptr<RtpReceiverInternal> receiver_selector) {
914 std::vector<std::string> rtpstream_ids;
915 if (filter_by_sender_selector) {
916 // Filter mode: RTCStatsCollector::RequestInfo::kSenderSelector
917 if (sender_selector) {
918 // Find outbound-rtp(s) of the sender, i.e. the outbound-rtp(s) that
919 // reference the sender stats.
920 // Because we do not implement sender stats, we look at outbound-rtp(s)
921 // that reference the track attachment stats for the sender instead.
922 std::string track_id =
923 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
924 kSender, sender_selector->AttachmentId());
925 for (const auto& stats : *report) {
926 if (stats.type() != RTCOutboundRTPStreamStats::kType)
927 continue;
928 const auto& outbound_rtp = stats.cast_to<RTCOutboundRTPStreamStats>();
929 if (outbound_rtp.track_id.is_defined() &&
930 *outbound_rtp.track_id == track_id) {
931 rtpstream_ids.push_back(outbound_rtp.id());
932 }
933 }
934 }
935 } else {
936 // Filter mode: RTCStatsCollector::RequestInfo::kReceiverSelector
937 if (receiver_selector) {
938 // Find inbound-rtp(s) of the receiver, i.e. the inbound-rtp(s) that
939 // reference the receiver stats.
940 // Because we do not implement receiver stats, we look at inbound-rtp(s)
941 // that reference the track attachment stats for the receiver instead.
942 std::string track_id =
943 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
944 kReceiver, receiver_selector->AttachmentId());
945 for (const auto& stats : *report) {
946 if (stats.type() != RTCInboundRTPStreamStats::kType)
947 continue;
948 const auto& inbound_rtp = stats.cast_to<RTCInboundRTPStreamStats>();
949 if (inbound_rtp.track_id.is_defined() &&
950 *inbound_rtp.track_id == track_id) {
951 rtpstream_ids.push_back(inbound_rtp.id());
952 }
953 }
954 }
955 }
956 if (rtpstream_ids.empty())
957 return RTCStatsReport::Create(report->timestamp_us());
958 return TakeReferencedStats(report->Copy(), rtpstream_ids);
959 }
960
961 } // namespace
962
RequestInfo(rtc::scoped_refptr<RTCStatsCollectorCallback> callback)963 RTCStatsCollector::RequestInfo::RequestInfo(
964 rtc::scoped_refptr<RTCStatsCollectorCallback> callback)
965 : RequestInfo(FilterMode::kAll, std::move(callback), nullptr, nullptr) {}
966
RequestInfo(rtc::scoped_refptr<RtpSenderInternal> selector,rtc::scoped_refptr<RTCStatsCollectorCallback> callback)967 RTCStatsCollector::RequestInfo::RequestInfo(
968 rtc::scoped_refptr<RtpSenderInternal> selector,
969 rtc::scoped_refptr<RTCStatsCollectorCallback> callback)
970 : RequestInfo(FilterMode::kSenderSelector,
971 std::move(callback),
972 std::move(selector),
973 nullptr) {}
974
RequestInfo(rtc::scoped_refptr<RtpReceiverInternal> selector,rtc::scoped_refptr<RTCStatsCollectorCallback> callback)975 RTCStatsCollector::RequestInfo::RequestInfo(
976 rtc::scoped_refptr<RtpReceiverInternal> selector,
977 rtc::scoped_refptr<RTCStatsCollectorCallback> callback)
978 : RequestInfo(FilterMode::kReceiverSelector,
979 std::move(callback),
980 nullptr,
981 std::move(selector)) {}
982
RequestInfo(RTCStatsCollector::RequestInfo::FilterMode filter_mode,rtc::scoped_refptr<RTCStatsCollectorCallback> callback,rtc::scoped_refptr<RtpSenderInternal> sender_selector,rtc::scoped_refptr<RtpReceiverInternal> receiver_selector)983 RTCStatsCollector::RequestInfo::RequestInfo(
984 RTCStatsCollector::RequestInfo::FilterMode filter_mode,
985 rtc::scoped_refptr<RTCStatsCollectorCallback> callback,
986 rtc::scoped_refptr<RtpSenderInternal> sender_selector,
987 rtc::scoped_refptr<RtpReceiverInternal> receiver_selector)
988 : filter_mode_(filter_mode),
989 callback_(std::move(callback)),
990 sender_selector_(std::move(sender_selector)),
991 receiver_selector_(std::move(receiver_selector)) {
992 RTC_DCHECK(callback_);
993 RTC_DCHECK(!sender_selector_ || !receiver_selector_);
994 }
995
Create(PeerConnectionInternal * pc,int64_t cache_lifetime_us)996 rtc::scoped_refptr<RTCStatsCollector> RTCStatsCollector::Create(
997 PeerConnectionInternal* pc,
998 int64_t cache_lifetime_us) {
999 return rtc::scoped_refptr<RTCStatsCollector>(
1000 new rtc::RefCountedObject<RTCStatsCollector>(pc, cache_lifetime_us));
1001 }
1002
RTCStatsCollector(PeerConnectionInternal * pc,int64_t cache_lifetime_us)1003 RTCStatsCollector::RTCStatsCollector(PeerConnectionInternal* pc,
1004 int64_t cache_lifetime_us)
1005 : pc_(pc),
1006 signaling_thread_(pc->signaling_thread()),
1007 worker_thread_(pc->worker_thread()),
1008 network_thread_(pc->network_thread()),
1009 num_pending_partial_reports_(0),
1010 partial_report_timestamp_us_(0),
1011 network_report_event_(true /* manual_reset */,
1012 true /* initially_signaled */),
1013 cache_timestamp_us_(0),
1014 cache_lifetime_us_(cache_lifetime_us) {
1015 RTC_DCHECK(pc_);
1016 RTC_DCHECK(signaling_thread_);
1017 RTC_DCHECK(worker_thread_);
1018 RTC_DCHECK(network_thread_);
1019 RTC_DCHECK_GE(cache_lifetime_us_, 0);
1020 pc_->SignalRtpDataChannelCreated().connect(
1021 this, &RTCStatsCollector::OnRtpDataChannelCreated);
1022 pc_->SignalSctpDataChannelCreated().connect(
1023 this, &RTCStatsCollector::OnSctpDataChannelCreated);
1024 }
1025
~RTCStatsCollector()1026 RTCStatsCollector::~RTCStatsCollector() {
1027 RTC_DCHECK_EQ(num_pending_partial_reports_, 0);
1028 }
1029
GetStatsReport(rtc::scoped_refptr<RTCStatsCollectorCallback> callback)1030 void RTCStatsCollector::GetStatsReport(
1031 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1032 GetStatsReportInternal(RequestInfo(std::move(callback)));
1033 }
1034
GetStatsReport(rtc::scoped_refptr<RtpSenderInternal> selector,rtc::scoped_refptr<RTCStatsCollectorCallback> callback)1035 void RTCStatsCollector::GetStatsReport(
1036 rtc::scoped_refptr<RtpSenderInternal> selector,
1037 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1038 GetStatsReportInternal(RequestInfo(std::move(selector), std::move(callback)));
1039 }
1040
GetStatsReport(rtc::scoped_refptr<RtpReceiverInternal> selector,rtc::scoped_refptr<RTCStatsCollectorCallback> callback)1041 void RTCStatsCollector::GetStatsReport(
1042 rtc::scoped_refptr<RtpReceiverInternal> selector,
1043 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1044 GetStatsReportInternal(RequestInfo(std::move(selector), std::move(callback)));
1045 }
1046
GetStatsReportInternal(RTCStatsCollector::RequestInfo request)1047 void RTCStatsCollector::GetStatsReportInternal(
1048 RTCStatsCollector::RequestInfo request) {
1049 RTC_DCHECK(signaling_thread_->IsCurrent());
1050 requests_.push_back(std::move(request));
1051
1052 // "Now" using a monotonically increasing timer.
1053 int64_t cache_now_us = rtc::TimeMicros();
1054 if (cached_report_ &&
1055 cache_now_us - cache_timestamp_us_ <= cache_lifetime_us_) {
1056 // We have a fresh cached report to deliver. Deliver asynchronously, since
1057 // the caller may not be expecting a synchronous callback, and it avoids
1058 // reentrancy problems.
1059 std::vector<RequestInfo> requests;
1060 requests.swap(requests_);
1061 signaling_thread_->PostTask(
1062 RTC_FROM_HERE, rtc::Bind(&RTCStatsCollector::DeliverCachedReport, this,
1063 cached_report_, std::move(requests)));
1064 } else if (!num_pending_partial_reports_) {
1065 // Only start gathering stats if we're not already gathering stats. In the
1066 // case of already gathering stats, |callback_| will be invoked when there
1067 // are no more pending partial reports.
1068
1069 // "Now" using a system clock, relative to the UNIX epoch (Jan 1, 1970,
1070 // UTC), in microseconds. The system clock could be modified and is not
1071 // necessarily monotonically increasing.
1072 int64_t timestamp_us = rtc::TimeUTCMicros();
1073
1074 num_pending_partial_reports_ = 2;
1075 partial_report_timestamp_us_ = cache_now_us;
1076
1077 // Prepare |transceiver_stats_infos_| for use in
1078 // |ProducePartialResultsOnNetworkThread| and
1079 // |ProducePartialResultsOnSignalingThread|.
1080 transceiver_stats_infos_ = PrepareTransceiverStatsInfos_s_w();
1081 // Prepare |transport_names_| for use in
1082 // |ProducePartialResultsOnNetworkThread|.
1083 transport_names_ = PrepareTransportNames_s();
1084
1085 // Prepare |call_stats_| here since GetCallStats() will hop to the worker
1086 // thread.
1087 // TODO(holmer): To avoid the hop we could move BWE and BWE stats to the
1088 // network thread, where it more naturally belongs.
1089 // TODO(https://crbug.com/webrtc/11767): In the meantime we can piggyback on
1090 // the blocking-invoke that is already performed in
1091 // PrepareTransceiverStatsInfos_s_w() so that we can call GetCallStats()
1092 // without additional blocking-invokes.
1093 call_stats_ = pc_->GetCallStats();
1094
1095 // Don't touch |network_report_| on the signaling thread until
1096 // ProducePartialResultsOnNetworkThread() has signaled the
1097 // |network_report_event_|.
1098 network_report_event_.Reset();
1099 network_thread_->PostTask(
1100 RTC_FROM_HERE,
1101 rtc::Bind(&RTCStatsCollector::ProducePartialResultsOnNetworkThread,
1102 this, timestamp_us));
1103 ProducePartialResultsOnSignalingThread(timestamp_us);
1104 }
1105 }
1106
ClearCachedStatsReport()1107 void RTCStatsCollector::ClearCachedStatsReport() {
1108 RTC_DCHECK(signaling_thread_->IsCurrent());
1109 cached_report_ = nullptr;
1110 }
1111
WaitForPendingRequest()1112 void RTCStatsCollector::WaitForPendingRequest() {
1113 RTC_DCHECK(signaling_thread_->IsCurrent());
1114 // If a request is pending, blocks until the |network_report_event_| is
1115 // signaled and then delivers the result. Otherwise this is a NO-OP.
1116 MergeNetworkReport_s();
1117 }
1118
ProducePartialResultsOnSignalingThread(int64_t timestamp_us)1119 void RTCStatsCollector::ProducePartialResultsOnSignalingThread(
1120 int64_t timestamp_us) {
1121 RTC_DCHECK(signaling_thread_->IsCurrent());
1122 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1123
1124 partial_report_ = RTCStatsReport::Create(timestamp_us);
1125
1126 ProducePartialResultsOnSignalingThreadImpl(timestamp_us,
1127 partial_report_.get());
1128
1129 // ProducePartialResultsOnSignalingThread() is running synchronously on the
1130 // signaling thread, so it is always the first partial result delivered on the
1131 // signaling thread. The request is not complete until MergeNetworkReport_s()
1132 // happens; we don't have to do anything here.
1133 RTC_DCHECK_GT(num_pending_partial_reports_, 1);
1134 --num_pending_partial_reports_;
1135 }
1136
ProducePartialResultsOnSignalingThreadImpl(int64_t timestamp_us,RTCStatsReport * partial_report)1137 void RTCStatsCollector::ProducePartialResultsOnSignalingThreadImpl(
1138 int64_t timestamp_us,
1139 RTCStatsReport* partial_report) {
1140 RTC_DCHECK(signaling_thread_->IsCurrent());
1141 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1142
1143 ProduceDataChannelStats_s(timestamp_us, partial_report);
1144 ProduceMediaStreamStats_s(timestamp_us, partial_report);
1145 ProduceMediaStreamTrackStats_s(timestamp_us, partial_report);
1146 ProduceMediaSourceStats_s(timestamp_us, partial_report);
1147 ProducePeerConnectionStats_s(timestamp_us, partial_report);
1148 }
1149
ProducePartialResultsOnNetworkThread(int64_t timestamp_us)1150 void RTCStatsCollector::ProducePartialResultsOnNetworkThread(
1151 int64_t timestamp_us) {
1152 RTC_DCHECK(network_thread_->IsCurrent());
1153 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1154
1155 // Touching |network_report_| on this thread is safe by this method because
1156 // |network_report_event_| is reset before this method is invoked.
1157 network_report_ = RTCStatsReport::Create(timestamp_us);
1158
1159 std::map<std::string, cricket::TransportStats> transport_stats_by_name =
1160 pc_->GetTransportStatsByNames(transport_names_);
1161 std::map<std::string, CertificateStatsPair> transport_cert_stats =
1162 PrepareTransportCertificateStats_n(transport_stats_by_name);
1163
1164 ProducePartialResultsOnNetworkThreadImpl(
1165 timestamp_us, transport_stats_by_name, transport_cert_stats,
1166 network_report_.get());
1167
1168 // Signal that it is now safe to touch |network_report_| on the signaling
1169 // thread, and post a task to merge it into the final results.
1170 network_report_event_.Set();
1171 signaling_thread_->PostTask(
1172 RTC_FROM_HERE, rtc::Bind(&RTCStatsCollector::MergeNetworkReport_s, this));
1173 }
1174
ProducePartialResultsOnNetworkThreadImpl(int64_t timestamp_us,const std::map<std::string,cricket::TransportStats> & transport_stats_by_name,const std::map<std::string,CertificateStatsPair> & transport_cert_stats,RTCStatsReport * partial_report)1175 void RTCStatsCollector::ProducePartialResultsOnNetworkThreadImpl(
1176 int64_t timestamp_us,
1177 const std::map<std::string, cricket::TransportStats>&
1178 transport_stats_by_name,
1179 const std::map<std::string, CertificateStatsPair>& transport_cert_stats,
1180 RTCStatsReport* partial_report) {
1181 RTC_DCHECK(network_thread_->IsCurrent());
1182 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1183
1184 ProduceCertificateStats_n(timestamp_us, transport_cert_stats, partial_report);
1185 ProduceCodecStats_n(timestamp_us, transceiver_stats_infos_, partial_report);
1186 ProduceIceCandidateAndPairStats_n(timestamp_us, transport_stats_by_name,
1187 call_stats_, partial_report);
1188 ProduceTransportStats_n(timestamp_us, transport_stats_by_name,
1189 transport_cert_stats, partial_report);
1190 ProduceRTPStreamStats_n(timestamp_us, transceiver_stats_infos_,
1191 partial_report);
1192 }
1193
MergeNetworkReport_s()1194 void RTCStatsCollector::MergeNetworkReport_s() {
1195 RTC_DCHECK(signaling_thread_->IsCurrent());
1196 // The |network_report_event_| must be signaled for it to be safe to touch
1197 // |network_report_|. This is normally not blocking, but if
1198 // WaitForPendingRequest() is called while a request is pending, we might have
1199 // to wait until the network thread is done touching |network_report_|.
1200 network_report_event_.Wait(rtc::Event::kForever);
1201 if (!network_report_) {
1202 // Normally, MergeNetworkReport_s() is executed because it is posted from
1203 // the network thread. But if WaitForPendingRequest() is called while a
1204 // request is pending, an early call to MergeNetworkReport_s() is made,
1205 // merging the report and setting |network_report_| to null. If so, when the
1206 // previously posted MergeNetworkReport_s() is later executed, the report is
1207 // already null and nothing needs to be done here.
1208 return;
1209 }
1210 RTC_DCHECK_GT(num_pending_partial_reports_, 0);
1211 RTC_DCHECK(partial_report_);
1212 partial_report_->TakeMembersFrom(network_report_);
1213 network_report_ = nullptr;
1214 --num_pending_partial_reports_;
1215 // |network_report_| is currently the only partial report collected
1216 // asynchronously, so |num_pending_partial_reports_| must now be 0 and we are
1217 // ready to deliver the result.
1218 RTC_DCHECK_EQ(num_pending_partial_reports_, 0);
1219 cache_timestamp_us_ = partial_report_timestamp_us_;
1220 cached_report_ = partial_report_;
1221 partial_report_ = nullptr;
1222 transceiver_stats_infos_.clear();
1223 // Trace WebRTC Stats when getStats is called on Javascript.
1224 // This allows access to WebRTC stats from trace logs. To enable them,
1225 // select the "webrtc_stats" category when recording traces.
1226 TRACE_EVENT_INSTANT1("webrtc_stats", "webrtc_stats", "report",
1227 cached_report_->ToJson());
1228
1229 // Deliver report and clear |requests_|.
1230 std::vector<RequestInfo> requests;
1231 requests.swap(requests_);
1232 DeliverCachedReport(cached_report_, std::move(requests));
1233 }
1234
DeliverCachedReport(rtc::scoped_refptr<const RTCStatsReport> cached_report,std::vector<RTCStatsCollector::RequestInfo> requests)1235 void RTCStatsCollector::DeliverCachedReport(
1236 rtc::scoped_refptr<const RTCStatsReport> cached_report,
1237 std::vector<RTCStatsCollector::RequestInfo> requests) {
1238 RTC_DCHECK(signaling_thread_->IsCurrent());
1239 RTC_DCHECK(!requests.empty());
1240 RTC_DCHECK(cached_report);
1241
1242 for (const RequestInfo& request : requests) {
1243 if (request.filter_mode() == RequestInfo::FilterMode::kAll) {
1244 request.callback()->OnStatsDelivered(cached_report);
1245 } else {
1246 bool filter_by_sender_selector;
1247 rtc::scoped_refptr<RtpSenderInternal> sender_selector;
1248 rtc::scoped_refptr<RtpReceiverInternal> receiver_selector;
1249 if (request.filter_mode() == RequestInfo::FilterMode::kSenderSelector) {
1250 filter_by_sender_selector = true;
1251 sender_selector = request.sender_selector();
1252 } else {
1253 RTC_DCHECK(request.filter_mode() ==
1254 RequestInfo::FilterMode::kReceiverSelector);
1255 filter_by_sender_selector = false;
1256 receiver_selector = request.receiver_selector();
1257 }
1258 request.callback()->OnStatsDelivered(CreateReportFilteredBySelector(
1259 filter_by_sender_selector, cached_report, sender_selector,
1260 receiver_selector));
1261 }
1262 }
1263 }
1264
ProduceCertificateStats_n(int64_t timestamp_us,const std::map<std::string,CertificateStatsPair> & transport_cert_stats,RTCStatsReport * report) const1265 void RTCStatsCollector::ProduceCertificateStats_n(
1266 int64_t timestamp_us,
1267 const std::map<std::string, CertificateStatsPair>& transport_cert_stats,
1268 RTCStatsReport* report) const {
1269 RTC_DCHECK(network_thread_->IsCurrent());
1270 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1271
1272 for (const auto& transport_cert_stats_pair : transport_cert_stats) {
1273 if (transport_cert_stats_pair.second.local) {
1274 ProduceCertificateStatsFromSSLCertificateStats(
1275 timestamp_us, *transport_cert_stats_pair.second.local.get(), report);
1276 }
1277 if (transport_cert_stats_pair.second.remote) {
1278 ProduceCertificateStatsFromSSLCertificateStats(
1279 timestamp_us, *transport_cert_stats_pair.second.remote.get(), report);
1280 }
1281 }
1282 }
1283
ProduceCodecStats_n(int64_t timestamp_us,const std::vector<RtpTransceiverStatsInfo> & transceiver_stats_infos,RTCStatsReport * report) const1284 void RTCStatsCollector::ProduceCodecStats_n(
1285 int64_t timestamp_us,
1286 const std::vector<RtpTransceiverStatsInfo>& transceiver_stats_infos,
1287 RTCStatsReport* report) const {
1288 RTC_DCHECK(network_thread_->IsCurrent());
1289 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1290
1291 for (const auto& stats : transceiver_stats_infos) {
1292 if (!stats.mid) {
1293 continue;
1294 }
1295 const cricket::VoiceMediaInfo* voice_media_info =
1296 stats.track_media_info_map->voice_media_info();
1297 const cricket::VideoMediaInfo* video_media_info =
1298 stats.track_media_info_map->video_media_info();
1299 // Audio
1300 if (voice_media_info) {
1301 // Inbound
1302 for (const auto& pair : voice_media_info->receive_codecs) {
1303 report->AddStats(CodecStatsFromRtpCodecParameters(
1304 timestamp_us, *stats.mid, true, pair.second));
1305 }
1306 // Outbound
1307 for (const auto& pair : voice_media_info->send_codecs) {
1308 report->AddStats(CodecStatsFromRtpCodecParameters(
1309 timestamp_us, *stats.mid, false, pair.second));
1310 }
1311 }
1312 // Video
1313 if (video_media_info) {
1314 // Inbound
1315 for (const auto& pair : video_media_info->receive_codecs) {
1316 report->AddStats(CodecStatsFromRtpCodecParameters(
1317 timestamp_us, *stats.mid, true, pair.second));
1318 }
1319 // Outbound
1320 for (const auto& pair : video_media_info->send_codecs) {
1321 report->AddStats(CodecStatsFromRtpCodecParameters(
1322 timestamp_us, *stats.mid, false, pair.second));
1323 }
1324 }
1325 }
1326 }
1327
ProduceDataChannelStats_s(int64_t timestamp_us,RTCStatsReport * report) const1328 void RTCStatsCollector::ProduceDataChannelStats_s(
1329 int64_t timestamp_us,
1330 RTCStatsReport* report) const {
1331 RTC_DCHECK_RUN_ON(signaling_thread_);
1332 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1333 std::vector<DataChannelStats> data_stats = pc_->GetDataChannelStats();
1334 for (const auto& stats : data_stats) {
1335 std::unique_ptr<RTCDataChannelStats> data_channel_stats(
1336 new RTCDataChannelStats(
1337 "RTCDataChannel_" + rtc::ToString(stats.internal_id),
1338 timestamp_us));
1339 data_channel_stats->label = std::move(stats.label);
1340 data_channel_stats->protocol = std::move(stats.protocol);
1341 data_channel_stats->data_channel_identifier = stats.id;
1342 data_channel_stats->state = DataStateToRTCDataChannelState(stats.state);
1343 data_channel_stats->messages_sent = stats.messages_sent;
1344 data_channel_stats->bytes_sent = stats.bytes_sent;
1345 data_channel_stats->messages_received = stats.messages_received;
1346 data_channel_stats->bytes_received = stats.bytes_received;
1347 report->AddStats(std::move(data_channel_stats));
1348 }
1349 }
1350
ProduceIceCandidateAndPairStats_n(int64_t timestamp_us,const std::map<std::string,cricket::TransportStats> & transport_stats_by_name,const Call::Stats & call_stats,RTCStatsReport * report) const1351 void RTCStatsCollector::ProduceIceCandidateAndPairStats_n(
1352 int64_t timestamp_us,
1353 const std::map<std::string, cricket::TransportStats>&
1354 transport_stats_by_name,
1355 const Call::Stats& call_stats,
1356 RTCStatsReport* report) const {
1357 RTC_DCHECK(network_thread_->IsCurrent());
1358 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1359
1360 for (const auto& entry : transport_stats_by_name) {
1361 const std::string& transport_name = entry.first;
1362 const cricket::TransportStats& transport_stats = entry.second;
1363 for (const auto& channel_stats : transport_stats.channel_stats) {
1364 std::string transport_id = RTCTransportStatsIDFromTransportChannel(
1365 transport_name, channel_stats.component);
1366 for (const cricket::ConnectionInfo& info :
1367 channel_stats.ice_transport_stats.connection_infos) {
1368 std::unique_ptr<RTCIceCandidatePairStats> candidate_pair_stats(
1369 new RTCIceCandidatePairStats(
1370 RTCIceCandidatePairStatsIDFromConnectionInfo(info),
1371 timestamp_us));
1372
1373 candidate_pair_stats->transport_id = transport_id;
1374 // TODO(hbos): There could be other candidates that are not paired with
1375 // anything. We don't have a complete list. Local candidates come from
1376 // Port objects, and prflx candidates (both local and remote) are only
1377 // stored in candidate pairs. https://crbug.com/632723
1378 candidate_pair_stats->local_candidate_id = ProduceIceCandidateStats(
1379 timestamp_us, info.local_candidate, true, transport_id, report);
1380 candidate_pair_stats->remote_candidate_id = ProduceIceCandidateStats(
1381 timestamp_us, info.remote_candidate, false, transport_id, report);
1382 candidate_pair_stats->state =
1383 IceCandidatePairStateToRTCStatsIceCandidatePairState(info.state);
1384 candidate_pair_stats->priority = info.priority;
1385 candidate_pair_stats->nominated = info.nominated;
1386 // TODO(hbos): This writable is different than the spec. It goes to
1387 // false after a certain amount of time without a response passes.
1388 // https://crbug.com/633550
1389 candidate_pair_stats->writable = info.writable;
1390 candidate_pair_stats->bytes_sent =
1391 static_cast<uint64_t>(info.sent_total_bytes);
1392 candidate_pair_stats->bytes_received =
1393 static_cast<uint64_t>(info.recv_total_bytes);
1394 candidate_pair_stats->total_round_trip_time =
1395 static_cast<double>(info.total_round_trip_time_ms) /
1396 rtc::kNumMillisecsPerSec;
1397 if (info.current_round_trip_time_ms) {
1398 candidate_pair_stats->current_round_trip_time =
1399 static_cast<double>(*info.current_round_trip_time_ms) /
1400 rtc::kNumMillisecsPerSec;
1401 }
1402 if (info.best_connection) {
1403 // The bandwidth estimations we have are for the selected candidate
1404 // pair ("info.best_connection").
1405 RTC_DCHECK_GE(call_stats.send_bandwidth_bps, 0);
1406 RTC_DCHECK_GE(call_stats.recv_bandwidth_bps, 0);
1407 if (call_stats.send_bandwidth_bps > 0) {
1408 candidate_pair_stats->available_outgoing_bitrate =
1409 static_cast<double>(call_stats.send_bandwidth_bps);
1410 }
1411 if (call_stats.recv_bandwidth_bps > 0) {
1412 candidate_pair_stats->available_incoming_bitrate =
1413 static_cast<double>(call_stats.recv_bandwidth_bps);
1414 }
1415 }
1416 candidate_pair_stats->requests_received =
1417 static_cast<uint64_t>(info.recv_ping_requests);
1418 candidate_pair_stats->requests_sent = static_cast<uint64_t>(
1419 info.sent_ping_requests_before_first_response);
1420 candidate_pair_stats->responses_received =
1421 static_cast<uint64_t>(info.recv_ping_responses);
1422 candidate_pair_stats->responses_sent =
1423 static_cast<uint64_t>(info.sent_ping_responses);
1424 RTC_DCHECK_GE(info.sent_ping_requests_total,
1425 info.sent_ping_requests_before_first_response);
1426 candidate_pair_stats->consent_requests_sent = static_cast<uint64_t>(
1427 info.sent_ping_requests_total -
1428 info.sent_ping_requests_before_first_response);
1429
1430 report->AddStats(std::move(candidate_pair_stats));
1431 }
1432 }
1433 }
1434 }
1435
ProduceMediaStreamStats_s(int64_t timestamp_us,RTCStatsReport * report) const1436 void RTCStatsCollector::ProduceMediaStreamStats_s(
1437 int64_t timestamp_us,
1438 RTCStatsReport* report) const {
1439 RTC_DCHECK(signaling_thread_->IsCurrent());
1440 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1441
1442 std::map<std::string, std::vector<std::string>> track_ids;
1443
1444 for (const auto& stats : transceiver_stats_infos_) {
1445 for (const auto& sender : stats.transceiver->senders()) {
1446 std::string track_id =
1447 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
1448 kSender, sender->internal()->AttachmentId());
1449 for (auto& stream_id : sender->stream_ids()) {
1450 track_ids[stream_id].push_back(track_id);
1451 }
1452 }
1453 for (const auto& receiver : stats.transceiver->receivers()) {
1454 std::string track_id =
1455 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
1456 kReceiver, receiver->internal()->AttachmentId());
1457 for (auto& stream : receiver->streams()) {
1458 track_ids[stream->id()].push_back(track_id);
1459 }
1460 }
1461 }
1462
1463 // Build stats for each stream ID known.
1464 for (auto& it : track_ids) {
1465 std::unique_ptr<RTCMediaStreamStats> stream_stats(
1466 new RTCMediaStreamStats("RTCMediaStream_" + it.first, timestamp_us));
1467 stream_stats->stream_identifier = it.first;
1468 stream_stats->track_ids = it.second;
1469 report->AddStats(std::move(stream_stats));
1470 }
1471 }
1472
ProduceMediaStreamTrackStats_s(int64_t timestamp_us,RTCStatsReport * report) const1473 void RTCStatsCollector::ProduceMediaStreamTrackStats_s(
1474 int64_t timestamp_us,
1475 RTCStatsReport* report) const {
1476 RTC_DCHECK(signaling_thread_->IsCurrent());
1477 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1478
1479 for (const RtpTransceiverStatsInfo& stats : transceiver_stats_infos_) {
1480 std::vector<rtc::scoped_refptr<RtpSenderInternal>> senders;
1481 for (const auto& sender : stats.transceiver->senders()) {
1482 senders.push_back(sender->internal());
1483 }
1484 ProduceSenderMediaTrackStats(timestamp_us, *stats.track_media_info_map,
1485 senders, report);
1486
1487 std::vector<rtc::scoped_refptr<RtpReceiverInternal>> receivers;
1488 for (const auto& receiver : stats.transceiver->receivers()) {
1489 receivers.push_back(receiver->internal());
1490 }
1491 ProduceReceiverMediaTrackStats(timestamp_us, *stats.track_media_info_map,
1492 receivers, report);
1493 }
1494 }
1495
ProduceMediaSourceStats_s(int64_t timestamp_us,RTCStatsReport * report) const1496 void RTCStatsCollector::ProduceMediaSourceStats_s(
1497 int64_t timestamp_us,
1498 RTCStatsReport* report) const {
1499 RTC_DCHECK(signaling_thread_->IsCurrent());
1500 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1501
1502 for (const RtpTransceiverStatsInfo& transceiver_stats_info :
1503 transceiver_stats_infos_) {
1504 const auto& track_media_info_map =
1505 transceiver_stats_info.track_media_info_map;
1506 for (const auto& sender : transceiver_stats_info.transceiver->senders()) {
1507 const auto& sender_internal = sender->internal();
1508 const auto& track = sender_internal->track();
1509 if (!track)
1510 continue;
1511 // TODO(https://crbug.com/webrtc/10771): The same track could be attached
1512 // to multiple senders which should result in multiple senders referencing
1513 // the same media-source stats. When all media source related metrics are
1514 // moved to the track's source (e.g. input frame rate is moved from
1515 // cricket::VideoSenderInfo to VideoTrackSourceInterface::Stats and audio
1516 // levels are moved to the corresponding audio track/source object), don't
1517 // create separate media source stats objects on a per-attachment basis.
1518 std::unique_ptr<RTCMediaSourceStats> media_source_stats;
1519 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1520 auto audio_source_stats = std::make_unique<RTCAudioSourceStats>(
1521 RTCMediaSourceStatsIDFromKindAndAttachment(
1522 cricket::MEDIA_TYPE_AUDIO, sender_internal->AttachmentId()),
1523 timestamp_us);
1524 // TODO(https://crbug.com/webrtc/10771): We shouldn't need to have an
1525 // SSRC assigned (there shouldn't need to exist a send-stream, created
1526 // by an O/A exchange) in order to read audio media-source stats.
1527 // TODO(https://crbug.com/webrtc/8694): SSRC 0 shouldn't be a magic
1528 // value indicating no SSRC.
1529 if (sender_internal->ssrc() != 0) {
1530 auto* voice_sender_info =
1531 track_media_info_map->GetVoiceSenderInfoBySsrc(
1532 sender_internal->ssrc());
1533 if (voice_sender_info) {
1534 audio_source_stats->audio_level = DoubleAudioLevelFromIntAudioLevel(
1535 voice_sender_info->audio_level);
1536 audio_source_stats->total_audio_energy =
1537 voice_sender_info->total_input_energy;
1538 audio_source_stats->total_samples_duration =
1539 voice_sender_info->total_input_duration;
1540 }
1541 }
1542 media_source_stats = std::move(audio_source_stats);
1543 } else {
1544 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
1545 auto video_source_stats = std::make_unique<RTCVideoSourceStats>(
1546 RTCMediaSourceStatsIDFromKindAndAttachment(
1547 cricket::MEDIA_TYPE_VIDEO, sender_internal->AttachmentId()),
1548 timestamp_us);
1549 auto* video_track = static_cast<VideoTrackInterface*>(track.get());
1550 auto* video_source = video_track->GetSource();
1551 VideoTrackSourceInterface::Stats source_stats;
1552 if (video_source && video_source->GetStats(&source_stats)) {
1553 video_source_stats->width = source_stats.input_width;
1554 video_source_stats->height = source_stats.input_height;
1555 }
1556 // TODO(https://crbug.com/webrtc/10771): We shouldn't need to have an
1557 // SSRC assigned (there shouldn't need to exist a send-stream, created
1558 // by an O/A exchange) in order to get framesPerSecond.
1559 // TODO(https://crbug.com/webrtc/8694): SSRC 0 shouldn't be a magic
1560 // value indicating no SSRC.
1561 if (sender_internal->ssrc() != 0) {
1562 auto* video_sender_info =
1563 track_media_info_map->GetVideoSenderInfoBySsrc(
1564 sender_internal->ssrc());
1565 if (video_sender_info) {
1566 video_source_stats->frames_per_second =
1567 video_sender_info->framerate_input;
1568 }
1569 }
1570 media_source_stats = std::move(video_source_stats);
1571 }
1572 media_source_stats->track_identifier = track->id();
1573 media_source_stats->kind = track->kind();
1574 report->AddStats(std::move(media_source_stats));
1575 }
1576 }
1577 }
1578
ProducePeerConnectionStats_s(int64_t timestamp_us,RTCStatsReport * report) const1579 void RTCStatsCollector::ProducePeerConnectionStats_s(
1580 int64_t timestamp_us,
1581 RTCStatsReport* report) const {
1582 RTC_DCHECK(signaling_thread_->IsCurrent());
1583 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1584
1585 std::unique_ptr<RTCPeerConnectionStats> stats(
1586 new RTCPeerConnectionStats("RTCPeerConnection", timestamp_us));
1587 stats->data_channels_opened = internal_record_.data_channels_opened;
1588 stats->data_channels_closed = internal_record_.data_channels_closed;
1589 report->AddStats(std::move(stats));
1590 }
1591
ProduceRTPStreamStats_n(int64_t timestamp_us,const std::vector<RtpTransceiverStatsInfo> & transceiver_stats_infos,RTCStatsReport * report) const1592 void RTCStatsCollector::ProduceRTPStreamStats_n(
1593 int64_t timestamp_us,
1594 const std::vector<RtpTransceiverStatsInfo>& transceiver_stats_infos,
1595 RTCStatsReport* report) const {
1596 RTC_DCHECK(network_thread_->IsCurrent());
1597 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1598
1599 for (const RtpTransceiverStatsInfo& stats : transceiver_stats_infos) {
1600 if (stats.media_type == cricket::MEDIA_TYPE_AUDIO) {
1601 ProduceAudioRTPStreamStats_n(timestamp_us, stats, report);
1602 } else if (stats.media_type == cricket::MEDIA_TYPE_VIDEO) {
1603 ProduceVideoRTPStreamStats_n(timestamp_us, stats, report);
1604 } else {
1605 RTC_NOTREACHED();
1606 }
1607 }
1608 }
1609
ProduceAudioRTPStreamStats_n(int64_t timestamp_us,const RtpTransceiverStatsInfo & stats,RTCStatsReport * report) const1610 void RTCStatsCollector::ProduceAudioRTPStreamStats_n(
1611 int64_t timestamp_us,
1612 const RtpTransceiverStatsInfo& stats,
1613 RTCStatsReport* report) const {
1614 RTC_DCHECK(network_thread_->IsCurrent());
1615 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1616
1617 if (!stats.mid || !stats.transport_name) {
1618 return;
1619 }
1620 RTC_DCHECK(stats.track_media_info_map);
1621 const TrackMediaInfoMap& track_media_info_map = *stats.track_media_info_map;
1622 RTC_DCHECK(track_media_info_map.voice_media_info());
1623 std::string mid = *stats.mid;
1624 std::string transport_id = RTCTransportStatsIDFromTransportChannel(
1625 *stats.transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
1626 // Inbound
1627 for (const cricket::VoiceReceiverInfo& voice_receiver_info :
1628 track_media_info_map.voice_media_info()->receivers) {
1629 if (!voice_receiver_info.connected())
1630 continue;
1631 auto inbound_audio = std::make_unique<RTCInboundRTPStreamStats>(
1632 RTCInboundRTPStreamStatsIDFromSSRC(true, voice_receiver_info.ssrc()),
1633 timestamp_us);
1634 SetInboundRTPStreamStatsFromVoiceReceiverInfo(mid, voice_receiver_info,
1635 inbound_audio.get());
1636 // TODO(hta): This lookup should look for the sender, not the track.
1637 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1638 track_media_info_map.GetAudioTrack(voice_receiver_info);
1639 if (audio_track) {
1640 inbound_audio->track_id =
1641 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
1642 kReceiver,
1643 track_media_info_map.GetAttachmentIdByTrack(audio_track).value());
1644 }
1645 inbound_audio->transport_id = transport_id;
1646 report->AddStats(std::move(inbound_audio));
1647 }
1648 // Outbound
1649 std::map<std::string, RTCOutboundRTPStreamStats*> audio_outbound_rtps;
1650 for (const cricket::VoiceSenderInfo& voice_sender_info :
1651 track_media_info_map.voice_media_info()->senders) {
1652 if (!voice_sender_info.connected())
1653 continue;
1654 auto outbound_audio = std::make_unique<RTCOutboundRTPStreamStats>(
1655 RTCOutboundRTPStreamStatsIDFromSSRC(true, voice_sender_info.ssrc()),
1656 timestamp_us);
1657 SetOutboundRTPStreamStatsFromVoiceSenderInfo(mid, voice_sender_info,
1658 outbound_audio.get());
1659 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1660 track_media_info_map.GetAudioTrack(voice_sender_info);
1661 if (audio_track) {
1662 int attachment_id =
1663 track_media_info_map.GetAttachmentIdByTrack(audio_track).value();
1664 outbound_audio->track_id =
1665 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(kSender,
1666 attachment_id);
1667 outbound_audio->media_source_id =
1668 RTCMediaSourceStatsIDFromKindAndAttachment(cricket::MEDIA_TYPE_AUDIO,
1669 attachment_id);
1670 }
1671 outbound_audio->transport_id = transport_id;
1672 audio_outbound_rtps.insert(
1673 std::make_pair(outbound_audio->id(), outbound_audio.get()));
1674 report->AddStats(std::move(outbound_audio));
1675 }
1676 // Remote-inbound
1677 // These are Report Block-based, information sent from the remote endpoint,
1678 // providing metrics about our Outbound streams. We take advantage of the fact
1679 // that RTCOutboundRtpStreamStats, RTCCodecStats and RTCTransport have already
1680 // been added to the report.
1681 for (const cricket::VoiceSenderInfo& voice_sender_info :
1682 track_media_info_map.voice_media_info()->senders) {
1683 for (const auto& report_block_data : voice_sender_info.report_block_datas) {
1684 report->AddStats(ProduceRemoteInboundRtpStreamStatsFromReportBlockData(
1685 report_block_data, cricket::MEDIA_TYPE_AUDIO, audio_outbound_rtps,
1686 *report));
1687 }
1688 }
1689 }
1690
ProduceVideoRTPStreamStats_n(int64_t timestamp_us,const RtpTransceiverStatsInfo & stats,RTCStatsReport * report) const1691 void RTCStatsCollector::ProduceVideoRTPStreamStats_n(
1692 int64_t timestamp_us,
1693 const RtpTransceiverStatsInfo& stats,
1694 RTCStatsReport* report) const {
1695 RTC_DCHECK(network_thread_->IsCurrent());
1696 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1697
1698 if (!stats.mid || !stats.transport_name) {
1699 return;
1700 }
1701 RTC_DCHECK(stats.track_media_info_map);
1702 const TrackMediaInfoMap& track_media_info_map = *stats.track_media_info_map;
1703 RTC_DCHECK(track_media_info_map.video_media_info());
1704 std::string mid = *stats.mid;
1705 std::string transport_id = RTCTransportStatsIDFromTransportChannel(
1706 *stats.transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
1707 // Inbound
1708 for (const cricket::VideoReceiverInfo& video_receiver_info :
1709 track_media_info_map.video_media_info()->receivers) {
1710 if (!video_receiver_info.connected())
1711 continue;
1712 auto inbound_video = std::make_unique<RTCInboundRTPStreamStats>(
1713 RTCInboundRTPStreamStatsIDFromSSRC(false, video_receiver_info.ssrc()),
1714 timestamp_us);
1715 SetInboundRTPStreamStatsFromVideoReceiverInfo(mid, video_receiver_info,
1716 inbound_video.get());
1717 rtc::scoped_refptr<VideoTrackInterface> video_track =
1718 track_media_info_map.GetVideoTrack(video_receiver_info);
1719 if (video_track) {
1720 inbound_video->track_id =
1721 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
1722 kReceiver,
1723 track_media_info_map.GetAttachmentIdByTrack(video_track).value());
1724 }
1725 inbound_video->transport_id = transport_id;
1726 report->AddStats(std::move(inbound_video));
1727 }
1728 // Outbound
1729 std::map<std::string, RTCOutboundRTPStreamStats*> video_outbound_rtps;
1730 for (const cricket::VideoSenderInfo& video_sender_info :
1731 track_media_info_map.video_media_info()->senders) {
1732 if (!video_sender_info.connected())
1733 continue;
1734 auto outbound_video = std::make_unique<RTCOutboundRTPStreamStats>(
1735 RTCOutboundRTPStreamStatsIDFromSSRC(false, video_sender_info.ssrc()),
1736 timestamp_us);
1737 SetOutboundRTPStreamStatsFromVideoSenderInfo(mid, video_sender_info,
1738 outbound_video.get());
1739 rtc::scoped_refptr<VideoTrackInterface> video_track =
1740 track_media_info_map.GetVideoTrack(video_sender_info);
1741 if (video_track) {
1742 int attachment_id =
1743 track_media_info_map.GetAttachmentIdByTrack(video_track).value();
1744 outbound_video->track_id =
1745 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(kSender,
1746 attachment_id);
1747 outbound_video->media_source_id =
1748 RTCMediaSourceStatsIDFromKindAndAttachment(cricket::MEDIA_TYPE_VIDEO,
1749 attachment_id);
1750 }
1751 outbound_video->transport_id = transport_id;
1752 video_outbound_rtps.insert(
1753 std::make_pair(outbound_video->id(), outbound_video.get()));
1754 report->AddStats(std::move(outbound_video));
1755 }
1756 // Remote-inbound
1757 // These are Report Block-based, information sent from the remote endpoint,
1758 // providing metrics about our Outbound streams. We take advantage of the fact
1759 // that RTCOutboundRtpStreamStats, RTCCodecStats and RTCTransport have already
1760 // been added to the report.
1761 for (const cricket::VideoSenderInfo& video_sender_info :
1762 track_media_info_map.video_media_info()->senders) {
1763 for (const auto& report_block_data : video_sender_info.report_block_datas) {
1764 report->AddStats(ProduceRemoteInboundRtpStreamStatsFromReportBlockData(
1765 report_block_data, cricket::MEDIA_TYPE_VIDEO, video_outbound_rtps,
1766 *report));
1767 }
1768 }
1769 }
1770
ProduceTransportStats_n(int64_t timestamp_us,const std::map<std::string,cricket::TransportStats> & transport_stats_by_name,const std::map<std::string,CertificateStatsPair> & transport_cert_stats,RTCStatsReport * report) const1771 void RTCStatsCollector::ProduceTransportStats_n(
1772 int64_t timestamp_us,
1773 const std::map<std::string, cricket::TransportStats>&
1774 transport_stats_by_name,
1775 const std::map<std::string, CertificateStatsPair>& transport_cert_stats,
1776 RTCStatsReport* report) const {
1777 RTC_DCHECK(network_thread_->IsCurrent());
1778 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1779
1780 for (const auto& entry : transport_stats_by_name) {
1781 const std::string& transport_name = entry.first;
1782 const cricket::TransportStats& transport_stats = entry.second;
1783
1784 // Get reference to RTCP channel, if it exists.
1785 std::string rtcp_transport_stats_id;
1786 for (const cricket::TransportChannelStats& channel_stats :
1787 transport_stats.channel_stats) {
1788 if (channel_stats.component == cricket::ICE_CANDIDATE_COMPONENT_RTCP) {
1789 rtcp_transport_stats_id = RTCTransportStatsIDFromTransportChannel(
1790 transport_name, channel_stats.component);
1791 break;
1792 }
1793 }
1794
1795 // Get reference to local and remote certificates of this transport, if they
1796 // exist.
1797 const auto& certificate_stats_it =
1798 transport_cert_stats.find(transport_name);
1799 RTC_DCHECK(certificate_stats_it != transport_cert_stats.cend());
1800 std::string local_certificate_id;
1801 if (certificate_stats_it->second.local) {
1802 local_certificate_id = RTCCertificateIDFromFingerprint(
1803 certificate_stats_it->second.local->fingerprint);
1804 }
1805 std::string remote_certificate_id;
1806 if (certificate_stats_it->second.remote) {
1807 remote_certificate_id = RTCCertificateIDFromFingerprint(
1808 certificate_stats_it->second.remote->fingerprint);
1809 }
1810
1811 // There is one transport stats for each channel.
1812 for (const cricket::TransportChannelStats& channel_stats :
1813 transport_stats.channel_stats) {
1814 std::unique_ptr<RTCTransportStats> transport_stats(
1815 new RTCTransportStats(RTCTransportStatsIDFromTransportChannel(
1816 transport_name, channel_stats.component),
1817 timestamp_us));
1818 transport_stats->bytes_sent = 0;
1819 transport_stats->packets_sent = 0;
1820 transport_stats->bytes_received = 0;
1821 transport_stats->packets_received = 0;
1822 transport_stats->dtls_state =
1823 DtlsTransportStateToRTCDtlsTransportState(channel_stats.dtls_state);
1824 transport_stats->selected_candidate_pair_changes =
1825 channel_stats.ice_transport_stats.selected_candidate_pair_changes;
1826 for (const cricket::ConnectionInfo& info :
1827 channel_stats.ice_transport_stats.connection_infos) {
1828 *transport_stats->bytes_sent += info.sent_total_bytes;
1829 *transport_stats->packets_sent +=
1830 info.sent_total_packets - info.sent_discarded_packets;
1831 *transport_stats->bytes_received += info.recv_total_bytes;
1832 *transport_stats->packets_received += info.packets_received;
1833 if (info.best_connection) {
1834 transport_stats->selected_candidate_pair_id =
1835 RTCIceCandidatePairStatsIDFromConnectionInfo(info);
1836 }
1837 }
1838 if (channel_stats.component != cricket::ICE_CANDIDATE_COMPONENT_RTCP &&
1839 !rtcp_transport_stats_id.empty()) {
1840 transport_stats->rtcp_transport_stats_id = rtcp_transport_stats_id;
1841 }
1842 if (!local_certificate_id.empty())
1843 transport_stats->local_certificate_id = local_certificate_id;
1844 if (!remote_certificate_id.empty())
1845 transport_stats->remote_certificate_id = remote_certificate_id;
1846 // Crypto information
1847 if (channel_stats.ssl_version_bytes) {
1848 char bytes[5];
1849 snprintf(bytes, sizeof(bytes), "%04X", channel_stats.ssl_version_bytes);
1850 transport_stats->tls_version = bytes;
1851 }
1852 if (channel_stats.ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL &&
1853 rtc::SSLStreamAdapter::SslCipherSuiteToName(
1854 channel_stats.ssl_cipher_suite)
1855 .length()) {
1856 transport_stats->dtls_cipher =
1857 rtc::SSLStreamAdapter::SslCipherSuiteToName(
1858 channel_stats.ssl_cipher_suite);
1859 }
1860 if (channel_stats.srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE &&
1861 rtc::SrtpCryptoSuiteToName(channel_stats.srtp_crypto_suite)
1862 .length()) {
1863 transport_stats->srtp_cipher =
1864 rtc::SrtpCryptoSuiteToName(channel_stats.srtp_crypto_suite);
1865 }
1866 report->AddStats(std::move(transport_stats));
1867 }
1868 }
1869 }
1870
1871 std::map<std::string, RTCStatsCollector::CertificateStatsPair>
PrepareTransportCertificateStats_n(const std::map<std::string,cricket::TransportStats> & transport_stats_by_name) const1872 RTCStatsCollector::PrepareTransportCertificateStats_n(
1873 const std::map<std::string, cricket::TransportStats>&
1874 transport_stats_by_name) const {
1875 RTC_DCHECK(network_thread_->IsCurrent());
1876 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1877
1878 std::map<std::string, CertificateStatsPair> transport_cert_stats;
1879 for (const auto& entry : transport_stats_by_name) {
1880 const std::string& transport_name = entry.first;
1881
1882 CertificateStatsPair certificate_stats_pair;
1883 rtc::scoped_refptr<rtc::RTCCertificate> local_certificate;
1884 if (pc_->GetLocalCertificate(transport_name, &local_certificate)) {
1885 certificate_stats_pair.local =
1886 local_certificate->GetSSLCertificateChain().GetStats();
1887 }
1888
1889 std::unique_ptr<rtc::SSLCertChain> remote_cert_chain =
1890 pc_->GetRemoteSSLCertChain(transport_name);
1891 if (remote_cert_chain) {
1892 certificate_stats_pair.remote = remote_cert_chain->GetStats();
1893 }
1894
1895 transport_cert_stats.insert(
1896 std::make_pair(transport_name, std::move(certificate_stats_pair)));
1897 }
1898 return transport_cert_stats;
1899 }
1900
1901 std::vector<RTCStatsCollector::RtpTransceiverStatsInfo>
PrepareTransceiverStatsInfos_s_w() const1902 RTCStatsCollector::PrepareTransceiverStatsInfos_s_w() const {
1903 RTC_DCHECK(signaling_thread_->IsCurrent());
1904
1905 std::vector<RtpTransceiverStatsInfo> transceiver_stats_infos;
1906 // These are used to invoke GetStats for all the media channels together in
1907 // one worker thread hop.
1908 std::map<cricket::VoiceMediaChannel*,
1909 std::unique_ptr<cricket::VoiceMediaInfo>>
1910 voice_stats;
1911 std::map<cricket::VideoMediaChannel*,
1912 std::unique_ptr<cricket::VideoMediaInfo>>
1913 video_stats;
1914
1915 {
1916 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1917
1918 for (const auto& transceiver : pc_->GetTransceiversInternal()) {
1919 cricket::MediaType media_type = transceiver->media_type();
1920
1921 // Prepare stats entry. The TrackMediaInfoMap will be filled in after the
1922 // stats have been fetched on the worker thread.
1923 transceiver_stats_infos.emplace_back();
1924 RtpTransceiverStatsInfo& stats = transceiver_stats_infos.back();
1925 stats.transceiver = transceiver->internal();
1926 stats.media_type = media_type;
1927
1928 cricket::ChannelInterface* channel = transceiver->internal()->channel();
1929 if (!channel) {
1930 // The remaining fields require a BaseChannel.
1931 continue;
1932 }
1933
1934 stats.mid = channel->content_name();
1935 stats.transport_name = channel->transport_name();
1936
1937 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1938 auto* voice_channel = static_cast<cricket::VoiceChannel*>(channel);
1939 RTC_DCHECK(voice_stats.find(voice_channel->media_channel()) ==
1940 voice_stats.end());
1941 voice_stats[voice_channel->media_channel()] =
1942 std::make_unique<cricket::VoiceMediaInfo>();
1943 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1944 auto* video_channel = static_cast<cricket::VideoChannel*>(channel);
1945 RTC_DCHECK(video_stats.find(video_channel->media_channel()) ==
1946 video_stats.end());
1947 video_stats[video_channel->media_channel()] =
1948 std::make_unique<cricket::VideoMediaInfo>();
1949 } else {
1950 RTC_NOTREACHED();
1951 }
1952 }
1953 }
1954
1955 // We jump to the worker thread and call GetStats() on each media channel. At
1956 // the same time we construct the TrackMediaInfoMaps, which also needs info
1957 // from the worker thread. This minimizes the number of thread jumps.
1958 worker_thread_->Invoke<void>(RTC_FROM_HERE, [&] {
1959 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1960
1961 for (const auto& entry : voice_stats) {
1962 if (!entry.first->GetStats(entry.second.get(),
1963 /*get_and_clear_legacy_stats=*/false)) {
1964 RTC_LOG(LS_WARNING) << "Failed to get voice stats.";
1965 }
1966 }
1967 for (const auto& entry : video_stats) {
1968 if (!entry.first->GetStats(entry.second.get())) {
1969 RTC_LOG(LS_WARNING) << "Failed to get video stats.";
1970 }
1971 }
1972
1973 // Create the TrackMediaInfoMap for each transceiver stats object.
1974 for (auto& stats : transceiver_stats_infos) {
1975 auto transceiver = stats.transceiver;
1976 std::unique_ptr<cricket::VoiceMediaInfo> voice_media_info;
1977 std::unique_ptr<cricket::VideoMediaInfo> video_media_info;
1978 if (transceiver->channel()) {
1979 cricket::MediaType media_type = transceiver->media_type();
1980 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1981 auto* voice_channel =
1982 static_cast<cricket::VoiceChannel*>(transceiver->channel());
1983 RTC_DCHECK(voice_stats[voice_channel->media_channel()]);
1984 voice_media_info =
1985 std::move(voice_stats[voice_channel->media_channel()]);
1986 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1987 auto* video_channel =
1988 static_cast<cricket::VideoChannel*>(transceiver->channel());
1989 RTC_DCHECK(video_stats[video_channel->media_channel()]);
1990 video_media_info =
1991 std::move(video_stats[video_channel->media_channel()]);
1992 }
1993 }
1994 std::vector<rtc::scoped_refptr<RtpSenderInternal>> senders;
1995 for (const auto& sender : transceiver->senders()) {
1996 senders.push_back(sender->internal());
1997 }
1998 std::vector<rtc::scoped_refptr<RtpReceiverInternal>> receivers;
1999 for (const auto& receiver : transceiver->receivers()) {
2000 receivers.push_back(receiver->internal());
2001 }
2002 stats.track_media_info_map = std::make_unique<TrackMediaInfoMap>(
2003 std::move(voice_media_info), std::move(video_media_info), senders,
2004 receivers);
2005 }
2006 });
2007
2008 return transceiver_stats_infos;
2009 }
2010
PrepareTransportNames_s() const2011 std::set<std::string> RTCStatsCollector::PrepareTransportNames_s() const {
2012 RTC_DCHECK(signaling_thread_->IsCurrent());
2013 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
2014
2015 std::set<std::string> transport_names;
2016 for (const auto& transceiver : pc_->GetTransceiversInternal()) {
2017 if (transceiver->internal()->channel()) {
2018 transport_names.insert(
2019 transceiver->internal()->channel()->transport_name());
2020 }
2021 }
2022 if (pc_->rtp_data_channel()) {
2023 transport_names.insert(pc_->rtp_data_channel()->transport_name());
2024 }
2025 if (pc_->sctp_transport_name()) {
2026 transport_names.insert(*pc_->sctp_transport_name());
2027 }
2028 return transport_names;
2029 }
2030
OnRtpDataChannelCreated(RtpDataChannel * channel)2031 void RTCStatsCollector::OnRtpDataChannelCreated(RtpDataChannel* channel) {
2032 channel->SignalOpened.connect(this, &RTCStatsCollector::OnDataChannelOpened);
2033 channel->SignalClosed.connect(this, &RTCStatsCollector::OnDataChannelClosed);
2034 }
2035
OnSctpDataChannelCreated(SctpDataChannel * channel)2036 void RTCStatsCollector::OnSctpDataChannelCreated(SctpDataChannel* channel) {
2037 channel->SignalOpened.connect(this, &RTCStatsCollector::OnDataChannelOpened);
2038 channel->SignalClosed.connect(this, &RTCStatsCollector::OnDataChannelClosed);
2039 }
2040
OnDataChannelOpened(DataChannelInterface * channel)2041 void RTCStatsCollector::OnDataChannelOpened(DataChannelInterface* channel) {
2042 RTC_DCHECK(signaling_thread_->IsCurrent());
2043 bool result = internal_record_.opened_data_channels
2044 .insert(reinterpret_cast<uintptr_t>(channel))
2045 .second;
2046 ++internal_record_.data_channels_opened;
2047 RTC_DCHECK(result);
2048 }
2049
OnDataChannelClosed(DataChannelInterface * channel)2050 void RTCStatsCollector::OnDataChannelClosed(DataChannelInterface* channel) {
2051 RTC_DCHECK(signaling_thread_->IsCurrent());
2052 // Only channels that have been fully opened (and have increased the
2053 // |data_channels_opened_| counter) increase the closed counter.
2054 if (internal_record_.opened_data_channels.erase(
2055 reinterpret_cast<uintptr_t>(channel))) {
2056 ++internal_record_.data_channels_closed;
2057 }
2058 }
2059
CandidateTypeToRTCIceCandidateTypeForTesting(const std::string & type)2060 const char* CandidateTypeToRTCIceCandidateTypeForTesting(
2061 const std::string& type) {
2062 return CandidateTypeToRTCIceCandidateType(type);
2063 }
2064
DataStateToRTCDataChannelStateForTesting(DataChannelInterface::DataState state)2065 const char* DataStateToRTCDataChannelStateForTesting(
2066 DataChannelInterface::DataState state) {
2067 return DataStateToRTCDataChannelState(state);
2068 }
2069
2070 } // namespace webrtc
2071