blob: d71b3f2fd34196b99279c65e127b3963d0739bf3 [file] [log] [blame]
hbosd565b732016-08-30 14:04:35 -07001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/rtcstatscollector.h"
hbosd565b732016-08-30 14:04:35 -070012
13#include <memory>
Steve Anton36b29d12017-10-30 09:57:42 -070014#include <string>
hbosd565b732016-08-30 14:04:35 -070015#include <utility>
16#include <vector>
17
Patrik Höglunde2d6a062017-10-05 14:53:33 +020018#include "api/candidate.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/mediastreaminterface.h"
20#include "api/peerconnectioninterface.h"
21#include "media/base/mediachannel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "p2p/base/p2pconstants.h"
23#include "p2p/base/port.h"
24#include "pc/peerconnection.h"
Henrik Boström5b3541f2018-03-19 13:52:56 +010025#include "pc/rtcstatstraversal.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/checks.h"
Steve Anton57858b32018-02-15 15:19:50 -080027#include "rtc_base/ptr_util.h"
Jonas Olsson43568dd2018-06-11 16:25:54 +020028#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/timeutils.h"
30#include "rtc_base/trace_event.h"
hbosd565b732016-08-30 14:04:35 -070031
32namespace webrtc {
33
hboscc555c52016-10-18 12:48:31 -070034namespace {
35
hbos2fa7c672016-10-24 04:00:05 -070036std::string RTCCertificateIDFromFingerprint(const std::string& fingerprint) {
37 return "RTCCertificate_" + fingerprint;
38}
39
Steve Anton57858b32018-02-15 15:19:50 -080040std::string RTCCodecStatsIDFromMidDirectionAndPayload(const std::string& mid,
41 bool inbound,
42 uint32_t payload_type) {
Jonas Olsson43568dd2018-06-11 16:25:54 +020043 char buf[1024];
44 rtc::SimpleStringBuilder sb(buf);
45 sb << "RTCCodec_" << mid << (inbound ? "_Inbound_" : "_Outbound_")
46 << payload_type;
47 return sb.str();
hbos0adb8282016-11-23 02:32:06 -080048}
49
hbos2fa7c672016-10-24 04:00:05 -070050std::string RTCIceCandidatePairStatsIDFromConnectionInfo(
51 const cricket::ConnectionInfo& info) {
Jonas Olsson43568dd2018-06-11 16:25:54 +020052 char buf[4096];
53 rtc::SimpleStringBuilder sb(buf);
54 sb << "RTCIceCandidatePair_" << info.local_candidate.id() << "_"
55 << info.remote_candidate.id();
56 return sb.str();
hbos2fa7c672016-10-24 04:00:05 -070057}
58
Harald Alvestranda3dab842018-01-14 09:18:58 +010059const char kSender[] = "sender";
60const char kReceiver[] = "receiver";
61
62std::string RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
63 const char* direction,
Harald Alvestrandc72af932018-01-11 17:18:19 +010064 int attachment_id) {
Jonas Olsson43568dd2018-06-11 16:25:54 +020065 char buf[1024];
66 rtc::SimpleStringBuilder sb(buf);
67 sb << "RTCMediaStreamTrack_" << direction << "_" << attachment_id;
68 return sb.str();
hbos09bc1282016-11-08 06:29:22 -080069}
70
hbos2fa7c672016-10-24 04:00:05 -070071std::string RTCTransportStatsIDFromTransportChannel(
72 const std::string& transport_name, int channel_component) {
Jonas Olsson43568dd2018-06-11 16:25:54 +020073 char buf[1024];
74 rtc::SimpleStringBuilder sb(buf);
75 sb << "RTCTransport_" << transport_name << "_" << channel_component;
76 return sb.str();
hbos2fa7c672016-10-24 04:00:05 -070077}
78
hboseeafe942016-11-01 03:00:17 -070079std::string RTCInboundRTPStreamStatsIDFromSSRC(bool audio, uint32_t ssrc) {
Jonas Olsson43568dd2018-06-11 16:25:54 +020080 char buf[1024];
81 rtc::SimpleStringBuilder sb(buf);
82 sb << "RTCInboundRTP" << (audio ? "Audio" : "Video") << "Stream_" << ssrc;
83 return sb.str();
hboseeafe942016-11-01 03:00:17 -070084}
85
hbos6ded1902016-11-01 01:50:46 -070086std::string RTCOutboundRTPStreamStatsIDFromSSRC(bool audio, uint32_t ssrc) {
Jonas Olsson43568dd2018-06-11 16:25:54 +020087 char buf[1024];
88 rtc::SimpleStringBuilder sb(buf);
89 sb << "RTCOutboundRTP" << (audio ? "Audio" : "Video") << "Stream_" << ssrc;
90 return sb.str();
hbos6ded1902016-11-01 01:50:46 -070091}
92
hbosab9f6e42016-10-07 02:18:47 -070093const char* CandidateTypeToRTCIceCandidateType(const std::string& type) {
94 if (type == cricket::LOCAL_PORT_TYPE)
95 return RTCIceCandidateType::kHost;
96 if (type == cricket::STUN_PORT_TYPE)
97 return RTCIceCandidateType::kSrflx;
98 if (type == cricket::PRFLX_PORT_TYPE)
99 return RTCIceCandidateType::kPrflx;
100 if (type == cricket::RELAY_PORT_TYPE)
101 return RTCIceCandidateType::kRelay;
102 RTC_NOTREACHED();
103 return nullptr;
104}
105
hboscc555c52016-10-18 12:48:31 -0700106const char* DataStateToRTCDataChannelState(
107 DataChannelInterface::DataState state) {
108 switch (state) {
109 case DataChannelInterface::kConnecting:
110 return RTCDataChannelState::kConnecting;
111 case DataChannelInterface::kOpen:
112 return RTCDataChannelState::kOpen;
113 case DataChannelInterface::kClosing:
114 return RTCDataChannelState::kClosing;
115 case DataChannelInterface::kClosed:
116 return RTCDataChannelState::kClosed;
117 default:
118 RTC_NOTREACHED();
119 return nullptr;
120 }
121}
122
hbos06495bc2017-01-02 08:08:18 -0800123const char* IceCandidatePairStateToRTCStatsIceCandidatePairState(
124 cricket::IceCandidatePairState state) {
125 switch (state) {
126 case cricket::IceCandidatePairState::WAITING:
127 return RTCStatsIceCandidatePairState::kWaiting;
128 case cricket::IceCandidatePairState::IN_PROGRESS:
129 return RTCStatsIceCandidatePairState::kInProgress;
130 case cricket::IceCandidatePairState::SUCCEEDED:
131 return RTCStatsIceCandidatePairState::kSucceeded;
132 case cricket::IceCandidatePairState::FAILED:
133 return RTCStatsIceCandidatePairState::kFailed;
134 default:
135 RTC_NOTREACHED();
136 return nullptr;
137 }
138}
139
hbos7064d592017-01-16 07:38:02 -0800140const char* DtlsTransportStateToRTCDtlsTransportState(
141 cricket::DtlsTransportState state) {
142 switch (state) {
143 case cricket::DTLS_TRANSPORT_NEW:
144 return RTCDtlsTransportState::kNew;
145 case cricket::DTLS_TRANSPORT_CONNECTING:
146 return RTCDtlsTransportState::kConnecting;
147 case cricket::DTLS_TRANSPORT_CONNECTED:
148 return RTCDtlsTransportState::kConnected;
149 case cricket::DTLS_TRANSPORT_CLOSED:
150 return RTCDtlsTransportState::kClosed;
151 case cricket::DTLS_TRANSPORT_FAILED:
152 return RTCDtlsTransportState::kFailed;
153 default:
154 RTC_NOTREACHED();
155 return nullptr;
156 }
157}
158
Gary Liu37e489c2017-11-21 10:49:36 -0800159const char* NetworkAdapterTypeToStatsType(rtc::AdapterType type) {
160 switch (type) {
161 case rtc::ADAPTER_TYPE_CELLULAR:
162 return RTCNetworkType::kCellular;
163 case rtc::ADAPTER_TYPE_ETHERNET:
164 return RTCNetworkType::kEthernet;
165 case rtc::ADAPTER_TYPE_WIFI:
166 return RTCNetworkType::kWifi;
167 case rtc::ADAPTER_TYPE_VPN:
168 return RTCNetworkType::kVpn;
169 case rtc::ADAPTER_TYPE_UNKNOWN:
170 case rtc::ADAPTER_TYPE_LOOPBACK:
171 return RTCNetworkType::kUnknown;
172 }
173 RTC_NOTREACHED();
174 return nullptr;
175}
176
hbos9e302742017-01-20 02:47:10 -0800177double DoubleAudioLevelFromIntAudioLevel(int audio_level) {
178 RTC_DCHECK_GE(audio_level, 0);
179 RTC_DCHECK_LE(audio_level, 32767);
180 return audio_level / 32767.0;
181}
182
hbos0adb8282016-11-23 02:32:06 -0800183std::unique_ptr<RTCCodecStats> CodecStatsFromRtpCodecParameters(
Steve Anton57858b32018-02-15 15:19:50 -0800184 uint64_t timestamp_us,
185 const std::string& mid,
186 bool inbound,
hbos0adb8282016-11-23 02:32:06 -0800187 const RtpCodecParameters& codec_params) {
188 RTC_DCHECK_GE(codec_params.payload_type, 0);
189 RTC_DCHECK_LE(codec_params.payload_type, 127);
deadbeefe702b302017-02-04 12:09:01 -0800190 RTC_DCHECK(codec_params.clock_rate);
hbos0adb8282016-11-23 02:32:06 -0800191 uint32_t payload_type = static_cast<uint32_t>(codec_params.payload_type);
192 std::unique_ptr<RTCCodecStats> codec_stats(new RTCCodecStats(
Steve Anton57858b32018-02-15 15:19:50 -0800193 RTCCodecStatsIDFromMidDirectionAndPayload(mid, inbound, payload_type),
hbos0adb8282016-11-23 02:32:06 -0800194 timestamp_us));
195 codec_stats->payload_type = payload_type;
hbos13f54b22017-02-28 06:56:04 -0800196 codec_stats->mime_type = codec_params.mime_type();
deadbeefe702b302017-02-04 12:09:01 -0800197 if (codec_params.clock_rate) {
198 codec_stats->clock_rate = static_cast<uint32_t>(*codec_params.clock_rate);
199 }
hbos0adb8282016-11-23 02:32:06 -0800200 return codec_stats;
201}
202
hbos09bc1282016-11-08 06:29:22 -0800203void SetMediaStreamTrackStatsFromMediaStreamTrackInterface(
204 const MediaStreamTrackInterface& track,
205 RTCMediaStreamTrackStats* track_stats) {
206 track_stats->track_identifier = track.id();
207 track_stats->ended = (track.state() == MediaStreamTrackInterface::kEnded);
208}
209
hbos820f5782016-11-22 03:16:50 -0800210// Provides the media independent counters (both audio and video).
hboseeafe942016-11-01 03:00:17 -0700211void SetInboundRTPStreamStatsFromMediaReceiverInfo(
212 const cricket::MediaReceiverInfo& media_receiver_info,
213 RTCInboundRTPStreamStats* inbound_stats) {
214 RTC_DCHECK(inbound_stats);
hbos3443bb72017-02-07 06:28:11 -0800215 inbound_stats->ssrc = media_receiver_info.ssrc();
Harald Alvestrand89061872018-01-02 14:08:34 +0100216 // TODO(hbos): Support the remote case. https://crbug.com/657855
hboseeafe942016-11-01 03:00:17 -0700217 inbound_stats->is_remote = false;
hboseeafe942016-11-01 03:00:17 -0700218 inbound_stats->packets_received =
219 static_cast<uint32_t>(media_receiver_info.packets_rcvd);
220 inbound_stats->bytes_received =
221 static_cast<uint64_t>(media_receiver_info.bytes_rcvd);
hbos02cd4d62016-12-09 04:19:44 -0800222 inbound_stats->packets_lost =
Harald Alvestrand719487e2017-12-13 12:26:04 +0100223 static_cast<int32_t>(media_receiver_info.packets_lost);
hboseeafe942016-11-01 03:00:17 -0700224 inbound_stats->fraction_lost =
225 static_cast<double>(media_receiver_info.fraction_lost);
226}
227
228void SetInboundRTPStreamStatsFromVoiceReceiverInfo(
Steve Anton57858b32018-02-15 15:19:50 -0800229 const std::string& mid,
hboseeafe942016-11-01 03:00:17 -0700230 const cricket::VoiceReceiverInfo& voice_receiver_info,
hbos820f5782016-11-22 03:16:50 -0800231 RTCInboundRTPStreamStats* inbound_audio) {
hboseeafe942016-11-01 03:00:17 -0700232 SetInboundRTPStreamStatsFromMediaReceiverInfo(
hbos820f5782016-11-22 03:16:50 -0800233 voice_receiver_info, inbound_audio);
234 inbound_audio->media_type = "audio";
hbos585a9b12017-02-07 04:59:16 -0800235 if (voice_receiver_info.codec_payload_type) {
Steve Anton57858b32018-02-15 15:19:50 -0800236 inbound_audio->codec_id = RTCCodecStatsIDFromMidDirectionAndPayload(
237 mid, true, *voice_receiver_info.codec_payload_type);
hbos585a9b12017-02-07 04:59:16 -0800238 }
hbos820f5782016-11-22 03:16:50 -0800239 inbound_audio->jitter =
hboseeafe942016-11-01 03:00:17 -0700240 static_cast<double>(voice_receiver_info.jitter_ms) /
241 rtc::kNumMillisecsPerSec;
hbos820f5782016-11-22 03:16:50 -0800242 // |fir_count|, |pli_count| and |sli_count| are only valid for video and are
243 // purposefully left undefined for audio.
hboseeafe942016-11-01 03:00:17 -0700244}
245
246void SetInboundRTPStreamStatsFromVideoReceiverInfo(
Steve Anton57858b32018-02-15 15:19:50 -0800247 const std::string& mid,
hboseeafe942016-11-01 03:00:17 -0700248 const cricket::VideoReceiverInfo& video_receiver_info,
hbos820f5782016-11-22 03:16:50 -0800249 RTCInboundRTPStreamStats* inbound_video) {
hboseeafe942016-11-01 03:00:17 -0700250 SetInboundRTPStreamStatsFromMediaReceiverInfo(
hbos820f5782016-11-22 03:16:50 -0800251 video_receiver_info, inbound_video);
252 inbound_video->media_type = "video";
hbos585a9b12017-02-07 04:59:16 -0800253 if (video_receiver_info.codec_payload_type) {
Steve Anton57858b32018-02-15 15:19:50 -0800254 inbound_video->codec_id = RTCCodecStatsIDFromMidDirectionAndPayload(
255 mid, true, *video_receiver_info.codec_payload_type);
hbos585a9b12017-02-07 04:59:16 -0800256 }
hbos820f5782016-11-22 03:16:50 -0800257 inbound_video->fir_count =
258 static_cast<uint32_t>(video_receiver_info.firs_sent);
259 inbound_video->pli_count =
260 static_cast<uint32_t>(video_receiver_info.plis_sent);
261 inbound_video->nack_count =
262 static_cast<uint32_t>(video_receiver_info.nacks_sent);
hbos6769c492017-01-02 08:35:13 -0800263 inbound_video->frames_decoded = video_receiver_info.frames_decoded;
hbosa51d4f32017-02-16 05:34:48 -0800264 if (video_receiver_info.qp_sum)
265 inbound_video->qp_sum = *video_receiver_info.qp_sum;
hboseeafe942016-11-01 03:00:17 -0700266}
267
hbos820f5782016-11-22 03:16:50 -0800268// Provides the media independent counters (both audio and video).
hbos6ded1902016-11-01 01:50:46 -0700269void SetOutboundRTPStreamStatsFromMediaSenderInfo(
270 const cricket::MediaSenderInfo& media_sender_info,
271 RTCOutboundRTPStreamStats* outbound_stats) {
272 RTC_DCHECK(outbound_stats);
hbos3443bb72017-02-07 06:28:11 -0800273 outbound_stats->ssrc = media_sender_info.ssrc();
Harald Alvestrand89061872018-01-02 14:08:34 +0100274 // TODO(hbos): Support the remote case. https://crbug.com/657856
hbos6ded1902016-11-01 01:50:46 -0700275 outbound_stats->is_remote = false;
hbos6ded1902016-11-01 01:50:46 -0700276 outbound_stats->packets_sent =
277 static_cast<uint32_t>(media_sender_info.packets_sent);
278 outbound_stats->bytes_sent =
279 static_cast<uint64_t>(media_sender_info.bytes_sent);
hbos6ded1902016-11-01 01:50:46 -0700280}
281
282void SetOutboundRTPStreamStatsFromVoiceSenderInfo(
Steve Anton57858b32018-02-15 15:19:50 -0800283 const std::string& mid,
hbos6ded1902016-11-01 01:50:46 -0700284 const cricket::VoiceSenderInfo& voice_sender_info,
285 RTCOutboundRTPStreamStats* outbound_audio) {
286 SetOutboundRTPStreamStatsFromMediaSenderInfo(
287 voice_sender_info, outbound_audio);
288 outbound_audio->media_type = "audio";
hbos585a9b12017-02-07 04:59:16 -0800289 if (voice_sender_info.codec_payload_type) {
Steve Anton57858b32018-02-15 15:19:50 -0800290 outbound_audio->codec_id = RTCCodecStatsIDFromMidDirectionAndPayload(
291 mid, false, *voice_sender_info.codec_payload_type);
hbos585a9b12017-02-07 04:59:16 -0800292 }
hbos6ded1902016-11-01 01:50:46 -0700293 // |fir_count|, |pli_count| and |sli_count| are only valid for video and are
294 // purposefully left undefined for audio.
295}
296
297void SetOutboundRTPStreamStatsFromVideoSenderInfo(
Steve Anton57858b32018-02-15 15:19:50 -0800298 const std::string& mid,
hbos6ded1902016-11-01 01:50:46 -0700299 const cricket::VideoSenderInfo& video_sender_info,
300 RTCOutboundRTPStreamStats* outbound_video) {
301 SetOutboundRTPStreamStatsFromMediaSenderInfo(
302 video_sender_info, outbound_video);
303 outbound_video->media_type = "video";
hbos585a9b12017-02-07 04:59:16 -0800304 if (video_sender_info.codec_payload_type) {
Steve Anton57858b32018-02-15 15:19:50 -0800305 outbound_video->codec_id = RTCCodecStatsIDFromMidDirectionAndPayload(
306 mid, false, *video_sender_info.codec_payload_type);
hbos585a9b12017-02-07 04:59:16 -0800307 }
hbos6ded1902016-11-01 01:50:46 -0700308 outbound_video->fir_count =
309 static_cast<uint32_t>(video_sender_info.firs_rcvd);
310 outbound_video->pli_count =
311 static_cast<uint32_t>(video_sender_info.plis_rcvd);
312 outbound_video->nack_count =
313 static_cast<uint32_t>(video_sender_info.nacks_rcvd);
hbos6769c492017-01-02 08:35:13 -0800314 if (video_sender_info.qp_sum)
315 outbound_video->qp_sum = *video_sender_info.qp_sum;
316 outbound_video->frames_encoded = video_sender_info.frames_encoded;
hbos6ded1902016-11-01 01:50:46 -0700317}
318
hbos02ba2112016-10-28 05:14:53 -0700319void ProduceCertificateStatsFromSSLCertificateStats(
320 int64_t timestamp_us, const rtc::SSLCertificateStats& certificate_stats,
321 RTCStatsReport* report) {
322 RTCCertificateStats* prev_certificate_stats = nullptr;
323 for (const rtc::SSLCertificateStats* s = &certificate_stats; s;
324 s = s->issuer.get()) {
hbos02d2a922016-12-21 01:29:05 -0800325 std::string certificate_stats_id =
326 RTCCertificateIDFromFingerprint(s->fingerprint);
327 // It is possible for the same certificate to show up multiple times, e.g.
328 // if local and remote side use the same certificate in a loopback call.
329 // If the report already contains stats for this certificate, skip it.
330 if (report->Get(certificate_stats_id)) {
331 RTC_DCHECK_EQ(s, &certificate_stats);
332 break;
333 }
hbos02ba2112016-10-28 05:14:53 -0700334 RTCCertificateStats* certificate_stats = new RTCCertificateStats(
hbos02d2a922016-12-21 01:29:05 -0800335 certificate_stats_id, timestamp_us);
hbos02ba2112016-10-28 05:14:53 -0700336 certificate_stats->fingerprint = s->fingerprint;
337 certificate_stats->fingerprint_algorithm = s->fingerprint_algorithm;
338 certificate_stats->base64_certificate = s->base64_certificate;
339 if (prev_certificate_stats)
340 prev_certificate_stats->issuer_certificate_id = certificate_stats->id();
341 report->AddStats(std::unique_ptr<RTCCertificateStats>(certificate_stats));
342 prev_certificate_stats = certificate_stats;
343 }
344}
345
346const std::string& ProduceIceCandidateStats(
347 int64_t timestamp_us, const cricket::Candidate& candidate, bool is_local,
hbosb4e426e2017-01-02 09:59:31 -0800348 const std::string& transport_id, RTCStatsReport* report) {
hbos02ba2112016-10-28 05:14:53 -0700349 const std::string& id = "RTCIceCandidate_" + candidate.id();
350 const RTCStats* stats = report->Get(id);
351 if (!stats) {
352 std::unique_ptr<RTCIceCandidateStats> candidate_stats;
353 if (is_local)
354 candidate_stats.reset(new RTCLocalIceCandidateStats(id, timestamp_us));
355 else
356 candidate_stats.reset(new RTCRemoteIceCandidateStats(id, timestamp_us));
hbosb4e426e2017-01-02 09:59:31 -0800357 candidate_stats->transport_id = transport_id;
Gary Liu37e489c2017-11-21 10:49:36 -0800358 if (is_local) {
359 candidate_stats->network_type =
360 NetworkAdapterTypeToStatsType(candidate.network_type());
361 } else {
362 // We don't expect to know the adapter type of remote candidates.
363 RTC_DCHECK_EQ(rtc::ADAPTER_TYPE_UNKNOWN, candidate.network_type());
364 }
hbos02ba2112016-10-28 05:14:53 -0700365 candidate_stats->ip = candidate.address().ipaddr().ToString();
366 candidate_stats->port = static_cast<int32_t>(candidate.address().port());
367 candidate_stats->protocol = candidate.protocol();
368 candidate_stats->candidate_type = CandidateTypeToRTCIceCandidateType(
369 candidate.type());
370 candidate_stats->priority = static_cast<int32_t>(candidate.priority());
371
372 stats = candidate_stats.get();
373 report->AddStats(std::move(candidate_stats));
374 }
375 RTC_DCHECK_EQ(stats->type(), is_local ? RTCLocalIceCandidateStats::kType
376 : RTCRemoteIceCandidateStats::kType);
377 return stats->id();
378}
379
hbos9e302742017-01-20 02:47:10 -0800380std::unique_ptr<RTCMediaStreamTrackStats>
381ProduceMediaStreamTrackStatsFromVoiceSenderInfo(
382 int64_t timestamp_us,
383 const AudioTrackInterface& audio_track,
Harald Alvestrandc72af932018-01-11 17:18:19 +0100384 const cricket::VoiceSenderInfo& voice_sender_info,
385 int attachment_id) {
hbos9e302742017-01-20 02:47:10 -0800386 std::unique_ptr<RTCMediaStreamTrackStats> audio_track_stats(
387 new RTCMediaStreamTrackStats(
Harald Alvestranda3dab842018-01-14 09:18:58 +0100388 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(kSender,
389 attachment_id),
Harald Alvestrandc72af932018-01-11 17:18:19 +0100390 timestamp_us, RTCMediaStreamTrackKind::kAudio));
hbos9e302742017-01-20 02:47:10 -0800391 SetMediaStreamTrackStatsFromMediaStreamTrackInterface(
392 audio_track, audio_track_stats.get());
393 audio_track_stats->remote_source = false;
394 audio_track_stats->detached = false;
395 if (voice_sender_info.audio_level >= 0) {
396 audio_track_stats->audio_level = DoubleAudioLevelFromIntAudioLevel(
397 voice_sender_info.audio_level);
398 }
zsteine76bd3a2017-07-14 12:17:49 -0700399 audio_track_stats->total_audio_energy = voice_sender_info.total_input_energy;
400 audio_track_stats->total_samples_duration =
401 voice_sender_info.total_input_duration;
Ivo Creusen56d46092017-11-24 17:29:59 +0100402 if (voice_sender_info.apm_statistics.echo_return_loss) {
403 audio_track_stats->echo_return_loss =
404 *voice_sender_info.apm_statistics.echo_return_loss;
hbos9e302742017-01-20 02:47:10 -0800405 }
Ivo Creusen56d46092017-11-24 17:29:59 +0100406 if (voice_sender_info.apm_statistics.echo_return_loss_enhancement) {
407 audio_track_stats->echo_return_loss_enhancement =
408 *voice_sender_info.apm_statistics.echo_return_loss_enhancement;
hbos9e302742017-01-20 02:47:10 -0800409 }
410 return audio_track_stats;
411}
412
413std::unique_ptr<RTCMediaStreamTrackStats>
414ProduceMediaStreamTrackStatsFromVoiceReceiverInfo(
415 int64_t timestamp_us,
416 const AudioTrackInterface& audio_track,
Harald Alvestrandc72af932018-01-11 17:18:19 +0100417 const cricket::VoiceReceiverInfo& voice_receiver_info,
418 int attachment_id) {
419 // Since receiver tracks can't be reattached, we use the SSRC as
420 // an attachment identifier.
hbos9e302742017-01-20 02:47:10 -0800421 std::unique_ptr<RTCMediaStreamTrackStats> audio_track_stats(
422 new RTCMediaStreamTrackStats(
Harald Alvestranda3dab842018-01-14 09:18:58 +0100423 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(kReceiver,
424 attachment_id),
Harald Alvestrandc72af932018-01-11 17:18:19 +0100425 timestamp_us, RTCMediaStreamTrackKind::kAudio));
hbos9e302742017-01-20 02:47:10 -0800426 SetMediaStreamTrackStatsFromMediaStreamTrackInterface(
427 audio_track, audio_track_stats.get());
428 audio_track_stats->remote_source = true;
429 audio_track_stats->detached = false;
430 if (voice_receiver_info.audio_level >= 0) {
431 audio_track_stats->audio_level = DoubleAudioLevelFromIntAudioLevel(
432 voice_receiver_info.audio_level);
433 }
Gustaf Ullbergb0a02072017-10-02 12:00:34 +0200434 audio_track_stats->jitter_buffer_delay =
435 voice_receiver_info.jitter_buffer_delay_seconds;
zsteine76bd3a2017-07-14 12:17:49 -0700436 audio_track_stats->total_audio_energy =
437 voice_receiver_info.total_output_energy;
Steve Anton2dbc69f2017-08-24 17:15:13 -0700438 audio_track_stats->total_samples_received =
439 voice_receiver_info.total_samples_received;
zsteine76bd3a2017-07-14 12:17:49 -0700440 audio_track_stats->total_samples_duration =
441 voice_receiver_info.total_output_duration;
Steve Anton2dbc69f2017-08-24 17:15:13 -0700442 audio_track_stats->concealed_samples = voice_receiver_info.concealed_samples;
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +0200443 audio_track_stats->concealment_events =
444 voice_receiver_info.concealment_events;
hbos9e302742017-01-20 02:47:10 -0800445 return audio_track_stats;
446}
447
448std::unique_ptr<RTCMediaStreamTrackStats>
449ProduceMediaStreamTrackStatsFromVideoSenderInfo(
450 int64_t timestamp_us,
451 const VideoTrackInterface& video_track,
Harald Alvestrandc72af932018-01-11 17:18:19 +0100452 const cricket::VideoSenderInfo& video_sender_info,
453 int attachment_id) {
hbos9e302742017-01-20 02:47:10 -0800454 std::unique_ptr<RTCMediaStreamTrackStats> video_track_stats(
455 new RTCMediaStreamTrackStats(
Harald Alvestranda3dab842018-01-14 09:18:58 +0100456 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(kSender,
457
458 attachment_id),
Harald Alvestrandc72af932018-01-11 17:18:19 +0100459 timestamp_us, RTCMediaStreamTrackKind::kVideo));
hbos9e302742017-01-20 02:47:10 -0800460 SetMediaStreamTrackStatsFromMediaStreamTrackInterface(
461 video_track, video_track_stats.get());
462 video_track_stats->remote_source = false;
463 video_track_stats->detached = false;
464 video_track_stats->frame_width = static_cast<uint32_t>(
465 video_sender_info.send_frame_width);
466 video_track_stats->frame_height = static_cast<uint32_t>(
467 video_sender_info.send_frame_height);
hbosfefe0762017-01-20 06:14:25 -0800468 // TODO(hbos): Will reduce this by frames dropped due to congestion control
Harald Alvestrand89061872018-01-02 14:08:34 +0100469 // when available. https://crbug.com/659137
hbosfefe0762017-01-20 06:14:25 -0800470 video_track_stats->frames_sent = video_sender_info.frames_encoded;
Ilya Nikolaevskiy70473fc2018-02-28 16:35:03 +0100471 video_track_stats->huge_frames_sent = video_sender_info.huge_frames_sent;
hbos9e302742017-01-20 02:47:10 -0800472 return video_track_stats;
473}
474
475std::unique_ptr<RTCMediaStreamTrackStats>
476ProduceMediaStreamTrackStatsFromVideoReceiverInfo(
477 int64_t timestamp_us,
478 const VideoTrackInterface& video_track,
Harald Alvestrandc72af932018-01-11 17:18:19 +0100479 const cricket::VideoReceiverInfo& video_receiver_info,
480 int attachment_id) {
hbos9e302742017-01-20 02:47:10 -0800481 std::unique_ptr<RTCMediaStreamTrackStats> video_track_stats(
482 new RTCMediaStreamTrackStats(
Harald Alvestranda3dab842018-01-14 09:18:58 +0100483 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(kReceiver,
484
485 attachment_id),
Harald Alvestrandc72af932018-01-11 17:18:19 +0100486 timestamp_us, RTCMediaStreamTrackKind::kVideo));
hbos9e302742017-01-20 02:47:10 -0800487 SetMediaStreamTrackStatsFromMediaStreamTrackInterface(
488 video_track, video_track_stats.get());
489 video_track_stats->remote_source = true;
490 video_track_stats->detached = false;
491 if (video_receiver_info.frame_width > 0 &&
492 video_receiver_info.frame_height > 0) {
493 video_track_stats->frame_width = static_cast<uint32_t>(
494 video_receiver_info.frame_width);
495 video_track_stats->frame_height = static_cast<uint32_t>(
496 video_receiver_info.frame_height);
497 }
hbos42f6d2f2017-01-20 03:56:50 -0800498 video_track_stats->frames_received = video_receiver_info.frames_received;
hbosf64941f2017-01-20 07:39:09 -0800499 // TODO(hbos): When we support receiving simulcast, this should be the total
500 // number of frames correctly decoded, independent of which SSRC it was
501 // received from. Since we don't support that, this is correct and is the same
Harald Alvestrand89061872018-01-02 14:08:34 +0100502 // value as "RTCInboundRTPStreamStats.framesDecoded". https://crbug.com/659137
hbosf64941f2017-01-20 07:39:09 -0800503 video_track_stats->frames_decoded = video_receiver_info.frames_decoded;
hbos50cfe1f2017-01-23 07:21:55 -0800504 RTC_DCHECK_GE(video_receiver_info.frames_received,
505 video_receiver_info.frames_rendered);
506 video_track_stats->frames_dropped = video_receiver_info.frames_received -
507 video_receiver_info.frames_rendered;
hbos9e302742017-01-20 02:47:10 -0800508 return video_track_stats;
509}
510
Harald Alvestrand89061872018-01-02 14:08:34 +0100511void ProduceSenderMediaTrackStats(
512 int64_t timestamp_us,
513 const TrackMediaInfoMap& track_media_info_map,
Steve Anton57858b32018-02-15 15:19:50 -0800514 std::vector<rtc::scoped_refptr<RtpSenderInternal>> senders,
Harald Alvestrand89061872018-01-02 14:08:34 +0100515 RTCStatsReport* report) {
516 // This function iterates over the senders to generate outgoing track stats.
517
518 // TODO(hbos): Return stats of detached tracks. We have to perform stats
519 // gathering at the time of detachment to get accurate stats and timestamps.
520 // https://crbug.com/659137
Steve Anton57858b32018-02-15 15:19:50 -0800521 for (auto sender : senders) {
Harald Alvestrand89061872018-01-02 14:08:34 +0100522 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
523 AudioTrackInterface* track =
524 static_cast<AudioTrackInterface*>(sender->track().get());
525 if (!track)
526 continue;
Harald Alvestrandb8e12012018-01-23 15:28:16 +0100527 cricket::VoiceSenderInfo null_sender_info;
528 const cricket::VoiceSenderInfo* voice_sender_info = &null_sender_info;
529 // TODO(hta): Checking on ssrc is not proper. There should be a way
530 // to see from a sender whether it's connected or not.
531 // Related to https://crbug.com/8694 (using ssrc 0 to indicate "none")
Steve Anton57858b32018-02-15 15:19:50 -0800532 if (sender->ssrc() != 0) {
Harald Alvestrand76d29522018-01-30 14:43:29 +0100533 // When pc.close is called, sender info is discarded, so
534 // we generate zeroes instead. Bug: It should be retained.
535 // https://crbug.com/807174
Steve Anton57858b32018-02-15 15:19:50 -0800536 const cricket::VoiceSenderInfo* sender_info =
Harald Alvestrandb8e12012018-01-23 15:28:16 +0100537 track_media_info_map.GetVoiceSenderInfoBySsrc(sender->ssrc());
Harald Alvestrand76d29522018-01-30 14:43:29 +0100538 if (sender_info) {
539 voice_sender_info = sender_info;
540 } else {
541 RTC_LOG(LS_INFO)
542 << "RTCStatsCollector: No voice sender info for sender with ssrc "
543 << sender->ssrc();
544 }
Harald Alvestrandb8e12012018-01-23 15:28:16 +0100545 }
Harald Alvestrand89061872018-01-02 14:08:34 +0100546 std::unique_ptr<RTCMediaStreamTrackStats> audio_track_stats =
Harald Alvestrandc72af932018-01-11 17:18:19 +0100547 ProduceMediaStreamTrackStatsFromVoiceSenderInfo(
548 timestamp_us, *track, *voice_sender_info, sender->AttachmentId());
Harald Alvestrand89061872018-01-02 14:08:34 +0100549 report->AddStats(std::move(audio_track_stats));
550 } else if (sender->media_type() == cricket::MEDIA_TYPE_VIDEO) {
551 VideoTrackInterface* track =
552 static_cast<VideoTrackInterface*>(sender->track().get());
553 if (!track)
554 continue;
Harald Alvestrandb8e12012018-01-23 15:28:16 +0100555 cricket::VideoSenderInfo null_sender_info;
556 const cricket::VideoSenderInfo* video_sender_info = &null_sender_info;
557 // TODO(hta): Check on state not ssrc when state is available
Harald Alvestrand76d29522018-01-30 14:43:29 +0100558 // Related to https://bugs.webrtc.org/8694 (using ssrc 0 to indicate
559 // "none")
Steve Anton57858b32018-02-15 15:19:50 -0800560 if (sender->ssrc() != 0) {
Harald Alvestrand76d29522018-01-30 14:43:29 +0100561 // When pc.close is called, sender info is discarded, so
562 // we generate zeroes instead. Bug: It should be retained.
563 // https://crbug.com/807174
Steve Anton57858b32018-02-15 15:19:50 -0800564 const cricket::VideoSenderInfo* sender_info =
Harald Alvestrandb8e12012018-01-23 15:28:16 +0100565 track_media_info_map.GetVideoSenderInfoBySsrc(sender->ssrc());
Harald Alvestrand76d29522018-01-30 14:43:29 +0100566 if (sender_info) {
567 video_sender_info = sender_info;
568 } else {
569 RTC_LOG(LS_INFO) << "No video sender info for sender with ssrc "
570 << sender->ssrc();
571 }
572 }
Harald Alvestrand89061872018-01-02 14:08:34 +0100573 std::unique_ptr<RTCMediaStreamTrackStats> video_track_stats =
Harald Alvestrandc72af932018-01-11 17:18:19 +0100574 ProduceMediaStreamTrackStatsFromVideoSenderInfo(
575 timestamp_us, *track, *video_sender_info, sender->AttachmentId());
Harald Alvestrand89061872018-01-02 14:08:34 +0100576 report->AddStats(std::move(video_track_stats));
577 } else {
578 RTC_NOTREACHED();
579 }
580 }
581}
582
583void ProduceReceiverMediaTrackStats(
584 int64_t timestamp_us,
585 const TrackMediaInfoMap& track_media_info_map,
Steve Anton57858b32018-02-15 15:19:50 -0800586 std::vector<rtc::scoped_refptr<RtpReceiverInternal>> receivers,
Harald Alvestrand89061872018-01-02 14:08:34 +0100587 RTCStatsReport* report) {
588 // This function iterates over the receivers to find the remote tracks.
Steve Anton57858b32018-02-15 15:19:50 -0800589 for (auto receiver : receivers) {
Harald Alvestrand89061872018-01-02 14:08:34 +0100590 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
591 AudioTrackInterface* track =
592 static_cast<AudioTrackInterface*>(receiver->track().get());
593 const cricket::VoiceReceiverInfo* voice_receiver_info =
594 track_media_info_map.GetVoiceReceiverInfo(*track);
595 if (!voice_receiver_info) {
596 continue;
597 }
598 std::unique_ptr<RTCMediaStreamTrackStats> audio_track_stats =
599 ProduceMediaStreamTrackStatsFromVoiceReceiverInfo(
Harald Alvestrandc72af932018-01-11 17:18:19 +0100600 timestamp_us, *track, *voice_receiver_info,
601 receiver->AttachmentId());
Harald Alvestrand89061872018-01-02 14:08:34 +0100602 report->AddStats(std::move(audio_track_stats));
603 } else if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
604 VideoTrackInterface* track =
605 static_cast<VideoTrackInterface*>(receiver->track().get());
606 const cricket::VideoReceiverInfo* video_receiver_info =
607 track_media_info_map.GetVideoReceiverInfo(*track);
608 if (!video_receiver_info) {
609 continue;
610 }
611 std::unique_ptr<RTCMediaStreamTrackStats> video_track_stats =
612 ProduceMediaStreamTrackStatsFromVideoReceiverInfo(
Harald Alvestrandc72af932018-01-11 17:18:19 +0100613 timestamp_us, *track, *video_receiver_info,
614 receiver->AttachmentId());
Harald Alvestrand89061872018-01-02 14:08:34 +0100615 report->AddStats(std::move(video_track_stats));
616 } else {
617 RTC_NOTREACHED();
618 }
619 }
620}
621
Henrik Boström5b3541f2018-03-19 13:52:56 +0100622rtc::scoped_refptr<RTCStatsReport> CreateReportFilteredBySelector(
623 bool filter_by_sender_selector,
624 rtc::scoped_refptr<const RTCStatsReport> report,
625 rtc::scoped_refptr<RtpSenderInternal> sender_selector,
626 rtc::scoped_refptr<RtpReceiverInternal> receiver_selector) {
627 std::vector<std::string> rtpstream_ids;
628 if (filter_by_sender_selector) {
629 // Filter mode: RTCStatsCollector::RequestInfo::kSenderSelector
630 if (sender_selector) {
631 // Find outbound-rtp(s) of the sender, i.e. the outbound-rtp(s) that
632 // reference the sender stats.
633 // Because we do not implement sender stats, we look at outbound-rtp(s)
634 // that reference the track attachment stats for the sender instead.
635 std::string track_id =
636 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
637 kSender, sender_selector->AttachmentId());
638 for (const auto& stats : *report) {
639 if (stats.type() != RTCOutboundRTPStreamStats::kType)
640 continue;
641 const auto& outbound_rtp = stats.cast_to<RTCOutboundRTPStreamStats>();
642 if (outbound_rtp.track_id.is_defined() &&
643 *outbound_rtp.track_id == track_id) {
644 rtpstream_ids.push_back(outbound_rtp.id());
645 }
646 }
647 }
648 } else {
649 // Filter mode: RTCStatsCollector::RequestInfo::kReceiverSelector
650 if (receiver_selector) {
651 // Find inbound-rtp(s) of the receiver, i.e. the inbound-rtp(s) that
652 // reference the receiver stats.
653 // Because we do not implement receiver stats, we look at inbound-rtp(s)
654 // that reference the track attachment stats for the receiver instead.
655 std::string track_id =
656 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
657 kReceiver, receiver_selector->AttachmentId());
658 for (const auto& stats : *report) {
659 if (stats.type() != RTCInboundRTPStreamStats::kType)
660 continue;
661 const auto& inbound_rtp = stats.cast_to<RTCInboundRTPStreamStats>();
662 if (inbound_rtp.track_id.is_defined() &&
663 *inbound_rtp.track_id == track_id) {
664 rtpstream_ids.push_back(inbound_rtp.id());
665 }
666 }
667 }
668 }
669 if (rtpstream_ids.empty())
670 return RTCStatsReport::Create(report->timestamp_us());
671 return TakeReferencedStats(report->Copy(), rtpstream_ids);
672}
673
hboscc555c52016-10-18 12:48:31 -0700674} // namespace
675
Henrik Boström5b3541f2018-03-19 13:52:56 +0100676RTCStatsCollector::RequestInfo::RequestInfo(
677 rtc::scoped_refptr<RTCStatsCollectorCallback> callback)
678 : RequestInfo(FilterMode::kAll, std::move(callback), nullptr, nullptr) {}
679
680RTCStatsCollector::RequestInfo::RequestInfo(
681 rtc::scoped_refptr<RtpSenderInternal> selector,
682 rtc::scoped_refptr<RTCStatsCollectorCallback> callback)
683 : RequestInfo(FilterMode::kSenderSelector,
684 std::move(callback),
685 std::move(selector),
686 nullptr) {}
687
688RTCStatsCollector::RequestInfo::RequestInfo(
689 rtc::scoped_refptr<RtpReceiverInternal> selector,
690 rtc::scoped_refptr<RTCStatsCollectorCallback> callback)
691 : RequestInfo(FilterMode::kReceiverSelector,
692 std::move(callback),
693 nullptr,
694 std::move(selector)) {}
695
696RTCStatsCollector::RequestInfo::RequestInfo(
697 RTCStatsCollector::RequestInfo::FilterMode filter_mode,
698 rtc::scoped_refptr<RTCStatsCollectorCallback> callback,
699 rtc::scoped_refptr<RtpSenderInternal> sender_selector,
700 rtc::scoped_refptr<RtpReceiverInternal> receiver_selector)
701 : filter_mode_(filter_mode),
702 callback_(std::move(callback)),
703 sender_selector_(std::move(sender_selector)),
704 receiver_selector_(std::move(receiver_selector)) {
705 RTC_DCHECK(callback_);
706 RTC_DCHECK(!sender_selector_ || !receiver_selector_);
707}
708
hbosc82f2e12016-09-05 01:36:50 -0700709rtc::scoped_refptr<RTCStatsCollector> RTCStatsCollector::Create(
Steve Anton2d8609c2018-01-23 16:38:46 -0800710 PeerConnectionInternal* pc,
711 int64_t cache_lifetime_us) {
hbosc82f2e12016-09-05 01:36:50 -0700712 return rtc::scoped_refptr<RTCStatsCollector>(
713 new rtc::RefCountedObject<RTCStatsCollector>(pc, cache_lifetime_us));
714}
715
Steve Anton2d8609c2018-01-23 16:38:46 -0800716RTCStatsCollector::RTCStatsCollector(PeerConnectionInternal* pc,
hbosc82f2e12016-09-05 01:36:50 -0700717 int64_t cache_lifetime_us)
hbosd565b732016-08-30 14:04:35 -0700718 : pc_(pc),
Steve Anton978b8762017-09-29 12:15:02 -0700719 signaling_thread_(pc->signaling_thread()),
720 worker_thread_(pc->worker_thread()),
721 network_thread_(pc->network_thread()),
hbosc82f2e12016-09-05 01:36:50 -0700722 num_pending_partial_reports_(0),
723 partial_report_timestamp_us_(0),
hbos0e6758d2016-08-31 07:57:36 -0700724 cache_timestamp_us_(0),
725 cache_lifetime_us_(cache_lifetime_us) {
hbosd565b732016-08-30 14:04:35 -0700726 RTC_DCHECK(pc_);
hbosc82f2e12016-09-05 01:36:50 -0700727 RTC_DCHECK(signaling_thread_);
728 RTC_DCHECK(worker_thread_);
729 RTC_DCHECK(network_thread_);
hbos0e6758d2016-08-31 07:57:36 -0700730 RTC_DCHECK_GE(cache_lifetime_us_, 0);
Steve Anton2d8609c2018-01-23 16:38:46 -0800731 pc_->SignalDataChannelCreated().connect(
hbos82ebe022016-11-14 01:41:09 -0800732 this, &RTCStatsCollector::OnDataChannelCreated);
hbosd565b732016-08-30 14:04:35 -0700733}
734
hbosb78306a2016-12-19 05:06:57 -0800735RTCStatsCollector::~RTCStatsCollector() {
736 RTC_DCHECK_EQ(num_pending_partial_reports_, 0);
737}
738
hbosc82f2e12016-09-05 01:36:50 -0700739void RTCStatsCollector::GetStatsReport(
740 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
Henrik Boström5b3541f2018-03-19 13:52:56 +0100741 GetStatsReportInternal(RequestInfo(std::move(callback)));
742}
743
744void RTCStatsCollector::GetStatsReport(
745 rtc::scoped_refptr<RtpSenderInternal> selector,
746 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
747 GetStatsReportInternal(RequestInfo(std::move(selector), std::move(callback)));
748}
749
750void RTCStatsCollector::GetStatsReport(
751 rtc::scoped_refptr<RtpReceiverInternal> selector,
752 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
753 GetStatsReportInternal(RequestInfo(std::move(selector), std::move(callback)));
754}
755
756void RTCStatsCollector::GetStatsReportInternal(
757 RTCStatsCollector::RequestInfo request) {
hbosc82f2e12016-09-05 01:36:50 -0700758 RTC_DCHECK(signaling_thread_->IsCurrent());
Henrik Boström5b3541f2018-03-19 13:52:56 +0100759 requests_.push_back(std::move(request));
hbosc82f2e12016-09-05 01:36:50 -0700760
hbos0e6758d2016-08-31 07:57:36 -0700761 // "Now" using a monotonically increasing timer.
762 int64_t cache_now_us = rtc::TimeMicros();
763 if (cached_report_ &&
764 cache_now_us - cache_timestamp_us_ <= cache_lifetime_us_) {
Taylor Brandstetter25e022f2018-03-08 09:53:47 -0800765 // We have a fresh cached report to deliver. Deliver asynchronously, since
766 // the caller may not be expecting a synchronous callback, and it avoids
767 // reentrancy problems.
Henrik Boström5b3541f2018-03-19 13:52:56 +0100768 std::vector<RequestInfo> requests;
769 requests.swap(requests_);
Taylor Brandstetter25e022f2018-03-08 09:53:47 -0800770 invoker_.AsyncInvoke<void>(
771 RTC_FROM_HERE, signaling_thread_,
772 rtc::Bind(&RTCStatsCollector::DeliverCachedReport, this, cached_report_,
Henrik Boström5b3541f2018-03-19 13:52:56 +0100773 std::move(requests)));
hbosc82f2e12016-09-05 01:36:50 -0700774 } else if (!num_pending_partial_reports_) {
775 // Only start gathering stats if we're not already gathering stats. In the
776 // case of already gathering stats, |callback_| will be invoked when there
777 // are no more pending partial reports.
778
779 // "Now" using a system clock, relative to the UNIX epoch (Jan 1, 1970,
780 // UTC), in microseconds. The system clock could be modified and is not
781 // necessarily monotonically increasing.
nissecdf37a92016-09-13 23:41:47 -0700782 int64_t timestamp_us = rtc::TimeUTCMicros();
hbosc82f2e12016-09-05 01:36:50 -0700783
hbosf415f8a2017-01-02 04:28:51 -0800784 num_pending_partial_reports_ = 2;
hbosc82f2e12016-09-05 01:36:50 -0700785 partial_report_timestamp_us_ = cache_now_us;
hbosdf6075a2016-12-19 04:58:02 -0800786
Steve Anton57858b32018-02-15 15:19:50 -0800787 // Prepare |transceiver_stats_infos_| for use in
hbos84abeb12017-01-16 06:16:44 -0800788 // |ProducePartialResultsOnNetworkThread| and
789 // |ProducePartialResultsOnSignalingThread|.
Steve Anton57858b32018-02-15 15:19:50 -0800790 transceiver_stats_infos_ = PrepareTransceiverStatsInfos_s();
Steve Anton7eca0932018-03-30 15:18:41 -0700791 // Prepare |transport_names_| for use in
792 // |ProducePartialResultsOnNetworkThread|.
793 transport_names_ = PrepareTransportNames_s();
Steve Anton5dfde182018-02-06 10:34:40 -0800794
stefanf79ade12017-06-02 06:44:03 -0700795 // Prepare |call_stats_| here since GetCallStats() will hop to the worker
796 // thread.
797 // TODO(holmer): To avoid the hop we could move BWE and BWE stats to the
798 // network thread, where it more naturally belongs.
Steve Anton978b8762017-09-29 12:15:02 -0700799 call_stats_ = pc_->GetCallStats();
stefanf79ade12017-06-02 06:44:03 -0700800
801 invoker_.AsyncInvoke<void>(
802 RTC_FROM_HERE, network_thread_,
hbosc82f2e12016-09-05 01:36:50 -0700803 rtc::Bind(&RTCStatsCollector::ProducePartialResultsOnNetworkThread,
stefanf79ade12017-06-02 06:44:03 -0700804 rtc::scoped_refptr<RTCStatsCollector>(this), timestamp_us));
hbosf415f8a2017-01-02 04:28:51 -0800805 ProducePartialResultsOnSignalingThread(timestamp_us);
hbos0e6758d2016-08-31 07:57:36 -0700806 }
hbosd565b732016-08-30 14:04:35 -0700807}
808
809void RTCStatsCollector::ClearCachedStatsReport() {
hbosc82f2e12016-09-05 01:36:50 -0700810 RTC_DCHECK(signaling_thread_->IsCurrent());
hbosd565b732016-08-30 14:04:35 -0700811 cached_report_ = nullptr;
812}
813
hbosb78306a2016-12-19 05:06:57 -0800814void RTCStatsCollector::WaitForPendingRequest() {
815 RTC_DCHECK(signaling_thread_->IsCurrent());
816 if (num_pending_partial_reports_) {
817 rtc::Thread::Current()->ProcessMessages(0);
818 while (num_pending_partial_reports_) {
819 rtc::Thread::Current()->SleepMs(1);
820 rtc::Thread::Current()->ProcessMessages(0);
821 }
822 }
823}
824
hbosc82f2e12016-09-05 01:36:50 -0700825void RTCStatsCollector::ProducePartialResultsOnSignalingThread(
826 int64_t timestamp_us) {
827 RTC_DCHECK(signaling_thread_->IsCurrent());
hbos6ded1902016-11-01 01:50:46 -0700828 rtc::scoped_refptr<RTCStatsReport> report = RTCStatsReport::Create(
829 timestamp_us);
hbosc82f2e12016-09-05 01:36:50 -0700830
hboscc555c52016-10-18 12:48:31 -0700831 ProduceDataChannelStats_s(timestamp_us, report.get());
Steve Anton57858b32018-02-15 15:19:50 -0800832 ProduceMediaStreamStats_s(timestamp_us, report.get());
833 ProduceMediaStreamTrackStats_s(timestamp_us, report.get());
hbos6ab97ce2016-10-03 14:16:56 -0700834 ProducePeerConnectionStats_s(timestamp_us, report.get());
hbosc82f2e12016-09-05 01:36:50 -0700835
836 AddPartialResults(report);
837}
838
hbosc82f2e12016-09-05 01:36:50 -0700839void RTCStatsCollector::ProducePartialResultsOnNetworkThread(
840 int64_t timestamp_us) {
841 RTC_DCHECK(network_thread_->IsCurrent());
hbos6ded1902016-11-01 01:50:46 -0700842 rtc::scoped_refptr<RTCStatsReport> report = RTCStatsReport::Create(
843 timestamp_us);
hbosc82f2e12016-09-05 01:36:50 -0700844
Steve Anton5dfde182018-02-06 10:34:40 -0800845 std::map<std::string, cricket::TransportStats> transport_stats_by_name =
Steve Anton7eca0932018-03-30 15:18:41 -0700846 pc_->GetTransportStatsByNames(transport_names_);
Steve Anton5dfde182018-02-06 10:34:40 -0800847
848 std::map<std::string, CertificateStatsPair> transport_cert_stats =
849 PrepareTransportCertificateStats_n(transport_stats_by_name);
850
851 ProduceCertificateStats_n(timestamp_us, transport_cert_stats, report.get());
Steve Anton57858b32018-02-15 15:19:50 -0800852 ProduceCodecStats_n(timestamp_us, transceiver_stats_infos_, report.get());
Steve Anton5dfde182018-02-06 10:34:40 -0800853 ProduceIceCandidateAndPairStats_n(timestamp_us, transport_stats_by_name,
Steve Anton5dfde182018-02-06 10:34:40 -0800854 call_stats_, report.get());
Steve Anton57858b32018-02-15 15:19:50 -0800855 ProduceRTPStreamStats_n(timestamp_us, transceiver_stats_infos_, report.get());
Steve Anton5dfde182018-02-06 10:34:40 -0800856 ProduceTransportStats_n(timestamp_us, transport_stats_by_name,
857 transport_cert_stats, report.get());
hbosc82f2e12016-09-05 01:36:50 -0700858
859 AddPartialResults(report);
860}
861
862void RTCStatsCollector::AddPartialResults(
863 const rtc::scoped_refptr<RTCStatsReport>& partial_report) {
864 if (!signaling_thread_->IsCurrent()) {
865 invoker_.AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread_,
866 rtc::Bind(&RTCStatsCollector::AddPartialResults_s,
867 rtc::scoped_refptr<RTCStatsCollector>(this),
868 partial_report));
869 return;
870 }
871 AddPartialResults_s(partial_report);
872}
873
874void RTCStatsCollector::AddPartialResults_s(
875 rtc::scoped_refptr<RTCStatsReport> partial_report) {
876 RTC_DCHECK(signaling_thread_->IsCurrent());
877 RTC_DCHECK_GT(num_pending_partial_reports_, 0);
878 if (!partial_report_)
879 partial_report_ = partial_report;
880 else
881 partial_report_->TakeMembersFrom(partial_report);
882 --num_pending_partial_reports_;
883 if (!num_pending_partial_reports_) {
884 cache_timestamp_us_ = partial_report_timestamp_us_;
885 cached_report_ = partial_report_;
886 partial_report_ = nullptr;
Steve Anton57858b32018-02-15 15:19:50 -0800887 transceiver_stats_infos_.clear();
ehmaldonadoa26196b2017-07-18 03:30:29 -0700888 // Trace WebRTC Stats when getStats is called on Javascript.
889 // This allows access to WebRTC stats from trace logs. To enable them,
890 // select the "webrtc_stats" category when recording traces.
ehmaldonado8ab0fd82017-09-04 14:35:04 -0700891 TRACE_EVENT_INSTANT1("webrtc_stats", "webrtc_stats", "report",
892 cached_report_->ToJson());
Taylor Brandstetter25e022f2018-03-08 09:53:47 -0800893
Henrik Boström5b3541f2018-03-19 13:52:56 +0100894 // Deliver report and clear |requests_|.
895 std::vector<RequestInfo> requests;
896 requests.swap(requests_);
897 DeliverCachedReport(cached_report_, std::move(requests));
hbosc82f2e12016-09-05 01:36:50 -0700898 }
899}
900
Taylor Brandstetter25e022f2018-03-08 09:53:47 -0800901void RTCStatsCollector::DeliverCachedReport(
902 rtc::scoped_refptr<const RTCStatsReport> cached_report,
Henrik Boström5b3541f2018-03-19 13:52:56 +0100903 std::vector<RTCStatsCollector::RequestInfo> requests) {
hbosc82f2e12016-09-05 01:36:50 -0700904 RTC_DCHECK(signaling_thread_->IsCurrent());
Henrik Boström5b3541f2018-03-19 13:52:56 +0100905 RTC_DCHECK(!requests.empty());
Taylor Brandstetter25e022f2018-03-08 09:53:47 -0800906 RTC_DCHECK(cached_report);
Taylor Brandstetter87d5a742018-03-06 09:42:25 -0800907
Henrik Boström5b3541f2018-03-19 13:52:56 +0100908 for (const RequestInfo& request : requests) {
909 if (request.filter_mode() == RequestInfo::FilterMode::kAll) {
910 request.callback()->OnStatsDelivered(cached_report);
911 } else {
912 bool filter_by_sender_selector;
913 rtc::scoped_refptr<RtpSenderInternal> sender_selector;
914 rtc::scoped_refptr<RtpReceiverInternal> receiver_selector;
915 if (request.filter_mode() == RequestInfo::FilterMode::kSenderSelector) {
916 filter_by_sender_selector = true;
917 sender_selector = request.sender_selector();
918 } else {
919 RTC_DCHECK(request.filter_mode() ==
920 RequestInfo::FilterMode::kReceiverSelector);
921 filter_by_sender_selector = false;
922 receiver_selector = request.receiver_selector();
923 }
924 request.callback()->OnStatsDelivered(CreateReportFilteredBySelector(
925 filter_by_sender_selector, cached_report, sender_selector,
926 receiver_selector));
927 }
hbosc82f2e12016-09-05 01:36:50 -0700928 }
hbosd565b732016-08-30 14:04:35 -0700929}
930
hbosdf6075a2016-12-19 04:58:02 -0800931void RTCStatsCollector::ProduceCertificateStats_n(
hbos2fa7c672016-10-24 04:00:05 -0700932 int64_t timestamp_us,
933 const std::map<std::string, CertificateStatsPair>& transport_cert_stats,
hbos6ab97ce2016-10-03 14:16:56 -0700934 RTCStatsReport* report) const {
hbosdf6075a2016-12-19 04:58:02 -0800935 RTC_DCHECK(network_thread_->IsCurrent());
hbos02ba2112016-10-28 05:14:53 -0700936 for (const auto& transport_cert_stats_pair : transport_cert_stats) {
937 if (transport_cert_stats_pair.second.local) {
938 ProduceCertificateStatsFromSSLCertificateStats(
939 timestamp_us, *transport_cert_stats_pair.second.local.get(), report);
hbos6ab97ce2016-10-03 14:16:56 -0700940 }
hbos02ba2112016-10-28 05:14:53 -0700941 if (transport_cert_stats_pair.second.remote) {
942 ProduceCertificateStatsFromSSLCertificateStats(
943 timestamp_us, *transport_cert_stats_pair.second.remote.get(), report);
hbos6ab97ce2016-10-03 14:16:56 -0700944 }
945 }
946}
947
hbosdf6075a2016-12-19 04:58:02 -0800948void RTCStatsCollector::ProduceCodecStats_n(
Steve Anton57858b32018-02-15 15:19:50 -0800949 int64_t timestamp_us,
950 const std::vector<RtpTransceiverStatsInfo>& transceiver_stats_infos,
hbos0adb8282016-11-23 02:32:06 -0800951 RTCStatsReport* report) const {
hbosdf6075a2016-12-19 04:58:02 -0800952 RTC_DCHECK(network_thread_->IsCurrent());
Steve Anton57858b32018-02-15 15:19:50 -0800953 for (const auto& stats : transceiver_stats_infos) {
954 if (!stats.mid) {
955 continue;
hbos0adb8282016-11-23 02:32:06 -0800956 }
Steve Anton57858b32018-02-15 15:19:50 -0800957 const cricket::VoiceMediaInfo* voice_media_info =
958 stats.track_media_info_map->voice_media_info();
959 const cricket::VideoMediaInfo* video_media_info =
960 stats.track_media_info_map->video_media_info();
961 // Audio
962 if (voice_media_info) {
963 // Inbound
964 for (const auto& pair : voice_media_info->receive_codecs) {
965 report->AddStats(CodecStatsFromRtpCodecParameters(
966 timestamp_us, *stats.mid, true, pair.second));
967 }
968 // Outbound
969 for (const auto& pair : voice_media_info->send_codecs) {
970 report->AddStats(CodecStatsFromRtpCodecParameters(
971 timestamp_us, *stats.mid, false, pair.second));
972 }
Guido Urdanetaee2388f2018-02-15 16:36:19 +0000973 }
Steve Anton57858b32018-02-15 15:19:50 -0800974 // Video
975 if (video_media_info) {
976 // Inbound
977 for (const auto& pair : video_media_info->receive_codecs) {
978 report->AddStats(CodecStatsFromRtpCodecParameters(
979 timestamp_us, *stats.mid, true, pair.second));
980 }
981 // Outbound
982 for (const auto& pair : video_media_info->send_codecs) {
983 report->AddStats(CodecStatsFromRtpCodecParameters(
984 timestamp_us, *stats.mid, false, pair.second));
985 }
hbos0adb8282016-11-23 02:32:06 -0800986 }
987 }
988}
989
hboscc555c52016-10-18 12:48:31 -0700990void RTCStatsCollector::ProduceDataChannelStats_s(
991 int64_t timestamp_us, RTCStatsReport* report) const {
992 RTC_DCHECK(signaling_thread_->IsCurrent());
993 for (const rtc::scoped_refptr<DataChannel>& data_channel :
994 pc_->sctp_data_channels()) {
995 std::unique_ptr<RTCDataChannelStats> data_channel_stats(
996 new RTCDataChannelStats(
997 "RTCDataChannel_" + rtc::ToString<>(data_channel->id()),
998 timestamp_us));
999 data_channel_stats->label = data_channel->label();
1000 data_channel_stats->protocol = data_channel->protocol();
1001 data_channel_stats->datachannelid = data_channel->id();
1002 data_channel_stats->state =
1003 DataStateToRTCDataChannelState(data_channel->state());
1004 data_channel_stats->messages_sent = data_channel->messages_sent();
1005 data_channel_stats->bytes_sent = data_channel->bytes_sent();
1006 data_channel_stats->messages_received = data_channel->messages_received();
1007 data_channel_stats->bytes_received = data_channel->bytes_received();
1008 report->AddStats(std::move(data_channel_stats));
1009 }
1010}
1011
hbosdf6075a2016-12-19 04:58:02 -08001012void RTCStatsCollector::ProduceIceCandidateAndPairStats_n(
stefanf79ade12017-06-02 06:44:03 -07001013 int64_t timestamp_us,
Steve Anton5dfde182018-02-06 10:34:40 -08001014 const std::map<std::string, cricket::TransportStats>&
1015 transport_stats_by_name,
stefanf79ade12017-06-02 06:44:03 -07001016 const Call::Stats& call_stats,
1017 RTCStatsReport* report) const {
hbosdf6075a2016-12-19 04:58:02 -08001018 RTC_DCHECK(network_thread_->IsCurrent());
Steve Anton5dfde182018-02-06 10:34:40 -08001019 for (const auto& entry : transport_stats_by_name) {
1020 const std::string& transport_name = entry.first;
1021 const cricket::TransportStats& transport_stats = entry.second;
1022 for (const auto& channel_stats : transport_stats.channel_stats) {
hbos0583b282016-11-30 01:50:14 -08001023 std::string transport_id = RTCTransportStatsIDFromTransportChannel(
Steve Anton5dfde182018-02-06 10:34:40 -08001024 transport_name, channel_stats.component);
hbosc47a0c32016-10-11 14:54:49 -07001025 for (const cricket::ConnectionInfo& info :
1026 channel_stats.connection_infos) {
hbosc47a0c32016-10-11 14:54:49 -07001027 std::unique_ptr<RTCIceCandidatePairStats> candidate_pair_stats(
hbos2fa7c672016-10-24 04:00:05 -07001028 new RTCIceCandidatePairStats(
1029 RTCIceCandidatePairStatsIDFromConnectionInfo(info),
1030 timestamp_us));
hbosc47a0c32016-10-11 14:54:49 -07001031
hbos0583b282016-11-30 01:50:14 -08001032 candidate_pair_stats->transport_id = transport_id;
hbosab9f6e42016-10-07 02:18:47 -07001033 // TODO(hbos): There could be other candidates that are not paired with
1034 // anything. We don't have a complete list. Local candidates come from
1035 // Port objects, and prflx candidates (both local and remote) are only
Harald Alvestrand89061872018-01-02 14:08:34 +01001036 // stored in candidate pairs. https://crbug.com/632723
hbos02ba2112016-10-28 05:14:53 -07001037 candidate_pair_stats->local_candidate_id = ProduceIceCandidateStats(
hbosb4e426e2017-01-02 09:59:31 -08001038 timestamp_us, info.local_candidate, true, transport_id, report);
hbos02ba2112016-10-28 05:14:53 -07001039 candidate_pair_stats->remote_candidate_id = ProduceIceCandidateStats(
hbosb4e426e2017-01-02 09:59:31 -08001040 timestamp_us, info.remote_candidate, false, transport_id, report);
hbos06495bc2017-01-02 08:08:18 -08001041 candidate_pair_stats->state =
1042 IceCandidatePairStateToRTCStatsIceCandidatePairState(info.state);
1043 candidate_pair_stats->priority = info.priority;
hbos92eaec62017-02-27 01:38:08 -08001044 candidate_pair_stats->nominated = info.nominated;
hbosc47a0c32016-10-11 14:54:49 -07001045 // TODO(hbos): This writable is different than the spec. It goes to
1046 // false after a certain amount of time without a response passes.
Harald Alvestrand89061872018-01-02 14:08:34 +01001047 // https://crbug.com/633550
hbosc47a0c32016-10-11 14:54:49 -07001048 candidate_pair_stats->writable = info.writable;
hbosc47a0c32016-10-11 14:54:49 -07001049 candidate_pair_stats->bytes_sent =
1050 static_cast<uint64_t>(info.sent_total_bytes);
1051 candidate_pair_stats->bytes_received =
1052 static_cast<uint64_t>(info.recv_total_bytes);
hbosbf8d3e52017-02-28 06:34:47 -08001053 candidate_pair_stats->total_round_trip_time =
1054 static_cast<double>(info.total_round_trip_time_ms) /
1055 rtc::kNumMillisecsPerSec;
1056 if (info.current_round_trip_time_ms) {
1057 candidate_pair_stats->current_round_trip_time =
1058 static_cast<double>(*info.current_round_trip_time_ms) /
1059 rtc::kNumMillisecsPerSec;
1060 }
stefanf79ade12017-06-02 06:44:03 -07001061 if (info.best_connection) {
hbos338f78a2017-02-07 06:41:21 -08001062 // The bandwidth estimations we have are for the selected candidate
1063 // pair ("info.best_connection").
stefanf79ade12017-06-02 06:44:03 -07001064 RTC_DCHECK_GE(call_stats.send_bandwidth_bps, 0);
1065 RTC_DCHECK_GE(call_stats.recv_bandwidth_bps, 0);
1066 if (call_stats.send_bandwidth_bps > 0) {
hbos338f78a2017-02-07 06:41:21 -08001067 candidate_pair_stats->available_outgoing_bitrate =
stefanf79ade12017-06-02 06:44:03 -07001068 static_cast<double>(call_stats.send_bandwidth_bps);
hbos338f78a2017-02-07 06:41:21 -08001069 }
stefanf79ade12017-06-02 06:44:03 -07001070 if (call_stats.recv_bandwidth_bps > 0) {
hbos338f78a2017-02-07 06:41:21 -08001071 candidate_pair_stats->available_incoming_bitrate =
stefanf79ade12017-06-02 06:44:03 -07001072 static_cast<double>(call_stats.recv_bandwidth_bps);
hbos338f78a2017-02-07 06:41:21 -08001073 }
1074 }
hbosd82f5122016-12-09 04:12:39 -08001075 candidate_pair_stats->requests_received =
1076 static_cast<uint64_t>(info.recv_ping_requests);
hbose448dd52016-12-12 01:22:53 -08001077 candidate_pair_stats->requests_sent = static_cast<uint64_t>(
1078 info.sent_ping_requests_before_first_response);
hbosc47a0c32016-10-11 14:54:49 -07001079 candidate_pair_stats->responses_received =
1080 static_cast<uint64_t>(info.recv_ping_responses);
1081 candidate_pair_stats->responses_sent =
1082 static_cast<uint64_t>(info.sent_ping_responses);
hbose448dd52016-12-12 01:22:53 -08001083 RTC_DCHECK_GE(info.sent_ping_requests_total,
1084 info.sent_ping_requests_before_first_response);
1085 candidate_pair_stats->consent_requests_sent = static_cast<uint64_t>(
1086 info.sent_ping_requests_total -
1087 info.sent_ping_requests_before_first_response);
hbosc47a0c32016-10-11 14:54:49 -07001088
1089 report->AddStats(std::move(candidate_pair_stats));
hbosab9f6e42016-10-07 02:18:47 -07001090 }
1091 }
1092 }
1093}
1094
Steve Anton57858b32018-02-15 15:19:50 -08001095void RTCStatsCollector::ProduceMediaStreamStats_s(
1096 int64_t timestamp_us,
1097 RTCStatsReport* report) const {
hbos09bc1282016-11-08 06:29:22 -08001098 RTC_DCHECK(signaling_thread_->IsCurrent());
Steve Anton57858b32018-02-15 15:19:50 -08001099
1100 std::map<std::string, std::vector<std::string>> track_ids;
1101
1102 for (const auto& stats : transceiver_stats_infos_) {
1103 for (auto sender : stats.transceiver->senders()) {
1104 std::string track_id =
1105 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
1106 kSender, sender->internal()->AttachmentId());
1107 for (auto& stream_id : sender->stream_ids()) {
1108 track_ids[stream_id].push_back(track_id);
1109 }
1110 }
1111 for (auto receiver : stats.transceiver->receivers()) {
1112 std::string track_id =
1113 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
1114 kReceiver, receiver->internal()->AttachmentId());
1115 for (auto& stream : receiver->streams()) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001116 track_ids[stream->id()].push_back(track_id);
Steve Anton57858b32018-02-15 15:19:50 -08001117 }
1118 }
1119 }
1120
1121 // Build stats for each stream ID known.
1122 for (auto& it : track_ids) {
1123 std::unique_ptr<RTCMediaStreamStats> stream_stats(
1124 new RTCMediaStreamStats("RTCMediaStream_" + it.first, timestamp_us));
1125 stream_stats->stream_identifier = it.first;
1126 stream_stats->track_ids = it.second;
1127 report->AddStats(std::move(stream_stats));
1128 }
1129}
1130
1131void RTCStatsCollector::ProduceMediaStreamTrackStats_s(
1132 int64_t timestamp_us,
1133 RTCStatsReport* report) const {
1134 RTC_DCHECK(signaling_thread_->IsCurrent());
1135 for (const RtpTransceiverStatsInfo& stats : transceiver_stats_infos_) {
1136 std::vector<rtc::scoped_refptr<RtpSenderInternal>> senders;
1137 for (auto sender : stats.transceiver->senders()) {
1138 senders.push_back(sender->internal());
1139 }
1140 ProduceSenderMediaTrackStats(timestamp_us, *stats.track_media_info_map,
1141 senders, report);
1142
1143 std::vector<rtc::scoped_refptr<RtpReceiverInternal>> receivers;
1144 for (auto receiver : stats.transceiver->receivers()) {
1145 receivers.push_back(receiver->internal());
1146 }
1147 ProduceReceiverMediaTrackStats(timestamp_us, *stats.track_media_info_map,
1148 receivers, report);
1149 }
hbos09bc1282016-11-08 06:29:22 -08001150}
1151
hbos6ab97ce2016-10-03 14:16:56 -07001152void RTCStatsCollector::ProducePeerConnectionStats_s(
1153 int64_t timestamp_us, RTCStatsReport* report) const {
hbosc82f2e12016-09-05 01:36:50 -07001154 RTC_DCHECK(signaling_thread_->IsCurrent());
hbosd565b732016-08-30 14:04:35 -07001155 std::unique_ptr<RTCPeerConnectionStats> stats(
hbos0e6758d2016-08-31 07:57:36 -07001156 new RTCPeerConnectionStats("RTCPeerConnection", timestamp_us));
hbos82ebe022016-11-14 01:41:09 -08001157 stats->data_channels_opened = internal_record_.data_channels_opened;
1158 stats->data_channels_closed = internal_record_.data_channels_closed;
hbos6ab97ce2016-10-03 14:16:56 -07001159 report->AddStats(std::move(stats));
hbosd565b732016-08-30 14:04:35 -07001160}
1161
hbosdf6075a2016-12-19 04:58:02 -08001162void RTCStatsCollector::ProduceRTPStreamStats_n(
Steve Anton593e3252017-12-15 11:44:48 -08001163 int64_t timestamp_us,
Steve Anton57858b32018-02-15 15:19:50 -08001164 const std::vector<RtpTransceiverStatsInfo>& transceiver_stats_infos,
hbos84abeb12017-01-16 06:16:44 -08001165 RTCStatsReport* report) const {
hbosdf6075a2016-12-19 04:58:02 -08001166 RTC_DCHECK(network_thread_->IsCurrent());
hbos6ded1902016-11-01 01:50:46 -07001167
Steve Anton57858b32018-02-15 15:19:50 -08001168 for (const RtpTransceiverStatsInfo& stats : transceiver_stats_infos) {
1169 if (stats.media_type == cricket::MEDIA_TYPE_AUDIO) {
1170 ProduceAudioRTPStreamStats_n(timestamp_us, stats, report);
1171 } else if (stats.media_type == cricket::MEDIA_TYPE_VIDEO) {
1172 ProduceVideoRTPStreamStats_n(timestamp_us, stats, report);
1173 } else {
1174 RTC_NOTREACHED();
Guido Urdanetaee2388f2018-02-15 16:36:19 +00001175 }
Steve Anton56bae8d2018-02-14 16:07:42 -08001176 }
Steve Anton57858b32018-02-15 15:19:50 -08001177}
1178
1179void RTCStatsCollector::ProduceAudioRTPStreamStats_n(
1180 int64_t timestamp_us,
1181 const RtpTransceiverStatsInfo& stats,
1182 RTCStatsReport* report) const {
1183 if (!stats.mid || !stats.transport_name) {
1184 return;
1185 }
1186 RTC_DCHECK(stats.track_media_info_map);
1187 const TrackMediaInfoMap& track_media_info_map = *stats.track_media_info_map;
1188 RTC_DCHECK(track_media_info_map.voice_media_info());
1189 std::string mid = *stats.mid;
1190 std::string transport_id = RTCTransportStatsIDFromTransportChannel(
1191 *stats.transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
1192 // Inbound
1193 for (const cricket::VoiceReceiverInfo& voice_receiver_info :
1194 track_media_info_map.voice_media_info()->receivers) {
1195 if (!voice_receiver_info.connected())
1196 continue;
1197 auto inbound_audio = rtc::MakeUnique<RTCInboundRTPStreamStats>(
1198 RTCInboundRTPStreamStatsIDFromSSRC(true, voice_receiver_info.ssrc()),
1199 timestamp_us);
1200 SetInboundRTPStreamStatsFromVoiceReceiverInfo(mid, voice_receiver_info,
1201 inbound_audio.get());
1202 // TODO(hta): This lookup should look for the sender, not the track.
1203 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1204 track_media_info_map.GetAudioTrack(voice_receiver_info);
1205 if (audio_track) {
1206 inbound_audio->track_id =
1207 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
1208 kReceiver,
1209 track_media_info_map.GetAttachmentIdByTrack(audio_track).value());
hbos6ded1902016-11-01 01:50:46 -07001210 }
Steve Anton57858b32018-02-15 15:19:50 -08001211 inbound_audio->transport_id = transport_id;
1212 report->AddStats(std::move(inbound_audio));
1213 }
1214 // Outbound
1215 for (const cricket::VoiceSenderInfo& voice_sender_info :
1216 track_media_info_map.voice_media_info()->senders) {
1217 if (!voice_sender_info.connected())
1218 continue;
1219 auto outbound_audio = rtc::MakeUnique<RTCOutboundRTPStreamStats>(
1220 RTCOutboundRTPStreamStatsIDFromSSRC(true, voice_sender_info.ssrc()),
1221 timestamp_us);
1222 SetOutboundRTPStreamStatsFromVoiceSenderInfo(mid, voice_sender_info,
1223 outbound_audio.get());
1224 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1225 track_media_info_map.GetAudioTrack(voice_sender_info);
1226 if (audio_track) {
1227 outbound_audio->track_id =
1228 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
1229 kSender,
1230 track_media_info_map.GetAttachmentIdByTrack(audio_track).value());
Steve Anton56bae8d2018-02-14 16:07:42 -08001231 }
Steve Anton57858b32018-02-15 15:19:50 -08001232 outbound_audio->transport_id = transport_id;
1233 report->AddStats(std::move(outbound_audio));
1234 }
1235}
1236
1237void RTCStatsCollector::ProduceVideoRTPStreamStats_n(
1238 int64_t timestamp_us,
1239 const RtpTransceiverStatsInfo& stats,
1240 RTCStatsReport* report) const {
1241 if (!stats.mid || !stats.transport_name) {
1242 return;
1243 }
1244 RTC_DCHECK(stats.track_media_info_map);
1245 const TrackMediaInfoMap& track_media_info_map = *stats.track_media_info_map;
1246 RTC_DCHECK(track_media_info_map.video_media_info());
1247 std::string mid = *stats.mid;
1248 std::string transport_id = RTCTransportStatsIDFromTransportChannel(
1249 *stats.transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
1250 // Inbound
1251 for (const cricket::VideoReceiverInfo& video_receiver_info :
1252 track_media_info_map.video_media_info()->receivers) {
1253 if (!video_receiver_info.connected())
1254 continue;
1255 auto inbound_video = rtc::MakeUnique<RTCInboundRTPStreamStats>(
1256 RTCInboundRTPStreamStatsIDFromSSRC(false, video_receiver_info.ssrc()),
1257 timestamp_us);
1258 SetInboundRTPStreamStatsFromVideoReceiverInfo(mid, video_receiver_info,
1259 inbound_video.get());
1260 rtc::scoped_refptr<VideoTrackInterface> video_track =
1261 track_media_info_map.GetVideoTrack(video_receiver_info);
1262 if (video_track) {
1263 inbound_video->track_id =
1264 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
1265 kReceiver,
1266 track_media_info_map.GetAttachmentIdByTrack(video_track).value());
1267 }
1268 inbound_video->transport_id = transport_id;
1269 report->AddStats(std::move(inbound_video));
1270 }
1271 // Outbound
1272 for (const cricket::VideoSenderInfo& video_sender_info :
1273 track_media_info_map.video_media_info()->senders) {
1274 if (!video_sender_info.connected())
1275 continue;
1276 auto outbound_video = rtc::MakeUnique<RTCOutboundRTPStreamStats>(
1277 RTCOutboundRTPStreamStatsIDFromSSRC(false, video_sender_info.ssrc()),
1278 timestamp_us);
1279 SetOutboundRTPStreamStatsFromVideoSenderInfo(mid, video_sender_info,
1280 outbound_video.get());
1281 rtc::scoped_refptr<VideoTrackInterface> video_track =
1282 track_media_info_map.GetVideoTrack(video_sender_info);
1283 if (video_track) {
1284 outbound_video->track_id =
1285 RTCMediaStreamTrackStatsIDFromDirectionAndAttachment(
1286 kSender,
1287 track_media_info_map.GetAttachmentIdByTrack(video_track).value());
1288 }
1289 outbound_video->transport_id = transport_id;
1290 report->AddStats(std::move(outbound_video));
hbos6ded1902016-11-01 01:50:46 -07001291 }
1292}
1293
hbosdf6075a2016-12-19 04:58:02 -08001294void RTCStatsCollector::ProduceTransportStats_n(
Steve Anton5dfde182018-02-06 10:34:40 -08001295 int64_t timestamp_us,
1296 const std::map<std::string, cricket::TransportStats>&
1297 transport_stats_by_name,
hbos2fa7c672016-10-24 04:00:05 -07001298 const std::map<std::string, CertificateStatsPair>& transport_cert_stats,
1299 RTCStatsReport* report) const {
hbosdf6075a2016-12-19 04:58:02 -08001300 RTC_DCHECK(network_thread_->IsCurrent());
Steve Anton5dfde182018-02-06 10:34:40 -08001301 for (const auto& entry : transport_stats_by_name) {
1302 const std::string& transport_name = entry.first;
1303 const cricket::TransportStats& transport_stats = entry.second;
1304
hbos2fa7c672016-10-24 04:00:05 -07001305 // Get reference to RTCP channel, if it exists.
1306 std::string rtcp_transport_stats_id;
Steve Anton5dfde182018-02-06 10:34:40 -08001307 for (const cricket::TransportChannelStats& channel_stats :
1308 transport_stats.channel_stats) {
hbos2fa7c672016-10-24 04:00:05 -07001309 if (channel_stats.component ==
1310 cricket::ICE_CANDIDATE_COMPONENT_RTCP) {
1311 rtcp_transport_stats_id = RTCTransportStatsIDFromTransportChannel(
Steve Anton5dfde182018-02-06 10:34:40 -08001312 transport_name, channel_stats.component);
hbos2fa7c672016-10-24 04:00:05 -07001313 break;
1314 }
1315 }
1316
1317 // Get reference to local and remote certificates of this transport, if they
1318 // exist.
Steve Anton5dfde182018-02-06 10:34:40 -08001319 const auto& certificate_stats_it =
1320 transport_cert_stats.find(transport_name);
hbos2fa7c672016-10-24 04:00:05 -07001321 RTC_DCHECK(certificate_stats_it != transport_cert_stats.cend());
1322 std::string local_certificate_id;
1323 if (certificate_stats_it->second.local) {
1324 local_certificate_id = RTCCertificateIDFromFingerprint(
1325 certificate_stats_it->second.local->fingerprint);
1326 }
1327 std::string remote_certificate_id;
1328 if (certificate_stats_it->second.remote) {
1329 remote_certificate_id = RTCCertificateIDFromFingerprint(
1330 certificate_stats_it->second.remote->fingerprint);
1331 }
1332
1333 // There is one transport stats for each channel.
Steve Anton5dfde182018-02-06 10:34:40 -08001334 for (const cricket::TransportChannelStats& channel_stats :
1335 transport_stats.channel_stats) {
hbos2fa7c672016-10-24 04:00:05 -07001336 std::unique_ptr<RTCTransportStats> transport_stats(
Steve Anton5dfde182018-02-06 10:34:40 -08001337 new RTCTransportStats(RTCTransportStatsIDFromTransportChannel(
1338 transport_name, channel_stats.component),
1339 timestamp_us));
hbos2fa7c672016-10-24 04:00:05 -07001340 transport_stats->bytes_sent = 0;
1341 transport_stats->bytes_received = 0;
hbos7064d592017-01-16 07:38:02 -08001342 transport_stats->dtls_state = DtlsTransportStateToRTCDtlsTransportState(
1343 channel_stats.dtls_state);
hbos2fa7c672016-10-24 04:00:05 -07001344 for (const cricket::ConnectionInfo& info :
1345 channel_stats.connection_infos) {
1346 *transport_stats->bytes_sent += info.sent_total_bytes;
1347 *transport_stats->bytes_received += info.recv_total_bytes;
1348 if (info.best_connection) {
hbos2fa7c672016-10-24 04:00:05 -07001349 transport_stats->selected_candidate_pair_id =
1350 RTCIceCandidatePairStatsIDFromConnectionInfo(info);
1351 }
1352 }
1353 if (channel_stats.component != cricket::ICE_CANDIDATE_COMPONENT_RTCP &&
1354 !rtcp_transport_stats_id.empty()) {
1355 transport_stats->rtcp_transport_stats_id = rtcp_transport_stats_id;
1356 }
1357 if (!local_certificate_id.empty())
1358 transport_stats->local_certificate_id = local_certificate_id;
1359 if (!remote_certificate_id.empty())
1360 transport_stats->remote_certificate_id = remote_certificate_id;
1361 report->AddStats(std::move(transport_stats));
1362 }
1363 }
1364}
1365
1366std::map<std::string, RTCStatsCollector::CertificateStatsPair>
hbosdf6075a2016-12-19 04:58:02 -08001367RTCStatsCollector::PrepareTransportCertificateStats_n(
Steve Anton5dfde182018-02-06 10:34:40 -08001368 const std::map<std::string, cricket::TransportStats>&
1369 transport_stats_by_name) const {
hbosdf6075a2016-12-19 04:58:02 -08001370 RTC_DCHECK(network_thread_->IsCurrent());
hbos2fa7c672016-10-24 04:00:05 -07001371 std::map<std::string, CertificateStatsPair> transport_cert_stats;
Steve Anton5dfde182018-02-06 10:34:40 -08001372 for (const auto& entry : transport_stats_by_name) {
1373 const std::string& transport_name = entry.first;
1374
hbos2fa7c672016-10-24 04:00:05 -07001375 CertificateStatsPair certificate_stats_pair;
1376 rtc::scoped_refptr<rtc::RTCCertificate> local_certificate;
Steve Anton5dfde182018-02-06 10:34:40 -08001377 if (pc_->GetLocalCertificate(transport_name, &local_certificate)) {
hbos2fa7c672016-10-24 04:00:05 -07001378 certificate_stats_pair.local =
Taylor Brandstetterc3928662018-02-23 13:04:51 -08001379 local_certificate->ssl_cert_chain().GetStats();
hbos2fa7c672016-10-24 04:00:05 -07001380 }
Steve Anton5dfde182018-02-06 10:34:40 -08001381
Taylor Brandstetterc3928662018-02-23 13:04:51 -08001382 std::unique_ptr<rtc::SSLCertChain> remote_cert_chain =
1383 pc_->GetRemoteSSLCertChain(transport_name);
1384 if (remote_cert_chain) {
1385 certificate_stats_pair.remote = remote_cert_chain->GetStats();
hbos2fa7c672016-10-24 04:00:05 -07001386 }
Steve Anton5dfde182018-02-06 10:34:40 -08001387
hbos2fa7c672016-10-24 04:00:05 -07001388 transport_cert_stats.insert(
Steve Anton5dfde182018-02-06 10:34:40 -08001389 std::make_pair(transport_name, std::move(certificate_stats_pair)));
hbos2fa7c672016-10-24 04:00:05 -07001390 }
1391 return transport_cert_stats;
1392}
1393
Steve Anton57858b32018-02-15 15:19:50 -08001394std::vector<RTCStatsCollector::RtpTransceiverStatsInfo>
1395RTCStatsCollector::PrepareTransceiverStatsInfos_s() const {
1396 std::vector<RtpTransceiverStatsInfo> transceiver_stats_infos;
Steve Anton56bae8d2018-02-14 16:07:42 -08001397
Steve Anton57858b32018-02-15 15:19:50 -08001398 // These are used to invoke GetStats for all the media channels together in
1399 // one worker thread hop.
1400 std::map<cricket::VoiceMediaChannel*,
1401 std::unique_ptr<cricket::VoiceMediaInfo>>
1402 voice_stats;
1403 std::map<cricket::VideoMediaChannel*,
1404 std::unique_ptr<cricket::VideoMediaInfo>>
1405 video_stats;
1406
1407 for (auto transceiver : pc_->GetTransceiversInternal()) {
1408 cricket::MediaType media_type = transceiver->media_type();
1409
1410 // Prepare stats entry. The TrackMediaInfoMap will be filled in after the
1411 // stats have been fetched on the worker thread.
1412 transceiver_stats_infos.emplace_back();
1413 RtpTransceiverStatsInfo& stats = transceiver_stats_infos.back();
1414 stats.transceiver = transceiver->internal();
1415 stats.media_type = media_type;
1416
1417 cricket::BaseChannel* channel = transceiver->internal()->channel();
1418 if (!channel) {
1419 // The remaining fields require a BaseChannel.
1420 continue;
1421 }
1422
1423 stats.mid = channel->content_name();
1424 stats.transport_name = channel->transport_name();
1425
1426 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1427 auto* voice_channel = static_cast<cricket::VoiceChannel*>(channel);
1428 RTC_DCHECK(voice_stats.find(voice_channel->media_channel()) ==
1429 voice_stats.end());
1430 voice_stats[voice_channel->media_channel()] =
1431 rtc::MakeUnique<cricket::VoiceMediaInfo>();
1432 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1433 auto* video_channel = static_cast<cricket::VideoChannel*>(channel);
1434 RTC_DCHECK(video_stats.find(video_channel->media_channel()) ==
1435 video_stats.end());
1436 video_stats[video_channel->media_channel()] =
1437 rtc::MakeUnique<cricket::VideoMediaInfo>();
1438 } else {
1439 RTC_NOTREACHED();
1440 }
Guido Urdanetaee2388f2018-02-15 16:36:19 +00001441 }
Steve Anton57858b32018-02-15 15:19:50 -08001442
1443 // Call GetStats for all media channels together on the worker thread in one
1444 // hop.
1445 worker_thread_->Invoke<void>(RTC_FROM_HERE, [&] {
1446 for (const auto& entry : voice_stats) {
1447 if (!entry.first->GetStats(entry.second.get())) {
1448 RTC_LOG(LS_WARNING) << "Failed to get voice stats.";
1449 }
1450 }
1451 for (const auto& entry : video_stats) {
1452 if (!entry.first->GetStats(entry.second.get())) {
1453 RTC_LOG(LS_WARNING) << "Failed to get video stats.";
1454 }
1455 }
1456 });
1457
1458 // Create the TrackMediaInfoMap for each transceiver stats object.
1459 for (auto& stats : transceiver_stats_infos) {
1460 auto transceiver = stats.transceiver;
1461 std::unique_ptr<cricket::VoiceMediaInfo> voice_media_info;
1462 std::unique_ptr<cricket::VideoMediaInfo> video_media_info;
1463 if (transceiver->channel()) {
1464 cricket::MediaType media_type = transceiver->media_type();
1465 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1466 auto* voice_channel =
1467 static_cast<cricket::VoiceChannel*>(transceiver->channel());
1468 RTC_DCHECK(voice_stats[voice_channel->media_channel()]);
1469 voice_media_info =
1470 std::move(voice_stats[voice_channel->media_channel()]);
1471 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1472 auto* video_channel =
1473 static_cast<cricket::VideoChannel*>(transceiver->channel());
1474 RTC_DCHECK(video_stats[video_channel->media_channel()]);
1475 video_media_info =
1476 std::move(video_stats[video_channel->media_channel()]);
1477 }
1478 }
1479 std::vector<rtc::scoped_refptr<RtpSenderInternal>> senders;
1480 for (auto sender : transceiver->senders()) {
1481 senders.push_back(sender->internal());
1482 }
1483 std::vector<rtc::scoped_refptr<RtpReceiverInternal>> receivers;
1484 for (auto receiver : transceiver->receivers()) {
1485 receivers.push_back(receiver->internal());
1486 }
1487 stats.track_media_info_map = rtc::MakeUnique<TrackMediaInfoMap>(
1488 std::move(voice_media_info), std::move(video_media_info), senders,
1489 receivers);
Guido Urdanetaee2388f2018-02-15 16:36:19 +00001490 }
Steve Anton57858b32018-02-15 15:19:50 -08001491
1492 return transceiver_stats_infos;
hbos0adb8282016-11-23 02:32:06 -08001493}
1494
Steve Anton7eca0932018-03-30 15:18:41 -07001495std::set<std::string> RTCStatsCollector::PrepareTransportNames_s() const {
1496 std::set<std::string> transport_names;
1497 for (const auto& transceiver : pc_->GetTransceiversInternal()) {
1498 if (transceiver->internal()->channel()) {
1499 transport_names.insert(
1500 transceiver->internal()->channel()->transport_name());
1501 }
1502 }
1503 if (pc_->rtp_data_channel()) {
1504 transport_names.insert(pc_->rtp_data_channel()->transport_name());
1505 }
1506 if (pc_->sctp_transport_name()) {
1507 transport_names.insert(*pc_->sctp_transport_name());
1508 }
1509 return transport_names;
1510}
1511
hbos82ebe022016-11-14 01:41:09 -08001512void RTCStatsCollector::OnDataChannelCreated(DataChannel* channel) {
1513 channel->SignalOpened.connect(this, &RTCStatsCollector::OnDataChannelOpened);
1514 channel->SignalClosed.connect(this, &RTCStatsCollector::OnDataChannelClosed);
1515}
1516
1517void RTCStatsCollector::OnDataChannelOpened(DataChannel* channel) {
1518 RTC_DCHECK(signaling_thread_->IsCurrent());
1519 bool result = internal_record_.opened_data_channels.insert(
1520 reinterpret_cast<uintptr_t>(channel)).second;
1521 ++internal_record_.data_channels_opened;
1522 RTC_DCHECK(result);
1523}
1524
1525void RTCStatsCollector::OnDataChannelClosed(DataChannel* channel) {
1526 RTC_DCHECK(signaling_thread_->IsCurrent());
1527 // Only channels that have been fully opened (and have increased the
1528 // |data_channels_opened_| counter) increase the closed counter.
hbos5bf9def2017-03-20 03:14:14 -07001529 if (internal_record_.opened_data_channels.erase(
1530 reinterpret_cast<uintptr_t>(channel))) {
hbos82ebe022016-11-14 01:41:09 -08001531 ++internal_record_.data_channels_closed;
1532 }
1533}
1534
hboscc555c52016-10-18 12:48:31 -07001535const char* CandidateTypeToRTCIceCandidateTypeForTesting(
1536 const std::string& type) {
1537 return CandidateTypeToRTCIceCandidateType(type);
1538}
1539
1540const char* DataStateToRTCDataChannelStateForTesting(
1541 DataChannelInterface::DataState state) {
1542 return DataStateToRTCDataChannelState(state);
1543}
1544
hbosd565b732016-08-30 14:04:35 -07001545} // namespace webrtc