Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(79)

Side by Side Diff: webrtc/api/statscollector.cc

Issue 2514883002: Create //webrtc/api:libjingle_peerconnection_api + refactorings. (Closed)
Patch Set: Rebase Created 3 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « webrtc/api/statscollector.h ('k') | webrtc/api/statscollector_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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 "webrtc/api/statscollector.h"
12
13 #include <memory>
14 #include <utility>
15 #include <vector>
16
17 #include "webrtc/api/peerconnection.h"
18 #include "webrtc/base/base64.h"
19 #include "webrtc/base/checks.h"
20 #include "webrtc/pc/channel.h"
21
22 namespace webrtc {
23 namespace {
24
25 // The following is the enum RTCStatsIceCandidateType from
26 // http://w3c.github.io/webrtc-stats/#rtcstatsicecandidatetype-enum such that
27 // our stats report for ice candidate type could conform to that.
28 const char STATSREPORT_LOCAL_PORT_TYPE[] = "host";
29 const char STATSREPORT_STUN_PORT_TYPE[] = "serverreflexive";
30 const char STATSREPORT_PRFLX_PORT_TYPE[] = "peerreflexive";
31 const char STATSREPORT_RELAY_PORT_TYPE[] = "relayed";
32
33 // Strings used by the stats collector to report adapter types. This fits the
34 // general stype of http://w3c.github.io/webrtc-stats than what
35 // AdapterTypeToString does.
36 const char* STATSREPORT_ADAPTER_TYPE_ETHERNET = "lan";
37 const char* STATSREPORT_ADAPTER_TYPE_WIFI = "wlan";
38 const char* STATSREPORT_ADAPTER_TYPE_WWAN = "wwan";
39 const char* STATSREPORT_ADAPTER_TYPE_VPN = "vpn";
40 const char* STATSREPORT_ADAPTER_TYPE_LOOPBACK = "loopback";
41
42 template<typename ValueType>
43 struct TypeForAdd {
44 const StatsReport::StatsValueName name;
45 const ValueType& value;
46 };
47
48 typedef TypeForAdd<bool> BoolForAdd;
49 typedef TypeForAdd<float> FloatForAdd;
50 typedef TypeForAdd<int64_t> Int64ForAdd;
51 typedef TypeForAdd<int> IntForAdd;
52
53 StatsReport::Id GetTransportIdFromProxy(const ProxyTransportMap& map,
54 const std::string& proxy) {
55 RTC_DCHECK(!proxy.empty());
56 auto found = map.find(proxy);
57 if (found == map.end()) {
58 return StatsReport::Id();
59 }
60
61 return StatsReport::NewComponentId(
62 found->second, cricket::ICE_CANDIDATE_COMPONENT_RTP);
63 }
64
65 StatsReport* AddTrackReport(StatsCollection* reports,
66 const std::string& track_id) {
67 // Adds an empty track report.
68 StatsReport::Id id(
69 StatsReport::NewTypedId(StatsReport::kStatsReportTypeTrack, track_id));
70 StatsReport* report = reports->ReplaceOrAddNew(id);
71 report->AddString(StatsReport::kStatsValueNameTrackId, track_id);
72 return report;
73 }
74
75 template <class TrackVector>
76 void CreateTrackReports(const TrackVector& tracks, StatsCollection* reports,
77 TrackIdMap& track_ids) {
78 for (const auto& track : tracks) {
79 const std::string& track_id = track->id();
80 StatsReport* report = AddTrackReport(reports, track_id);
81 RTC_DCHECK(report != nullptr);
82 track_ids[track_id] = report;
83 }
84 }
85
86 void ExtractCommonSendProperties(const cricket::MediaSenderInfo& info,
87 StatsReport* report) {
88 report->AddString(StatsReport::kStatsValueNameCodecName, info.codec_name);
89 report->AddInt64(StatsReport::kStatsValueNameBytesSent, info.bytes_sent);
90 if (info.rtt_ms >= 0) {
91 report->AddInt64(StatsReport::kStatsValueNameRtt, info.rtt_ms);
92 }
93 }
94
95 void ExtractCommonReceiveProperties(const cricket::MediaReceiverInfo& info,
96 StatsReport* report) {
97 report->AddString(StatsReport::kStatsValueNameCodecName, info.codec_name);
98 }
99
100 void SetAudioProcessingStats(StatsReport* report,
101 bool typing_noise_detected,
102 int echo_return_loss,
103 int echo_return_loss_enhancement,
104 int echo_delay_median_ms,
105 float aec_quality_min,
106 int echo_delay_std_ms,
107 float residual_echo_likelihood,
108 float residual_echo_likelihood_recent_max) {
109 report->AddBoolean(StatsReport::kStatsValueNameTypingNoiseState,
110 typing_noise_detected);
111 if (aec_quality_min >= 0.0f) {
112 report->AddFloat(StatsReport::kStatsValueNameEchoCancellationQualityMin,
113 aec_quality_min);
114 }
115 const IntForAdd ints[] = {
116 { StatsReport::kStatsValueNameEchoDelayMedian, echo_delay_median_ms },
117 { StatsReport::kStatsValueNameEchoDelayStdDev, echo_delay_std_ms },
118 };
119 for (const auto& i : ints) {
120 if (i.value >= 0) {
121 report->AddInt(i.name, i.value);
122 }
123 }
124 // These can take on valid negative values.
125 report->AddInt(StatsReport::kStatsValueNameEchoReturnLoss, echo_return_loss);
126 report->AddInt(StatsReport::kStatsValueNameEchoReturnLossEnhancement,
127 echo_return_loss_enhancement);
128 if (residual_echo_likelihood >= 0.0f) {
129 report->AddFloat(StatsReport::kStatsValueNameResidualEchoLikelihood,
130 residual_echo_likelihood);
131 }
132 if (residual_echo_likelihood_recent_max >= 0.0f) {
133 report->AddFloat(
134 StatsReport::kStatsValueNameResidualEchoLikelihoodRecentMax,
135 residual_echo_likelihood_recent_max);
136 }
137 }
138
139 void ExtractStats(const cricket::VoiceReceiverInfo& info, StatsReport* report) {
140 ExtractCommonReceiveProperties(info, report);
141 const FloatForAdd floats[] = {
142 { StatsReport::kStatsValueNameExpandRate, info.expand_rate },
143 { StatsReport::kStatsValueNameSecondaryDecodedRate,
144 info.secondary_decoded_rate },
145 { StatsReport::kStatsValueNameSpeechExpandRate, info.speech_expand_rate },
146 { StatsReport::kStatsValueNameAccelerateRate, info.accelerate_rate },
147 { StatsReport::kStatsValueNamePreemptiveExpandRate,
148 info.preemptive_expand_rate },
149 };
150
151 const IntForAdd ints[] = {
152 { StatsReport::kStatsValueNameCurrentDelayMs, info.delay_estimate_ms },
153 { StatsReport::kStatsValueNameDecodingCNG, info.decoding_cng },
154 { StatsReport::kStatsValueNameDecodingCTN, info.decoding_calls_to_neteq },
155 { StatsReport::kStatsValueNameDecodingCTSG,
156 info.decoding_calls_to_silence_generator },
157 { StatsReport::kStatsValueNameDecodingMutedOutput,
158 info.decoding_muted_output },
159 { StatsReport::kStatsValueNameDecodingNormal, info.decoding_normal },
160 { StatsReport::kStatsValueNameDecodingPLC, info.decoding_plc },
161 { StatsReport::kStatsValueNameDecodingPLCCNG, info.decoding_plc_cng },
162 { StatsReport::kStatsValueNameJitterBufferMs, info.jitter_buffer_ms },
163 { StatsReport::kStatsValueNameJitterReceived, info.jitter_ms },
164 { StatsReport::kStatsValueNamePacketsLost, info.packets_lost },
165 { StatsReport::kStatsValueNamePacketsReceived, info.packets_rcvd },
166 { StatsReport::kStatsValueNamePreferredJitterBufferMs,
167 info.jitter_buffer_preferred_ms },
168 };
169
170 for (const auto& f : floats)
171 report->AddFloat(f.name, f.value);
172
173 for (const auto& i : ints)
174 report->AddInt(i.name, i.value);
175 if (info.audio_level >= 0) {
176 report->AddInt(StatsReport::kStatsValueNameAudioOutputLevel,
177 info.audio_level);
178 }
179
180 report->AddInt64(StatsReport::kStatsValueNameBytesReceived,
181 info.bytes_rcvd);
182 if (info.capture_start_ntp_time_ms >= 0) {
183 report->AddInt64(StatsReport::kStatsValueNameCaptureStartNtpTimeMs,
184 info.capture_start_ntp_time_ms);
185 }
186 report->AddString(StatsReport::kStatsValueNameMediaType, "audio");
187 }
188
189 void ExtractStats(const cricket::VoiceSenderInfo& info, StatsReport* report) {
190 ExtractCommonSendProperties(info, report);
191
192 SetAudioProcessingStats(
193 report, info.typing_noise_detected, info.echo_return_loss,
194 info.echo_return_loss_enhancement, info.echo_delay_median_ms,
195 info.aec_quality_min, info.echo_delay_std_ms,
196 info.residual_echo_likelihood, info.residual_echo_likelihood_recent_max);
197
198 RTC_DCHECK_GE(info.audio_level, 0);
199 const IntForAdd ints[] = {
200 { StatsReport::kStatsValueNameAudioInputLevel, info.audio_level},
201 { StatsReport::kStatsValueNameJitterReceived, info.jitter_ms },
202 { StatsReport::kStatsValueNamePacketsLost, info.packets_lost },
203 { StatsReport::kStatsValueNamePacketsSent, info.packets_sent },
204 };
205
206 for (const auto& i : ints) {
207 if (i.value >= 0) {
208 report->AddInt(i.name, i.value);
209 }
210 }
211 report->AddString(StatsReport::kStatsValueNameMediaType, "audio");
212 }
213
214 void ExtractStats(const cricket::VideoReceiverInfo& info, StatsReport* report) {
215 ExtractCommonReceiveProperties(info, report);
216 report->AddString(StatsReport::kStatsValueNameCodecImplementationName,
217 info.decoder_implementation_name);
218 report->AddInt64(StatsReport::kStatsValueNameBytesReceived,
219 info.bytes_rcvd);
220 if (info.capture_start_ntp_time_ms >= 0) {
221 report->AddInt64(StatsReport::kStatsValueNameCaptureStartNtpTimeMs,
222 info.capture_start_ntp_time_ms);
223 }
224 const IntForAdd ints[] = {
225 { StatsReport::kStatsValueNameCurrentDelayMs, info.current_delay_ms },
226 { StatsReport::kStatsValueNameDecodeMs, info.decode_ms },
227 { StatsReport::kStatsValueNameFirsSent, info.firs_sent },
228 { StatsReport::kStatsValueNameFrameHeightReceived, info.frame_height },
229 { StatsReport::kStatsValueNameFrameRateDecoded, info.framerate_decoded },
230 { StatsReport::kStatsValueNameFrameRateOutput, info.framerate_output },
231 { StatsReport::kStatsValueNameFrameRateReceived, info.framerate_rcvd },
232 { StatsReport::kStatsValueNameFrameWidthReceived, info.frame_width },
233 { StatsReport::kStatsValueNameJitterBufferMs, info.jitter_buffer_ms },
234 { StatsReport::kStatsValueNameMaxDecodeMs, info.max_decode_ms },
235 { StatsReport::kStatsValueNameMinPlayoutDelayMs,
236 info.min_playout_delay_ms },
237 { StatsReport::kStatsValueNameNacksSent, info.nacks_sent },
238 { StatsReport::kStatsValueNamePacketsLost, info.packets_lost },
239 { StatsReport::kStatsValueNamePacketsReceived, info.packets_rcvd },
240 { StatsReport::kStatsValueNamePlisSent, info.plis_sent },
241 { StatsReport::kStatsValueNameRenderDelayMs, info.render_delay_ms },
242 { StatsReport::kStatsValueNameTargetDelayMs, info.target_delay_ms },
243 { StatsReport::kStatsValueNameFramesDecoded, info.frames_decoded },
244 };
245
246 for (const auto& i : ints)
247 report->AddInt(i.name, i.value);
248 report->AddString(StatsReport::kStatsValueNameMediaType, "video");
249 }
250
251 void ExtractStats(const cricket::VideoSenderInfo& info, StatsReport* report) {
252 ExtractCommonSendProperties(info, report);
253
254 report->AddString(StatsReport::kStatsValueNameCodecImplementationName,
255 info.encoder_implementation_name);
256 report->AddBoolean(StatsReport::kStatsValueNameBandwidthLimitedResolution,
257 (info.adapt_reason & 0x2) > 0);
258 report->AddBoolean(StatsReport::kStatsValueNameCpuLimitedResolution,
259 (info.adapt_reason & 0x1) > 0);
260 if (info.qp_sum)
261 report->AddInt(StatsReport::kStatsValueNameQpSum, *info.qp_sum);
262
263 const IntForAdd ints[] = {
264 { StatsReport::kStatsValueNameAdaptationChanges, info.adapt_changes },
265 { StatsReport::kStatsValueNameAvgEncodeMs, info.avg_encode_ms },
266 { StatsReport::kStatsValueNameEncodeUsagePercent,
267 info.encode_usage_percent },
268 { StatsReport::kStatsValueNameFirsReceived, info.firs_rcvd },
269 { StatsReport::kStatsValueNameFrameHeightSent, info.send_frame_height },
270 { StatsReport::kStatsValueNameFrameRateInput, info.framerate_input },
271 { StatsReport::kStatsValueNameFrameRateSent, info.framerate_sent },
272 { StatsReport::kStatsValueNameFrameWidthSent, info.send_frame_width },
273 { StatsReport::kStatsValueNameNacksReceived, info.nacks_rcvd },
274 { StatsReport::kStatsValueNamePacketsLost, info.packets_lost },
275 { StatsReport::kStatsValueNamePacketsSent, info.packets_sent },
276 { StatsReport::kStatsValueNamePlisReceived, info.plis_rcvd },
277 { StatsReport::kStatsValueNameFramesEncoded, info.frames_encoded },
278 };
279
280 for (const auto& i : ints)
281 report->AddInt(i.name, i.value);
282 report->AddString(StatsReport::kStatsValueNameMediaType, "video");
283 }
284
285 void ExtractStats(const cricket::BandwidthEstimationInfo& info,
286 double stats_gathering_started,
287 PeerConnectionInterface::StatsOutputLevel level,
288 StatsReport* report) {
289 RTC_DCHECK(report->type() == StatsReport::kStatsReportTypeBwe);
290
291 report->set_timestamp(stats_gathering_started);
292 const IntForAdd ints[] = {
293 { StatsReport::kStatsValueNameAvailableSendBandwidth,
294 info.available_send_bandwidth },
295 { StatsReport::kStatsValueNameAvailableReceiveBandwidth,
296 info.available_recv_bandwidth },
297 { StatsReport::kStatsValueNameTargetEncBitrate, info.target_enc_bitrate },
298 { StatsReport::kStatsValueNameActualEncBitrate, info.actual_enc_bitrate },
299 { StatsReport::kStatsValueNameRetransmitBitrate, info.retransmit_bitrate },
300 { StatsReport::kStatsValueNameTransmitBitrate, info.transmit_bitrate },
301 };
302 for (const auto& i : ints)
303 report->AddInt(i.name, i.value);
304 report->AddInt64(StatsReport::kStatsValueNameBucketDelay, info.bucket_delay);
305 }
306
307 void ExtractRemoteStats(const cricket::MediaSenderInfo& info,
308 StatsReport* report) {
309 report->set_timestamp(info.remote_stats[0].timestamp);
310 // TODO(hta): Extract some stats here.
311 }
312
313 void ExtractRemoteStats(const cricket::MediaReceiverInfo& info,
314 StatsReport* report) {
315 report->set_timestamp(info.remote_stats[0].timestamp);
316 // TODO(hta): Extract some stats here.
317 }
318
319 // Template to extract stats from a data vector.
320 // In order to use the template, the functions that are called from it,
321 // ExtractStats and ExtractRemoteStats, must be defined and overloaded
322 // for each type.
323 template<typename T>
324 void ExtractStatsFromList(const std::vector<T>& data,
325 const StatsReport::Id& transport_id,
326 StatsCollector* collector,
327 StatsReport::Direction direction) {
328 for (const auto& d : data) {
329 uint32_t ssrc = d.ssrc();
330 // Each track can have stats for both local and remote objects.
331 // TODO(hta): Handle the case of multiple SSRCs per object.
332 StatsReport* report = collector->PrepareReport(true, ssrc, transport_id,
333 direction);
334 if (report)
335 ExtractStats(d, report);
336
337 if (!d.remote_stats.empty()) {
338 report = collector->PrepareReport(false, ssrc, transport_id, direction);
339 if (report)
340 ExtractRemoteStats(d, report);
341 }
342 }
343 }
344
345 } // namespace
346
347 const char* IceCandidateTypeToStatsType(const std::string& candidate_type) {
348 if (candidate_type == cricket::LOCAL_PORT_TYPE) {
349 return STATSREPORT_LOCAL_PORT_TYPE;
350 }
351 if (candidate_type == cricket::STUN_PORT_TYPE) {
352 return STATSREPORT_STUN_PORT_TYPE;
353 }
354 if (candidate_type == cricket::PRFLX_PORT_TYPE) {
355 return STATSREPORT_PRFLX_PORT_TYPE;
356 }
357 if (candidate_type == cricket::RELAY_PORT_TYPE) {
358 return STATSREPORT_RELAY_PORT_TYPE;
359 }
360 RTC_NOTREACHED();
361 return "unknown";
362 }
363
364 const char* AdapterTypeToStatsType(rtc::AdapterType type) {
365 switch (type) {
366 case rtc::ADAPTER_TYPE_UNKNOWN:
367 return "unknown";
368 case rtc::ADAPTER_TYPE_ETHERNET:
369 return STATSREPORT_ADAPTER_TYPE_ETHERNET;
370 case rtc::ADAPTER_TYPE_WIFI:
371 return STATSREPORT_ADAPTER_TYPE_WIFI;
372 case rtc::ADAPTER_TYPE_CELLULAR:
373 return STATSREPORT_ADAPTER_TYPE_WWAN;
374 case rtc::ADAPTER_TYPE_VPN:
375 return STATSREPORT_ADAPTER_TYPE_VPN;
376 case rtc::ADAPTER_TYPE_LOOPBACK:
377 return STATSREPORT_ADAPTER_TYPE_LOOPBACK;
378 default:
379 RTC_NOTREACHED();
380 return "";
381 }
382 }
383
384 StatsCollector::StatsCollector(PeerConnection* pc)
385 : pc_(pc), stats_gathering_started_(0) {
386 RTC_DCHECK(pc_);
387 }
388
389 StatsCollector::~StatsCollector() {
390 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
391 }
392
393 // Wallclock time in ms.
394 double StatsCollector::GetTimeNow() {
395 return rtc::TimeUTCMicros() /
396 static_cast<double>(rtc::kNumMicrosecsPerMillisec);
397 }
398
399 // Adds a MediaStream with tracks that can be used as a |selector| in a call
400 // to GetStats.
401 void StatsCollector::AddStream(MediaStreamInterface* stream) {
402 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
403 RTC_DCHECK(stream != NULL);
404
405 CreateTrackReports<AudioTrackVector>(stream->GetAudioTracks(),
406 &reports_, track_ids_);
407 CreateTrackReports<VideoTrackVector>(stream->GetVideoTracks(),
408 &reports_, track_ids_);
409 }
410
411 void StatsCollector::AddLocalAudioTrack(AudioTrackInterface* audio_track,
412 uint32_t ssrc) {
413 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
414 RTC_DCHECK(audio_track != NULL);
415 #if RTC_DCHECK_IS_ON
416 for (const auto& track : local_audio_tracks_)
417 RTC_DCHECK(track.first != audio_track || track.second != ssrc);
418 #endif
419
420 local_audio_tracks_.push_back(std::make_pair(audio_track, ssrc));
421
422 // Create the kStatsReportTypeTrack report for the new track if there is no
423 // report yet.
424 StatsReport::Id id(StatsReport::NewTypedId(StatsReport::kStatsReportTypeTrack,
425 audio_track->id()));
426 StatsReport* report = reports_.Find(id);
427 if (!report) {
428 report = reports_.InsertNew(id);
429 report->AddString(StatsReport::kStatsValueNameTrackId, audio_track->id());
430 }
431 }
432
433 void StatsCollector::RemoveLocalAudioTrack(AudioTrackInterface* audio_track,
434 uint32_t ssrc) {
435 RTC_DCHECK(audio_track != NULL);
436 local_audio_tracks_.erase(std::remove_if(local_audio_tracks_.begin(),
437 local_audio_tracks_.end(),
438 [audio_track, ssrc](const LocalAudioTrackVector::value_type& track) {
439 return track.first == audio_track && track.second == ssrc;
440 }));
441 }
442
443 void StatsCollector::GetStats(MediaStreamTrackInterface* track,
444 StatsReports* reports) {
445 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
446 RTC_DCHECK(reports != NULL);
447 RTC_DCHECK(reports->empty());
448
449 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
450
451 if (!track) {
452 reports->reserve(reports_.size());
453 for (auto* r : reports_)
454 reports->push_back(r);
455 return;
456 }
457
458 StatsReport* report = reports_.Find(StatsReport::NewTypedId(
459 StatsReport::kStatsReportTypeSession, pc_->session()->id()));
460 if (report)
461 reports->push_back(report);
462
463 report = reports_.Find(StatsReport::NewTypedId(
464 StatsReport::kStatsReportTypeTrack, track->id()));
465
466 if (!report)
467 return;
468
469 reports->push_back(report);
470
471 std::string track_id;
472 for (const auto* r : reports_) {
473 if (r->type() != StatsReport::kStatsReportTypeSsrc)
474 continue;
475
476 const StatsReport::Value* v =
477 r->FindValue(StatsReport::kStatsValueNameTrackId);
478 if (v && v->string_val() == track->id())
479 reports->push_back(r);
480 }
481 }
482
483 void
484 StatsCollector::UpdateStats(PeerConnectionInterface::StatsOutputLevel level) {
485 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
486 double time_now = GetTimeNow();
487 // Calls to UpdateStats() that occur less than kMinGatherStatsPeriod number of
488 // ms apart will be ignored.
489 const double kMinGatherStatsPeriod = 50;
490 if (stats_gathering_started_ != 0 &&
491 stats_gathering_started_ + kMinGatherStatsPeriod > time_now) {
492 return;
493 }
494 stats_gathering_started_ = time_now;
495
496 // TODO(pthatcher): Merge PeerConnection and WebRtcSession so there is no
497 // pc_->session().
498 if (pc_->session()) {
499 // TODO(tommi): All of these hop over to the worker thread to fetch
500 // information. We could use an AsyncInvoker to run all of these and post
501 // the information back to the signaling thread where we can create and
502 // update stats reports. That would also clean up the threading story a bit
503 // since we'd be creating/updating the stats report objects consistently on
504 // the same thread (this class has no locks right now).
505 ExtractSessionInfo();
506 ExtractVoiceInfo();
507 ExtractVideoInfo(level);
508 ExtractSenderInfo();
509 ExtractDataInfo();
510 UpdateTrackReports();
511 }
512 }
513
514 StatsReport* StatsCollector::PrepareReport(
515 bool local,
516 uint32_t ssrc,
517 const StatsReport::Id& transport_id,
518 StatsReport::Direction direction) {
519 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
520 StatsReport::Id id(StatsReport::NewIdWithDirection(
521 local ? StatsReport::kStatsReportTypeSsrc
522 : StatsReport::kStatsReportTypeRemoteSsrc,
523 rtc::ToString<uint32_t>(ssrc), direction));
524 StatsReport* report = reports_.Find(id);
525
526 // Use the ID of the track that is currently mapped to the SSRC, if any.
527 std::string track_id;
528 if (!GetTrackIdBySsrc(ssrc, &track_id, direction)) {
529 if (!report) {
530 // The ssrc is not used by any track or existing report, return NULL
531 // in such case to indicate no report is prepared for the ssrc.
532 return NULL;
533 }
534
535 // The ssrc is not used by any existing track. Keeps the old track id
536 // since we want to report the stats for inactive ssrc.
537 const StatsReport::Value* v =
538 report->FindValue(StatsReport::kStatsValueNameTrackId);
539 if (v)
540 track_id = v->string_val();
541 }
542
543 if (!report)
544 report = reports_.InsertNew(id);
545
546 // FYI - for remote reports, the timestamp will be overwritten later.
547 report->set_timestamp(stats_gathering_started_);
548
549 report->AddInt64(StatsReport::kStatsValueNameSsrc, ssrc);
550 report->AddString(StatsReport::kStatsValueNameTrackId, track_id);
551 // Add the mapping of SSRC to transport.
552 report->AddId(StatsReport::kStatsValueNameTransportId, transport_id);
553 return report;
554 }
555
556 bool StatsCollector::IsValidTrack(const std::string& track_id) {
557 return reports_.Find(StatsReport::NewTypedId(
558 StatsReport::kStatsReportTypeTrack, track_id)) != nullptr;
559 }
560
561 StatsReport* StatsCollector::AddCertificateReports(
562 const rtc::SSLCertificate* cert) {
563 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
564 RTC_DCHECK(cert != NULL);
565
566 std::unique_ptr<rtc::SSLCertificateStats> first_stats = cert->GetStats();
567 StatsReport* first_report = nullptr;
568 StatsReport* prev_report = nullptr;
569 for (rtc::SSLCertificateStats* stats = first_stats.get(); stats;
570 stats = stats->issuer.get()) {
571 StatsReport::Id id(StatsReport::NewTypedId(
572 StatsReport::kStatsReportTypeCertificate, stats->fingerprint));
573
574 StatsReport* report = reports_.ReplaceOrAddNew(id);
575 report->set_timestamp(stats_gathering_started_);
576 report->AddString(StatsReport::kStatsValueNameFingerprint,
577 stats->fingerprint);
578 report->AddString(StatsReport::kStatsValueNameFingerprintAlgorithm,
579 stats->fingerprint_algorithm);
580 report->AddString(StatsReport::kStatsValueNameDer,
581 stats->base64_certificate);
582 if (!first_report)
583 first_report = report;
584 else
585 prev_report->AddId(StatsReport::kStatsValueNameIssuerId, id);
586 prev_report = report;
587 }
588 return first_report;
589 }
590
591 StatsReport* StatsCollector::AddConnectionInfoReport(
592 const std::string& content_name, int component, int connection_id,
593 const StatsReport::Id& channel_report_id,
594 const cricket::ConnectionInfo& info) {
595 StatsReport::Id id(StatsReport::NewCandidatePairId(content_name, component,
596 connection_id));
597 StatsReport* report = reports_.ReplaceOrAddNew(id);
598 report->set_timestamp(stats_gathering_started_);
599
600 const BoolForAdd bools[] = {
601 {StatsReport::kStatsValueNameActiveConnection, info.best_connection},
602 {StatsReport::kStatsValueNameReceiving, info.receiving},
603 {StatsReport::kStatsValueNameWritable, info.writable},
604 };
605 for (const auto& b : bools)
606 report->AddBoolean(b.name, b.value);
607
608 report->AddId(StatsReport::kStatsValueNameChannelId, channel_report_id);
609 report->AddId(StatsReport::kStatsValueNameLocalCandidateId,
610 AddCandidateReport(info.local_candidate, true)->id());
611 report->AddId(StatsReport::kStatsValueNameRemoteCandidateId,
612 AddCandidateReport(info.remote_candidate, false)->id());
613
614 const Int64ForAdd int64s[] = {
615 {StatsReport::kStatsValueNameBytesReceived, info.recv_total_bytes},
616 {StatsReport::kStatsValueNameBytesSent, info.sent_total_bytes},
617 {StatsReport::kStatsValueNamePacketsSent, info.sent_total_packets},
618 {StatsReport::kStatsValueNameRtt, info.rtt},
619 {StatsReport::kStatsValueNameSendPacketsDiscarded,
620 info.sent_discarded_packets},
621 {StatsReport::kStatsValueNameSentPingRequestsTotal,
622 info.sent_ping_requests_total},
623 {StatsReport::kStatsValueNameSentPingRequestsBeforeFirstResponse,
624 info.sent_ping_requests_before_first_response},
625 {StatsReport::kStatsValueNameSentPingResponses, info.sent_ping_responses},
626 {StatsReport::kStatsValueNameRecvPingRequests, info.recv_ping_requests},
627 {StatsReport::kStatsValueNameRecvPingResponses, info.recv_ping_responses},
628 };
629 for (const auto& i : int64s)
630 report->AddInt64(i.name, i.value);
631
632 report->AddString(StatsReport::kStatsValueNameLocalAddress,
633 info.local_candidate.address().ToString());
634 report->AddString(StatsReport::kStatsValueNameLocalCandidateType,
635 info.local_candidate.type());
636 report->AddString(StatsReport::kStatsValueNameRemoteAddress,
637 info.remote_candidate.address().ToString());
638 report->AddString(StatsReport::kStatsValueNameRemoteCandidateType,
639 info.remote_candidate.type());
640 report->AddString(StatsReport::kStatsValueNameTransportType,
641 info.local_candidate.protocol());
642
643 return report;
644 }
645
646 StatsReport* StatsCollector::AddCandidateReport(
647 const cricket::Candidate& candidate,
648 bool local) {
649 StatsReport::Id id(StatsReport::NewCandidateId(local, candidate.id()));
650 StatsReport* report = reports_.Find(id);
651 if (!report) {
652 report = reports_.InsertNew(id);
653 report->set_timestamp(stats_gathering_started_);
654 if (local) {
655 report->AddString(StatsReport::kStatsValueNameCandidateNetworkType,
656 AdapterTypeToStatsType(candidate.network_type()));
657 }
658 report->AddString(StatsReport::kStatsValueNameCandidateIPAddress,
659 candidate.address().ipaddr().ToString());
660 report->AddString(StatsReport::kStatsValueNameCandidatePortNumber,
661 candidate.address().PortAsString());
662 report->AddInt(StatsReport::kStatsValueNameCandidatePriority,
663 candidate.priority());
664 report->AddString(StatsReport::kStatsValueNameCandidateType,
665 IceCandidateTypeToStatsType(candidate.type()));
666 report->AddString(StatsReport::kStatsValueNameCandidateTransportType,
667 candidate.protocol());
668 }
669
670 return report;
671 }
672
673 void StatsCollector::ExtractSessionInfo() {
674 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
675
676 // Extract information from the base session.
677 StatsReport::Id id(StatsReport::NewTypedId(
678 StatsReport::kStatsReportTypeSession, pc_->session()->id()));
679 StatsReport* report = reports_.ReplaceOrAddNew(id);
680 report->set_timestamp(stats_gathering_started_);
681 report->AddBoolean(StatsReport::kStatsValueNameInitiator,
682 pc_->session()->initial_offerer());
683
684 std::unique_ptr<SessionStats> stats = pc_->session()->GetStats_s();
685 if (!stats) {
686 return;
687 }
688
689 // Store the proxy map away for use in SSRC reporting.
690 // TODO(tommi): This shouldn't be necessary if we post the stats back to the
691 // signaling thread after fetching them on the worker thread, then just use
692 // the proxy map directly from the session stats.
693 // As is, if GetStats() failed, we could be using old (incorrect?) proxy
694 // data.
695 proxy_to_transport_ = stats->proxy_to_transport;
696
697 for (const auto& transport_iter : stats->transport_stats) {
698 // Attempt to get a copy of the certificates from the transport and
699 // expose them in stats reports. All channels in a transport share the
700 // same local and remote certificates.
701 //
702 StatsReport::Id local_cert_report_id, remote_cert_report_id;
703 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
704 if (pc_->session()->GetLocalCertificate(
705 transport_iter.second.transport_name, &certificate)) {
706 StatsReport* r = AddCertificateReports(&(certificate->ssl_certificate()));
707 if (r)
708 local_cert_report_id = r->id();
709 }
710
711 std::unique_ptr<rtc::SSLCertificate> cert =
712 pc_->session()->GetRemoteSSLCertificate(
713 transport_iter.second.transport_name);
714 if (cert) {
715 StatsReport* r = AddCertificateReports(cert.get());
716 if (r)
717 remote_cert_report_id = r->id();
718 }
719
720 for (const auto& channel_iter : transport_iter.second.channel_stats) {
721 StatsReport::Id id(StatsReport::NewComponentId(
722 transport_iter.second.transport_name, channel_iter.component));
723 StatsReport* channel_report = reports_.ReplaceOrAddNew(id);
724 channel_report->set_timestamp(stats_gathering_started_);
725 channel_report->AddInt(StatsReport::kStatsValueNameComponent,
726 channel_iter.component);
727 if (local_cert_report_id.get()) {
728 channel_report->AddId(StatsReport::kStatsValueNameLocalCertificateId,
729 local_cert_report_id);
730 }
731 if (remote_cert_report_id.get()) {
732 channel_report->AddId(StatsReport::kStatsValueNameRemoteCertificateId,
733 remote_cert_report_id);
734 }
735 int srtp_crypto_suite = channel_iter.srtp_crypto_suite;
736 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE &&
737 rtc::SrtpCryptoSuiteToName(srtp_crypto_suite).length()) {
738 channel_report->AddString(
739 StatsReport::kStatsValueNameSrtpCipher,
740 rtc::SrtpCryptoSuiteToName(srtp_crypto_suite));
741 }
742 int ssl_cipher_suite = channel_iter.ssl_cipher_suite;
743 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL &&
744 rtc::SSLStreamAdapter::SslCipherSuiteToName(ssl_cipher_suite)
745 .length()) {
746 channel_report->AddString(
747 StatsReport::kStatsValueNameDtlsCipher,
748 rtc::SSLStreamAdapter::SslCipherSuiteToName(ssl_cipher_suite));
749 }
750
751 int connection_id = 0;
752 for (const cricket::ConnectionInfo& info :
753 channel_iter.connection_infos) {
754 StatsReport* connection_report = AddConnectionInfoReport(
755 transport_iter.first, channel_iter.component, connection_id++,
756 channel_report->id(), info);
757 if (info.best_connection) {
758 channel_report->AddId(
759 StatsReport::kStatsValueNameSelectedCandidatePairId,
760 connection_report->id());
761 }
762 }
763 }
764 }
765 }
766
767 void StatsCollector::ExtractVoiceInfo() {
768 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
769
770 if (!pc_->session()->voice_channel()) {
771 return;
772 }
773 cricket::VoiceMediaInfo voice_info;
774 if (!pc_->session()->voice_channel()->GetStats(&voice_info)) {
775 LOG(LS_ERROR) << "Failed to get voice channel stats.";
776 return;
777 }
778
779 // TODO(tommi): The above code should run on the worker thread and post the
780 // results back to the signaling thread, where we can add data to the reports.
781 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
782
783 StatsReport::Id transport_id(GetTransportIdFromProxy(
784 proxy_to_transport_, pc_->session()->voice_channel()->content_name()));
785 if (!transport_id.get()) {
786 LOG(LS_ERROR) << "Failed to get transport name for proxy "
787 << pc_->session()->voice_channel()->content_name();
788 return;
789 }
790
791 ExtractStatsFromList(voice_info.receivers, transport_id, this,
792 StatsReport::kReceive);
793 ExtractStatsFromList(voice_info.senders, transport_id, this,
794 StatsReport::kSend);
795
796 UpdateStatsFromExistingLocalAudioTracks();
797 }
798
799 void StatsCollector::ExtractVideoInfo(
800 PeerConnectionInterface::StatsOutputLevel level) {
801 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
802
803 if (!pc_->session()->video_channel())
804 return;
805
806 cricket::VideoMediaInfo video_info;
807 if (!pc_->session()->video_channel()->GetStats(&video_info)) {
808 LOG(LS_ERROR) << "Failed to get video channel stats.";
809 return;
810 }
811
812 // TODO(tommi): The above code should run on the worker thread and post the
813 // results back to the signaling thread, where we can add data to the reports.
814 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
815
816 StatsReport::Id transport_id(GetTransportIdFromProxy(
817 proxy_to_transport_, pc_->session()->video_channel()->content_name()));
818 if (!transport_id.get()) {
819 LOG(LS_ERROR) << "Failed to get transport name for proxy "
820 << pc_->session()->video_channel()->content_name();
821 return;
822 }
823 ExtractStatsFromList(video_info.receivers, transport_id, this,
824 StatsReport::kReceive);
825 ExtractStatsFromList(video_info.senders, transport_id, this,
826 StatsReport::kSend);
827 if (video_info.bw_estimations.size() != 1) {
828 LOG(LS_ERROR) << "BWEs count: " << video_info.bw_estimations.size();
829 } else {
830 StatsReport::Id report_id(StatsReport::NewBandwidthEstimationId());
831 StatsReport* report = reports_.FindOrAddNew(report_id);
832 ExtractStats(
833 video_info.bw_estimations[0], stats_gathering_started_, level, report);
834 }
835 }
836
837 void StatsCollector::ExtractSenderInfo() {
838 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
839
840 for (const auto& sender : pc_->GetSenders()) {
841 // TODO(nisse): SSRC == 0 currently means none. Delete check when
842 // that is fixed.
843 if (!sender->ssrc()) {
844 continue;
845 }
846 const rtc::scoped_refptr<MediaStreamTrackInterface> track(sender->track());
847 if (!track || track->kind() != MediaStreamTrackInterface::kVideoKind) {
848 continue;
849 }
850 // Safe, because kind() == kVideoKind implies a subclass of
851 // VideoTrackInterface; see mediastreaminterface.h.
852 VideoTrackSourceInterface* source =
853 static_cast<VideoTrackInterface*>(track.get())->GetSource();
854
855 VideoTrackSourceInterface::Stats stats;
856 if (!source->GetStats(&stats)) {
857 continue;
858 }
859 const StatsReport::Id stats_id = StatsReport::NewIdWithDirection(
860 StatsReport::kStatsReportTypeSsrc,
861 rtc::ToString<uint32_t>(sender->ssrc()), StatsReport::kSend);
862 StatsReport* report = reports_.FindOrAddNew(stats_id);
863 report->AddInt(StatsReport::kStatsValueNameFrameWidthInput,
864 stats.input_width);
865 report->AddInt(StatsReport::kStatsValueNameFrameHeightInput,
866 stats.input_height);
867 }
868 }
869
870 void StatsCollector::ExtractDataInfo() {
871 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
872
873 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
874
875 for (const auto& dc : pc_->sctp_data_channels()) {
876 StatsReport::Id id(StatsReport::NewTypedIntId(
877 StatsReport::kStatsReportTypeDataChannel, dc->id()));
878 StatsReport* report = reports_.ReplaceOrAddNew(id);
879 report->set_timestamp(stats_gathering_started_);
880 report->AddString(StatsReport::kStatsValueNameLabel, dc->label());
881 // Filter out the initial id (-1).
882 if (dc->id() >= 0) {
883 report->AddInt(StatsReport::kStatsValueNameDataChannelId, dc->id());
884 }
885 report->AddString(StatsReport::kStatsValueNameProtocol, dc->protocol());
886 report->AddString(StatsReport::kStatsValueNameState,
887 DataChannelInterface::DataStateString(dc->state()));
888 }
889 }
890
891 StatsReport* StatsCollector::GetReport(const StatsReport::StatsType& type,
892 const std::string& id,
893 StatsReport::Direction direction) {
894 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
895 RTC_DCHECK(type == StatsReport::kStatsReportTypeSsrc ||
896 type == StatsReport::kStatsReportTypeRemoteSsrc);
897 return reports_.Find(StatsReport::NewIdWithDirection(type, id, direction));
898 }
899
900 void StatsCollector::UpdateStatsFromExistingLocalAudioTracks() {
901 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
902 // Loop through the existing local audio tracks.
903 for (const auto& it : local_audio_tracks_) {
904 AudioTrackInterface* track = it.first;
905 uint32_t ssrc = it.second;
906 StatsReport* report =
907 GetReport(StatsReport::kStatsReportTypeSsrc,
908 rtc::ToString<uint32_t>(ssrc), StatsReport::kSend);
909 if (report == NULL) {
910 // This can happen if a local audio track is added to a stream on the
911 // fly and the report has not been set up yet. Do nothing in this case.
912 LOG(LS_ERROR) << "Stats report does not exist for ssrc " << ssrc;
913 continue;
914 }
915
916 // The same ssrc can be used by both local and remote audio tracks.
917 const StatsReport::Value* v =
918 report->FindValue(StatsReport::kStatsValueNameTrackId);
919 if (!v || v->string_val() != track->id())
920 continue;
921
922 report->set_timestamp(stats_gathering_started_);
923 UpdateReportFromAudioTrack(track, report);
924 }
925 }
926
927 void StatsCollector::UpdateReportFromAudioTrack(AudioTrackInterface* track,
928 StatsReport* report) {
929 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
930 RTC_DCHECK(track != NULL);
931
932 // Don't overwrite report values if they're not available.
933 int signal_level;
934 if (track->GetSignalLevel(&signal_level)) {
935 RTC_DCHECK_GE(signal_level, 0);
936 report->AddInt(StatsReport::kStatsValueNameAudioInputLevel, signal_level);
937 }
938
939 auto audio_processor(track->GetAudioProcessor());
940
941 if (audio_processor.get()) {
942 AudioProcessorInterface::AudioProcessorStats stats;
943 audio_processor->GetStats(&stats);
944
945 SetAudioProcessingStats(
946 report, stats.typing_noise_detected, stats.echo_return_loss,
947 stats.echo_return_loss_enhancement, stats.echo_delay_median_ms,
948 stats.aec_quality_min, stats.echo_delay_std_ms,
949 stats.residual_echo_likelihood,
950 stats.residual_echo_likelihood_recent_max);
951
952 report->AddFloat(StatsReport::kStatsValueNameAecDivergentFilterFraction,
953 stats.aec_divergent_filter_fraction);
954 }
955 }
956
957 bool StatsCollector::GetTrackIdBySsrc(uint32_t ssrc,
958 std::string* track_id,
959 StatsReport::Direction direction) {
960 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
961 if (direction == StatsReport::kSend) {
962 if (!pc_->session()->GetLocalTrackIdBySsrc(ssrc, track_id)) {
963 LOG(LS_WARNING) << "The SSRC " << ssrc
964 << " is not associated with a sending track";
965 return false;
966 }
967 } else {
968 RTC_DCHECK(direction == StatsReport::kReceive);
969 if (!pc_->session()->GetRemoteTrackIdBySsrc(ssrc, track_id)) {
970 LOG(LS_WARNING) << "The SSRC " << ssrc
971 << " is not associated with a receiving track";
972 return false;
973 }
974 }
975
976 return true;
977 }
978
979 void StatsCollector::UpdateTrackReports() {
980 RTC_DCHECK(pc_->session()->signaling_thread()->IsCurrent());
981
982 rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
983
984 for (const auto& entry : track_ids_) {
985 StatsReport* report = entry.second;
986 report->set_timestamp(stats_gathering_started_);
987 }
988 }
989
990 void StatsCollector::ClearUpdateStatsCacheForTest() {
991 stats_gathering_started_ = 0;
992 }
993
994 } // namespace webrtc
OLDNEW
« no previous file with comments | « webrtc/api/statscollector.h ('k') | webrtc/api/statscollector_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698