blob: 7cba4c6a9317e679a9dbcc32210fbc103d708563 [file] [log] [blame]
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -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
18#define LOG_TAG "PerformanceAnalysis"
19// #define LOG_NDEBUG 0
20
21#include <algorithm>
22#include <climits>
23#include <deque>
24#include <fstream>
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -070025#include <iostream>
26#include <math.h>
27#include <numeric>
28#include <vector>
29#include <stdarg.h>
30#include <stdint.h>
31#include <stdio.h>
32#include <string.h>
33#include <sys/prctl.h>
34#include <time.h>
35#include <new>
36#include <audio_utils/roundup.h>
37#include <media/nbaio/NBLog.h>
38#include <media/nbaio/PerformanceAnalysis.h>
39// #include <utils/CallStack.h> // used to print callstack
40#include <utils/Log.h>
41#include <utils/String8.h>
42
43#include <queue>
44#include <utility>
45
46namespace android {
47
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -070048PerformanceAnalysis::PerformanceAnalysis() {
49 // These variables will be (FIXME) learned from the data
50 kPeriodMs = 4; // typical buffer period (mode)
51 // average number of Ms spent processing buffer
52 kPeriodMsCPU = static_cast<int>(kPeriodMs * kRatio);
53}
54
55// converts a time series into a map. key: buffer period length. value: count
56static std::map<int, int> buildBuckets(const std::vector<int64_t> &samples) {
57 // TODO allow buckets of variable resolution
58 std::map<int, int> buckets;
59 for (size_t i = 1; i < samples.size(); ++i) {
60 ++buckets[deltaMs(samples[i - 1], samples[i])];
61 }
62 return buckets;
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -070063}
64
65static int widthOf(int x) {
66 int width = 0;
67 while (x > 0) {
68 ++width;
69 x /= 10;
70 }
71 return width;
72}
73
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070074// Given a series of audio processing wakeup timestamps,
75// buckets the time intervals into a histogram, searches for
76// outliers, analyzes the outlier series for unexpectedly
77// small or large values and stores these as peaks, and flushes
78// the timestamp series from memory.
79void PerformanceAnalysis::processAndFlushTimeStampSeries(int author) {
80 // 1) analyze the series to store all outliers and their exact timestamps:
81 storeOutlierData(mTimeStampSeries[author]);
82
83 // 2) detect peaks in the outlier series
84 detectPeaks();
85
86 // 3) compute its histogram, append this to mRecentHists and erase the time series
87 // FIXME: need to store the timestamp of the beginning of each histogram
88 // FIXME: Restore LOG_HIST_FLUSH to separate histograms at every end-of-stream event
89 // A histogram should not span data between audio off/on timespans
90 mRecentHists.emplace_back(author, buildBuckets(mTimeStampSeries[author]));
91 // do not let mRecentHists exceed capacity
92 // ALOGD("mRecentHists size: %d", static_cast<int>(mRecentHists.size()));
93 if (mRecentHists.size() >= kRecentHistsCapacity) {
94 // ALOGD("popped back mRecentHists");
95 mRecentHists.pop_front();
96 }
97 mTimeStampSeries[author].clear();
98}
99
100// forces short-term histogram storage to avoid adding idle audio time interval
101// to buffer period data
102void PerformanceAnalysis::handleStateChange(int author) {
103 ALOGD("handleStateChange");
104 processAndFlushTimeStampSeries(author);
105 return;
106}
107
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700108// Takes a single buffer period timestamp entry with author information and stores it
109// in a temporary series of timestamps. Once the series is full, the data is analyzed,
110// stored, and emptied.
111// TODO: decide whether author or file location information is more important to store
112// for now, only stores author (thread)
113void PerformanceAnalysis::logTsEntry(int author, int64_t ts) {
114 // TODO might want to filter excessively high outliers, which are usually caused
115 // by the thread being inactive.
116 // Store time series data for each reader in order to bucket it once there
117 // is enough data. Then, write to recentHists as a histogram.
118 mTimeStampSeries[author].push_back(ts);
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700119 // if length of the time series has reached kShortHistSize samples,
120 // analyze the data and flush the timestamp series from memory
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700121 if (mTimeStampSeries[author].size() >= kShortHistSize) {
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700122 processAndFlushTimeStampSeries(author);
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700123 }
124}
125
126// Given a series of outlier intervals (mOutlier data),
127// looks for changes in distribution (peaks), which can be either positive or negative.
128// The function sets the mean to the starting value and sigma to 0, and updates
129// them as long as no peak is detected. When a value is more than 'threshold'
130// standard deviations from the mean, a peak is detected and the mean and sigma
131// are set to the peak value and 0.
132void PerformanceAnalysis::detectPeaks() {
133 if (mOutlierData.empty()) {
134 ALOGD("peak detector called on empty array");
135 return;
136 }
137
138 // compute mean of the distribution. Used to check whether a value is large
139 const double kTypicalDiff = std::accumulate(
140 mOutlierData.begin(), mOutlierData.end(), 0,
141 [](auto &a, auto &b){return a + b.first;}) / mOutlierData.size();
142 // ALOGD("typicalDiff %f", kTypicalDiff);
143
144 // iterator at the beginning of a sequence, or updated to the most recent peak
145 std::deque<std::pair<uint64_t, uint64_t>>::iterator start = mOutlierData.begin();
146 // the mean and standard deviation are updated every time a peak is detected
147 // initialize first time. The mean from the previous sequence is stored
148 // for the next sequence. Here, they are initialized for the first time.
149 if (mPeakDetectorMean < 0) {
150 mPeakDetectorMean = static_cast<double>(start->first);
151 mPeakDetectorSd = 0;
152 }
153 auto sqr = [](auto x){ return x * x; };
154 for (auto it = mOutlierData.begin(); it != mOutlierData.end(); ++it) {
155 // no surprise occurred:
156 // the new element is a small number of standard deviations from the mean
157 if ((fabs(it->first - mPeakDetectorMean) < kStddevThreshold * mPeakDetectorSd) ||
158 // or: right after peak has been detected, the delta is smaller than average
159 (mPeakDetectorSd == 0 && fabs(it->first - mPeakDetectorMean) < kTypicalDiff)) {
160 // update the mean and sd:
161 // count number of elements (distance between start interator and current)
162 const int kN = std::distance(start, it) + 1;
163 // usual formulas for mean and sd
164 mPeakDetectorMean = std::accumulate(start, it + 1, 0.0,
165 [](auto &a, auto &b){return a + b.first;}) / kN;
166 mPeakDetectorSd = sqrt(std::accumulate(start, it + 1, 0.0,
167 [=](auto &a, auto &b){ return a + sqr(b.first - mPeakDetectorMean);})) /
168 ((kN > 1)? kN - 1 : kN); // kN - 1: mean is correlated with variance
169 // ALOGD("value, mean, sd: %f, %f, %f", static_cast<double>(it->first), mean, sd);
170 }
171 // surprising value: store peak timestamp and reset mean, sd, and start iterator
172 else {
173 mPeakTimestamps.emplace_back(it->second);
174 // TODO: remove pop_front once a circular buffer is in place
175 if (mPeakTimestamps.size() >= kShortHistSize) {
176 ALOGD("popped back mPeakTimestamps");
177 mPeakTimestamps.pop_front();
178 }
179 mPeakDetectorMean = static_cast<double>(it->first);
180 mPeakDetectorSd = 0;
181 start = it;
182 }
183 }
184 //for (const auto &it : mPeakTimestamps) {
185 // ALOGE("mPeakTimestamps %f", static_cast<double>(it));
186 //}
187 return;
188}
189
190// Called by LogTsEntry. The input is a vector of timestamps.
191// Finds outliers and writes to mOutlierdata.
192// Each value in mOutlierdata consists of: <outlier timestamp, time elapsed since previous outlier>.
193// e.g. timestamps (ms) 1, 4, 5, 16, 18, 28 will produce pairs (4, 5), (13, 18).
194// This function is applied to the time series before it is converted into a histogram.
195void PerformanceAnalysis::storeOutlierData(const std::vector<int64_t> &timestamps) {
196 if (timestamps.size() < 1) {
197 ALOGE("storeOutlierData called on empty vector");
198 return;
199 }
200 // first pass: need to initialize
201 if (mElapsed == 0) {
202 mPrevNs = timestamps[0];
203 }
204 for (const auto &ts: timestamps) {
205 const uint64_t diffMs = static_cast<uint64_t>(deltaMs(mPrevNs, ts));
206 if (diffMs >= static_cast<uint64_t>(kOutlierMs)) {
207 mOutlierData.emplace_back(mElapsed, static_cast<uint64_t>(mPrevNs));
208 // Remove oldest value if the vector is full
209 // TODO: remove pop_front once circular buffer is in place
210 // FIXME: change kShortHistSize to some other constant. Make sure it is large
211 // enough that data will never be lost before being written to a long-term FIFO
212 if (mOutlierData.size() >= kShortHistSize) {
213 ALOGD("popped back mOutlierData");
214 mOutlierData.pop_front();
215 }
216 mElapsed = 0;
217 }
218 mElapsed += diffMs;
219 mPrevNs = ts;
220 }
221}
222
223
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700224// FIXME: delete this temporary test code, recycled for various new functions
225void PerformanceAnalysis::testFunction() {
226 // produces values (4: 5000000), (13: 18000000)
227 // ns timestamps of buffer periods
228 const std::vector<int64_t>kTempTestData = {1000000, 4000000, 5000000,
229 16000000, 18000000, 28000000};
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700230 PerformanceAnalysis::storeOutlierData(kTempTestData);
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700231 for (const auto &outlier: mOutlierData) {
232 ALOGE("PerformanceAnalysis test %lld: %lld",
233 static_cast<long long>(outlier.first), static_cast<long long>(outlier.second));
234 }
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700235 detectPeaks();
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700236}
237
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700238// TODO Make it return a std::string instead of modifying body --> is this still relevant?
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700239// FIXME: as can be seen when printing the values, the outlier timestamps typically occur
240// in the first histogram 35 to 38 indices from the end (most often 35).
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700241// TODO consider changing all ints to uint32_t or uint64_t
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700242void PerformanceAnalysis::reportPerformance(String8 *body, int maxHeight) {
243 if (mRecentHists.size() < 1) {
244 ALOGD("reportPerformance: mRecentHists is empty");
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700245 return;
246 }
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700247 ALOGD("reportPerformance: hists size %d", static_cast<int>(mRecentHists.size()));
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700248 // TODO: more elaborate data analysis
249 std::map<int, int> buckets;
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700250 for (const auto &shortHist: mRecentHists) {
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700251 for (const auto &countPair : shortHist.second) {
252 buckets[countPair.first] += countPair.second;
253 }
254 }
255
256 // underscores and spaces length corresponds to maximum width of histogram
257 static const int kLen = 40;
258 std::string underscores(kLen, '_');
259 std::string spaces(kLen, ' ');
260
261 auto it = buckets.begin();
262 int maxDelta = it->first;
263 int maxCount = it->second;
264 // Compute maximum values
265 while (++it != buckets.end()) {
266 if (it->first > maxDelta) {
267 maxDelta = it->first;
268 }
269 if (it->second > maxCount) {
270 maxCount = it->second;
271 }
272 }
273 int height = log2(maxCount) + 1; // maxCount > 0, safe to call log2
274 const int leftPadding = widthOf(1 << height);
275 const int colWidth = std::max(std::max(widthOf(maxDelta) + 1, 3), leftPadding + 2);
276 int scalingFactor = 1;
277 // scale data if it exceeds maximum height
278 if (height > maxHeight) {
279 scalingFactor = (height + maxHeight) / maxHeight;
280 height /= scalingFactor;
281 }
282 body->appendFormat("\n%*s", leftPadding + 11, "Occurrences");
283 // write histogram label line with bucket values
284 body->appendFormat("\n%s", " ");
285 body->appendFormat("%*s", leftPadding, " ");
286 for (auto const &x : buckets) {
287 body->appendFormat("%*d", colWidth, x.second);
288 }
289 // write histogram ascii art
290 body->appendFormat("\n%s", " ");
291 for (int row = height * scalingFactor; row >= 0; row -= scalingFactor) {
292 const int value = 1 << row;
293 body->appendFormat("%.*s", leftPadding, spaces.c_str());
294 for (auto const &x : buckets) {
295 body->appendFormat("%.*s%s", colWidth - 1, spaces.c_str(), x.second < value ? " " : "|");
296 }
297 body->appendFormat("\n%s", " ");
298 }
299 // print x-axis
300 const int columns = static_cast<int>(buckets.size());
301 body->appendFormat("%*c", leftPadding, ' ');
302 body->appendFormat("%.*s", (columns + 1) * colWidth, underscores.c_str());
303 body->appendFormat("\n%s", " ");
304
305 // write footer with bucket labels
306 body->appendFormat("%*s", leftPadding, " ");
307 for (auto const &x : buckets) {
308 body->appendFormat("%*d", colWidth, x.first);
309 }
310 body->appendFormat("%.*s%s", colWidth, spaces.c_str(), "ms\n");
311
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700312 // Now report glitches
313 body->appendFormat("\ntime elapsed between glitches and glitch timestamps\n");
314 for (const auto &outlier: mOutlierData) {
315 body->appendFormat("%lld: %lld\n", static_cast<long long>(outlier.first),
316 static_cast<long long>(outlier.second));
317 }
318
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700319}
320
321
322// Produces a log warning if the timing of recent buffer periods caused a glitch
323// Computes sum of running window of three buffer periods
324// Checks whether the buffer periods leave enough CPU time for the next one
325// e.g. if a buffer period is expected to be 4 ms and a buffer requires 3 ms of CPU time,
326// here are some glitch cases:
327// 4 + 4 + 6 ; 5 + 4 + 5; 2 + 2 + 10
328// TODO: develop this code to track changes in histogram distribution in addition
329// to / instead of glitches.
330void PerformanceAnalysis::alertIfGlitch(const std::vector<int64_t> &samples) {
331 std::deque<int> periods(kNumBuff, kPeriodMs);
332 for (size_t i = 2; i < samples.size(); ++i) { // skip first time entry
333 periods.push_front(deltaMs(samples[i - 1], samples[i]));
334 periods.pop_back();
335 // TODO: check that all glitch cases are covered
336 if (std::accumulate(periods.begin(), periods.end(), 0) > kNumBuff * kPeriodMs +
337 kPeriodMs - kPeriodMsCPU) {
338 ALOGW("A glitch occurred");
339 periods.assign(kNumBuff, kPeriodMs);
340 }
341 }
342 return;
343}
344
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700345} // namespace android