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         pstNtpTime.m_uiNtpHigh32Bits = stAndrodTp.tv_sec + 2208988800UL;
34         pstNtpTime.m_uiNtpLow32Bits = (RtpDt_UInt32)(stAndrodTp.tv_usec * 4294UL);
35     }
36 }
37 
Srand()38 RtpDt_Void RtpOsUtil::Srand()
39 {
40     struct timeval stSysTime;
41     gettimeofday(&stSysTime, nullptr);
42     RtpDt_UInt32 uiSeed = stSysTime.tv_usec * 1000;
43     srand(uiSeed);
44 }
45 
Rand()46 RtpDt_UInt32 RtpOsUtil::Rand()
47 {
48     RtpOsUtil::Srand();
49     return rand();
50 }
51 
Ntohl(RtpDt_UInt32 uiNetlong)52 RtpDt_UInt32 RtpOsUtil::Ntohl(RtpDt_UInt32 uiNetlong)
53 {
54     return ntohl(uiNetlong);
55 }
56 
RRand()57 RtpDt_Double RtpOsUtil::RRand()
58 {
59     tRTP_NTP_TIME stNtpTs = {0, 0};
60     RtpOsUtil::Srand();
61     RtpDt_Double dRandNum = static_cast<RtpDt_Double>(rand()) / static_cast<RtpDt_Double>(RAND_MAX);
62     RtpOsUtil::GetNtpTime(stNtpTs);
63     RtpDt_Double dTemp = ((dRandNum * stNtpTs.m_uiNtpHigh32Bits) +
64             (stNtpTs.m_uiNtpLow32Bits / static_cast<RtpDt_Double>(RTP_MILLISEC_MICRO)));
65 
66     if (dTemp > RTP_ZERO)
67     {
68         return 1.0 / dTemp;
69     }
70     else
71     {
72         return 1.0;
73     }
74 }
75