1/*
2 * Copyright (c) 2021-2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#ifndef HISTREAMER_PLUGIN_COMMON_TIME_H
17#define HISTREAMER_PLUGIN_COMMON_TIME_H
18
19namespace OHOS {
20namespace Media {
21namespace Plugins {
22constexpr int HST_TIME_NONE = (int64_t)-1;
23constexpr int HST_TIME_BASE = (int64_t)1;
24constexpr int HST_NSECOND = HST_TIME_BASE;
25constexpr int HST_USECOND = ((int64_t)1000 * HST_NSECOND);
26constexpr int HST_MSECOND = ((int64_t)1000 * HST_USECOND);
27constexpr int HST_SECOND = ((int64_t)1000 * HST_MSECOND);
28
29inline int64_t HstTime2Ns(int64_t hTime)
30{
31    return hTime / HST_NSECOND;
32}
33
34inline bool Ns2HstTime (int64_t ns, int64_t& hTime)
35{
36    hTime = ns * HST_NSECOND;
37    return true;
38}
39
40inline int64_t HstTime2Us(int64_t hTime)
41{
42    return hTime / HST_USECOND;
43}
44
45inline int32_t HstTime2Us32(int64_t hTime)
46{
47    int64_t ms = hTime / HST_USECOND;
48    if (INT32_MAX < ms ||  INT32_MIN > ms) { // overflow
49        return INT32_MAX;
50    }
51    return static_cast<int32_t>(ms);
52}
53
54inline bool Us2HstTime (int64_t us, int64_t& hTime)
55{
56    if (INT64_MAX / HST_USECOND < us || INT64_MIN / HST_USECOND > us) { // overflow
57        return false;
58    }
59    hTime = us * HST_USECOND;
60    return true;
61}
62
63inline int64_t HstTime2Ms(int64_t hTime)
64{
65    return hTime / HST_MSECOND;
66}
67
68inline bool Ms2HstTime (int64_t ms, int64_t& hTime)
69{
70    if (INT64_MAX / HST_MSECOND < ms || INT64_MIN / HST_MSECOND > ms) { // overflow
71        return false;
72    }
73    hTime = ms * HST_MSECOND;
74    return true;
75}
76
77inline int64_t HstTime2Sec(int64_t hTime)
78{
79    return hTime / HST_SECOND;
80}
81
82inline bool Sec2HstTime (int64_t sec, int64_t& hTime)
83{
84    if (INT64_MAX / HST_SECOND < sec || INT64_MIN / HST_SECOND > sec) { // overflow
85        return false;
86    }
87    hTime = sec * HST_SECOND;
88    return true;
89}
90
91inline int64_t Us2Ms(int64_t us)
92{
93    return us / HST_USECOND;
94}
95
96inline int64_t Ms2Us(int64_t ms)
97{
98    return ms * HST_USECOND;
99}
100} // Plugins
101} // Media
102} // OHOS
103#endif // HISTREAMER_PLUGIN_COMMON_TIME_H
104