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

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

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

Powered by Google App Engine
This is Rietveld 408576698