1 /**
2  * Copyright (C) 2022 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 #include <sys/time.h>
18 #include <stdlib.h>
19 #include <netinet/in.h>
20 #include <RtpOsUtil.h>
21 
RtpOsUtil()22 RtpOsUtil::RtpOsUtil() {}
23 
~RtpOsUtil()24 RtpOsUtil::~RtpOsUtil() {}
25 
GetNtpTime(tRTP_NTP_TIME & pstNtpTime)26 RtpDt_Void RtpOsUtil::GetNtpTime(tRTP_NTP_TIME& pstNtpTime)
27 {
28     struct timeval stAndrodTp;
29 
30     if (gettimeofday(&stAndrodTp, nullptr) != -1)
31     {
32         // To convert a UNIX timestamp (seconds since 1970) to NTP time, add 2,208,988,800 seconds
33         uint64_t ntpts = ((unsigned long long)(stAndrodTp.tv_sec + 2208988800UL) << 32) +
34                 (unsigned long long)(stAndrodTp.tv_usec / 1e6 * 4294967296.);
35 
36         pstNtpTime.m_uiNtpHigh32Bits = (ntpts >> 32);
37         pstNtpTime.m_uiNtpLow32Bits = ntpts;
38     }
39 }
40 
Srand()41 RtpDt_Void RtpOsUtil::Srand()
42 {
43     struct timeval stSysTime;
44     gettimeofday(&stSysTime, nullptr);
45     RtpDt_UInt32 uiSeed = stSysTime.tv_usec * 1000;
46     srand(uiSeed);
47 }
48 
Rand()49 RtpDt_UInt32 RtpOsUtil::Rand()
50 {
51     RtpOsUtil::Srand();
52     return rand();
53 }
54 
Ntohl(RtpDt_UInt32 uiNetlong)55 RtpDt_UInt32 RtpOsUtil::Ntohl(RtpDt_UInt32 uiNetlong)
56 {
57     return ntohl(uiNetlong);
58 }
59 
RRand()60 RtpDt_Double RtpOsUtil::RRand()
61 {
62     tRTP_NTP_TIME stNtpTs = {0, 0};
63     RtpOsUtil::Srand();
64     RtpDt_Double dRandNum = static_cast<RtpDt_Double>(rand()) / static_cast<RtpDt_Double>(RAND_MAX);
65     RtpOsUtil::GetNtpTime(stNtpTs);
66     RtpDt_Double dTemp = ((dRandNum * stNtpTs.m_uiNtpHigh32Bits) +
67             (stNtpTs.m_uiNtpLow32Bits / static_cast<RtpDt_Double>(RTP_MILLISEC_MICRO)));
68 
69     if (dTemp > RTP_ZERO)
70     {
71         return 1.0 / dTemp;
72     }
73     else
74     {
75         return 1.0;
76     }
77 }
78