blob: 6cbcc58c674d7d149a32c819cc66f39647f56657 [file] [log] [blame]
Eric Laurent629afae2017-05-25 18:25:51 -07001/*
2 * Copyright (C) 2017 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 AAUDIO_EXAMPLE_UTILS_H
18#define AAUDIO_EXAMPLE_UTILS_H
19
20#include <unistd.h>
21#include <sched.h>
22#include <aaudio/AAudio.h>
23
24#define NANOS_PER_MICROSECOND ((int64_t)1000)
25#define NANOS_PER_MILLISECOND (NANOS_PER_MICROSECOND * 1000)
26#define NANOS_PER_SECOND (NANOS_PER_MILLISECOND * 1000)
27
Phil Burk97350f92017-07-21 15:59:44 -070028const char *getSharingModeText(aaudio_sharing_mode_t mode) {
Eric Laurent629afae2017-05-25 18:25:51 -070029 const char *modeText = "unknown";
30 switch (mode) {
31 case AAUDIO_SHARING_MODE_EXCLUSIVE:
32 modeText = "EXCLUSIVE";
33 break;
34 case AAUDIO_SHARING_MODE_SHARED:
35 modeText = "SHARED";
36 break;
37 default:
38 break;
39 }
40 return modeText;
41}
42
43static int64_t getNanoseconds(clockid_t clockId = CLOCK_MONOTONIC) {
44 struct timespec time;
45 int result = clock_gettime(clockId, &time);
46 if (result < 0) {
47 return -errno;
48 }
49 return (time.tv_sec * NANOS_PER_SECOND) + time.tv_nsec;
50}
51
Phil Burk97350f92017-07-21 15:59:44 -070052static void displayPeakLevel(float peakLevel) {
Eric Laurent629afae2017-05-25 18:25:51 -070053 printf("%5.3f ", peakLevel);
54 const int maxStars = 50; // arbitrary, fits on one line
55 int numStars = (int) (peakLevel * maxStars);
56 for (int i = 0; i < numStars; i++) {
57 printf("*");
58 }
59 printf("\n");
60}
61
Phil Burk97350f92017-07-21 15:59:44 -070062/**
63 * @param position1 position of hardware frame
64 * @param nanoseconds1
65 * @param position2 position of client read/write
66 * @param nanoseconds2
67 * @param sampleRate
68 * @return latency in milliseconds
69 */
70static double calculateLatencyMillis(int64_t position1, int64_t nanoseconds1,
71 int64_t position2, int64_t nanoseconds2,
72 int64_t sampleRate) {
73 int64_t deltaFrames = position2 - position1;
74 int64_t deltaTime =
75 (NANOS_PER_SECOND * deltaFrames / sampleRate);
76 int64_t timeCurrentFramePlayed = nanoseconds1 + deltaTime;
77 int64_t latencyNanos = timeCurrentFramePlayed - nanoseconds2;
78 double latencyMillis = latencyNanos / 1000000.0;
79 return latencyMillis;
80}
81
Eric Laurent629afae2017-05-25 18:25:51 -070082#endif // AAUDIO_EXAMPLE_UTILS_H