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