blob: 3418dc0ef3f7d144db4a769529ab1f7af65d5336 [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>
Eric Tan39ec8d62018-07-24 09:49:29 -070035#include <audio_utils/LogPlot.h>
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -070036#include <audio_utils/roundup.h>
Glenn Kasten8589ce72017-09-08 17:03:42 -070037#include <media/nblog/NBLog.h>
38#include <media/nblog/PerformanceAnalysis.h>
39#include <media/nblog/ReportPerformance.h>
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -070040#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 Wager14316442017-08-11 10:45:29 -070050// Given an audio processing wakeup timestamp, buckets the time interval
51// since the previous timestamp into a histogram, searches for
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070052// outliers, analyzes the outlier series for unexpectedly
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -070053// small or large values and stores these as peaks
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -070054void PerformanceAnalysis::logTsEntry(timestamp ts) {
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -070055 // after a state change, start a new series and do not
56 // record time intervals in-between
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -070057 if (mBufferPeriod.mPrevTs == 0) {
58 mBufferPeriod.mPrevTs = ts;
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -070059 return;
60 }
61
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -070062 // calculate time interval between current and previous timestamp
63 const msInterval diffMs = static_cast<msInterval>(
64 deltaMs(mBufferPeriod.mPrevTs, ts));
65
66 const int diffJiffy = deltaJiffy(mBufferPeriod.mPrevTs, ts);
67
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -070068 // old versus new weight ratio when updating the buffer period mean
69 static constexpr double exponentialWeight = 0.999;
70 // update buffer period mean with exponential weighting
71 mBufferPeriod.mMean = (mBufferPeriod.mMean < 0) ? diffMs :
72 exponentialWeight * mBufferPeriod.mMean + (1.0 - exponentialWeight) * diffMs;
73 // set mOutlierFactor to a smaller value for the fastmixer thread
74 const int kFastMixerMax = 10;
75 // NormalMixer times vary much more than FastMixer times.
76 // TODO: mOutlierFactor values are set empirically based on what appears to be
77 // an outlier. Learn these values from the data.
Sanna Catherine de Treville Wager847b6e62017-08-03 11:35:51 -070078 mBufferPeriod.mOutlierFactor = mBufferPeriod.mMean < kFastMixerMax ? 1.8 : 2.0;
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -070079 // set outlier threshold
80 mBufferPeriod.mOutlier = mBufferPeriod.mMean * mBufferPeriod.mOutlierFactor;
81
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -070082 // Check whether the time interval between the current timestamp
83 // and the previous one is long enough to count as an outlier
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -070084 const bool isOutlier = detectAndStoreOutlier(diffMs);
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -070085 // If an outlier was found, check whether it was a peak
86 if (isOutlier) {
87 /*bool isPeak =*/ detectAndStorePeak(
88 mOutlierData[0].first, mOutlierData[0].second);
89 // TODO: decide whether to insert a new empty histogram if a peak
90 // TODO: remove isPeak if unused to avoid "unused variable" error
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -070091 // occurred at the current timestamp
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -070092 }
93
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -070094 // Insert a histogram to mHists if it is empty, or
95 // close the current histogram and insert a new empty one if
96 // if the current histogram has spanned its maximum time interval.
97 if (mHists.empty() ||
98 deltaMs(mHists[0].first, ts) >= kMaxLength.HistTimespanMs) {
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -070099 mHists.emplace_front(ts, std::map<int, int>());
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700100 // When memory is full, delete oldest histogram
101 // TODO: use a circular buffer
102 if (mHists.size() >= kMaxLength.Hists) {
103 mHists.resize(kMaxLength.Hists);
104 }
105 }
106 // add current time intervals to histogram
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -0700107 ++mHists[0].second[diffJiffy];
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700108 // update previous timestamp
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -0700109 mBufferPeriod.mPrevTs = ts;
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700110}
111
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700112
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700113// forces short-term histogram storage to avoid adding idle audio time interval
114// to buffer period data
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700115void PerformanceAnalysis::handleStateChange() {
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -0700116 mBufferPeriod.mPrevTs = 0;
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700117 return;
118}
119
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700120
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700121// Checks whether the time interval between two outliers is far enough from
122// a typical delta to be considered a peak.
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700123// looks for changes in distribution (peaks), which can be either positive or negative.
124// The function sets the mean to the starting value and sigma to 0, and updates
125// them as long as no peak is detected. When a value is more than 'threshold'
126// standard deviations from the mean, a peak is detected and the mean and sigma
127// are set to the peak value and 0.
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -0700128bool PerformanceAnalysis::detectAndStorePeak(msInterval diff, timestamp ts) {
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700129 bool isPeak = false;
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700130 if (mOutlierData.empty()) {
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700131 return false;
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700132 }
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700133 // Update mean of the distribution
134 // TypicalDiff is used to check whether a value is unusually large
135 // when we cannot use standard deviations from the mean because the sd is set to 0.
136 mOutlierDistribution.mTypicalDiff = (mOutlierDistribution.mTypicalDiff *
137 (mOutlierData.size() - 1) + diff) / mOutlierData.size();
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700138
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700139 // Initialize short-term mean at start of program
140 if (mOutlierDistribution.mMean == 0) {
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -0700141 mOutlierDistribution.mMean = diff;
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700142 }
143 // Update length of current sequence of outliers
144 mOutlierDistribution.mN++;
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700145
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -0700146 // Check whether a large deviation from the mean occurred.
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700147 // If the standard deviation has been reset to zero, the comparison is
148 // instead to the mean of the full mOutlierInterval sequence.
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -0700149 if ((fabs(diff - mOutlierDistribution.mMean) <
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700150 mOutlierDistribution.kMaxDeviation * mOutlierDistribution.mSd) ||
151 (mOutlierDistribution.mSd == 0 &&
152 fabs(diff - mOutlierDistribution.mMean) <
153 mOutlierDistribution.mTypicalDiff)) {
154 // update the mean and sd using online algorithm
155 // https://en.wikipedia.org/wiki/
156 // Algorithms_for_calculating_variance#Online_algorithm
157 mOutlierDistribution.mN++;
158 const double kDelta = diff - mOutlierDistribution.mMean;
159 mOutlierDistribution.mMean += kDelta / mOutlierDistribution.mN;
160 const double kDelta2 = diff - mOutlierDistribution.mMean;
161 mOutlierDistribution.mM2 += kDelta * kDelta2;
162 mOutlierDistribution.mSd = (mOutlierDistribution.mN < 2) ? 0 :
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700163 sqrt(mOutlierDistribution.mM2 / (mOutlierDistribution.mN - 1));
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700164 } else {
165 // new value is far from the mean:
166 // store peak timestamp and reset mean, sd, and short-term sequence
167 isPeak = true;
168 mPeakTimestamps.emplace_front(ts);
169 // if mPeaks has reached capacity, delete oldest data
170 // Note: this means that mOutlierDistribution values do not exactly
171 // match the data we have in mPeakTimestamps, but this is not an issue
172 // in practice for estimating future peaks.
173 // TODO: turn this into a circular buffer
174 if (mPeakTimestamps.size() >= kMaxLength.Peaks) {
175 mPeakTimestamps.resize(kMaxLength.Peaks);
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700176 }
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700177 mOutlierDistribution.mMean = 0;
178 mOutlierDistribution.mSd = 0;
179 mOutlierDistribution.mN = 0;
180 mOutlierDistribution.mM2 = 0;
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700181 }
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700182 return isPeak;
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700183}
184
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700185
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700186// Determines whether the difference between a timestamp and the previous
187// one is beyond a threshold. If yes, stores the timestamp as an outlier
188// and writes to mOutlierdata in the following format:
189// Time elapsed since previous outlier: Timestamp of start of outlier
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700190// e.g. timestamps (ms) 1, 4, 5, 16, 18, 28 will produce pairs (4, 5), (13, 18).
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700191// TODO: learn what timestamp sequences correlate with glitches instead of
192// manually designing a heuristic.
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -0700193bool PerformanceAnalysis::detectAndStoreOutlier(const msInterval diffMs) {
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700194 bool isOutlier = false;
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -0700195 if (diffMs >= mBufferPeriod.mOutlier) {
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700196 isOutlier = true;
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -0700197 mOutlierData.emplace_front(
198 mOutlierDistribution.mElapsed, mBufferPeriod.mPrevTs);
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700199 // Remove oldest value if the vector is full
200 // TODO: turn this into a circular buffer
201 // TODO: make sure kShortHistSize is large enough that that data will never be lost
202 // before being written to file or to a FIFO
203 if (mOutlierData.size() >= kMaxLength.Outliers) {
204 mOutlierData.resize(kMaxLength.Outliers);
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700205 }
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700206 mOutlierDistribution.mElapsed = 0;
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700207 }
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700208 mOutlierDistribution.mElapsed += diffMs;
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700209 return isOutlier;
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700210}
211
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700212// rounds value to precision based on log-distance from mean
Ivan Lozanobb4b8b52017-11-30 15:43:19 -0800213__attribute__((no_sanitize("signed-integer-overflow")))
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700214inline double logRound(double x, double mean) {
Sanna Catherine de Treville Wager847b6e62017-08-03 11:35:51 -0700215 // Larger values decrease range of high resolution and prevent overflow
216 // of a histogram on the console.
217 // The following formula adjusts kBase based on the buffer period length.
218 // Different threads have buffer periods ranging from 2 to 40. The
219 // formula below maps buffer period 2 to kBase = ~1, 4 to ~2, 20 to ~3, 40 to ~4.
220 // TODO: tighten this for higher means, the data still overflows
221 const double kBase = log(mean) / log(2.2);
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700222 const double power = floor(
Sanna Catherine de Treville Wager847b6e62017-08-03 11:35:51 -0700223 log(abs(x - mean) / mean) / log(kBase)) + 2;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700224 // do not round values close to the mean
225 if (power < 1) {
226 return x;
227 }
228 const int factor = static_cast<int>(pow(10, power));
229 return (static_cast<int>(x) * factor) / factor;
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -0700230}
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700231
Sanna Catherine de Treville Wager6ad40ee2017-07-28 10:10:55 -0700232// TODO Make it return a std::string instead of modifying body
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700233// TODO: move this to ReportPerformance, probably make it a friend function
234// of PerformanceAnalysis
235void PerformanceAnalysis::reportPerformance(String8 *body, int author, log_hash_t hash,
236 int maxHeight) {
Eric Tan8180b742018-07-10 15:23:29 -0700237 if (mHists.empty() || body == nullptr) {
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700238 return;
239 }
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700240
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700241 // ms of active audio in displayed histogram
242 double elapsedMs = 0;
243 // starting timestamp of histogram
244 timestamp startingTs = mHists[0].first;
245
246 // histogram which stores .1 precision ms counts instead of Jiffy multiple counts
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700247 std::map<double, int> buckets;
Sanna Catherine de Treville Wagera80649a2017-07-21 16:16:38 -0700248 for (const auto &shortHist: mHists) {
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700249 for (const auto &countPair : shortHist.second) {
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700250 const double ms = static_cast<double>(countPair.first) / kJiffyPerMs;
251 buckets[logRound(ms, mBufferPeriod.mMean)] += countPair.second;
Sanna Catherine de Treville Wager847b6e62017-08-03 11:35:51 -0700252 elapsedMs += ms * countPair.second;
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700253 }
254 }
255
Eric Tan8180b742018-07-10 15:23:29 -0700256 static const int SIZE = 128;
257 char title[SIZE];
258 snprintf(title, sizeof(title), "\n%s %3.2f %s\n%s%d, %lld, %lld\n",
259 "Occurrences in", (elapsedMs / kMsPerSec), "seconds of audio:",
260 "Thread, hash, starting timestamp: ", author,
261 static_cast<long long>(hash), static_cast<long long>(startingTs));
262 static const char * const kLabel = "ms";
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700263
Eric Tan39ec8d62018-07-24 09:49:29 -0700264 body->appendFormat("%s",
265 audio_utils_plot_histogram(buckets, title, kLabel, maxHeight).c_str());
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700266
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700267 // Now report glitches
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700268 body->appendFormat("\ntime elapsed between glitches and glitch timestamps:\n");
Sanna Catherine de Treville Wager316f1fd2017-06-23 09:10:15 -0700269 for (const auto &outlier: mOutlierData) {
270 body->appendFormat("%lld: %lld\n", static_cast<long long>(outlier.first),
271 static_cast<long long>(outlier.second));
272 }
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700273}
274
Sanna Catherine de Treville Wagercf6c75a2017-07-21 17:05:25 -0700275//------------------------------------------------------------------------------
276
277// writes summary of performance into specified file descriptor
Sanna Catherine de Treville Wager23f89d32017-07-24 18:24:48 -0700278void dump(int fd, int indent, PerformanceAnalysisMap &threadPerformanceAnalysis) {
Sanna Catherine de Treville Wagercf6c75a2017-07-21 17:05:25 -0700279 String8 body;
Sanna Catherine de Treville Wagerf8c34282017-07-25 11:31:18 -0700280 const char* const kDirectory = "/data/misc/audioserver/";
Sanna Catherine de Treville Wagercf6c75a2017-07-21 17:05:25 -0700281 for (auto & thread : threadPerformanceAnalysis) {
Sanna Catherine de Treville Wagerd0965172017-07-24 13:42:44 -0700282 for (auto & hash: thread.second) {
Sanna Catherine de Treville Wager23f89d32017-07-24 18:24:48 -0700283 PerformanceAnalysis& curr = hash.second;
Sanna Catherine de Treville Wager23f89d32017-07-24 18:24:48 -0700284 // write performance data to console
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700285 curr.reportPerformance(&body, thread.first, hash.first);
Sanna Catherine de Treville Wager0a3959e2017-07-25 16:08:17 -0700286 if (!body.isEmpty()) {
287 dumpLine(fd, indent, body);
288 body.clear();
289 }
Sanna Catherine de Treville Wager23f89d32017-07-24 18:24:48 -0700290 // write to file
Sanna Catherine de Treville Wagerf8c34282017-07-25 11:31:18 -0700291 writeToFile(curr.mHists, curr.mOutlierData, curr.mPeakTimestamps,
292 kDirectory, false, thread.first, hash.first);
Sanna Catherine de Treville Wagerd0965172017-07-24 13:42:44 -0700293 }
Sanna Catherine de Treville Wagercf6c75a2017-07-21 17:05:25 -0700294 }
Sanna Catherine de Treville Wagercf6c75a2017-07-21 17:05:25 -0700295}
296
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700297
Sanna Catherine de Treville Wagercf6c75a2017-07-21 17:05:25 -0700298// Writes a string into specified file descriptor
299void dumpLine(int fd, int indent, const String8 &body) {
300 dprintf(fd, "%.*s%s \n", indent, "", body.string());
301}
302
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700303} // namespace ReportPerformance
304
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700305} // namespace android