1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef AP_HUB_SYNC_H__
18 #define AP_HUB_SYNC_H__
19 
20 #include <stdio.h>
21 #include <stdint.h>
22 #include <stdbool.h>
23 
24 #ifdef __cplusplus
25 extern "C" {
26 #endif
27 
28 /*
29  * This implements an AP-HUB time sync algorithm that is expected to improve time sync accuracy by
30  * avoiding communication latency jitter.
31  *
32  * It uses max of (apTime - hubTime) in a window, which is more consistent than average, to
33  * establish mapping between ap timestamp and hub stamp. Additional low pass filtering is added
34  * to further lowering jitter (it is not expected for two clocks to drift much in short time).
35  *
36  * Max is slightly anti-intuitive here because difference is defined as apTime - hubTime. Max of
37  * that is equivalent to min of hubTime - apTime, which corresponds to a packet that get delayed
38  * by system scheduling minimally (closer to the more consistent hardware related latency).
39  */
40 
41 struct ApHubSync {
42     uint64_t lastTs;           // AP time of previous data point, used for control expiration
43     int64_t deltaEstimation;   // the estimated delta between two clocks, filtered.
44 
45     int64_t windowMax;         // track the maximum timestamp difference in a window
46     uint64_t windowTimeout;    // track window expiration time
47     uint8_t state;             // internal state of the sync
48 };
49 
50 // reset data structure
51 void apHubSyncReset(struct ApHubSync* sync);
52 
53 // add a data point (a pair of apTime and the corresponding hub time).
54 void apHubSyncAddDelta(struct ApHubSync* sync, uint64_t apTime, uint64_t hubTime);
55 
56 // get the estimation of time delta
57 int64_t apHubSyncGetDelta(struct ApHubSync* sync, uint64_t hubTime);
58 
59 #ifdef __cplusplus
60 }
61 #endif
62 
63 #endif  // AP_HUB_SYNC_H__
64