blob: 6cb2a31b44b155beddcfbf0d97d63603e6170568 [file] [log] [blame]
hbosd565b732016-08-30 14:04:35 -07001/*
2 * Copyright 2016 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/stats/rtcstatscollector.h"
12
13#include <memory>
14#include <utility>
15#include <vector>
16
17#include "webrtc/api/peerconnection.h"
18#include "webrtc/base/checks.h"
19
20namespace webrtc {
21
22RTCStatsCollector::RTCStatsCollector(
23 PeerConnection* pc,
24 double cache_lifetime,
25 std::unique_ptr<rtc::Timing> timing)
26 : pc_(pc),
27 timing_(std::move(timing)),
28 cache_timestamp_(0.0),
29 cache_lifetime_(cache_lifetime) {
30 RTC_DCHECK(pc_);
31 RTC_DCHECK(timing_);
32 RTC_DCHECK(IsOnSignalingThread());
33 RTC_DCHECK_GE(cache_lifetime_, 0.0);
34}
35
36rtc::scoped_refptr<const RTCStatsReport> RTCStatsCollector::GetStatsReport() {
37 RTC_DCHECK(IsOnSignalingThread());
38 double now = timing_->TimerNow();
39 if (cached_report_ && now - cache_timestamp_ <= cache_lifetime_)
40 return cached_report_;
41 cache_timestamp_ = now;
42
43 rtc::scoped_refptr<RTCStatsReport> report = RTCStatsReport::Create();
44 report->AddStats(ProducePeerConnectionStats());
45
46 cached_report_ = report;
47 return cached_report_;
48}
49
50void RTCStatsCollector::ClearCachedStatsReport() {
51 RTC_DCHECK(IsOnSignalingThread());
52 cached_report_ = nullptr;
53}
54
55bool RTCStatsCollector::IsOnSignalingThread() const {
56 return pc_->session()->signaling_thread()->IsCurrent();
57}
58
59std::unique_ptr<RTCPeerConnectionStats>
60RTCStatsCollector::ProducePeerConnectionStats() const {
61 // TODO(hbos): If data channels are removed from the peer connection this will
62 // yield incorrect counts. Address before closing crbug.com/636818. See
63 // https://w3c.github.io/webrtc-stats/webrtc-stats.html#pcstats-dict*.
64 uint32_t data_channels_opened = 0;
65 const std::vector<rtc::scoped_refptr<DataChannel>>& data_channels =
66 pc_->sctp_data_channels();
67 for (const rtc::scoped_refptr<DataChannel>& data_channel : data_channels) {
68 if (data_channel->state() == DataChannelInterface::kOpen)
69 ++data_channels_opened;
70 }
71 // There is always just one |RTCPeerConnectionStats| so its |id| can be a
72 // constant.
73 std::unique_ptr<RTCPeerConnectionStats> stats(
74 new RTCPeerConnectionStats("RTCPeerConnection", cache_timestamp_));
75 stats->data_channels_opened = data_channels_opened;
76 stats->data_channels_closed = static_cast<uint32_t>(data_channels.size()) -
77 data_channels_opened;
78 return stats;
79}
80
81} // namespace webrtc