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

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

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

Powered by Google App Engine
This is Rietveld 408576698