1 /*
2 * Copyright 2012 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/stats_collector.h"
12
13 #include <memory>
14 #include <set>
15 #include <utility>
16 #include <vector>
17
18 #include "pc/channel.h"
19 #include "pc/peer_connection.h"
20 #include "rtc_base/checks.h"
21 #include "rtc_base/third_party/base64/base64.h"
22 #include "system_wrappers/include/field_trial.h"
23
24 namespace webrtc {
25 namespace {
26
27 // Field trial which controls whether to report standard-compliant bytes
28 // sent/received per stream. If enabled, padding and headers are not included
29 // in bytes sent or received.
30 constexpr char kUseStandardBytesStats[] = "WebRTC-UseStandardBytesStats";
31
32 // The following is the enum RTCStatsIceCandidateType from
33 // http://w3c.github.io/webrtc-stats/#rtcstatsicecandidatetype-enum such that
34 // our stats report for ice candidate type could conform to that.
35 const char STATSREPORT_LOCAL_PORT_TYPE[] = "host";
36 const char STATSREPORT_STUN_PORT_TYPE[] = "serverreflexive";
37 const char STATSREPORT_PRFLX_PORT_TYPE[] = "peerreflexive";
38 const char STATSREPORT_RELAY_PORT_TYPE[] = "relayed";
39
40 // Strings used by the stats collector to report adapter types. This fits the
41 // general stype of http://w3c.github.io/webrtc-stats than what
42 // AdapterTypeToString does.
43 const char* STATSREPORT_ADAPTER_TYPE_ETHERNET = "lan";
44 const char* STATSREPORT_ADAPTER_TYPE_WIFI = "wlan";
45 const char* STATSREPORT_ADAPTER_TYPE_WWAN = "wwan";
46 const char* STATSREPORT_ADAPTER_TYPE_VPN = "vpn";
47 const char* STATSREPORT_ADAPTER_TYPE_LOOPBACK = "loopback";
48 const char* STATSREPORT_ADAPTER_TYPE_WILDCARD = "wildcard";
49
50 template <typename ValueType>
51 struct TypeForAdd {
52 const StatsReport::StatsValueName name;
53 const ValueType& value;
54 };
55
56 typedef TypeForAdd<bool> BoolForAdd;
57 typedef TypeForAdd<float> FloatForAdd;
58 typedef TypeForAdd<int64_t> Int64ForAdd;
59 typedef TypeForAdd<int> IntForAdd;
60
AddTrackReport(StatsCollection * reports,const std::string & track_id)61 StatsReport* AddTrackReport(StatsCollection* reports,
62 const std::string& track_id) {
63 // Adds an empty track report.
64 StatsReport::Id id(
65 StatsReport::NewTypedId(StatsReport::kStatsReportTypeTrack, track_id));
66 StatsReport* report = reports->ReplaceOrAddNew(id);
67 report->AddString(StatsReport::kStatsValueNameTrackId, track_id);
68 return report;
69 }
70
71 template <class Track>
CreateTrackReport(const Track * track,StatsCollection * reports,TrackIdMap * track_ids)72 void CreateTrackReport(const Track* track,
73 StatsCollection* reports,
74 TrackIdMap* track_ids) {
75 const std::string& track_id = track->id();
76 StatsReport* report = AddTrackReport(reports, track_id);
77 RTC_DCHECK(report != nullptr);
78 (*track_ids)[track_id] = report;
79 }
80
81 template <class TrackVector>
CreateTrackReports(const TrackVector & tracks,StatsCollection * reports,TrackIdMap * track_ids)82 void CreateTrackReports(const TrackVector& tracks,
83 StatsCollection* reports,
84 TrackIdMap* track_ids) {
85 for (const auto& track : tracks) {
86 CreateTrackReport(track.get(), reports, track_ids);
87 }
88 }
89
ExtractCommonSendProperties(const cricket::MediaSenderInfo & info,StatsReport * report,bool use_standard_bytes_stats)90 void ExtractCommonSendProperties(const cricket::MediaSenderInfo& info,
91 StatsReport* report,
92 bool use_standard_bytes_stats) {
93 report->AddString(StatsReport::kStatsValueNameCodecName, info.codec_name);
94 int64_t bytes_sent = info.payload_bytes_sent;
95 if (!use_standard_bytes_stats) {
96 bytes_sent += info.header_and_padding_bytes_sent;
97 }
98 report->AddInt64(StatsReport::kStatsValueNameBytesSent, bytes_sent);
99 if (info.rtt_ms >= 0) {
100 report->AddInt64(StatsReport::kStatsValueNameRtt, info.rtt_ms);
101 }
102 }
103
ExtractCommonReceiveProperties(const cricket::MediaReceiverInfo & info,StatsReport * report)104 void ExtractCommonReceiveProperties(const cricket::MediaReceiverInfo& info,
105 StatsReport* report) {
106 report->AddString(StatsReport::kStatsValueNameCodecName, info.codec_name);
107 }
108
SetAudioProcessingStats(StatsReport * report,bool typing_noise_detected,const AudioProcessingStats & apm_stats)109 void SetAudioProcessingStats(StatsReport* report,
110 bool typing_noise_detected,
111 const AudioProcessingStats& apm_stats) {
112 report->AddBoolean(StatsReport::kStatsValueNameTypingNoiseState,
113 typing_noise_detected);
114 if (apm_stats.delay_median_ms) {
115 report->AddInt(StatsReport::kStatsValueNameEchoDelayMedian,
116 *apm_stats.delay_median_ms);
117 }
118 if (apm_stats.delay_standard_deviation_ms) {
119 report->AddInt(StatsReport::kStatsValueNameEchoDelayStdDev,
120 *apm_stats.delay_standard_deviation_ms);
121 }
122 if (apm_stats.echo_return_loss) {
123 report->AddInt(StatsReport::kStatsValueNameEchoReturnLoss,
124 *apm_stats.echo_return_loss);
125 }
126 if (apm_stats.echo_return_loss_enhancement) {
127 report->AddInt(StatsReport::kStatsValueNameEchoReturnLossEnhancement,
128 *apm_stats.echo_return_loss_enhancement);
129 }
130 if (apm_stats.residual_echo_likelihood) {
131 report->AddFloat(StatsReport::kStatsValueNameResidualEchoLikelihood,
132 static_cast<float>(*apm_stats.residual_echo_likelihood));
133 }
134 if (apm_stats.residual_echo_likelihood_recent_max) {
135 report->AddFloat(
136 StatsReport::kStatsValueNameResidualEchoLikelihoodRecentMax,
137 static_cast<float>(*apm_stats.residual_echo_likelihood_recent_max));
138 }
139 if (apm_stats.divergent_filter_fraction) {
140 report->AddFloat(StatsReport::kStatsValueNameAecDivergentFilterFraction,
141 static_cast<float>(*apm_stats.divergent_filter_fraction));
142 }
143 }
144
ExtractStats(const cricket::VoiceReceiverInfo & info,StatsReport * report,bool use_standard_bytes_stats)145 void ExtractStats(const cricket::VoiceReceiverInfo& info,
146 StatsReport* report,
147 bool use_standard_bytes_stats) {
148 ExtractCommonReceiveProperties(info, report);
149 const FloatForAdd floats[] = {
150 {StatsReport::kStatsValueNameExpandRate, info.expand_rate},
151 {StatsReport::kStatsValueNameSecondaryDecodedRate,
152 info.secondary_decoded_rate},
153 {StatsReport::kStatsValueNameSecondaryDiscardedRate,
154 info.secondary_discarded_rate},
155 {StatsReport::kStatsValueNameSpeechExpandRate, info.speech_expand_rate},
156 {StatsReport::kStatsValueNameAccelerateRate, info.accelerate_rate},
157 {StatsReport::kStatsValueNamePreemptiveExpandRate,
158 info.preemptive_expand_rate},
159 {StatsReport::kStatsValueNameTotalAudioEnergy, info.total_output_energy},
160 {StatsReport::kStatsValueNameTotalSamplesDuration,
161 info.total_output_duration}};
162
163 const IntForAdd ints[] = {
164 {StatsReport::kStatsValueNameCurrentDelayMs, info.delay_estimate_ms},
165 {StatsReport::kStatsValueNameDecodingCNG, info.decoding_cng},
166 {StatsReport::kStatsValueNameDecodingCTN, info.decoding_calls_to_neteq},
167 {StatsReport::kStatsValueNameDecodingCTSG,
168 info.decoding_calls_to_silence_generator},
169 {StatsReport::kStatsValueNameDecodingMutedOutput,
170 info.decoding_muted_output},
171 {StatsReport::kStatsValueNameDecodingNormal, info.decoding_normal},
172 {StatsReport::kStatsValueNameDecodingPLC, info.decoding_plc},
173 {StatsReport::kStatsValueNameDecodingPLCCNG, info.decoding_plc_cng},
174 {StatsReport::kStatsValueNameJitterBufferMs, info.jitter_buffer_ms},
175 {StatsReport::kStatsValueNameJitterReceived, info.jitter_ms},
176 {StatsReport::kStatsValueNamePacketsLost, info.packets_lost},
177 {StatsReport::kStatsValueNamePacketsReceived, info.packets_rcvd},
178 {StatsReport::kStatsValueNamePreferredJitterBufferMs,
179 info.jitter_buffer_preferred_ms},
180 };
181
182 for (const auto& f : floats)
183 report->AddFloat(f.name, f.value);
184
185 for (const auto& i : ints)
186 report->AddInt(i.name, i.value);
187 if (info.audio_level >= 0) {
188 report->AddInt(StatsReport::kStatsValueNameAudioOutputLevel,
189 info.audio_level);
190 }
191 if (info.decoding_codec_plc)
192 report->AddInt(StatsReport::kStatsValueNameDecodingCodecPLC,
193 info.decoding_codec_plc);
194
195 int64_t bytes_rcvd = info.payload_bytes_rcvd;
196 if (!use_standard_bytes_stats) {
197 bytes_rcvd += info.header_and_padding_bytes_rcvd;
198 }
199 report->AddInt64(StatsReport::kStatsValueNameBytesReceived, bytes_rcvd);
200 if (info.capture_start_ntp_time_ms >= 0) {
201 report->AddInt64(StatsReport::kStatsValueNameCaptureStartNtpTimeMs,
202 info.capture_start_ntp_time_ms);
203 }
204 report->AddString(StatsReport::kStatsValueNameMediaType, "audio");
205 }
206
ExtractStats(const cricket::VoiceSenderInfo & info,StatsReport * report,bool use_standard_bytes_stats)207 void ExtractStats(const cricket::VoiceSenderInfo& info,
208 StatsReport* report,
209 bool use_standard_bytes_stats) {
210 ExtractCommonSendProperties(info, report, use_standard_bytes_stats);
211
212 SetAudioProcessingStats(report, info.typing_noise_detected,
213 info.apm_statistics);
214
215 const FloatForAdd floats[] = {
216 {StatsReport::kStatsValueNameTotalAudioEnergy, info.total_input_energy},
217 {StatsReport::kStatsValueNameTotalSamplesDuration,
218 info.total_input_duration}};
219
220 RTC_DCHECK_GE(info.audio_level, 0);
221 const IntForAdd ints[] = {
222 {StatsReport::kStatsValueNameAudioInputLevel, info.audio_level},
223 {StatsReport::kStatsValueNameJitterReceived, info.jitter_ms},
224 {StatsReport::kStatsValueNamePacketsLost, info.packets_lost},
225 {StatsReport::kStatsValueNamePacketsSent, info.packets_sent},
226 };
227
228 for (const auto& f : floats) {
229 report->AddFloat(f.name, f.value);
230 }
231
232 for (const auto& i : ints) {
233 if (i.value >= 0) {
234 report->AddInt(i.name, i.value);
235 }
236 }
237 report->AddString(StatsReport::kStatsValueNameMediaType, "audio");
238 if (info.ana_statistics.bitrate_action_counter) {
239 report->AddInt(StatsReport::kStatsValueNameAnaBitrateActionCounter,
240 *info.ana_statistics.bitrate_action_counter);
241 }
242 if (info.ana_statistics.channel_action_counter) {
243 report->AddInt(StatsReport::kStatsValueNameAnaChannelActionCounter,
244 *info.ana_statistics.channel_action_counter);
245 }
246 if (info.ana_statistics.dtx_action_counter) {
247 report->AddInt(StatsReport::kStatsValueNameAnaDtxActionCounter,
248 *info.ana_statistics.dtx_action_counter);
249 }
250 if (info.ana_statistics.fec_action_counter) {
251 report->AddInt(StatsReport::kStatsValueNameAnaFecActionCounter,
252 *info.ana_statistics.fec_action_counter);
253 }
254 if (info.ana_statistics.frame_length_increase_counter) {
255 report->AddInt(StatsReport::kStatsValueNameAnaFrameLengthIncreaseCounter,
256 *info.ana_statistics.frame_length_increase_counter);
257 }
258 if (info.ana_statistics.frame_length_decrease_counter) {
259 report->AddInt(StatsReport::kStatsValueNameAnaFrameLengthDecreaseCounter,
260 *info.ana_statistics.frame_length_decrease_counter);
261 }
262 if (info.ana_statistics.uplink_packet_loss_fraction) {
263 report->AddFloat(StatsReport::kStatsValueNameAnaUplinkPacketLossFraction,
264 *info.ana_statistics.uplink_packet_loss_fraction);
265 }
266 }
267
ExtractStats(const cricket::VideoReceiverInfo & info,StatsReport * report,bool use_standard_bytes_stats)268 void ExtractStats(const cricket::VideoReceiverInfo& info,
269 StatsReport* report,
270 bool use_standard_bytes_stats) {
271 ExtractCommonReceiveProperties(info, report);
272 report->AddString(StatsReport::kStatsValueNameCodecImplementationName,
273 info.decoder_implementation_name);
274 int64_t bytes_rcvd = info.payload_bytes_rcvd;
275 if (!use_standard_bytes_stats) {
276 bytes_rcvd += info.header_and_padding_bytes_rcvd;
277 }
278 report->AddInt64(StatsReport::kStatsValueNameBytesReceived, bytes_rcvd);
279 if (info.capture_start_ntp_time_ms >= 0) {
280 report->AddInt64(StatsReport::kStatsValueNameCaptureStartNtpTimeMs,
281 info.capture_start_ntp_time_ms);
282 }
283 if (info.first_frame_received_to_decoded_ms >= 0) {
284 report->AddInt64(StatsReport::kStatsValueNameFirstFrameReceivedToDecodedMs,
285 info.first_frame_received_to_decoded_ms);
286 }
287 if (info.qp_sum)
288 report->AddInt64(StatsReport::kStatsValueNameQpSum, *info.qp_sum);
289
290 const IntForAdd ints[] = {
291 {StatsReport::kStatsValueNameCurrentDelayMs, info.current_delay_ms},
292 {StatsReport::kStatsValueNameDecodeMs, info.decode_ms},
293 {StatsReport::kStatsValueNameFirsSent, info.firs_sent},
294 {StatsReport::kStatsValueNameFrameHeightReceived, info.frame_height},
295 {StatsReport::kStatsValueNameFrameRateDecoded, info.framerate_decoded},
296 {StatsReport::kStatsValueNameFrameRateOutput, info.framerate_output},
297 {StatsReport::kStatsValueNameFrameRateReceived, info.framerate_rcvd},
298 {StatsReport::kStatsValueNameFrameWidthReceived, info.frame_width},
299 {StatsReport::kStatsValueNameJitterBufferMs, info.jitter_buffer_ms},
300 {StatsReport::kStatsValueNameMaxDecodeMs, info.max_decode_ms},
301 {StatsReport::kStatsValueNameMinPlayoutDelayMs,
302 info.min_playout_delay_ms},
303 {StatsReport::kStatsValueNameNacksSent, info.nacks_sent},
304 {StatsReport::kStatsValueNamePacketsLost, info.packets_lost},
305 {StatsReport::kStatsValueNamePacketsReceived, info.packets_rcvd},
306 {StatsReport::kStatsValueNamePlisSent, info.plis_sent},
307 {StatsReport::kStatsValueNameRenderDelayMs, info.render_delay_ms},
308 {StatsReport::kStatsValueNameTargetDelayMs, info.target_delay_ms},
309 {StatsReport::kStatsValueNameFramesDecoded, info.frames_decoded},
310 };
311
312 for (const auto& i : ints)
313 report->AddInt(i.name, i.value);
314 report->AddString(StatsReport::kStatsValueNameMediaType, "video");
315
316 if (info.timing_frame_info) {
317 report->AddString(StatsReport::kStatsValueNameTimingFrameInfo,
318 info.timing_frame_info->ToString());
319 }
320
321 report->AddInt64(StatsReport::kStatsValueNameInterframeDelayMaxMs,
322 info.interframe_delay_max_ms);
323
324 report->AddString(
325 StatsReport::kStatsValueNameContentType,
326 webrtc::videocontenttypehelpers::ToString(info.content_type));
327 }
328
ExtractStats(const cricket::VideoSenderInfo & info,StatsReport * report,bool use_standard_bytes_stats)329 void ExtractStats(const cricket::VideoSenderInfo& info,
330 StatsReport* report,
331 bool use_standard_bytes_stats) {
332 ExtractCommonSendProperties(info, report, use_standard_bytes_stats);
333
334 report->AddString(StatsReport::kStatsValueNameCodecImplementationName,
335 info.encoder_implementation_name);
336 report->AddBoolean(StatsReport::kStatsValueNameBandwidthLimitedResolution,
337 (info.adapt_reason & 0x2) > 0);
338 report->AddBoolean(StatsReport::kStatsValueNameCpuLimitedResolution,
339 (info.adapt_reason & 0x1) > 0);
340 report->AddBoolean(StatsReport::kStatsValueNameHasEnteredLowResolution,
341 info.has_entered_low_resolution);
342
343 if (info.qp_sum)
344 report->AddInt(StatsReport::kStatsValueNameQpSum, *info.qp_sum);
345
346 const IntForAdd ints[] = {
347 {StatsReport::kStatsValueNameAdaptationChanges, info.adapt_changes},
348 {StatsReport::kStatsValueNameAvgEncodeMs, info.avg_encode_ms},
349 {StatsReport::kStatsValueNameEncodeUsagePercent,
350 info.encode_usage_percent},
351 {StatsReport::kStatsValueNameFirsReceived, info.firs_rcvd},
352 {StatsReport::kStatsValueNameFrameHeightSent, info.send_frame_height},
353 {StatsReport::kStatsValueNameFrameRateInput, info.framerate_input},
354 {StatsReport::kStatsValueNameFrameRateSent, info.framerate_sent},
355 {StatsReport::kStatsValueNameFrameWidthSent, info.send_frame_width},
356 {StatsReport::kStatsValueNameNacksReceived, info.nacks_rcvd},
357 {StatsReport::kStatsValueNamePacketsLost, info.packets_lost},
358 {StatsReport::kStatsValueNamePacketsSent, info.packets_sent},
359 {StatsReport::kStatsValueNamePlisReceived, info.plis_rcvd},
360 {StatsReport::kStatsValueNameFramesEncoded, info.frames_encoded},
361 {StatsReport::kStatsValueNameHugeFramesSent, info.huge_frames_sent},
362 };
363
364 for (const auto& i : ints)
365 report->AddInt(i.name, i.value);
366 report->AddString(StatsReport::kStatsValueNameMediaType, "video");
367 report->AddString(
368 StatsReport::kStatsValueNameContentType,
369 webrtc::videocontenttypehelpers::ToString(info.content_type));
370 }
371
ExtractStats(const cricket::BandwidthEstimationInfo & info,double stats_gathering_started,StatsReport * report)372 void ExtractStats(const cricket::BandwidthEstimationInfo& info,
373 double stats_gathering_started,
374 StatsReport* report) {
375 RTC_DCHECK(report->type() == StatsReport::kStatsReportTypeBwe);
376
377 report->set_timestamp(stats_gathering_started);
378 const IntForAdd ints[] = {
379 {StatsReport::kStatsValueNameAvailableSendBandwidth,
380 info.available_send_bandwidth},
381 {StatsReport::kStatsValueNameAvailableReceiveBandwidth,
382 info.available_recv_bandwidth},
383 {StatsReport::kStatsValueNameTargetEncBitrate, info.target_enc_bitrate},
384 {StatsReport::kStatsValueNameActualEncBitrate, info.actual_enc_bitrate},
385 {StatsReport::kStatsValueNameRetransmitBitrate, info.retransmit_bitrate},
386 {StatsReport::kStatsValueNameTransmitBitrate, info.transmit_bitrate},
387 };
388 for (const auto& i : ints)
389 report->AddInt(i.name, i.value);
390 report->AddInt64(StatsReport::kStatsValueNameBucketDelay, info.bucket_delay);
391 }
392
ExtractRemoteStats(const cricket::MediaSenderInfo & info,StatsReport * report)393 void ExtractRemoteStats(const cricket::MediaSenderInfo& info,
394 StatsReport* report) {
395 report->set_timestamp(info.remote_stats[0].timestamp);
396 // TODO(hta): Extract some stats here.
397 }
398
ExtractRemoteStats(const cricket::MediaReceiverInfo & info,StatsReport * report)399 void ExtractRemoteStats(const cricket::MediaReceiverInfo& info,
400 StatsReport* report) {
401 report->set_timestamp(info.remote_stats[0].timestamp);
402 // TODO(hta): Extract some stats here.
403 }
404
GetTrackIdBySsrc(uint32_t ssrc,StatsReport::Direction direction,const std::map<uint32_t,std::string> & track_id_by_ssrc)405 std::string GetTrackIdBySsrc(
406 uint32_t ssrc,
407 StatsReport::Direction direction,
408 const std::map<uint32_t, std::string>& track_id_by_ssrc) {
409 auto it = track_id_by_ssrc.find(ssrc);
410 if (it != track_id_by_ssrc.end()) {
411 return it->second;
412 }
413 if (direction == StatsReport::kReceive) {
414 // If the track ID was not found, this might be an unsignaled receive
415 // SSRC, so try looking up by the special SSRC 0.
416 it = track_id_by_ssrc.find(0);
417 if (it != track_id_by_ssrc.end()) {
418 RTC_LOG(LS_INFO) << "Assuming SSRC=" << ssrc
419 << " is an unsignalled receive stream corresponding "
420 "to the RtpReceiver with track ID \""
421 << it->second << "\".";
422 return it->second;
423 }
424 }
425 return "";
426 }
427
428 // Template to extract stats from a data vector.
429 // In order to use the template, the functions that are called from it,
430 // ExtractStats and ExtractRemoteStats, must be defined and overloaded
431 // for each type.
432 template <typename T>
ExtractStatsFromList(const std::vector<T> & data,const StatsReport::Id & transport_id,StatsCollector * collector,StatsReport::Direction direction,const std::map<uint32_t,std::string> & track_id_by_ssrc)433 void ExtractStatsFromList(
434 const std::vector<T>& data,
435 const StatsReport::Id& transport_id,
436 StatsCollector* collector,
437 StatsReport::Direction direction,
438 const std::map<uint32_t, std::string>& track_id_by_ssrc) {
439 for (const auto& d : data) {
440 uint32_t ssrc = d.ssrc();
441 std::string track_id = GetTrackIdBySsrc(ssrc, direction, track_id_by_ssrc);
442 // Each track can have stats for both local and remote objects.
443 // TODO(hta): Handle the case of multiple SSRCs per object.
444 StatsReport* report =
445 collector->PrepareReport(true, ssrc, track_id, transport_id, direction);
446 if (report)
447 ExtractStats(d, report, collector->UseStandardBytesStats());
448
449 if (!d.remote_stats.empty()) {
450 report = collector->PrepareReport(false, ssrc, track_id, transport_id,
451 direction);
452 if (report)
453 ExtractRemoteStats(d, report);
454 }
455 }
456 }
457
458 } // namespace
459
IceCandidateTypeToStatsType(const std::string & candidate_type)460 const char* IceCandidateTypeToStatsType(const std::string& candidate_type) {
461 if (candidate_type == cricket::LOCAL_PORT_TYPE) {
462 return STATSREPORT_LOCAL_PORT_TYPE;
463 }
464 if (candidate_type == cricket::STUN_PORT_TYPE) {
465 return STATSREPORT_STUN_PORT_TYPE;
466 }
467 if (candidate_type == cricket::PRFLX_PORT_TYPE) {
468 return STATSREPORT_PRFLX_PORT_TYPE;
469 }
470 if (candidate_type == cricket::RELAY_PORT_TYPE) {
471 return STATSREPORT_RELAY_PORT_TYPE;
472 }
473 RTC_NOTREACHED();
474 return "unknown";
475 }
476
AdapterTypeToStatsType(rtc::AdapterType type)477 const char* AdapterTypeToStatsType(rtc::AdapterType type) {
478 switch (type) {
479 case rtc::ADAPTER_TYPE_UNKNOWN:
480 return "unknown";
481 case rtc::ADAPTER_TYPE_ETHERNET:
482 return STATSREPORT_ADAPTER_TYPE_ETHERNET;
483 case rtc::ADAPTER_TYPE_WIFI:
484 return STATSREPORT_ADAPTER_TYPE_WIFI;
485 case rtc::ADAPTER_TYPE_CELLULAR:
486 case rtc::ADAPTER_TYPE_CELLULAR_2G:
487 case rtc::ADAPTER_TYPE_CELLULAR_3G:
488 case rtc::ADAPTER_TYPE_CELLULAR_4G:
489 case rtc::ADAPTER_TYPE_CELLULAR_5G:
490 return STATSREPORT_ADAPTER_TYPE_WWAN;
491 case rtc::ADAPTER_TYPE_VPN:
492 return STATSREPORT_ADAPTER_TYPE_VPN;
493 case rtc::ADAPTER_TYPE_LOOPBACK:
494 return STATSREPORT_ADAPTER_TYPE_LOOPBACK;
495 case rtc::ADAPTER_TYPE_ANY:
496 return STATSREPORT_ADAPTER_TYPE_WILDCARD;
497 default:
498 RTC_NOTREACHED();
499 return "";
500 }
501 }
502
StatsCollector(PeerConnectionInternal * pc)503 StatsCollector::StatsCollector(PeerConnectionInternal* pc)
504 : pc_(pc),
505 stats_gathering_started_(0),
506 use_standard_bytes_stats_(
507 webrtc::field_trial::IsEnabled(kUseStandardBytesStats)) {
508 RTC_DCHECK(pc_);
509 }
510
~StatsCollector()511 StatsCollector::~StatsCollector() {
512 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
513 }
514
515 // Wallclock time in ms.
GetTimeNow()516 double StatsCollector::GetTimeNow() {
517 return static_cast<double>(rtc::TimeUTCMillis());
518 }
519
520 // Adds a MediaStream with tracks that can be used as a |selector| in a call
521 // to GetStats.
AddStream(MediaStreamInterface * stream)522 void StatsCollector::AddStream(MediaStreamInterface* stream) {
523 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
524 RTC_DCHECK(stream != NULL);
525
526 CreateTrackReports<AudioTrackVector>(stream->GetAudioTracks(), &reports_,
527 &track_ids_);
528 CreateTrackReports<VideoTrackVector>(stream->GetVideoTracks(), &reports_,
529 &track_ids_);
530 }
531
AddTrack(MediaStreamTrackInterface * track)532 void StatsCollector::AddTrack(MediaStreamTrackInterface* track) {
533 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
534 CreateTrackReport(static_cast<AudioTrackInterface*>(track), &reports_,
535 &track_ids_);
536 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
537 CreateTrackReport(static_cast<VideoTrackInterface*>(track), &reports_,
538 &track_ids_);
539 } else {
540 RTC_NOTREACHED() << "Illegal track kind";
541 }
542 }
543
AddLocalAudioTrack(AudioTrackInterface * audio_track,uint32_t ssrc)544 void StatsCollector::AddLocalAudioTrack(AudioTrackInterface* audio_track,
545 uint32_t ssrc) {
546 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
547 RTC_DCHECK(audio_track != NULL);
548 #if RTC_DCHECK_IS_ON
549 for (const auto& track : local_audio_tracks_)
550 RTC_DCHECK(track.first != audio_track || track.second != ssrc);
551 #endif
552
553 local_audio_tracks_.push_back(std::make_pair(audio_track, ssrc));
554
555 // Create the kStatsReportTypeTrack report for the new track if there is no
556 // report yet.
557 StatsReport::Id id(StatsReport::NewTypedId(StatsReport::kStatsReportTypeTrack,
558 audio_track->id()));
559 StatsReport* report = reports_.Find(id);
560 if (!report) {
561 report = reports_.InsertNew(id);
562 report->AddString(StatsReport::kStatsValueNameTrackId, audio_track->id());
563 }
564 }
565
RemoveLocalAudioTrack(AudioTrackInterface * audio_track,uint32_t ssrc)566 void StatsCollector::RemoveLocalAudioTrack(AudioTrackInterface* audio_track,
567 uint32_t ssrc) {
568 RTC_DCHECK(audio_track != NULL);
569 local_audio_tracks_.erase(
570 std::remove_if(
571 local_audio_tracks_.begin(), local_audio_tracks_.end(),
572 [audio_track, ssrc](const LocalAudioTrackVector::value_type& track) {
573 return track.first == audio_track && track.second == ssrc;
574 }),
575 local_audio_tracks_.end());
576 }
577
GetStats(MediaStreamTrackInterface * track,StatsReports * reports)578 void StatsCollector::GetStats(MediaStreamTrackInterface* track,
579 StatsReports* reports) {
580 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
581 RTC_DCHECK(reports != NULL);
582 RTC_DCHECK(reports->empty());
583
584 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
585
586 if (!track) {
587 reports->reserve(reports_.size());
588 for (auto* r : reports_)
589 reports->push_back(r);
590 return;
591 }
592
593 StatsReport* report = reports_.Find(StatsReport::NewTypedId(
594 StatsReport::kStatsReportTypeSession, pc_->session_id()));
595 if (report)
596 reports->push_back(report);
597
598 report = reports_.Find(
599 StatsReport::NewTypedId(StatsReport::kStatsReportTypeTrack, track->id()));
600
601 if (!report)
602 return;
603
604 reports->push_back(report);
605
606 std::string track_id;
607 for (const auto* r : reports_) {
608 if (r->type() != StatsReport::kStatsReportTypeSsrc)
609 continue;
610
611 const StatsReport::Value* v =
612 r->FindValue(StatsReport::kStatsValueNameTrackId);
613 if (v && v->string_val() == track->id())
614 reports->push_back(r);
615 }
616 }
617
UpdateStats(PeerConnectionInterface::StatsOutputLevel level)618 void StatsCollector::UpdateStats(
619 PeerConnectionInterface::StatsOutputLevel level) {
620 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
621 double time_now = GetTimeNow();
622 // Calls to UpdateStats() that occur less than kMinGatherStatsPeriod number of
623 // ms apart will be ignored.
624 const double kMinGatherStatsPeriod = 50;
625 if (stats_gathering_started_ != 0 &&
626 stats_gathering_started_ + kMinGatherStatsPeriod > time_now) {
627 return;
628 }
629 stats_gathering_started_ = time_now;
630
631 // TODO(tommi): All of these hop over to the worker thread to fetch
632 // information. We could use an AsyncInvoker to run all of these and post
633 // the information back to the signaling thread where we can create and
634 // update stats reports. That would also clean up the threading story a bit
635 // since we'd be creating/updating the stats report objects consistently on
636 // the same thread (this class has no locks right now).
637 ExtractSessionInfo();
638 ExtractBweInfo();
639 ExtractMediaInfo();
640 ExtractSenderInfo();
641 ExtractDataInfo();
642 UpdateTrackReports();
643 }
644
PrepareReport(bool local,uint32_t ssrc,const std::string & track_id,const StatsReport::Id & transport_id,StatsReport::Direction direction)645 StatsReport* StatsCollector::PrepareReport(bool local,
646 uint32_t ssrc,
647 const std::string& track_id,
648 const StatsReport::Id& transport_id,
649 StatsReport::Direction direction) {
650 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
651 StatsReport::Id id(StatsReport::NewIdWithDirection(
652 local ? StatsReport::kStatsReportTypeSsrc
653 : StatsReport::kStatsReportTypeRemoteSsrc,
654 rtc::ToString(ssrc), direction));
655 StatsReport* report = reports_.Find(id);
656 if (!report) {
657 report = reports_.InsertNew(id);
658 }
659
660 // FYI - for remote reports, the timestamp will be overwritten later.
661 report->set_timestamp(stats_gathering_started_);
662
663 report->AddInt64(StatsReport::kStatsValueNameSsrc, ssrc);
664 if (!track_id.empty()) {
665 report->AddString(StatsReport::kStatsValueNameTrackId, track_id);
666 }
667 // Add the mapping of SSRC to transport.
668 report->AddId(StatsReport::kStatsValueNameTransportId, transport_id);
669 return report;
670 }
671
PrepareADMReport()672 StatsReport* StatsCollector::PrepareADMReport() {
673 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
674 StatsReport::Id id(StatsReport::NewTypedId(
675 StatsReport::kStatsReportTypeSession, pc_->session_id()));
676 StatsReport* report = reports_.FindOrAddNew(id);
677 return report;
678 }
679
IsValidTrack(const std::string & track_id)680 bool StatsCollector::IsValidTrack(const std::string& track_id) {
681 return reports_.Find(StatsReport::NewTypedId(
682 StatsReport::kStatsReportTypeTrack, track_id)) != nullptr;
683 }
684
AddCertificateReports(std::unique_ptr<rtc::SSLCertificateStats> cert_stats)685 StatsReport* StatsCollector::AddCertificateReports(
686 std::unique_ptr<rtc::SSLCertificateStats> cert_stats) {
687 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
688
689 StatsReport* first_report = nullptr;
690 StatsReport* prev_report = nullptr;
691 for (rtc::SSLCertificateStats* stats = cert_stats.get(); stats;
692 stats = stats->issuer.get()) {
693 StatsReport::Id id(StatsReport::NewTypedId(
694 StatsReport::kStatsReportTypeCertificate, stats->fingerprint));
695
696 StatsReport* report = reports_.ReplaceOrAddNew(id);
697 report->set_timestamp(stats_gathering_started_);
698 report->AddString(StatsReport::kStatsValueNameFingerprint,
699 stats->fingerprint);
700 report->AddString(StatsReport::kStatsValueNameFingerprintAlgorithm,
701 stats->fingerprint_algorithm);
702 report->AddString(StatsReport::kStatsValueNameDer,
703 stats->base64_certificate);
704 if (!first_report)
705 first_report = report;
706 else
707 prev_report->AddId(StatsReport::kStatsValueNameIssuerId, id);
708 prev_report = report;
709 }
710 return first_report;
711 }
712
AddConnectionInfoReport(const std::string & content_name,int component,int connection_id,const StatsReport::Id & channel_report_id,const cricket::ConnectionInfo & info)713 StatsReport* StatsCollector::AddConnectionInfoReport(
714 const std::string& content_name,
715 int component,
716 int connection_id,
717 const StatsReport::Id& channel_report_id,
718 const cricket::ConnectionInfo& info) {
719 StatsReport::Id id(
720 StatsReport::NewCandidatePairId(content_name, component, connection_id));
721 StatsReport* report = reports_.ReplaceOrAddNew(id);
722 report->set_timestamp(stats_gathering_started_);
723
724 const BoolForAdd bools[] = {
725 {StatsReport::kStatsValueNameActiveConnection, info.best_connection},
726 {StatsReport::kStatsValueNameReceiving, info.receiving},
727 {StatsReport::kStatsValueNameWritable, info.writable},
728 };
729 for (const auto& b : bools)
730 report->AddBoolean(b.name, b.value);
731
732 report->AddId(StatsReport::kStatsValueNameChannelId, channel_report_id);
733 cricket::CandidateStats local_candidate_stats(info.local_candidate);
734 cricket::CandidateStats remote_candidate_stats(info.remote_candidate);
735 report->AddId(StatsReport::kStatsValueNameLocalCandidateId,
736 AddCandidateReport(local_candidate_stats, true)->id());
737 report->AddId(StatsReport::kStatsValueNameRemoteCandidateId,
738 AddCandidateReport(remote_candidate_stats, false)->id());
739
740 const Int64ForAdd int64s[] = {
741 {StatsReport::kStatsValueNameBytesReceived, info.recv_total_bytes},
742 {StatsReport::kStatsValueNameBytesSent, info.sent_total_bytes},
743 {StatsReport::kStatsValueNamePacketsSent, info.sent_total_packets},
744 {StatsReport::kStatsValueNameRtt, info.rtt},
745 {StatsReport::kStatsValueNameSendPacketsDiscarded,
746 info.sent_discarded_packets},
747 {StatsReport::kStatsValueNameSentPingRequestsTotal,
748 info.sent_ping_requests_total},
749 {StatsReport::kStatsValueNameSentPingRequestsBeforeFirstResponse,
750 info.sent_ping_requests_before_first_response},
751 {StatsReport::kStatsValueNameSentPingResponses, info.sent_ping_responses},
752 {StatsReport::kStatsValueNameRecvPingRequests, info.recv_ping_requests},
753 {StatsReport::kStatsValueNameRecvPingResponses, info.recv_ping_responses},
754 };
755 for (const auto& i : int64s)
756 report->AddInt64(i.name, i.value);
757
758 report->AddString(StatsReport::kStatsValueNameLocalAddress,
759 info.local_candidate.address().ToString());
760 report->AddString(StatsReport::kStatsValueNameLocalCandidateType,
761 info.local_candidate.type());
762 report->AddString(StatsReport::kStatsValueNameRemoteAddress,
763 info.remote_candidate.address().ToString());
764 report->AddString(StatsReport::kStatsValueNameRemoteCandidateType,
765 info.remote_candidate.type());
766 report->AddString(StatsReport::kStatsValueNameTransportType,
767 info.local_candidate.protocol());
768
769 return report;
770 }
771
AddCandidateReport(const cricket::CandidateStats & candidate_stats,bool local)772 StatsReport* StatsCollector::AddCandidateReport(
773 const cricket::CandidateStats& candidate_stats,
774 bool local) {
775 const auto& candidate = candidate_stats.candidate;
776 StatsReport::Id id(StatsReport::NewCandidateId(local, candidate.id()));
777 StatsReport* report = reports_.Find(id);
778 if (!report) {
779 report = reports_.InsertNew(id);
780 report->set_timestamp(stats_gathering_started_);
781 if (local) {
782 report->AddString(StatsReport::kStatsValueNameCandidateNetworkType,
783 AdapterTypeToStatsType(candidate.network_type()));
784 }
785 report->AddString(StatsReport::kStatsValueNameCandidateIPAddress,
786 candidate.address().ipaddr().ToString());
787 report->AddString(StatsReport::kStatsValueNameCandidatePortNumber,
788 candidate.address().PortAsString());
789 report->AddInt(StatsReport::kStatsValueNameCandidatePriority,
790 candidate.priority());
791 report->AddString(StatsReport::kStatsValueNameCandidateType,
792 IceCandidateTypeToStatsType(candidate.type()));
793 report->AddString(StatsReport::kStatsValueNameCandidateTransportType,
794 candidate.protocol());
795 }
796 report->set_timestamp(stats_gathering_started_);
797
798 if (local && candidate_stats.stun_stats.has_value()) {
799 const auto& stun_stats = candidate_stats.stun_stats.value();
800 report->AddInt64(StatsReport::kStatsValueNameSentStunKeepaliveRequests,
801 stun_stats.stun_binding_requests_sent);
802 report->AddInt64(StatsReport::kStatsValueNameRecvStunKeepaliveResponses,
803 stun_stats.stun_binding_responses_received);
804 report->AddFloat(StatsReport::kStatsValueNameStunKeepaliveRttTotal,
805 stun_stats.stun_binding_rtt_ms_total);
806 report->AddFloat(StatsReport::kStatsValueNameStunKeepaliveRttSquaredTotal,
807 stun_stats.stun_binding_rtt_ms_squared_total);
808 }
809
810 return report;
811 }
812
ExtractSessionInfo()813 void StatsCollector::ExtractSessionInfo() {
814 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
815
816 // Extract information from the base session.
817 StatsReport::Id id(StatsReport::NewTypedId(
818 StatsReport::kStatsReportTypeSession, pc_->session_id()));
819 StatsReport* report = reports_.ReplaceOrAddNew(id);
820 report->set_timestamp(stats_gathering_started_);
821 report->AddBoolean(StatsReport::kStatsValueNameInitiator,
822 pc_->initial_offerer());
823
824 cricket::CandidateStatsList pooled_candidate_stats_list =
825 pc_->GetPooledCandidateStats();
826
827 for (const cricket::CandidateStats& stats : pooled_candidate_stats_list) {
828 AddCandidateReport(stats, true);
829 }
830
831 std::set<std::string> transport_names;
832 for (const auto& entry : pc_->GetTransportNamesByMid()) {
833 transport_names.insert(entry.second);
834 }
835
836 std::map<std::string, cricket::TransportStats> transport_stats_by_name =
837 pc_->GetTransportStatsByNames(transport_names);
838
839 for (const auto& entry : transport_stats_by_name) {
840 const std::string& transport_name = entry.first;
841 const cricket::TransportStats& transport_stats = entry.second;
842
843 // Attempt to get a copy of the certificates from the transport and
844 // expose them in stats reports. All channels in a transport share the
845 // same local and remote certificates.
846 //
847 StatsReport::Id local_cert_report_id, remote_cert_report_id;
848 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
849 if (pc_->GetLocalCertificate(transport_name, &certificate)) {
850 StatsReport* r = AddCertificateReports(
851 certificate->GetSSLCertificateChain().GetStats());
852 if (r)
853 local_cert_report_id = r->id();
854 }
855
856 std::unique_ptr<rtc::SSLCertChain> remote_cert_chain =
857 pc_->GetRemoteSSLCertChain(transport_name);
858 if (remote_cert_chain) {
859 StatsReport* r = AddCertificateReports(remote_cert_chain->GetStats());
860 if (r)
861 remote_cert_report_id = r->id();
862 }
863
864 for (const auto& channel_iter : transport_stats.channel_stats) {
865 StatsReport::Id id(
866 StatsReport::NewComponentId(transport_name, channel_iter.component));
867 StatsReport* channel_report = reports_.ReplaceOrAddNew(id);
868 channel_report->set_timestamp(stats_gathering_started_);
869 channel_report->AddInt(StatsReport::kStatsValueNameComponent,
870 channel_iter.component);
871 if (local_cert_report_id.get()) {
872 channel_report->AddId(StatsReport::kStatsValueNameLocalCertificateId,
873 local_cert_report_id);
874 }
875 if (remote_cert_report_id.get()) {
876 channel_report->AddId(StatsReport::kStatsValueNameRemoteCertificateId,
877 remote_cert_report_id);
878 }
879 int srtp_crypto_suite = channel_iter.srtp_crypto_suite;
880 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE &&
881 rtc::SrtpCryptoSuiteToName(srtp_crypto_suite).length()) {
882 channel_report->AddString(
883 StatsReport::kStatsValueNameSrtpCipher,
884 rtc::SrtpCryptoSuiteToName(srtp_crypto_suite));
885 }
886 int ssl_cipher_suite = channel_iter.ssl_cipher_suite;
887 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL &&
888 rtc::SSLStreamAdapter::SslCipherSuiteToName(ssl_cipher_suite)
889 .length()) {
890 channel_report->AddString(
891 StatsReport::kStatsValueNameDtlsCipher,
892 rtc::SSLStreamAdapter::SslCipherSuiteToName(ssl_cipher_suite));
893 }
894
895 // Collect stats for non-pooled candidates. Note that the reports
896 // generated here supersedes the candidate reports generated in
897 // AddConnectionInfoReport below, and they may report candidates that are
898 // not paired. Also, the candidate report generated in
899 // AddConnectionInfoReport do not report port stats like StunStats.
900 for (const cricket::CandidateStats& stats :
901 channel_iter.ice_transport_stats.candidate_stats_list) {
902 AddCandidateReport(stats, true);
903 }
904
905 int connection_id = 0;
906 for (const cricket::ConnectionInfo& info :
907 channel_iter.ice_transport_stats.connection_infos) {
908 StatsReport* connection_report = AddConnectionInfoReport(
909 transport_name, channel_iter.component, connection_id++,
910 channel_report->id(), info);
911 if (info.best_connection) {
912 channel_report->AddId(
913 StatsReport::kStatsValueNameSelectedCandidatePairId,
914 connection_report->id());
915 }
916 }
917 }
918 }
919 }
920
ExtractBweInfo()921 void StatsCollector::ExtractBweInfo() {
922 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
923
924 if (pc_->signaling_state() == PeerConnectionInterface::kClosed)
925 return;
926
927 webrtc::Call::Stats call_stats = pc_->GetCallStats();
928 cricket::BandwidthEstimationInfo bwe_info;
929 bwe_info.available_send_bandwidth = call_stats.send_bandwidth_bps;
930 bwe_info.available_recv_bandwidth = call_stats.recv_bandwidth_bps;
931 bwe_info.bucket_delay = call_stats.pacer_delay_ms;
932
933 // Fill in target encoder bitrate, actual encoder bitrate, rtx bitrate, etc.
934 // TODO(holmer): Also fill this in for audio.
935 for (const auto& transceiver : pc_->GetTransceiversInternal()) {
936 if (transceiver->media_type() != cricket::MEDIA_TYPE_VIDEO) {
937 continue;
938 }
939 auto* video_channel =
940 static_cast<cricket::VideoChannel*>(transceiver->internal()->channel());
941 if (!video_channel) {
942 continue;
943 }
944 video_channel->FillBitrateInfo(&bwe_info);
945 }
946
947 StatsReport::Id report_id(StatsReport::NewBandwidthEstimationId());
948 StatsReport* report = reports_.FindOrAddNew(report_id);
949 ExtractStats(bwe_info, stats_gathering_started_, report);
950 }
951
952 namespace {
953
954 class MediaChannelStatsGatherer {
955 public:
956 virtual ~MediaChannelStatsGatherer() = default;
957
958 virtual bool GetStatsOnWorkerThread() = 0;
959
960 virtual void ExtractStats(StatsCollector* collector) const = 0;
961
962 virtual bool HasRemoteAudio() const = 0;
963
964 std::string mid;
965 std::string transport_name;
966 std::map<uint32_t, std::string> sender_track_id_by_ssrc;
967 std::map<uint32_t, std::string> receiver_track_id_by_ssrc;
968
969 protected:
970 template <typename ReceiverT, typename SenderT>
ExtractSenderReceiverStats(StatsCollector * collector,const std::vector<ReceiverT> & receiver_data,const std::vector<SenderT> & sender_data) const971 void ExtractSenderReceiverStats(
972 StatsCollector* collector,
973 const std::vector<ReceiverT>& receiver_data,
974 const std::vector<SenderT>& sender_data) const {
975 RTC_DCHECK(collector);
976 StatsReport::Id transport_id = StatsReport::NewComponentId(
977 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
978 ExtractStatsFromList(receiver_data, transport_id, collector,
979 StatsReport::kReceive, receiver_track_id_by_ssrc);
980 ExtractStatsFromList(sender_data, transport_id, collector,
981 StatsReport::kSend, sender_track_id_by_ssrc);
982 }
983 };
984
985 class VoiceMediaChannelStatsGatherer final : public MediaChannelStatsGatherer {
986 public:
VoiceMediaChannelStatsGatherer(cricket::VoiceMediaChannel * voice_media_channel)987 VoiceMediaChannelStatsGatherer(
988 cricket::VoiceMediaChannel* voice_media_channel)
989 : voice_media_channel_(voice_media_channel) {
990 RTC_DCHECK(voice_media_channel_);
991 }
992
GetStatsOnWorkerThread()993 bool GetStatsOnWorkerThread() override {
994 return voice_media_channel_->GetStats(&voice_media_info);
995 }
996
ExtractStats(StatsCollector * collector) const997 void ExtractStats(StatsCollector* collector) const override {
998 ExtractSenderReceiverStats(collector, voice_media_info.receivers,
999 voice_media_info.senders);
1000 if (voice_media_info.device_underrun_count == -2 ||
1001 voice_media_info.device_underrun_count > 0) {
1002 StatsReport* report = collector->PrepareADMReport();
1003 report->AddInt(StatsReport::kStatsValueNameAudioDeviceUnderrunCounter,
1004 voice_media_info.device_underrun_count);
1005 }
1006 }
1007
HasRemoteAudio() const1008 bool HasRemoteAudio() const override {
1009 return !voice_media_info.receivers.empty();
1010 }
1011
1012 private:
1013 cricket::VoiceMediaChannel* voice_media_channel_;
1014 cricket::VoiceMediaInfo voice_media_info;
1015 };
1016
1017 class VideoMediaChannelStatsGatherer final : public MediaChannelStatsGatherer {
1018 public:
VideoMediaChannelStatsGatherer(cricket::VideoMediaChannel * video_media_channel)1019 VideoMediaChannelStatsGatherer(
1020 cricket::VideoMediaChannel* video_media_channel)
1021 : video_media_channel_(video_media_channel) {
1022 RTC_DCHECK(video_media_channel_);
1023 }
1024
GetStatsOnWorkerThread()1025 bool GetStatsOnWorkerThread() override {
1026 return video_media_channel_->GetStats(&video_media_info);
1027 }
1028
ExtractStats(StatsCollector * collector) const1029 void ExtractStats(StatsCollector* collector) const override {
1030 ExtractSenderReceiverStats(collector, video_media_info.receivers,
1031 video_media_info.aggregated_senders);
1032 }
1033
HasRemoteAudio() const1034 bool HasRemoteAudio() const override { return false; }
1035
1036 private:
1037 cricket::VideoMediaChannel* video_media_channel_;
1038 cricket::VideoMediaInfo video_media_info;
1039 };
1040
CreateMediaChannelStatsGatherer(cricket::MediaChannel * channel)1041 std::unique_ptr<MediaChannelStatsGatherer> CreateMediaChannelStatsGatherer(
1042 cricket::MediaChannel* channel) {
1043 RTC_DCHECK(channel);
1044 if (channel->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1045 return std::make_unique<VoiceMediaChannelStatsGatherer>(
1046 static_cast<cricket::VoiceMediaChannel*>(channel));
1047 } else {
1048 RTC_DCHECK_EQ(channel->media_type(), cricket::MEDIA_TYPE_VIDEO);
1049 return std::make_unique<VideoMediaChannelStatsGatherer>(
1050 static_cast<cricket::VideoMediaChannel*>(channel));
1051 }
1052 }
1053
1054 } // namespace
1055
ExtractMediaInfo()1056 void StatsCollector::ExtractMediaInfo() {
1057 RTC_DCHECK_RUN_ON(pc_->signaling_thread());
1058
1059 std::vector<std::unique_ptr<MediaChannelStatsGatherer>> gatherers;
1060
1061 {
1062 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1063 for (const auto& transceiver : pc_->GetTransceiversInternal()) {
1064 cricket::ChannelInterface* channel = transceiver->internal()->channel();
1065 if (!channel) {
1066 continue;
1067 }
1068 std::unique_ptr<MediaChannelStatsGatherer> gatherer =
1069 CreateMediaChannelStatsGatherer(channel->media_channel());
1070 gatherer->mid = channel->content_name();
1071 gatherer->transport_name = channel->transport_name();
1072 for (const auto& sender : transceiver->internal()->senders()) {
1073 std::string track_id = (sender->track() ? sender->track()->id() : "");
1074 gatherer->sender_track_id_by_ssrc.insert(
1075 std::make_pair(sender->ssrc(), track_id));
1076 }
1077 for (const auto& receiver : transceiver->internal()->receivers()) {
1078 gatherer->receiver_track_id_by_ssrc.insert(std::make_pair(
1079 receiver->internal()->ssrc(), receiver->track()->id()));
1080 }
1081 gatherers.push_back(std::move(gatherer));
1082 }
1083 }
1084
1085 pc_->worker_thread()->Invoke<void>(RTC_FROM_HERE, [&] {
1086 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1087 for (auto it = gatherers.begin(); it != gatherers.end();
1088 /* incremented manually */) {
1089 MediaChannelStatsGatherer* gatherer = it->get();
1090 if (!gatherer->GetStatsOnWorkerThread()) {
1091 RTC_LOG(LS_ERROR) << "Failed to get media channel stats for mid="
1092 << gatherer->mid;
1093 it = gatherers.erase(it);
1094 continue;
1095 }
1096 ++it;
1097 }
1098 });
1099
1100 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1101
1102 bool has_remote_audio = false;
1103 for (const auto& gatherer : gatherers) {
1104 gatherer->ExtractStats(this);
1105 has_remote_audio |= gatherer->HasRemoteAudio();
1106 }
1107
1108 UpdateStatsFromExistingLocalAudioTracks(has_remote_audio);
1109 }
1110
ExtractSenderInfo()1111 void StatsCollector::ExtractSenderInfo() {
1112 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
1113
1114 for (const auto& sender : pc_->GetSenders()) {
1115 // TODO(nisse): SSRC == 0 currently means none. Delete check when
1116 // that is fixed.
1117 if (!sender->ssrc()) {
1118 continue;
1119 }
1120 const rtc::scoped_refptr<MediaStreamTrackInterface> track(sender->track());
1121 if (!track || track->kind() != MediaStreamTrackInterface::kVideoKind) {
1122 continue;
1123 }
1124 // Safe, because kind() == kVideoKind implies a subclass of
1125 // VideoTrackInterface; see mediastreaminterface.h.
1126 VideoTrackSourceInterface* source =
1127 static_cast<VideoTrackInterface*>(track.get())->GetSource();
1128
1129 VideoTrackSourceInterface::Stats stats;
1130 if (!source->GetStats(&stats)) {
1131 continue;
1132 }
1133 const StatsReport::Id stats_id = StatsReport::NewIdWithDirection(
1134 StatsReport::kStatsReportTypeSsrc, rtc::ToString(sender->ssrc()),
1135 StatsReport::kSend);
1136 StatsReport* report = reports_.FindOrAddNew(stats_id);
1137 report->AddInt(StatsReport::kStatsValueNameFrameWidthInput,
1138 stats.input_width);
1139 report->AddInt(StatsReport::kStatsValueNameFrameHeightInput,
1140 stats.input_height);
1141 }
1142 }
1143
ExtractDataInfo()1144 void StatsCollector::ExtractDataInfo() {
1145 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
1146
1147 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1148
1149 std::vector<DataChannelStats> data_stats = pc_->GetDataChannelStats();
1150 for (const auto& stats : data_stats) {
1151 StatsReport::Id id(StatsReport::NewTypedIntId(
1152 StatsReport::kStatsReportTypeDataChannel, stats.id));
1153 StatsReport* report = reports_.ReplaceOrAddNew(id);
1154 report->set_timestamp(stats_gathering_started_);
1155 report->AddString(StatsReport::kStatsValueNameLabel, stats.label);
1156 // Filter out the initial id (-1).
1157 if (stats.id >= 0) {
1158 report->AddInt(StatsReport::kStatsValueNameDataChannelId, stats.id);
1159 }
1160 report->AddString(StatsReport::kStatsValueNameProtocol, stats.protocol);
1161 report->AddString(StatsReport::kStatsValueNameState,
1162 DataChannelInterface::DataStateString(stats.state));
1163 }
1164 }
1165
GetReport(const StatsReport::StatsType & type,const std::string & id,StatsReport::Direction direction)1166 StatsReport* StatsCollector::GetReport(const StatsReport::StatsType& type,
1167 const std::string& id,
1168 StatsReport::Direction direction) {
1169 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
1170 RTC_DCHECK(type == StatsReport::kStatsReportTypeSsrc ||
1171 type == StatsReport::kStatsReportTypeRemoteSsrc);
1172 return reports_.Find(StatsReport::NewIdWithDirection(type, id, direction));
1173 }
1174
UpdateStatsFromExistingLocalAudioTracks(bool has_remote_tracks)1175 void StatsCollector::UpdateStatsFromExistingLocalAudioTracks(
1176 bool has_remote_tracks) {
1177 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
1178 // Loop through the existing local audio tracks.
1179 for (const auto& it : local_audio_tracks_) {
1180 AudioTrackInterface* track = it.first;
1181 uint32_t ssrc = it.second;
1182 StatsReport* report = GetReport(StatsReport::kStatsReportTypeSsrc,
1183 rtc::ToString(ssrc), StatsReport::kSend);
1184 if (report == NULL) {
1185 // This can happen if a local audio track is added to a stream on the
1186 // fly and the report has not been set up yet. Do nothing in this case.
1187 RTC_LOG(LS_ERROR) << "Stats report does not exist for ssrc " << ssrc;
1188 continue;
1189 }
1190
1191 // The same ssrc can be used by both local and remote audio tracks.
1192 const StatsReport::Value* v =
1193 report->FindValue(StatsReport::kStatsValueNameTrackId);
1194 if (!v || v->string_val() != track->id())
1195 continue;
1196
1197 report->set_timestamp(stats_gathering_started_);
1198 UpdateReportFromAudioTrack(track, report, has_remote_tracks);
1199 }
1200 }
1201
UpdateReportFromAudioTrack(AudioTrackInterface * track,StatsReport * report,bool has_remote_tracks)1202 void StatsCollector::UpdateReportFromAudioTrack(AudioTrackInterface* track,
1203 StatsReport* report,
1204 bool has_remote_tracks) {
1205 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
1206 RTC_DCHECK(track != NULL);
1207
1208 // Don't overwrite report values if they're not available.
1209 int signal_level;
1210 if (track->GetSignalLevel(&signal_level)) {
1211 RTC_DCHECK_GE(signal_level, 0);
1212 report->AddInt(StatsReport::kStatsValueNameAudioInputLevel, signal_level);
1213 }
1214
1215 auto audio_processor(track->GetAudioProcessor());
1216
1217 if (audio_processor.get()) {
1218 AudioProcessorInterface::AudioProcessorStatistics stats =
1219 audio_processor->GetStats(has_remote_tracks);
1220
1221 SetAudioProcessingStats(report, stats.typing_noise_detected,
1222 stats.apm_statistics);
1223 }
1224 }
1225
UpdateTrackReports()1226 void StatsCollector::UpdateTrackReports() {
1227 RTC_DCHECK(pc_->signaling_thread()->IsCurrent());
1228
1229 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
1230
1231 for (const auto& entry : track_ids_) {
1232 StatsReport* report = entry.second;
1233 report->set_timestamp(stats_gathering_started_);
1234 }
1235 }
1236
ClearUpdateStatsCacheForTest()1237 void StatsCollector::ClearUpdateStatsCacheForTest() {
1238 stats_gathering_started_ = 0;
1239 }
1240
1241 } // namespace webrtc
1242