blob: 41184a633bc4d06d608aa0d338fff5ca63e40f01 [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>
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -070024#include <iostream>
25#include <math.h>
26#include <numeric>
27#include <vector>
28#include <stdarg.h>
29#include <stdint.h>
30#include <stdio.h>
31#include <string.h>
32#include <sys/prctl.h>
33#include <time.h>
34#include <new>
35#include <audio_utils/roundup.h>
36#include <media/nbaio/NBLog.h>
37#include <media/nbaio/PerformanceAnalysis.h>
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -070038#include <media/nbaio/ReportPerformance.h>
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -070039// #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 Wager80448082017-07-11 14:07:59 -070048namespace ReportPerformance {
49
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -070050PerformanceAnalysis::PerformanceAnalysis() {
51 // These variables will be (FIXME) learned from the data
52 kPeriodMs = 4; // typical buffer period (mode)
53 // average number of Ms spent processing buffer
54 kPeriodMsCPU = static_cast<int>(kPeriodMs * kRatio);
55}
56
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -070057static int widthOf(int x) {
58 int width = 0;
59 while (x > 0) {
60 ++width;
61 x /= 10;
62 }
63 return width;
64}
65
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070066// Given a series of audio processing wakeup timestamps,
67// buckets the time intervals into a histogram, searches for
68// outliers, analyzes the outlier series for unexpectedly
69// small or large values and stores these as peaks, and flushes
70// the timestamp series from memory.
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -070071void PerformanceAnalysis::processAndFlushTimeStampSeries() {
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -070072 if (mTimeStampSeries.empty()) {
73 ALOGD("Timestamp series is empty");
74 return;
75 }
76
77 // mHists is empty if program just started
78 if (mHists.empty()) {
79 mHists.emplace_front(static_cast<uint64_t>(mTimeStampSeries[0]),
80 std::map<int, int>());
81 }
82
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070083 // 1) analyze the series to store all outliers and their exact timestamps:
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -070084 storeOutlierData(mTimeStampSeries);
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070085
86 // 2) detect peaks in the outlier series
87 detectPeaks();
88
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -070089 // if the current histogram has spanned its maximum time interval,
90 // insert a new empty histogram to the front of mHists
91 if (deltaMs(mHists[0].first, mTimeStampSeries[0]) >= kMaxHistTimespanMs) {
92 mHists.emplace_front(static_cast<uint64_t>(mTimeStampSeries[0]),
93 std::map<int, int>());
94 // When memory is full, delete oldest histogram
95 if (mHists.size() >= kHistsCapacity) {
96 mHists.resize(kHistsCapacity);
97 }
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070098 }
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -070099
100 // 3) add current time intervals to histogram
101 for (size_t i = 1; i < mTimeStampSeries.size(); ++i) {
102 ++mHists[0].second[deltaMs(
103 mTimeStampSeries[i - 1], mTimeStampSeries[i])];
104 }
105
106 // clear the timestamps
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700107 mTimeStampSeries.clear();
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700108}
109
110// forces short-term histogram storage to avoid adding idle audio time interval
111// to buffer period data
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700112void PerformanceAnalysis::handleStateChange() {
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700113 ALOGD("handleStateChange");
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700114 processAndFlushTimeStampSeries();
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700115 return;
116}
117
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700118// Takes a single buffer period timestamp entry information and stores it in a
119// temporary series of timestamps. Once the series is full, the data is analyzed,
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700120// stored, and emptied.
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700121void PerformanceAnalysis::logTsEntry(int64_t ts) {
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700122 // TODO might want to filter excessively high outliers, which are usually caused
123 // by the thread being inactive.
124 // Store time series data for each reader in order to bucket it once there
125 // is enough data. Then, write to recentHists as a histogram.
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700126 mTimeStampSeries.push_back(ts);
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700127 // if length of the time series has reached kShortHistSize samples,
128 // analyze the data and flush the timestamp series from memory
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -0700129 if (mTimeStampSeries.size() >= kHistSize) {
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700130 processAndFlushTimeStampSeries();
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700131 }
132}
133
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -0700134// TODO: move this someplace
135// static const char* const kName = (const char *) "/data/misc/audioserver/sample_results.txt";
136// writeToFile(mOutlierData, mLongTermHists, kName, false);
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700137
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700138// Given a series of outlier intervals (mOutlier data),
139// looks for changes in distribution (peaks), which can be either positive or negative.
140// The function sets the mean to the starting value and sigma to 0, and updates
141// them as long as no peak is detected. When a value is more than 'threshold'
142// standard deviations from the mean, a peak is detected and the mean and sigma
143// are set to the peak value and 0.
144void PerformanceAnalysis::detectPeaks() {
145 if (mOutlierData.empty()) {
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700146 return;
147 }
148
149 // compute mean of the distribution. Used to check whether a value is large
150 const double kTypicalDiff = std::accumulate(
151 mOutlierData.begin(), mOutlierData.end(), 0,
152 [](auto &a, auto &b){return a + b.first;}) / mOutlierData.size();
153 // ALOGD("typicalDiff %f", kTypicalDiff);
154
155 // iterator at the beginning of a sequence, or updated to the most recent peak
156 std::deque<std::pair<uint64_t, uint64_t>>::iterator start = mOutlierData.begin();
157 // the mean and standard deviation are updated every time a peak is detected
158 // initialize first time. The mean from the previous sequence is stored
159 // for the next sequence. Here, they are initialized for the first time.
160 if (mPeakDetectorMean < 0) {
161 mPeakDetectorMean = static_cast<double>(start->first);
162 mPeakDetectorSd = 0;
163 }
164 auto sqr = [](auto x){ return x * x; };
165 for (auto it = mOutlierData.begin(); it != mOutlierData.end(); ++it) {
166 // no surprise occurred:
167 // the new element is a small number of standard deviations from the mean
168 if ((fabs(it->first - mPeakDetectorMean) < kStddevThreshold * mPeakDetectorSd) ||
169 // or: right after peak has been detected, the delta is smaller than average
170 (mPeakDetectorSd == 0 && fabs(it->first - mPeakDetectorMean) < kTypicalDiff)) {
171 // update the mean and sd:
172 // count number of elements (distance between start interator and current)
173 const int kN = std::distance(start, it) + 1;
174 // usual formulas for mean and sd
175 mPeakDetectorMean = std::accumulate(start, it + 1, 0.0,
176 [](auto &a, auto &b){return a + b.first;}) / kN;
177 mPeakDetectorSd = sqrt(std::accumulate(start, it + 1, 0.0,
178 [=](auto &a, auto &b){ return a + sqr(b.first - mPeakDetectorMean);})) /
179 ((kN > 1)? kN - 1 : kN); // kN - 1: mean is correlated with variance
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700180 }
181 // surprising value: store peak timestamp and reset mean, sd, and start iterator
182 else {
183 mPeakTimestamps.emplace_back(it->second);
184 // TODO: remove pop_front once a circular buffer is in place
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700185 if (mPeakTimestamps.size() >= kPeakSeriesSize) {
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700186 mPeakTimestamps.pop_front();
187 }
188 mPeakDetectorMean = static_cast<double>(it->first);
189 mPeakDetectorSd = 0;
190 start = it;
191 }
192 }
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700193 return;
194}
195
196// Called by LogTsEntry. The input is a vector of timestamps.
197// Finds outliers and writes to mOutlierdata.
198// Each value in mOutlierdata consists of: <outlier timestamp, time elapsed since previous outlier>.
199// e.g. timestamps (ms) 1, 4, 5, 16, 18, 28 will produce pairs (4, 5), (13, 18).
200// This function is applied to the time series before it is converted into a histogram.
201void PerformanceAnalysis::storeOutlierData(const std::vector<int64_t> &timestamps) {
202 if (timestamps.size() < 1) {
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700203 return;
204 }
205 // first pass: need to initialize
206 if (mElapsed == 0) {
207 mPrevNs = timestamps[0];
208 }
209 for (const auto &ts: timestamps) {
210 const uint64_t diffMs = static_cast<uint64_t>(deltaMs(mPrevNs, ts));
211 if (diffMs >= static_cast<uint64_t>(kOutlierMs)) {
212 mOutlierData.emplace_back(mElapsed, static_cast<uint64_t>(mPrevNs));
213 // Remove oldest value if the vector is full
214 // TODO: remove pop_front once circular buffer is in place
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700215 // FIXME: make sure kShortHistSize is large enough that that data will never be lost
216 // before being written to file or to a FIFO
217 if (mOutlierData.size() >= kOutlierSeriesSize) {
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700218 mOutlierData.pop_front();
219 }
220 mElapsed = 0;
221 }
222 mElapsed += diffMs;
223 mPrevNs = ts;
224 }
225}
226
227
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700228// FIXME: delete this temporary test code, recycled for various new functions
229void PerformanceAnalysis::testFunction() {
230 // produces values (4: 5000000), (13: 18000000)
231 // ns timestamps of buffer periods
232 const std::vector<int64_t>kTempTestData = {1000000, 4000000, 5000000,
233 16000000, 18000000, 28000000};
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700234 PerformanceAnalysis::storeOutlierData(kTempTestData);
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700235 for (const auto &outlier: mOutlierData) {
236 ALOGE("PerformanceAnalysis test %lld: %lld",
237 static_cast<long long>(outlier.first), static_cast<long long>(outlier.second));
238 }
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700239 detectPeaks();
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700240}
241
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700242// 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 -0700243// TODO consider changing all ints to uint32_t or uint64_t
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700244// TODO: move this to ReportPerformance, probably make it a friend function of PerformanceAnalysis
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700245void PerformanceAnalysis::reportPerformance(String8 *body, int maxHeight) {
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -0700246 if (mHists.empty()) {
247 ALOGD("reportPerformance: mHists is empty");
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700248 return;
249 }
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -0700250 ALOGD("reportPerformance: hists size %d", static_cast<int>(mHists.size()));
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700251 // TODO: more elaborate data analysis
252 std::map<int, int> buckets;
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -0700253 for (const auto &shortHist: mHists) {
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700254 for (const auto &countPair : shortHist.second) {
255 buckets[countPair.first] += countPair.second;
256 }
257 }
258
259 // underscores and spaces length corresponds to maximum width of histogram
260 static const int kLen = 40;
261 std::string underscores(kLen, '_');
262 std::string spaces(kLen, ' ');
263
264 auto it = buckets.begin();
265 int maxDelta = it->first;
266 int maxCount = it->second;
267 // Compute maximum values
268 while (++it != buckets.end()) {
269 if (it->first > maxDelta) {
270 maxDelta = it->first;
271 }
272 if (it->second > maxCount) {
273 maxCount = it->second;
274 }
275 }
276 int height = log2(maxCount) + 1; // maxCount > 0, safe to call log2
277 const int leftPadding = widthOf(1 << height);
278 const int colWidth = std::max(std::max(widthOf(maxDelta) + 1, 3), leftPadding + 2);
279 int scalingFactor = 1;
280 // scale data if it exceeds maximum height
281 if (height > maxHeight) {
282 scalingFactor = (height + maxHeight) / maxHeight;
283 height /= scalingFactor;
284 }
Sanna Catherine de Treville Wagere4865262017-07-14 16:24:15 -0700285 // TODO: print reader (author) ID
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700286 body->appendFormat("\n%*s", leftPadding + 11, "Occurrences");
287 // write histogram label line with bucket values
288 body->appendFormat("\n%s", " ");
289 body->appendFormat("%*s", leftPadding, " ");
290 for (auto const &x : buckets) {
291 body->appendFormat("%*d", colWidth, x.second);
292 }
293 // write histogram ascii art
294 body->appendFormat("\n%s", " ");
295 for (int row = height * scalingFactor; row >= 0; row -= scalingFactor) {
296 const int value = 1 << row;
297 body->appendFormat("%.*s", leftPadding, spaces.c_str());
298 for (auto const &x : buckets) {
299 body->appendFormat("%.*s%s", colWidth - 1, spaces.c_str(), x.second < value ? " " : "|");
300 }
301 body->appendFormat("\n%s", " ");
302 }
303 // print x-axis
304 const int columns = static_cast<int>(buckets.size());
305 body->appendFormat("%*c", leftPadding, ' ');
306 body->appendFormat("%.*s", (columns + 1) * colWidth, underscores.c_str());
307 body->appendFormat("\n%s", " ");
308
309 // write footer with bucket labels
310 body->appendFormat("%*s", leftPadding, " ");
311 for (auto const &x : buckets) {
312 body->appendFormat("%*d", colWidth, x.first);
313 }
314 body->appendFormat("%.*s%s", colWidth, spaces.c_str(), "ms\n");
315
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700316 // Now report glitches
317 body->appendFormat("\ntime elapsed between glitches and glitch timestamps\n");
318 for (const auto &outlier: mOutlierData) {
319 body->appendFormat("%lld: %lld\n", static_cast<long long>(outlier.first),
320 static_cast<long long>(outlier.second));
321 }
322
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700323}
324
325
326// Produces a log warning if the timing of recent buffer periods caused a glitch
327// Computes sum of running window of three buffer periods
328// Checks whether the buffer periods leave enough CPU time for the next one
329// e.g. if a buffer period is expected to be 4 ms and a buffer requires 3 ms of CPU time,
330// here are some glitch cases:
331// 4 + 4 + 6 ; 5 + 4 + 5; 2 + 2 + 10
332// TODO: develop this code to track changes in histogram distribution in addition
333// to / instead of glitches.
334void PerformanceAnalysis::alertIfGlitch(const std::vector<int64_t> &samples) {
335 std::deque<int> periods(kNumBuff, kPeriodMs);
336 for (size_t i = 2; i < samples.size(); ++i) { // skip first time entry
337 periods.push_front(deltaMs(samples[i - 1], samples[i]));
338 periods.pop_back();
339 // TODO: check that all glitch cases are covered
340 if (std::accumulate(periods.begin(), periods.end(), 0) > kNumBuff * kPeriodMs +
341 kPeriodMs - kPeriodMsCPU) {
342 ALOGW("A glitch occurred");
343 periods.assign(kNumBuff, kPeriodMs);
344 }
345 }
346 return;
347}
348
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700349} // namespace ReportPerformance
350
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700351} // namespace android