Gustaf Ullberg | 777cf26 | 2018-11-22 16:02:34 +0100 | [diff] [blame] | 1 | /* |
| 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 | #include "modules/audio_processing/aec3/clockdrift_detector.h" |
| 11 | |
| 12 | namespace webrtc { |
| 13 | |
| 14 | ClockdriftDetector::ClockdriftDetector() |
| 15 | : level_(Level::kNone), stability_counter_(0) { |
| 16 | delay_history_.fill(0); |
| 17 | } |
| 18 | |
| 19 | ClockdriftDetector::~ClockdriftDetector() = default; |
| 20 | |
| 21 | void ClockdriftDetector::Update(int delay_estimate) { |
| 22 | if (delay_estimate == delay_history_[0]) { |
| 23 | // Reset clockdrift level if delay estimate is stable for 7500 blocks (30 |
| 24 | // seconds). |
| 25 | if (++stability_counter_ > 7500) |
| 26 | level_ = Level::kNone; |
| 27 | return; |
| 28 | } |
| 29 | |
| 30 | stability_counter_ = 0; |
| 31 | const int d1 = delay_history_[0] - delay_estimate; |
| 32 | const int d2 = delay_history_[1] - delay_estimate; |
| 33 | const int d3 = delay_history_[2] - delay_estimate; |
| 34 | |
| 35 | // Patterns recognized as positive clockdrift: |
| 36 | // [x-3], x-2, x-1, x. |
| 37 | // [x-3], x-1, x-2, x. |
| 38 | const bool probable_drift_up = |
| 39 | (d1 == -1 && d2 == -2) || (d1 == -2 && d2 == -1); |
| 40 | const bool drift_up = probable_drift_up && d3 == -3; |
| 41 | |
| 42 | // Patterns recognized as negative clockdrift: |
| 43 | // [x+3], x+2, x+1, x. |
| 44 | // [x+3], x+1, x+2, x. |
| 45 | const bool probable_drift_down = (d1 == 1 && d2 == 2) || (d1 == 2 && d2 == 1); |
| 46 | const bool drift_down = probable_drift_down && d3 == 3; |
| 47 | |
| 48 | // Set clockdrift level. |
| 49 | if (drift_up || drift_down) { |
| 50 | level_ = Level::kVerified; |
| 51 | } else if ((probable_drift_up || probable_drift_down) && |
| 52 | level_ == Level::kNone) { |
| 53 | level_ = Level::kProbable; |
| 54 | } |
| 55 | |
| 56 | // Shift delay history one step. |
| 57 | delay_history_[2] = delay_history_[1]; |
| 58 | delay_history_[1] = delay_history_[0]; |
| 59 | delay_history_[0] = delay_estimate; |
| 60 | } |
| 61 | } // namespace webrtc |