diff --git a/frameworks/native/audioutils/include/audio_utils.h b/frameworks/native/audioutils/include/audio_utils.h index 4b2d48838151920f78e33908368519d665896314..fdbbad9c3187a689f7016127ffe4590bc80c51f2 100644 --- a/frameworks/native/audioutils/include/audio_utils.h +++ b/frameworks/native/audioutils/include/audio_utils.h @@ -17,8 +17,18 @@ #include +#define AUDIO_MS_PER_SECOND 1000 +#define AUDIO_US_PER_SECOND 1000000 +#define AUDIO_NS_PER_SECOND ((int64_t)1000000000) namespace OHOS { namespace AudioStandard { +class ClockTime { +public: + static int64_t GetCurNano(); + static int32_t AbsoluteSleep(int64_t nanoTime); + static int32_t RelativeSleep(int64_t nanoTime); +}; + int64_t GetNowTimeMs(); int64_t GetNowTimeUs(); void AdjustStereoToMonoForPCM8Bit(int8_t *data, uint64_t len); diff --git a/frameworks/native/audioutils/src/audio_utils.cpp b/frameworks/native/audioutils/src/audio_utils.cpp index 791ea8dd41ab13d9d401eefb23156de1bff47ca1..b08dda32bb961ad1d0dc3f6175aaf97c79c084e8 100644 --- a/frameworks/native/audioutils/src/audio_utils.cpp +++ b/frameworks/native/audioutils/src/audio_utils.cpp @@ -14,6 +14,8 @@ */ #include +#include +#include #include #include #include "audio_utils.h" @@ -22,6 +24,61 @@ namespace OHOS { namespace AudioStandard { +int64_t ClockTime::GetCurNano() +{ + int64_t result = -1; // -1 for bad result. + struct timespec time; + clockid_t clockId = CLOCK_MONOTONIC; + int ret = clock_gettime(clockId, &time); + if (ret < 0) { + AUDIO_WARNING_LOG("GetCurNanoTime fail, result:%{public}d", ret); + return result; + } + result = (time.tv_sec * AUDIO_NS_PER_SECOND) + time.tv_nsec; + return result; +} + +int32_t ClockTime::AbsoluteSleep(int64_t nanoTime) +{ + int32_t ret = -1; // -1 for bad result. + if (nanoTime <= 0) { + AUDIO_WARNING_LOG("AbsoluteSleep invalid sleep time :%{public}" PRId64 " ns", nanoTime); + return ret; + } + struct timespec time; + time.tv_sec = nanoTime / AUDIO_NS_PER_SECOND; + time.tv_nsec = nanoTime - (time.tv_sec * AUDIO_NS_PER_SECOND); // Avoids % operation. + + clockid_t clockId = CLOCK_MONOTONIC; + ret = clock_nanosleep(clockId, TIMER_ABSTIME, &time, nullptr); + if (ret != 0) { + AUDIO_WARNING_LOG("AbsoluteSleep may failed, ret is :%{public}d", ret); + } + + return ret; +} + +int32_t ClockTime::RelativeSleep(int64_t nanoTime) +{ + int32_t ret = -1; // -1 for bad result. + if (nanoTime <= 0) { + AUDIO_WARNING_LOG("AbsoluteSleep invalid sleep time :%{public}" PRId64 " ns", nanoTime); + return ret; + } + struct timespec time; + time.tv_sec = nanoTime / AUDIO_NS_PER_SECOND; + time.tv_nsec = nanoTime - (time.tv_sec * AUDIO_NS_PER_SECOND); // Avoids % operation. + + clockid_t clockId = CLOCK_MONOTONIC; + const int relativeFlag = 0; // flag of relative sleep. + ret = clock_nanosleep(clockId, relativeFlag, &time, nullptr); + if (ret != 0) { + AUDIO_WARNING_LOG("RelativeSleep may failed, ret is :%{public}d", ret); + } + + return ret; +} + int64_t GetNowTimeMs() { std::chrono::milliseconds nowMs =