blob: ecc0272f9903c6bbc4b34fa7f9bfb28349ec3a4a [file] [log] [blame]
Sebastian Janssonb34556e2018-03-21 14:38:32 +01001/*
2 * Copyright (c) 2018 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 "call/receive_time_calculator.h"
12#include "rtc_base/logging.h"
13#include "rtc_base/ptr_util.h"
14#include "system_wrappers/include/field_trial.h"
15
16namespace webrtc {
17namespace {
18using ::webrtc::field_trial::FindFullName;
19using ::webrtc::field_trial::IsEnabled;
20
21const char kBweReceiveTimeCorrection[] = "WebRTC-BweReceiveTimeCorrection";
22} // namespace
23
24ReceiveTimeCalculator::ReceiveTimeCalculator(int64_t min_delta_ms,
25 int64_t max_delta_diff_ms)
26 : min_delta_us_(min_delta_ms * 1000),
27 max_delta_diff_us_(max_delta_diff_ms * 1000) {}
28
29std::unique_ptr<ReceiveTimeCalculator>
30ReceiveTimeCalculator::CreateFromFieldTrial() {
31 if (!IsEnabled(kBweReceiveTimeCorrection))
32 return nullptr;
33 int min, max;
34 if (sscanf(FindFullName(kBweReceiveTimeCorrection).c_str(), "Enabled/%d,%d",
35 &min, &max) != 2) {
36 RTC_LOG(LS_WARNING) << "Invalid number of parameters provided.";
37 return nullptr;
38 }
39 return rtc::MakeUnique<ReceiveTimeCalculator>(min, max);
40}
41
42int64_t ReceiveTimeCalculator::ReconcileReceiveTimes(int64_t packet_time_us_,
43 int64_t safe_time_us_) {
44 if (!receive_time_offset_us_) {
45 receive_time_offset_us_ = safe_time_us_ - packet_time_us_;
46 } else {
47 int64_t safe_delta_us = safe_time_us_ - last_safe_time_us_;
48 int64_t packet_delta_us_ = packet_time_us_ - last_packet_time_us_;
49 int64_t delta_diff = packet_delta_us_ - safe_delta_us;
50 // Packet time should not decrease significantly, a large decrease indicates
51 // a reset of the packet time clock and we should reset the offest
52 // parameter. The safe reference time can increase in large jumps if the
53 // thread measuring it is backgrounded for longer periods. But if the packet
54 // time increases significantly more than the safe time, it indicates a
55 // clock reset and we should reset the offset.
56
57 if (packet_delta_us_ < min_delta_us_ || delta_diff > max_delta_diff_us_) {
58 RTC_LOG(LS_WARNING) << "Received a clock jump of " << delta_diff
59 << " resetting offset";
60 receive_time_offset_us_ = safe_time_us_ - packet_time_us_;
61 }
62 }
63 last_packet_time_us_ = packet_time_us_;
64 last_safe_time_us_ = safe_time_us_;
65 return packet_time_us_ + *receive_time_offset_us_;
66}
67} // namespace webrtc