blob: d1dff47291abb2e3daae3d3327907c490ab23880 [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/Log.h>
40#include <utils/String8.h>
41
42#include <queue>
43#include <utility>
44
45namespace android {
46
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -070047namespace ReportPerformance {
48
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -070049PerformanceAnalysis::PerformanceAnalysis() {
50 // These variables will be (FIXME) learned from the data
51 kPeriodMs = 4; // typical buffer period (mode)
52 // average number of Ms spent processing buffer
53 kPeriodMsCPU = static_cast<int>(kPeriodMs * kRatio);
54}
55
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -070056static int widthOf(int x) {
57 int width = 0;
58 while (x > 0) {
59 ++width;
60 x /= 10;
61 }
62 return width;
63}
64
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070065// Given a series of audio processing wakeup timestamps,
66// buckets the time intervals into a histogram, searches for
67// outliers, analyzes the outlier series for unexpectedly
68// small or large values and stores these as peaks, and flushes
69// the timestamp series from memory.
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -070070void PerformanceAnalysis::processAndFlushTimeStampSeries() {
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -070071 if (mTimeStampSeries.empty()) {
72 ALOGD("Timestamp series is empty");
73 return;
74 }
75
Sanna Catherine de Treville Wager23f89d32017-07-24 18:24:48 -070076 // mHists is empty if thread/hash pair is sending data for the first time
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -070077 if (mHists.empty()) {
78 mHists.emplace_front(static_cast<uint64_t>(mTimeStampSeries[0]),
79 std::map<int, int>());
80 }
81
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070082 // 1) analyze the series to store all outliers and their exact timestamps:
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -070083 storeOutlierData(mTimeStampSeries);
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070084
85 // 2) detect peaks in the outlier series
86 detectPeaks();
87
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -070088 // if the current histogram has spanned its maximum time interval,
89 // insert a new empty histogram to the front of mHists
90 if (deltaMs(mHists[0].first, mTimeStampSeries[0]) >= kMaxHistTimespanMs) {
91 mHists.emplace_front(static_cast<uint64_t>(mTimeStampSeries[0]),
92 std::map<int, int>());
93 // When memory is full, delete oldest histogram
94 if (mHists.size() >= kHistsCapacity) {
95 mHists.resize(kHistsCapacity);
96 }
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070097 }
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -070098
99 // 3) add current time intervals to histogram
100 for (size_t i = 1; i < mTimeStampSeries.size(); ++i) {
101 ++mHists[0].second[deltaMs(
102 mTimeStampSeries[i - 1], mTimeStampSeries[i])];
103 }
104
105 // clear the timestamps
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700106 mTimeStampSeries.clear();
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700107}
108
109// forces short-term histogram storage to avoid adding idle audio time interval
110// to buffer period data
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700111void PerformanceAnalysis::handleStateChange() {
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700112 ALOGD("handleStateChange");
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700113 processAndFlushTimeStampSeries();
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700114 return;
115}
116
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700117// Takes a single buffer period timestamp entry information and stores it in a
118// temporary series of timestamps. Once the series is full, the data is analyzed,
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700119// stored, and emptied.
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700120void PerformanceAnalysis::logTsEntry(int64_t ts) {
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700121 // TODO might want to filter excessively high outliers, which are usually caused
122 // by the thread being inactive.
123 // Store time series data for each reader in order to bucket it once there
124 // is enough data. Then, write to recentHists as a histogram.
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700125 mTimeStampSeries.push_back(ts);
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700126 // if length of the time series has reached kShortHistSize samples,
127 // analyze the data and flush the timestamp series from memory
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -0700128 if (mTimeStampSeries.size() >= kHistSize) {
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700129 processAndFlushTimeStampSeries();
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700130 }
131}
132
133// Given a series of outlier intervals (mOutlier data),
134// looks for changes in distribution (peaks), which can be either positive or negative.
135// The function sets the mean to the starting value and sigma to 0, and updates
136// them as long as no peak is detected. When a value is more than 'threshold'
137// standard deviations from the mean, a peak is detected and the mean and sigma
138// are set to the peak value and 0.
139void PerformanceAnalysis::detectPeaks() {
140 if (mOutlierData.empty()) {
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700141 return;
142 }
143
144 // compute mean of the distribution. Used to check whether a value is large
145 const double kTypicalDiff = std::accumulate(
146 mOutlierData.begin(), mOutlierData.end(), 0,
147 [](auto &a, auto &b){return a + b.first;}) / mOutlierData.size();
148 // ALOGD("typicalDiff %f", kTypicalDiff);
149
150 // iterator at the beginning of a sequence, or updated to the most recent peak
151 std::deque<std::pair<uint64_t, uint64_t>>::iterator start = mOutlierData.begin();
152 // the mean and standard deviation are updated every time a peak is detected
153 // initialize first time. The mean from the previous sequence is stored
154 // for the next sequence. Here, they are initialized for the first time.
155 if (mPeakDetectorMean < 0) {
156 mPeakDetectorMean = static_cast<double>(start->first);
157 mPeakDetectorSd = 0;
158 }
159 auto sqr = [](auto x){ return x * x; };
160 for (auto it = mOutlierData.begin(); it != mOutlierData.end(); ++it) {
161 // no surprise occurred:
162 // the new element is a small number of standard deviations from the mean
163 if ((fabs(it->first - mPeakDetectorMean) < kStddevThreshold * mPeakDetectorSd) ||
164 // or: right after peak has been detected, the delta is smaller than average
165 (mPeakDetectorSd == 0 && fabs(it->first - mPeakDetectorMean) < kTypicalDiff)) {
166 // update the mean and sd:
167 // count number of elements (distance between start interator and current)
168 const int kN = std::distance(start, it) + 1;
169 // usual formulas for mean and sd
170 mPeakDetectorMean = std::accumulate(start, it + 1, 0.0,
171 [](auto &a, auto &b){return a + b.first;}) / kN;
172 mPeakDetectorSd = sqrt(std::accumulate(start, it + 1, 0.0,
173 [=](auto &a, auto &b){ return a + sqr(b.first - mPeakDetectorMean);})) /
174 ((kN > 1)? kN - 1 : kN); // kN - 1: mean is correlated with variance
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700175 }
176 // surprising value: store peak timestamp and reset mean, sd, and start iterator
177 else {
178 mPeakTimestamps.emplace_back(it->second);
179 // TODO: remove pop_front once a circular buffer is in place
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700180 if (mPeakTimestamps.size() >= kPeakSeriesSize) {
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700181 mPeakTimestamps.pop_front();
182 }
183 mPeakDetectorMean = static_cast<double>(it->first);
184 mPeakDetectorSd = 0;
185 start = it;
186 }
187 }
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700188 return;
189}
190
191// Called by LogTsEntry. The input is a vector of timestamps.
192// Finds outliers and writes to mOutlierdata.
193// Each value in mOutlierdata consists of: <outlier timestamp, time elapsed since previous outlier>.
194// e.g. timestamps (ms) 1, 4, 5, 16, 18, 28 will produce pairs (4, 5), (13, 18).
195// This function is applied to the time series before it is converted into a histogram.
196void PerformanceAnalysis::storeOutlierData(const std::vector<int64_t> &timestamps) {
197 if (timestamps.size() < 1) {
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700198 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
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700210 // FIXME: make sure kShortHistSize is large enough that that data will never be lost
211 // before being written to file or to a FIFO
212 if (mOutlierData.size() >= kOutlierSeriesSize) {
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700213 mOutlierData.pop_front();
214 }
215 mElapsed = 0;
216 }
217 mElapsed += diffMs;
218 mPrevNs = ts;
219 }
220}
221
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700222// FIXME: delete this temporary test code, recycled for various new functions
223void PerformanceAnalysis::testFunction() {
224 // produces values (4: 5000000), (13: 18000000)
225 // ns timestamps of buffer periods
226 const std::vector<int64_t>kTempTestData = {1000000, 4000000, 5000000,
227 16000000, 18000000, 28000000};
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700228 PerformanceAnalysis::storeOutlierData(kTempTestData);
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700229 for (const auto &outlier: mOutlierData) {
230 ALOGE("PerformanceAnalysis test %lld: %lld",
231 static_cast<long long>(outlier.first), static_cast<long long>(outlier.second));
232 }
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700233 detectPeaks();
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700234}
235
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700236// 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 -0700237// TODO consider changing all ints to uint32_t or uint64_t
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700238// TODO: move this to ReportPerformance, probably make it a friend function of PerformanceAnalysis
Sanna Catherine de Treville Wager23f89d32017-07-24 18:24:48 -0700239void PerformanceAnalysis::reportPerformance(String8 *body, int maxHeight) {
240 // Add any new data
241 processAndFlushTimeStampSeries();
242
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -0700243 if (mHists.empty()) {
244 ALOGD("reportPerformance: mHists is empty");
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700245 return;
246 }
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -0700247 ALOGD("reportPerformance: hists size %d", static_cast<int>(mHists.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 Wagera80649a2017-07-21 16:16:38 -0700250 for (const auto &shortHist: mHists) {
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 }
Sanna Catherine de Treville Wagere4865262017-07-14 16:24:15 -0700282 // TODO: print reader (author) ID
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700283 body->appendFormat("\n%*s", leftPadding + 11, "Occurrences");
284 // write histogram label line with bucket values
285 body->appendFormat("\n%s", " ");
286 body->appendFormat("%*s", leftPadding, " ");
287 for (auto const &x : buckets) {
288 body->appendFormat("%*d", colWidth, x.second);
289 }
290 // write histogram ascii art
291 body->appendFormat("\n%s", " ");
292 for (int row = height * scalingFactor; row >= 0; row -= scalingFactor) {
293 const int value = 1 << row;
294 body->appendFormat("%.*s", leftPadding, spaces.c_str());
295 for (auto const &x : buckets) {
296 body->appendFormat("%.*s%s", colWidth - 1, spaces.c_str(), x.second < value ? " " : "|");
297 }
298 body->appendFormat("\n%s", " ");
299 }
300 // print x-axis
301 const int columns = static_cast<int>(buckets.size());
302 body->appendFormat("%*c", leftPadding, ' ');
303 body->appendFormat("%.*s", (columns + 1) * colWidth, underscores.c_str());
304 body->appendFormat("\n%s", " ");
305
306 // write footer with bucket labels
307 body->appendFormat("%*s", leftPadding, " ");
308 for (auto const &x : buckets) {
309 body->appendFormat("%*d", colWidth, x.first);
310 }
311 body->appendFormat("%.*s%s", colWidth, spaces.c_str(), "ms\n");
312
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700313 // Now report glitches
314 body->appendFormat("\ntime elapsed between glitches and glitch timestamps\n");
315 for (const auto &outlier: mOutlierData) {
316 body->appendFormat("%lld: %lld\n", static_cast<long long>(outlier.first),
317 static_cast<long long>(outlier.second));
318 }
319
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700320}
321
322
323// Produces a log warning if the timing of recent buffer periods caused a glitch
324// Computes sum of running window of three buffer periods
325// Checks whether the buffer periods leave enough CPU time for the next one
326// e.g. if a buffer period is expected to be 4 ms and a buffer requires 3 ms of CPU time,
327// here are some glitch cases:
328// 4 + 4 + 6 ; 5 + 4 + 5; 2 + 2 + 10
329// TODO: develop this code to track changes in histogram distribution in addition
330// to / instead of glitches.
331void PerformanceAnalysis::alertIfGlitch(const std::vector<int64_t> &samples) {
332 std::deque<int> periods(kNumBuff, kPeriodMs);
333 for (size_t i = 2; i < samples.size(); ++i) { // skip first time entry
334 periods.push_front(deltaMs(samples[i - 1], samples[i]));
335 periods.pop_back();
336 // TODO: check that all glitch cases are covered
337 if (std::accumulate(periods.begin(), periods.end(), 0) > kNumBuff * kPeriodMs +
338 kPeriodMs - kPeriodMsCPU) {
339 ALOGW("A glitch occurred");
340 periods.assign(kNumBuff, kPeriodMs);
341 }
342 }
343 return;
344}
345
Sanna Catherine de Treville Wagercf6c75a2017-07-21 17:05:25 -0700346//------------------------------------------------------------------------------
347
348// writes summary of performance into specified file descriptor
Sanna Catherine de Treville Wager23f89d32017-07-24 18:24:48 -0700349void dump(int fd, int indent, PerformanceAnalysisMap &threadPerformanceAnalysis) {
Sanna Catherine de Treville Wagercf6c75a2017-07-21 17:05:25 -0700350 String8 body;
Sanna Catherine de Treville Wager23f89d32017-07-24 18:24:48 -0700351 const char* const kName = "/data/misc/audioserver/";
Sanna Catherine de Treville Wagercf6c75a2017-07-21 17:05:25 -0700352 for (auto & thread : threadPerformanceAnalysis) {
Sanna Catherine de Treville Wagerd0965172017-07-24 13:42:44 -0700353 for (auto & hash: thread.second) {
Sanna Catherine de Treville Wager23f89d32017-07-24 18:24:48 -0700354 PerformanceAnalysis& curr = hash.second;
355 curr.processAndFlushTimeStampSeries();
356 // write performance data to console
357 curr.reportPerformance(&body);
358 // write to file
359 writeToFile(curr.mOutlierData, curr.mHists, kName, false,
360 thread.first, hash.first);
Sanna Catherine de Treville Wagerd0965172017-07-24 13:42:44 -0700361 }
Sanna Catherine de Treville Wagercf6c75a2017-07-21 17:05:25 -0700362 }
363 if (!body.isEmpty()) {
364 dumpLine(fd, indent, body);
365 body.clear();
366 }
367}
368
369// Writes a string into specified file descriptor
370void dumpLine(int fd, int indent, const String8 &body) {
371 dprintf(fd, "%.*s%s \n", indent, "", body.string());
372}
373
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700374} // namespace ReportPerformance
375
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700376} // namespace android