OSDN Git Service

Make inlines static
[android-x86/system-media.git] / audio_utils / PowerLog.cpp
1 /*
2  * Copyright 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 // #define LOG_NDEBUG 0
18 #define LOG_TAG "audio_utils_PowerLog"
19 #include <log/log.h>
20
21 #include <algorithm>
22 #include <iomanip>
23 #include <math.h>
24 #include <sstream>
25 #include <stdint.h>
26
27 #include <audio_utils/clock.h>
28 #include <audio_utils/power.h>
29 #include <audio_utils/PowerLog.h>
30
31 namespace android {
32
33 // TODO move to separate file
34 template <typename T, size_t N>
35 constexpr size_t array_size(const T(&)[N])
36 {
37     return N;
38 }
39
40 PowerLog::PowerLog(uint32_t sampleRate,
41         uint32_t channelCount,
42         audio_format_t format,
43         size_t entries,
44         size_t framesPerEntry)
45     : mCurrentTime(0)
46     , mCurrentEnergy(0)
47     , mCurrentFrames(0)
48     , mIdx(0)
49     , mConsecutiveZeroes(0)
50     , mSampleRate(sampleRate)
51     , mChannelCount(channelCount)
52     , mFormat(format)
53     , mFramesPerEntry(framesPerEntry)
54     , mEntries(entries)
55 {
56     (void)mSampleRate; // currently unused, for future use
57     LOG_ALWAYS_FATAL_IF(!audio_utils_is_compute_power_format_supported(format),
58             "unsupported format: %#x", format);
59 }
60
61 void PowerLog::log(const void *buffer, size_t frames, int64_t nowNs)
62 {
63     std::lock_guard<std::mutex> guard(mLock);
64
65     const size_t bytes_per_sample = audio_bytes_per_sample(mFormat);
66     while (frames > 0) {
67         // check partial computation
68         size_t required = mFramesPerEntry - mCurrentFrames;
69         size_t process = std::min(required, frames);
70
71         if (mCurrentTime == 0) {
72             mCurrentTime = nowNs;
73         }
74         mCurrentEnergy +=
75                 audio_utils_compute_energy_mono(buffer, mFormat, process * mChannelCount);
76         mCurrentFrames += process;
77
78         ALOGV("nowNs:%lld, required:%zu, process:%zu, mCurrentEnergy:%f, mCurrentFrames:%zu",
79                 (long long)nowNs, required, process, mCurrentEnergy, mCurrentFrames);
80         if (process < required) {
81             return;
82         }
83
84         // We store the data as normalized energy per sample. The energy sequence is
85         // zero terminated. Consecutive zeroes are ignored.
86         if (mCurrentEnergy == 0.f) {
87             if (mConsecutiveZeroes++ == 0) {
88                 mEntries[mIdx++] = std::make_pair(nowNs, 0.f);
89                 // zero terminate the signal sequence.
90             }
91         } else {
92             mConsecutiveZeroes = 0;
93             mEntries[mIdx++] = std::make_pair(mCurrentTime, mCurrentEnergy);
94             ALOGV("writing %lld %f", (long long)mCurrentTime, mCurrentEnergy);
95         }
96         if (mIdx >= mEntries.size()) {
97             mIdx -= mEntries.size();
98         }
99         mCurrentTime = 0;
100         mCurrentEnergy = 0;
101         mCurrentFrames = 0;
102         frames -= process;
103         buffer = (const uint8_t *)buffer + mCurrentFrames * mChannelCount * bytes_per_sample;
104     }
105 }
106
107 std::string PowerLog::dumpToString(const char *prefix, size_t lines, int64_t limitNs) const
108 {
109     std::lock_guard<std::mutex> guard(mLock);
110
111     const size_t maxColumns = 10;
112     const size_t numberOfEntries = mEntries.size();
113     if (lines == 0) lines = SIZE_MAX;
114
115     // compute where to start logging
116     enum {
117         AT_END,
118         IN_SIGNAL,
119     } state = IN_SIGNAL;
120     size_t count = 1;
121     size_t column = 0;
122     size_t nonzeros = 0;
123     ssize_t offset; // TODO doesn't dump if # entries exceeds SSIZE_MAX
124     for (offset = 0; offset < (ssize_t)numberOfEntries && count < lines; ++offset) {
125         const size_t idx = (mIdx + numberOfEntries - offset - 1) % numberOfEntries; // reverse direction
126         const int64_t time = mEntries[idx].first;
127         const float energy = mEntries[idx].second;
128
129         if (state == AT_END) {
130             if (energy == 0.f) {
131                 ALOGV("two zeroes detected");
132                 break; // normally single zero terminated - two zeroes means no more data.
133             }
134             state = IN_SIGNAL;
135         } else { // IN_SIGNAL
136             if (energy == 0.f) {
137                 if (column != 0) {
138                     column = 0;
139                     ++count;
140                 }
141                 state = AT_END;
142                 continue;
143             }
144         }
145         if (column == 0 && time < limitNs) {
146             break;
147         }
148         ++nonzeros;
149         if (++column == maxColumns) {
150             column = 0;
151             // TODO ideally we would peek the previous entry to see if it is 0
152             // to ensure we properly put in a starting signal bracket.
153             // We don't do that because it would complicate the logic here.
154             ++count;
155         }
156     }
157     if (offset > 0) {
158         --offset;
159     }
160     // We accumulate the log info into a string, and write to the fd once.
161     std::stringstream ss;
162     ss << std::fixed << std::setprecision(1);
163     // ss << std::scientific;
164     if (nonzeros == 0) {
165         ss << prefix << "Signal power history: (none)\n";
166     } else {
167         ss << prefix << "Signal power history:\n";
168
169         size_t column = 0;
170         bool first = true;
171         bool start = false;
172         float cumulative = 0.f;
173         for (; offset >= 0; --offset) {
174             const size_t idx = (mIdx + numberOfEntries - offset - 1) % numberOfEntries;
175             const int64_t time = mEntries[idx].first;
176             const float energy = mEntries[idx].second;
177
178             if (energy == 0.f) {
179                 if (!first) {
180                     ss << " ] sum(" << audio_utils_power_from_energy(cumulative) << ")";
181                 }
182                 cumulative = 0.f;
183                 column = 0;
184                 start = true;
185                 continue;
186             }
187             if (column == 0) {
188                 // print time if at start of column
189                 if (!first) {
190                     ss << "\n";
191                 }
192                 ss << prefix << " " << audio_utils_time_string_from_ns(time).time
193                         << (start ? ": [ ": ":   ");
194                 first = false;
195                 start = false;
196             }  else {
197                 ss << " ";
198             }
199             if (++column >= maxColumns) {
200                 column = 0;
201             }
202
203             cumulative += energy;
204             // convert energy to power and print
205             const float power =
206                     audio_utils_power_from_energy(energy / (mChannelCount * mFramesPerEntry));
207             ss << std::setw(6) << power;
208             ALOGV("state: %d %lld %f", state, (long long)time, power);
209         }
210         ss << "\n";
211     }
212     return ss.str();
213 }
214
215 status_t PowerLog::dump(int fd, const char *prefix, size_t lines, int64_t limitNs) const
216 {
217     // Since dumpToString and write are thread safe, this function
218     // is conceptually thread-safe but simultaneous calls to dump
219     // by different threads to the same file descriptor may not write
220     // the two logs in time order.
221     const std::string s = dumpToString(prefix, lines, limitNs);
222     if (s.size() > 0 && write(fd, s.c_str(), s.size()) < 0) {
223         return -errno;
224     }
225     return NO_ERROR;
226 }
227
228 } // namespace android
229
230 using namespace android;
231
232 power_log_t *power_log_create(uint32_t sample_rate,
233         uint32_t channel_count, audio_format_t format, size_t entries, size_t frames_per_entry)
234 {
235     if (!audio_utils_is_compute_power_format_supported(format)) {
236         return nullptr;
237     }
238     return reinterpret_cast<power_log_t *>
239             (new(std::nothrow)
240                     PowerLog(sample_rate, channel_count, format, entries, frames_per_entry));
241 }
242
243 void power_log_log(power_log_t *power_log,
244         const void *buffer, size_t frames, int64_t now_ns)
245 {
246     if (power_log == nullptr) {
247         return;
248     }
249     reinterpret_cast<PowerLog *>(power_log)->log(buffer, frames, now_ns);
250 }
251
252 int power_log_dump(
253         power_log_t *power_log, int fd, const char *prefix, size_t lines, int64_t limit_ns)
254 {
255     if (power_log == nullptr) {
256         return BAD_VALUE;
257     }
258     return reinterpret_cast<PowerLog *>(power_log)->dump(fd, prefix, lines, limit_ns);
259 }
260
261 void power_log_destroy(power_log_t *power_log)
262 {
263     delete reinterpret_cast<PowerLog *>(power_log);
264 }