blob: 0e5693da4c2e5c310ce02c167198a51be305c086 [file] [log] [blame]
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001/*
2 * Copyright (C) 2013 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
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070017/*
18* Documentation: Workflow summary for histogram data processing:
19* For more details on FIFO, please see system/media/audio_utils; doxygen
20* TODO: add this documentation to doxygen once it is further developed
21* 1) writing the data to a buffer
22* onWork
23* Called every period length (e.g., 4ms)
24* Calls LOG_HIST_TS
25* LOG_HIST_TS
26* Hashes file name and line number
27* calls NBLOG::Writer::logHistTS once
28* NBLOG::Writer::logHistTS
29* calls NBLOG::Writer::log on hash and current timestamp
30* time is in CLOCK_MONOTONIC converted to ns
31* NBLOG::Writer::log(Event, const void*, size_t)
32* Initializes Entry, a struct containing one log entry
33* Entry contains the event type (mEvent), data length (mLength),
34* and data pointer (mData)
35* TODO: why mLength (max length of buffer data) must be <= kMaxLength = 255?
36* calls NBLOG::Writer::log(Entry *, bool)
37* NBLog::Writer::log(Entry *, bool)
38* Calls copyEntryDataAt to format data as follows in temp array:
39* [type][length][data ... ][length]
40* calls audio_utils_fifo_writer.write on temp
41* audio_utils_fifo_writer.write
42* calls obtain(), memcpy (reference in doxygen)
43* returns number of frames written
44* ssize_t audio_utils_fifo_reader::obtain
45* Determines readable buffer section via pointer arithmetic on reader
46* and writer pointers
47*
48* 2) reading the data from shared memory
49* Thread::threadloop()
50* TODO: add description?
51* NBLog::MergeThread::threadLoop()
52* calls NBLog::Merger::merge
53* NBLog::Merger::merge
54* for each reader in vector of class NamedReader,
55* callsNamedReader::reader()->getSnapshot
56* TODO: check whether the rest of this function is relevant
57* NBLog::Reader::getSnapshot
58* copies snapshot of reader's fifo buffer into its own buffer
59* calls mFifoReader->obtain to find readable data
60* sets snapshot.begin() and .end() iterators to boundaries of valid entries
61* moves the fifo reader index to after the last entry read
62* in this case, the buffer is in shared memory. in (3), the buffer is private
63*
64* 3) reading the data from private buffer
65* MediaLogService::dump
66* calls NBLog::Reader::dump(int) on instance of subclass mergeReader
67* NBLog::Reader::dump(int)
68* calls getSnapshot on the current reader
69* calls dump(int, size_t, Snapshot)
70* NBLog::Reader::dump(int, size, snapshot)
71* iterates through snapshot's events and switches based on their type
72* (string, timestamp, etc...)
73* In the case of EVENT_HISTOGRAM_ENTRY_TS, adds a list of timestamp sequences
74* (histogram entry) to NBLog::mHists
75* In the case of EVENT_HISTOGRAM_FLUSH, calls drawHistogram on each element in
76* the list and erases it
77* TODO: when do these events occur?
78* NBLog::drawHistogram
79* input: timestamp array
80* buckets this to a histogram and prints
81*
82*/
83
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080084#define LOG_TAG "NBLog"
85//#define LOG_NDEBUG 0
86
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -080087#include <climits>
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -070088#include <deque>
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -070089#include <math.h>
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -070090#include <numeric>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080091#include <stdarg.h>
92#include <stdint.h>
93#include <stdio.h>
94#include <string.h>
Nicolas Rouletc20cb502017-02-01 12:35:24 -080095#include <sys/prctl.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080096#include <time.h>
97#include <new>
Glenn Kasten535e1612016-12-05 12:19:36 -080098#include <audio_utils/roundup.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080099#include <media/nbaio/NBLog.h>
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700100// #include <utils/CallStack.h> // used to print callstack
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800101#include <utils/Log.h>
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700102#include <utils/String8.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800103
Nicolas Roulet40a44982017-02-03 13:39:57 -0800104#include <queue>
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700105#include <utility>
Nicolas Roulet40a44982017-02-03 13:39:57 -0800106
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800107namespace android {
108
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700109int NBLog::Entry::copyEntryDataAt(size_t offset) const
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800110{
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700111 // FIXME This is too slow
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800112 if (offset == 0)
113 return mEvent;
114 else if (offset == 1)
115 return mLength;
116 else if (offset < (size_t) (mLength + 2))
117 return ((char *) mData)[offset - 2];
118 else if (offset == (size_t) (mLength + 2))
119 return mLength;
120 else
121 return 0;
122}
123
124// ---------------------------------------------------------------------------
125
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700126/*static*/
127std::unique_ptr<NBLog::AbstractEntry> NBLog::AbstractEntry::buildEntry(const uint8_t *ptr) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -0700128 const uint8_t type = EntryIterator(ptr)->type;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700129 switch (type) {
130 case EVENT_START_FMT:
131 return std::make_unique<FormatEntry>(FormatEntry(ptr));
132 case EVENT_HISTOGRAM_FLUSH:
133 case EVENT_HISTOGRAM_ENTRY_TS:
134 return std::make_unique<HistogramEntry>(HistogramEntry(ptr));
135 default:
136 ALOGW("Tried to create AbstractEntry of type %d", type);
137 return nullptr;
138 }
Nicolas Roulet40a44982017-02-03 13:39:57 -0800139}
140
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700141NBLog::AbstractEntry::AbstractEntry(const uint8_t *entry) : mEntry(entry) {
142}
143
144// ---------------------------------------------------------------------------
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800145
Sanna Catherine de Treville Wagerdd92d7e2017-05-15 14:56:53 -0700146NBLog::EntryIterator NBLog::FormatEntry::begin() const {
147 return EntryIterator(mEntry);
148}
149
Nicolas Roulet40a44982017-02-03 13:39:57 -0800150const char *NBLog::FormatEntry::formatString() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800151 return (const char*) mEntry + offsetof(entry, data);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800152}
153
154size_t NBLog::FormatEntry::formatStringLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800155 return mEntry[offsetof(entry, length)];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800156}
157
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700158NBLog::EntryIterator NBLog::FormatEntry::args() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800159 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700160 // skip start fmt
161 ++it;
162 // skip timestamp
163 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700164 // skip hash
165 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700166 // Skip author if present
167 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800168 ++it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800169 }
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700170 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800171}
172
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700173int64_t NBLog::FormatEntry::timestamp() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800174 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700175 // skip start fmt
176 ++it;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700177 return it.payload<int64_t>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800178}
179
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700180NBLog::log_hash_t NBLog::FormatEntry::hash() const {
181 auto it = begin();
182 // skip start fmt
183 ++it;
184 // skip timestamp
185 ++it;
186 // unaligned 64-bit read not supported
187 log_hash_t hash;
188 memcpy(&hash, it->data, sizeof(hash));
189 return hash;
190}
191
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700192int NBLog::FormatEntry::author() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800193 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700194 // skip start fmt
195 ++it;
196 // skip timestamp
197 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700198 // skip hash
199 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700200 // if there is an author entry, return it, return -1 otherwise
201 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800202 return it.payload<int>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800203 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800204 return -1;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800205}
206
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700207NBLog::EntryIterator NBLog::FormatEntry::copyWithAuthor(
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800208 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
209 auto it = begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800210 // copy fmt start entry
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800211 it.copyTo(dst);
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700212 // copy timestamp
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700213 (++it).copyTo(dst); // copy hash
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700214 (++it).copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800215 // insert author entry
216 size_t authorEntrySize = NBLog::Entry::kOverhead + sizeof(author);
217 uint8_t authorEntry[authorEntrySize];
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800218 authorEntry[offsetof(entry, type)] = EVENT_AUTHOR;
219 authorEntry[offsetof(entry, length)] =
220 authorEntry[authorEntrySize + NBLog::Entry::kPreviousLengthOffset] =
221 sizeof(author);
222 *(int*) (&authorEntry[offsetof(entry, data)]) = author;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800223 dst->write(authorEntry, authorEntrySize);
224 // copy rest of entries
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800225 while ((++it)->type != EVENT_END_FMT) {
226 it.copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800227 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800228 it.copyTo(dst);
229 ++it;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800230 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800231}
232
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700233void NBLog::EntryIterator::copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800234 size_t length = ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
235 dst->write(ptr, length);
236}
Nicolas Roulet40a44982017-02-03 13:39:57 -0800237
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700238void NBLog::EntryIterator::copyData(uint8_t *dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800239 memcpy((void*) dst, ptr + offsetof(entry, data), ptr[offsetof(entry, length)]);
240}
241
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700242NBLog::EntryIterator::EntryIterator()
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800243 : ptr(nullptr) {}
244
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700245NBLog::EntryIterator::EntryIterator(const uint8_t *entry)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800246 : ptr(entry) {}
247
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700248NBLog::EntryIterator::EntryIterator(const NBLog::EntryIterator &other)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800249 : ptr(other.ptr) {}
250
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700251const NBLog::entry& NBLog::EntryIterator::operator*() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800252 return *(entry*) ptr;
253}
254
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700255const NBLog::entry* NBLog::EntryIterator::operator->() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800256 return (entry*) ptr;
257}
258
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700259NBLog::EntryIterator& NBLog::EntryIterator::operator++() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800260 ptr += ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
261 return *this;
262}
263
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700264NBLog::EntryIterator& NBLog::EntryIterator::operator--() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800265 ptr -= ptr[NBLog::Entry::kPreviousLengthOffset] + NBLog::Entry::kOverhead;
266 return *this;
267}
268
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700269NBLog::EntryIterator NBLog::EntryIterator::next() const {
270 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800271 return ++aux;
272}
273
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700274NBLog::EntryIterator NBLog::EntryIterator::prev() const {
275 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800276 return --aux;
277}
278
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700279int NBLog::EntryIterator::operator-(const NBLog::EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800280 return ptr - other.ptr;
281}
282
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700283bool NBLog::EntryIterator::operator!=(const EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800284 return ptr != other.ptr;
285}
286
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700287bool NBLog::EntryIterator::hasConsistentLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800288 return ptr[offsetof(entry, length)] == ptr[ptr[offsetof(entry, length)] +
289 NBLog::Entry::kOverhead + NBLog::Entry::kPreviousLengthOffset];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800290}
291
292// ---------------------------------------------------------------------------
293
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700294int64_t NBLog::HistogramEntry::timestamp() const {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700295 return EntryIterator(mEntry).payload<HistTsEntry>().ts;
296}
297
298NBLog::log_hash_t NBLog::HistogramEntry::hash() const {
299 return EntryIterator(mEntry).payload<HistTsEntry>().hash;
300}
301
302int NBLog::HistogramEntry::author() const {
303 EntryIterator it(mEntry);
304 if (it->length == sizeof(HistTsEntryWithAuthor)) {
305 return it.payload<HistTsEntryWithAuthor>().author;
306 } else {
307 return -1;
308 }
309}
310
311NBLog::EntryIterator NBLog::HistogramEntry::copyWithAuthor(
312 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
313 // Current histogram entry has {type, length, struct HistTsEntry, length}.
314 // We now want {type, length, struct HistTsEntryWithAuthor, length}
315 uint8_t buffer[Entry::kOverhead + sizeof(HistTsEntryWithAuthor)];
316 // Copy content until the point we want to add the author
317 memcpy(buffer, mEntry, sizeof(entry) + sizeof(HistTsEntry));
318 // Copy the author
319 *(int*) (buffer + sizeof(entry) + sizeof(HistTsEntry)) = author;
320 // Update lengths
321 buffer[offsetof(entry, length)] = sizeof(HistTsEntryWithAuthor);
322 buffer[sizeof(buffer) + Entry::kPreviousLengthOffset] = sizeof(HistTsEntryWithAuthor);
323 // Write new buffer into FIFO
324 dst->write(buffer, sizeof(buffer));
325 return EntryIterator(mEntry).next();
326}
327
328// ---------------------------------------------------------------------------
329
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800330#if 0 // FIXME see note in NBLog.h
331NBLog::Timeline::Timeline(size_t size, void *shared)
332 : mSize(roundup(size)), mOwn(shared == NULL),
333 mShared((Shared *) (mOwn ? new char[sharedSize(size)] : shared))
334{
335 new (mShared) Shared;
336}
337
338NBLog::Timeline::~Timeline()
339{
340 mShared->~Shared();
341 if (mOwn) {
342 delete[] (char *) mShared;
343 }
344}
345#endif
346
347/*static*/
348size_t NBLog::Timeline::sharedSize(size_t size)
349{
Glenn Kastened99c2b2016-12-12 08:31:24 -0800350 // TODO fifo now supports non-power-of-2 buffer sizes, so could remove the roundup
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800351 return sizeof(Shared) + roundup(size);
352}
353
354// ---------------------------------------------------------------------------
355
356NBLog::Writer::Writer()
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800357 : mShared(NULL), mFifo(NULL), mFifoWriter(NULL), mEnabled(false), mPidTag(NULL), mPidTagSize(0)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800358{
359}
360
Glenn Kasten535e1612016-12-05 12:19:36 -0800361NBLog::Writer::Writer(void *shared, size_t size)
362 : mShared((Shared *) shared),
363 mFifo(mShared != NULL ?
364 new audio_utils_fifo(size, sizeof(uint8_t),
365 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
366 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL),
367 mEnabled(mFifoWriter != NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800368{
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800369 // caching pid and process name
370 pid_t id = ::getpid();
371 char procName[16];
372 int status = prctl(PR_GET_NAME, procName);
373 if (status) { // error getting process name
374 procName[0] = '\0';
375 }
376 size_t length = strlen(procName);
377 mPidTagSize = length + sizeof(pid_t);
378 mPidTag = new char[mPidTagSize];
379 memcpy(mPidTag, &id, sizeof(pid_t));
380 memcpy(mPidTag + sizeof(pid_t), procName, length);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800381}
382
Glenn Kasten535e1612016-12-05 12:19:36 -0800383NBLog::Writer::Writer(const sp<IMemory>& iMemory, size_t size)
384 : Writer(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800385{
Glenn Kasten535e1612016-12-05 12:19:36 -0800386 mIMemory = iMemory;
387}
388
389NBLog::Writer::~Writer()
390{
391 delete mFifoWriter;
392 delete mFifo;
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800393 delete[] mPidTag;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800394}
395
396void NBLog::Writer::log(const char *string)
397{
398 if (!mEnabled) {
399 return;
400 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800401 LOG_ALWAYS_FATAL_IF(string == NULL, "Attempted to log NULL string");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800402 size_t length = strlen(string);
Glenn Kasten535e1612016-12-05 12:19:36 -0800403 if (length > Entry::kMaxLength) {
404 length = Entry::kMaxLength;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800405 }
406 log(EVENT_STRING, string, length);
407}
408
409void NBLog::Writer::logf(const char *fmt, ...)
410{
411 if (!mEnabled) {
412 return;
413 }
414 va_list ap;
415 va_start(ap, fmt);
416 Writer::logvf(fmt, ap); // the Writer:: is needed to avoid virtual dispatch for LockedWriter
417 va_end(ap);
418}
419
420void NBLog::Writer::logvf(const char *fmt, va_list ap)
421{
422 if (!mEnabled) {
423 return;
424 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800425 char buffer[Entry::kMaxLength + 1 /*NUL*/];
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800426 int length = vsnprintf(buffer, sizeof(buffer), fmt, ap);
427 if (length >= (int) sizeof(buffer)) {
428 length = sizeof(buffer) - 1;
429 // NUL termination is not required
430 // buffer[length] = '\0';
431 }
432 if (length >= 0) {
433 log(EVENT_STRING, buffer, length);
434 }
435}
436
437void NBLog::Writer::logTimestamp()
438{
439 if (!mEnabled) {
440 return;
441 }
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700442 int64_t ts = get_monotonic_ns();
443 if (ts > 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800444 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700445 } else {
446 ALOGE("Failed to get timestamp");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800447 }
448}
449
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700450void NBLog::Writer::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800451{
452 if (!mEnabled) {
453 return;
454 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800455 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
456}
457
458void NBLog::Writer::logInteger(const int x)
459{
460 if (!mEnabled) {
461 return;
462 }
463 log(EVENT_INTEGER, &x, sizeof(x));
464}
465
466void NBLog::Writer::logFloat(const float x)
467{
468 if (!mEnabled) {
469 return;
470 }
471 log(EVENT_FLOAT, &x, sizeof(x));
472}
473
474void NBLog::Writer::logPID()
475{
476 if (!mEnabled) {
477 return;
478 }
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800479 log(EVENT_PID, mPidTag, mPidTagSize);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800480}
481
482void NBLog::Writer::logStart(const char *fmt)
483{
484 if (!mEnabled) {
485 return;
486 }
487 size_t length = strlen(fmt);
488 if (length > Entry::kMaxLength) {
489 length = Entry::kMaxLength;
490 }
491 log(EVENT_START_FMT, fmt, length);
492}
493
494void NBLog::Writer::logEnd()
495{
496 if (!mEnabled) {
497 return;
498 }
499 Entry entry = Entry(EVENT_END_FMT, NULL, 0);
500 log(&entry, true);
501}
502
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700503void NBLog::Writer::logHash(log_hash_t hash)
504{
505 if (!mEnabled) {
506 return;
507 }
508 log(EVENT_HASH, &hash, sizeof(hash));
509}
510
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700511void NBLog::Writer::logHistTS(log_hash_t hash)
512{
513 if (!mEnabled) {
514 return;
515 }
516 HistTsEntry data;
517 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700518 data.ts = get_monotonic_ns();
519 if (data.ts > 0) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700520 log(EVENT_HISTOGRAM_ENTRY_TS, &data, sizeof(data));
521 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700522 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700523 }
524}
525
526void NBLog::Writer::logHistFlush(log_hash_t hash)
527{
528 if (!mEnabled) {
529 return;
530 }
531 HistTsEntry data;
532 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700533 data.ts = get_monotonic_ns();
534 if (data.ts > 0) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700535 log(EVENT_HISTOGRAM_FLUSH, &data, sizeof(data));
536 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700537 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700538 }
539}
540
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700541void NBLog::Writer::logFormat(const char *fmt, log_hash_t hash, ...)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800542{
543 if (!mEnabled) {
544 return;
545 }
546
547 va_list ap;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700548 va_start(ap, hash);
549 Writer::logVFormat(fmt, hash, ap);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800550 va_end(ap);
551}
552
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700553void NBLog::Writer::logVFormat(const char *fmt, log_hash_t hash, va_list argp)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800554{
555 if (!mEnabled) {
556 return;
557 }
558 Writer::logStart(fmt);
559 int i;
560 double f;
561 char* s;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700562 int64_t t;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800563 Writer::logTimestamp();
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700564 Writer::logHash(hash);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800565 for (const char *p = fmt; *p != '\0'; p++) {
566 // TODO: implement more complex formatting such as %.3f
567 if (*p != '%') {
568 continue;
569 }
570 switch(*++p) {
571 case 's': // string
572 s = va_arg(argp, char *);
573 Writer::log(s);
574 break;
575
576 case 't': // timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700577 t = va_arg(argp, int64_t);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800578 Writer::logTimestamp(t);
579 break;
580
581 case 'd': // integer
582 i = va_arg(argp, int);
583 Writer::logInteger(i);
584 break;
585
586 case 'f': // float
587 f = va_arg(argp, double); // float arguments are promoted to double in vararg lists
588 Writer::logFloat((float)f);
589 break;
590
591 case 'p': // pid
592 Writer::logPID();
593 break;
594
595 // the "%\0" case finishes parsing
596 case '\0':
597 --p;
598 break;
599
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800600 case '%':
601 break;
602
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800603 default:
604 ALOGW("NBLog Writer parsed invalid format specifier: %c", *p);
605 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800606 }
607 }
608 Writer::logEnd();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800609}
610
611void NBLog::Writer::log(Event event, const void *data, size_t length)
612{
613 if (!mEnabled) {
614 return;
615 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800616 if (data == NULL || length > Entry::kMaxLength) {
617 // TODO Perhaps it makes sense to display truncated data or at least a
618 // message that the data is too long? The current behavior can create
619 // a confusion for a programmer debugging their code.
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800620 return;
621 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700622 // Ignore if invalid event
623 if (event == EVENT_RESERVED || event >= EVENT_UPPER_BOUND) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800624 return;
625 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700626 Entry etr(event, data, length);
627 log(&etr, true /*trusted*/);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800628}
629
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700630void NBLog::Writer::log(const NBLog::Entry *etr, bool trusted)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800631{
632 if (!mEnabled) {
633 return;
634 }
635 if (!trusted) {
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700636 log(etr->mEvent, etr->mData, etr->mLength);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800637 return;
638 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700639 size_t need = etr->mLength + Entry::kOverhead; // mEvent, mLength, data[mLength], mLength
640 // need = number of bytes written to FIFO
Glenn Kasten535e1612016-12-05 12:19:36 -0800641
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800642 // FIXME optimize this using memcpy for the data part of the Entry.
643 // The Entry could have a method copyTo(ptr, offset, size) to optimize the copy.
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700644 // checks size of a single log Entry: type, length, data pointer and ending
Glenn Kasten535e1612016-12-05 12:19:36 -0800645 uint8_t temp[Entry::kMaxLength + Entry::kOverhead];
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700646 // write this data to temp array
Glenn Kasten535e1612016-12-05 12:19:36 -0800647 for (size_t i = 0; i < need; i++) {
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700648 temp[i] = etr->copyEntryDataAt(i);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800649 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700650 // write to circular buffer
Glenn Kasten535e1612016-12-05 12:19:36 -0800651 mFifoWriter->write(temp, need);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800652}
653
654bool NBLog::Writer::isEnabled() const
655{
656 return mEnabled;
657}
658
659bool NBLog::Writer::setEnabled(bool enabled)
660{
661 bool old = mEnabled;
662 mEnabled = enabled && mShared != NULL;
663 return old;
664}
665
666// ---------------------------------------------------------------------------
667
668NBLog::LockedWriter::LockedWriter()
669 : Writer()
670{
671}
672
Glenn Kasten535e1612016-12-05 12:19:36 -0800673NBLog::LockedWriter::LockedWriter(void *shared, size_t size)
674 : Writer(shared, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800675{
676}
677
678void NBLog::LockedWriter::log(const char *string)
679{
680 Mutex::Autolock _l(mLock);
681 Writer::log(string);
682}
683
684void NBLog::LockedWriter::logf(const char *fmt, ...)
685{
686 // FIXME should not take the lock until after formatting is done
687 Mutex::Autolock _l(mLock);
688 va_list ap;
689 va_start(ap, fmt);
690 Writer::logvf(fmt, ap);
691 va_end(ap);
692}
693
694void NBLog::LockedWriter::logvf(const char *fmt, va_list ap)
695{
696 // FIXME should not take the lock until after formatting is done
697 Mutex::Autolock _l(mLock);
698 Writer::logvf(fmt, ap);
699}
700
701void NBLog::LockedWriter::logTimestamp()
702{
703 // FIXME should not take the lock until after the clock_gettime() syscall
704 Mutex::Autolock _l(mLock);
705 Writer::logTimestamp();
706}
707
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700708void NBLog::LockedWriter::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800709{
710 Mutex::Autolock _l(mLock);
711 Writer::logTimestamp(ts);
712}
713
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800714void NBLog::LockedWriter::logInteger(const int x)
715{
716 Mutex::Autolock _l(mLock);
717 Writer::logInteger(x);
718}
719
720void NBLog::LockedWriter::logFloat(const float x)
721{
722 Mutex::Autolock _l(mLock);
723 Writer::logFloat(x);
724}
725
726void NBLog::LockedWriter::logPID()
727{
728 Mutex::Autolock _l(mLock);
729 Writer::logPID();
730}
731
732void NBLog::LockedWriter::logStart(const char *fmt)
733{
734 Mutex::Autolock _l(mLock);
735 Writer::logStart(fmt);
736}
737
738
739void NBLog::LockedWriter::logEnd()
740{
741 Mutex::Autolock _l(mLock);
742 Writer::logEnd();
743}
744
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700745void NBLog::LockedWriter::logHash(log_hash_t hash)
746{
747 Mutex::Autolock _l(mLock);
748 Writer::logHash(hash);
749}
750
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800751bool NBLog::LockedWriter::isEnabled() const
752{
753 Mutex::Autolock _l(mLock);
754 return Writer::isEnabled();
755}
756
757bool NBLog::LockedWriter::setEnabled(bool enabled)
758{
759 Mutex::Autolock _l(mLock);
760 return Writer::setEnabled(enabled);
761}
762
763// ---------------------------------------------------------------------------
764
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700765const std::set<NBLog::Event> NBLog::Reader::startingTypes {NBLog::Event::EVENT_START_FMT,
766 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
767const std::set<NBLog::Event> NBLog::Reader::endingTypes {NBLog::Event::EVENT_END_FMT,
768 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
769 NBLog::Event::EVENT_HISTOGRAM_FLUSH};
Glenn Kasten535e1612016-12-05 12:19:36 -0800770NBLog::Reader::Reader(const void *shared, size_t size)
771 : mShared((/*const*/ Shared *) shared), /*mIMemory*/
772 mFd(-1), mIndent(0),
773 mFifo(mShared != NULL ?
774 new audio_utils_fifo(size, sizeof(uint8_t),
775 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -0700776 mFifoReader(mFifo != NULL ? new audio_utils_fifo_reader(*mFifo) : NULL),
777 findGlitch(false)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800778{
779}
780
Glenn Kasten535e1612016-12-05 12:19:36 -0800781NBLog::Reader::Reader(const sp<IMemory>& iMemory, size_t size)
782 : Reader(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800783{
Glenn Kasten535e1612016-12-05 12:19:36 -0800784 mIMemory = iMemory;
785}
786
787NBLog::Reader::~Reader()
788{
789 delete mFifoReader;
790 delete mFifo;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800791}
792
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -0700793inline static int deltaMs(int64_t ns1, int64_t ns2) {
794 return (ns2 - ns1) / (1000 * 1000);
795}
796
797// Produces a log warning if the timing of recent buffer periods caused a glitch
798// Computes sum of running window of three buffer periods
799// Checks whether the buffer periods leave enough CPU time for the next one
800// e.g. if a buffer period is expected to be 4 ms and a buffer requires 3 ms of CPU time,
801// here are some glitch cases:
802// 4 + 4 + 6 ; 5 + 4 + 5; 2 + 2 + 10
803// TODO: develop this code to track changes in histogram distribution in addition
804// to / instead of glitches
805void NBLog::Reader::alertIfGlitch(const std::vector<int64_t> &samples) {
806 //TODO: measure kPeriodLen and kRatio from the data as they may change.
807 static const int kPeriodLen = 4; // current period length is ideally 4 ms
808 static const double kRatio = 0.75; // estimate of CPU time as ratio of period length
809 // DAC processing time for 4 ms buffer
810 static const int kPeriodTime = static_cast<int>(round(kPeriodLen * kRatio));
811 static const int kNumBuff = 3; // number of buffers considered in local history
812 std::deque<int> periods(kNumBuff, kPeriodLen);
813 for (size_t i = 2; i < samples.size(); ++i) { // skip first time entry
814 periods.push_front(deltaMs(samples[i - 1], samples[i]));
815 periods.pop_back();
816 // TODO: check that all glitch cases are covered
817 if (std::accumulate(periods.begin(), periods.end(), 0) > kNumBuff * kPeriodLen +
818 kPeriodLen - kPeriodTime) {
819 ALOGW("A glitch occurred");
820 periods.assign(kNumBuff, kPeriodLen);
821 }
822 }
823 return;
824}
825
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700826const uint8_t *NBLog::Reader::findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
827 const std::set<Event> &types) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800828 while (back + Entry::kPreviousLengthOffset >= front) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700829 const uint8_t *prev = back - back[Entry::kPreviousLengthOffset] - Entry::kOverhead;
830 if (prev < front || prev + prev[offsetof(entry, length)] +
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800831 Entry::kOverhead != back) {
832
833 // prev points to an out of limits or inconsistent entry
834 return nullptr;
835 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700836 if (types.find((const Event) prev[offsetof(entry, type)]) != types.end()) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800837 return prev;
838 }
839 back = prev;
840 }
841 return nullptr; // no entry found
842}
843
Nicolas Roulet40a44982017-02-03 13:39:57 -0800844std::unique_ptr<NBLog::Reader::Snapshot> NBLog::Reader::getSnapshot()
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800845{
Glenn Kasten535e1612016-12-05 12:19:36 -0800846 if (mFifoReader == NULL) {
Nicolas Roulet40a44982017-02-03 13:39:57 -0800847 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800848 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800849 // make a copy to avoid race condition with writer
Glenn Kasten535e1612016-12-05 12:19:36 -0800850 size_t capacity = mFifo->capacity();
851
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800852 // This emulates the behaviour of audio_utils_fifo_reader::read, but without incrementing the
853 // reader index. The index is incremented after handling corruption, to after the last complete
854 // entry of the buffer
855 size_t lost;
856 audio_utils_iovec iovec[2];
857 ssize_t availToRead = mFifoReader->obtain(iovec, capacity, NULL /*timeout*/, &lost);
858 if (availToRead <= 0) {
859 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
860 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800861
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800862 std::unique_ptr<Snapshot> snapshot(new Snapshot(availToRead));
863 memcpy(snapshot->mData, (const char *) mFifo->buffer() + iovec[0].mOffset, iovec[0].mLength);
864 if (iovec[1].mLength > 0) {
865 memcpy(snapshot->mData + (iovec[0].mLength),
866 (const char *) mFifo->buffer() + iovec[1].mOffset, iovec[1].mLength);
867 }
868
869 // Handle corrupted buffer
870 // Potentially, a buffer has corrupted data on both beginning (due to overflow) and end
871 // (due to incomplete format entry). But even if the end format entry is incomplete,
872 // it ends in a complete entry (which is not an END_FMT). So is safe to traverse backwards.
873 // TODO: handle client corruption (in the middle of a buffer)
874
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700875 const uint8_t *back = snapshot->mData + availToRead;
876 const uint8_t *front = snapshot->mData;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800877
878 // Find last END_FMT. <back> is sitting on an entry which might be the middle of a FormatEntry.
879 // We go backwards until we find an EVENT_END_FMT.
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700880 const uint8_t *lastEnd = findLastEntryOfTypes(front, back, endingTypes);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800881 if (lastEnd == nullptr) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700882 snapshot->mEnd = snapshot->mBegin = EntryIterator(front);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800883 } else {
884 // end of snapshot points to after last END_FMT entry
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700885 snapshot->mEnd = EntryIterator(lastEnd).next();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800886 // find first START_FMT
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700887 const uint8_t *firstStart = nullptr;
888 const uint8_t *firstStartTmp = snapshot->mEnd;
889 while ((firstStartTmp = findLastEntryOfTypes(front, firstStartTmp, startingTypes))
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800890 != nullptr) {
891 firstStart = firstStartTmp;
892 }
893 // firstStart is null if no START_FMT entry was found before lastEnd
894 if (firstStart == nullptr) {
895 snapshot->mBegin = snapshot->mEnd;
896 } else {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700897 snapshot->mBegin = EntryIterator(firstStart);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800898 }
899 }
900
901 // advance fifo reader index to after last entry read.
902 mFifoReader->release(snapshot->mEnd - front);
903
904 snapshot->mLost = lost;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800905 return snapshot;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800906
Nicolas Roulet40a44982017-02-03 13:39:57 -0800907}
908
909void NBLog::Reader::dump(int fd, size_t indent, NBLog::Reader::Snapshot &snapshot)
910{
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700911 // CallStack cs(LOG_TAG);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800912#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800913 struct timespec ts;
914 time_t maxSec = -1;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800915 while (entry - start >= (int) Entry::kOverhead) {
916 if (prevEntry - start < 0 || !prevEntry.hasConsistentLength()) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800917 break;
918 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800919 if (prevEntry->type == EVENT_TIMESTAMP) {
920 if (prevEntry->length != sizeof(struct timespec)) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800921 // corrupt
922 break;
923 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800924 prevEntry.copyData((uint8_t*) &ts);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800925 if (ts.tv_sec > maxSec) {
926 maxSec = ts.tv_sec;
927 }
928 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800929 --entry;
930 --prevEntry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800931 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800932#endif
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700933 mFd = fd;
934 mIndent = indent;
935 String8 timestamp, body;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700936 size_t lost = snapshot.lost() + (snapshot.begin() - EntryIterator(snapshot.data()));
Glenn Kastenc02c9612013-10-15 09:25:11 -0700937 if (lost > 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700938 body.appendFormat("warning: lost %zu bytes worth of events", lost);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700939 // TODO timestamp empty here, only other choice to wait for the first timestamp event in the
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700940 // log to push it out. Consider keeping the timestamp/body between calls to copyEntryDataAt().
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700941 dumpLine(timestamp, body);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800942 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800943#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800944 size_t width = 1;
945 while (maxSec >= 10) {
946 ++width;
947 maxSec /= 10;
948 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800949 if (maxSec >= 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700950 timestamp.appendFormat("[%*s]", (int) width + 4, "");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800951 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700952 bool deferredTimestamp = false;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800953#endif
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700954
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800955 for (auto entry = snapshot.begin(); entry != snapshot.end();) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800956 switch (entry->type) {
957#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800958 case EVENT_STRING:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800959 body.appendFormat("%.*s", (int) entry.length(), entry.data());
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700960 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800961 case EVENT_TIMESTAMP: {
962 // already checked that length == sizeof(struct timespec);
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800963 entry.copyData((const uint8_t*) &ts);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800964 long prevNsec = ts.tv_nsec;
965 long deltaMin = LONG_MAX;
966 long deltaMax = -1;
967 long deltaTotal = 0;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800968 auto aux(entry);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800969 for (;;) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800970 ++aux;
971 if (end - aux >= 0 || aux.type() != EVENT_TIMESTAMP) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800972 break;
973 }
974 struct timespec tsNext;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800975 aux.copyData((const uint8_t*) &tsNext);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800976 if (tsNext.tv_sec != ts.tv_sec) {
977 break;
978 }
979 long delta = tsNext.tv_nsec - prevNsec;
980 if (delta < 0) {
981 break;
982 }
983 if (delta < deltaMin) {
984 deltaMin = delta;
985 }
986 if (delta > deltaMax) {
987 deltaMax = delta;
988 }
989 deltaTotal += delta;
990 prevNsec = tsNext.tv_nsec;
991 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800992 size_t n = (aux - entry) / (sizeof(struct timespec) + 3 /*Entry::kOverhead?*/);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700993 if (deferredTimestamp) {
994 dumpLine(timestamp, body);
995 deferredTimestamp = false;
996 }
997 timestamp.clear();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800998 if (n >= kSquashTimestamp) {
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700999 timestamp.appendFormat("[%d.%03d to .%.03d by .%.03d to .%.03d]",
1000 (int) ts.tv_sec, (int) (ts.tv_nsec / 1000000),
1001 (int) ((ts.tv_nsec + deltaTotal) / 1000000),
1002 (int) (deltaMin / 1000000), (int) (deltaMax / 1000000));
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001003 entry = aux;
1004 // advance = 0;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001005 break;
1006 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -07001007 timestamp.appendFormat("[%d.%03d]", (int) ts.tv_sec,
1008 (int) (ts.tv_nsec / 1000000));
1009 deferredTimestamp = true;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001010 }
1011 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001012 case EVENT_INTEGER:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001013 appendInt(&body, entry.data());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001014 break;
1015 case EVENT_FLOAT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001016 appendFloat(&body, entry.data());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001017 break;
1018 case EVENT_PID:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001019 appendPID(&body, entry.data(), entry.length());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001020 break;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001021#endif
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001022 case EVENT_START_FMT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001023 entry = handleFormat(FormatEntry(entry), &timestamp, &body);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001024 break;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001025 case EVENT_HISTOGRAM_ENTRY_TS: {
1026 HistTsEntryWithAuthor *data = (HistTsEntryWithAuthor *) (entry->data);
1027 // TODO This memcpies are here to avoid unaligned memory access crash.
1028 // There's probably a more efficient way to do it
1029 log_hash_t hash;
1030 memcpy(&hash, &(data->hash), sizeof(hash));
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001031 int64_t ts;
1032 memcpy(&ts, &data->ts, sizeof(ts));
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001033 const std::pair<log_hash_t, int> key(hash, data->author);
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001034 // TODO might want to filter excessively high outliers, which are usually caused
1035 // by the thread being inactive.
1036 mHists[key].push_back(ts);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001037 ++entry;
1038 break;
1039 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -07001040 // draws histograms stored in global Reader::mHists and erases them
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001041 case EVENT_HISTOGRAM_FLUSH: {
1042 HistogramEntry histEntry(entry);
1043 // Log timestamp
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -07001044 // Timestamp of call to drawHistogram, not when audio was generated
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001045 const int64_t ts = histEntry.timestamp();
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001046 timestamp.clear();
1047 timestamp.appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1048 (int) ((ts / (1000 * 1000)) % 1000));
1049 // Log histograms
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -07001050 setFindGlitch(true);
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001051 body.appendFormat("Histogram flush - ");
1052 handleAuthor(histEntry, &body);
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001053 for (auto hist = mHists.begin(); hist != mHists.end();) {
1054 if (hist->first.second == histEntry.author()) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001055 body.appendFormat("%X", (int)hist->first.first);
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -07001056 if (findGlitch) {
1057 alertIfGlitch(hist->second);
1058 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -07001059 // validateFirstTimestamp(hist->second);
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001060 drawHistogram(&body, hist->second, true, indent);
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001061 hist = mHists.erase(hist);
1062 } else {
1063 ++hist;
1064 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001065 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001066 ++entry;
1067 break;
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001068 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001069 case EVENT_END_FMT:
1070 body.appendFormat("warning: got to end format event");
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001071 ++entry;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001072 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001073 case EVENT_RESERVED:
1074 default:
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001075 body.appendFormat("warning: unexpected event %d", entry->type);
1076 ++entry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001077 break;
1078 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -07001079
1080 if (!body.isEmpty()) {
1081 dumpLine(timestamp, body);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001082 // deferredTimestamp = false;
Glenn Kasten4e01ef62013-07-11 14:29:59 -07001083 }
1084 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001085 // if (deferredTimestamp) {
1086 // dumpLine(timestamp, body);
1087 // }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001088}
1089
Nicolas Roulet40a44982017-02-03 13:39:57 -08001090void NBLog::Reader::dump(int fd, size_t indent)
1091{
1092 // get a snapshot, dump it
1093 std::unique_ptr<Snapshot> snap = getSnapshot();
1094 dump(fd, indent, *snap);
1095}
1096
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001097void NBLog::Reader::dumpLine(const String8 &timestamp, String8 &body)
Glenn Kasten4e01ef62013-07-11 14:29:59 -07001098{
1099 if (mFd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07001100 dprintf(mFd, "%.*s%s %s\n", mIndent, "", timestamp.string(), body.string());
Glenn Kasten4e01ef62013-07-11 14:29:59 -07001101 } else {
1102 ALOGI("%.*s%s %s", mIndent, "", timestamp.string(), body.string());
1103 }
1104 body.clear();
1105}
1106
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001107bool NBLog::Reader::isIMemory(const sp<IMemory>& iMemory) const
1108{
Glenn Kasten481fb672013-09-30 14:39:28 -07001109 return iMemory != 0 && mIMemory != 0 && iMemory->pointer() == mIMemory->pointer();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001110}
1111
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -07001112void NBLog::Reader::setFindGlitch(bool s)
1113{
1114 findGlitch = s;
1115}
1116
1117bool NBLog::Reader::isFindGlitch() const
1118{
1119 return findGlitch;
1120}
1121
Glenn Kasten1c446272017-04-07 09:49:07 -07001122// ---------------------------------------------------------------------------
1123
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001124void NBLog::appendTimestamp(String8 *body, const void *data) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001125 int64_t ts;
1126 memcpy(&ts, data, sizeof(ts));
1127 body->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1128 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001129}
1130
1131void NBLog::appendInt(String8 *body, const void *data) {
1132 int x = *((int*) data);
1133 body->appendFormat("<%d>", x);
1134}
1135
1136void NBLog::appendFloat(String8 *body, const void *data) {
1137 float f;
1138 memcpy(&f, data, sizeof(float));
1139 body->appendFormat("<%f>", f);
1140}
1141
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001142void NBLog::appendPID(String8 *body, const void* data, size_t length) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001143 pid_t id = *((pid_t*) data);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001144 char * name = &((char*) data)[sizeof(pid_t)];
1145 body->appendFormat("<PID: %d, name: %.*s>", id, (int) (length - sizeof(pid_t)), name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001146}
1147
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001148String8 NBLog::bufferDump(const uint8_t *buffer, size_t size)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001149{
1150 String8 str;
1151 str.append("[ ");
1152 for(size_t i = 0; i < size; i++)
1153 {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001154 str.appendFormat("%d ", buffer[i]);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001155 }
1156 str.append("]");
1157 return str;
1158}
1159
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001160String8 NBLog::bufferDump(const EntryIterator &it)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001161{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001162 return bufferDump(it, it->length + Entry::kOverhead);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001163}
1164
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001165NBLog::EntryIterator NBLog::Reader::handleFormat(const FormatEntry &fmtEntry,
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001166 String8 *timestamp,
1167 String8 *body) {
Nicolas Roulet40a44982017-02-03 13:39:57 -08001168 // log timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001169 int64_t ts = fmtEntry.timestamp();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001170 timestamp->clear();
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001171 timestamp->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1172 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Roulet40a44982017-02-03 13:39:57 -08001173
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -07001174 // log unique hash
1175 log_hash_t hash = fmtEntry.hash();
1176 // print only lower 16bit of hash as hex and line as int to reduce spam in the log
1177 body->appendFormat("%.4X-%d ", (int)(hash >> 16) & 0xFFFF, (int) hash & 0xFFFF);
1178
Nicolas Roulet40a44982017-02-03 13:39:57 -08001179 // log author (if present)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001180 handleAuthor(fmtEntry, body);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001181
1182 // log string
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001183 NBLog::EntryIterator arg = fmtEntry.args();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001184
1185 const char* fmt = fmtEntry.formatString();
1186 size_t fmt_length = fmtEntry.formatStringLength();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001187
1188 for (size_t fmt_offset = 0; fmt_offset < fmt_length; ++fmt_offset) {
1189 if (fmt[fmt_offset] != '%') {
1190 body->append(&fmt[fmt_offset], 1); // TODO optimize to write consecutive strings at once
1191 continue;
1192 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001193 // case "%%""
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001194 if (fmt[++fmt_offset] == '%') {
1195 body->append("%");
1196 continue;
1197 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001198 // case "%\0"
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001199 if (fmt_offset == fmt_length) {
1200 continue;
1201 }
1202
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001203 NBLog::Event event = (NBLog::Event) arg->type;
1204 size_t length = arg->length;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001205
1206 // TODO check length for event type is correct
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001207
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001208 if (event == EVENT_END_FMT) {
1209 break;
1210 }
1211
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001212 // TODO: implement more complex formatting such as %.3f
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001213 const uint8_t *datum = arg->data; // pointer to the current event args
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001214 switch(fmt[fmt_offset])
1215 {
1216 case 's': // string
Nicolas Roulet4da78202017-02-03 12:53:39 -08001217 ALOGW_IF(event != EVENT_STRING,
1218 "NBLog Reader incompatible event for string specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001219 body->append((const char*) datum, length);
1220 break;
1221
1222 case 't': // timestamp
Nicolas Roulet4da78202017-02-03 12:53:39 -08001223 ALOGW_IF(event != EVENT_TIMESTAMP,
1224 "NBLog Reader incompatible event for timestamp specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001225 appendTimestamp(body, datum);
1226 break;
1227
1228 case 'd': // integer
Nicolas Roulet4da78202017-02-03 12:53:39 -08001229 ALOGW_IF(event != EVENT_INTEGER,
1230 "NBLog Reader incompatible event for integer specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001231 appendInt(body, datum);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001232 break;
1233
1234 case 'f': // float
Nicolas Roulet4da78202017-02-03 12:53:39 -08001235 ALOGW_IF(event != EVENT_FLOAT,
1236 "NBLog Reader incompatible event for float specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001237 appendFloat(body, datum);
1238 break;
1239
1240 case 'p': // pid
Nicolas Roulet4da78202017-02-03 12:53:39 -08001241 ALOGW_IF(event != EVENT_PID,
1242 "NBLog Reader incompatible event for pid specifier: %d", event);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001243 appendPID(body, datum, length);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001244 break;
1245
1246 default:
1247 ALOGW("NBLog Reader encountered unknown character %c", fmt[fmt_offset]);
1248 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001249 ++arg;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001250 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001251 ALOGW_IF(arg->type != EVENT_END_FMT, "Expected end of format, got %d", arg->type);
1252 ++arg;
1253 return arg;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001254}
1255
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001256static int widthOf(int x) {
1257 int width = 0;
1258 while (x > 0) {
1259 ++width;
1260 x /= 10;
1261 }
1262 return width;
1263}
1264
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001265static std::map<int, int> buildBuckets(const std::vector<int64_t> &samples) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001266 // TODO allow buckets of variable resolution
1267 std::map<int, int> buckets;
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001268 for (size_t i = 1; i < samples.size(); ++i) {
1269 ++buckets[deltaMs(samples[i - 1], samples[i])];
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001270 }
1271 return buckets;
1272}
1273
Nicolas Roulet4f033492017-04-03 19:17:03 -07001274static inline uint32_t log2(uint32_t x) {
1275 // This works for x > 0
1276 return 31 - __builtin_clz(x);
1277}
1278
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001279// TODO put this function in separate file. Make it return a std::string instead of modifying body
Nicolas Roulet4f033492017-04-03 19:17:03 -07001280/*
1281Example output:
1282[54.234] Histogram flush - AudioOut_D:
1283Histogram 33640BF1
1284 [ 1][ 1][ 1][ 3][54][69][ 1][ 2][ 1]
1285 64| []
1286 32| [] []
1287 16| [] []
1288 8| [] []
1289 4| [] []
1290 2|______________[]__[]__[]______[]____
1291 4 5 6 8 9 10 11 13 15
1292Notice that all values that fall in the same row have the same height (65 and 127 are displayed
1293identically). That's why exact counts are added at the top.
1294*/
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001295void NBLog::Reader::drawHistogram(String8 *body,
1296 const std::vector<int64_t> &samples,
Nicolas Roulet4f033492017-04-03 19:17:03 -07001297 bool logScale,
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001298 int indent,
1299 int maxHeight) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001300 // this avoids some corner cases
Nicolas Roulet4f033492017-04-03 19:17:03 -07001301 if (samples.size() <= 1) {
1302 return;
1303 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -07001304 // temp code for debugging the outlier timestamp
1305 const int kMaxMs = 100;
1306 for (size_t i = 1; i < samples.size()-1; ++i) {
1307 const int currDelta = deltaMs(samples[i - 1], samples[i]);
1308 if (currDelta > kMaxMs) {
1309 body->appendFormat("\nlocation: %zu, size: %zu, pos from end: %zu, %d\t", i,
1310 samples.size(), samples.size() - i, currDelta);
1311 }
1312 }
1313 // FIXME: as can be seen when printing the values, the outlier timestamps typically occur
1314 // in the first histogram 35 to 38 indices from the end (most often 35).
1315 // TODO: build histogram buckets earlier and discard timestamps to save memory
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001316 std::map<int, int> buckets = buildBuckets(samples);
Nicolas Roulet4f033492017-04-03 19:17:03 -07001317 // TODO consider changing all ints to uint32_t or uint64_t
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001318
1319 // underscores and spaces length corresponds to maximum width of histogram
1320 static const int kLen = 40;
1321 std::string underscores(kLen, '-');
1322 std::string spaces(kLen, ' ');
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001323
1324 auto it = buckets.begin();
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001325 int maxDelta = it->first;
1326 int maxCount = it->second;
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001327 // Compute maximum values
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001328 while (++it != buckets.end()) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001329 if (it->first > maxDelta) {
1330 maxDelta = it->first;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001331 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001332 if (it->second > maxCount) {
1333 maxCount = it->second;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001334 }
1335 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001336 int height = logScale ? log2(maxCount) + 1 : maxCount; // maxCount > 0, safe to call log2
1337 const int leftPadding = widthOf(logScale ? pow(2, height) : maxCount);
1338 const int colWidth = std::max(std::max(widthOf(maxDelta) + 1, 3), leftPadding + 2);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001339 int scalingFactor = 1;
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001340 // scale data if it exceeds maximum height
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001341 if (height > maxHeight) {
1342 scalingFactor = (height + maxHeight) / maxHeight;
1343 height /= scalingFactor;
1344 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001345 body->appendFormat("\n%*s", leftPadding + 11, "Occurrences");
1346 // write histogram label line with bucket values
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001347 body->appendFormat("\n%*s", indent, " ");
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001348 body->appendFormat("%*s", leftPadding, " ");
1349 for (auto const &x : buckets) {
1350 body->appendFormat("%*d", colWidth, x.second);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001351 }
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001352 // write histogram ascii art
1353 body->appendFormat("\n%*s", indent, " ");
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001354 for (int row = height * scalingFactor; row >= 0; row -= scalingFactor) {
1355 const int value = logScale ? (1 << row) : row;
1356 body->appendFormat("%.*s", leftPadding, spaces.c_str());
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001357 for (auto const &x : buckets) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001358 body->appendFormat("%.*s%s", colWidth - 1, spaces.c_str(), x.second < value ? " " : "|");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001359 }
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001360 body->appendFormat("\n%*s", indent, " ");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001361 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001362 // print x-axis
1363 const int columns = static_cast<int>(buckets.size());
1364 body->appendFormat("%*c", leftPadding, ' ');
1365 body->appendFormat("%.*s", (columns + 1) * colWidth, underscores.c_str());
1366 body->appendFormat("\n%*s", indent, " ");
1367
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001368 // write footer with bucket labels
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001369 body->appendFormat("%*s", leftPadding, " ");
1370 for (auto const &x : buckets) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001371 body->appendFormat("%*d", colWidth, x.first);
1372 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001373 body->appendFormat("%.*s%s", colWidth, spaces.c_str(), "ms\n");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001374}
1375
Nicolas Roulet40a44982017-02-03 13:39:57 -08001376NBLog::Merger::Merger(const void *shared, size_t size):
Nicolas Roulet40a44982017-02-03 13:39:57 -08001377 mShared((Shared *) shared),
1378 mFifo(mShared != NULL ?
1379 new audio_utils_fifo(size, sizeof(uint8_t),
1380 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
1381 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL)
1382 {}
1383
1384void NBLog::Merger::addReader(const NBLog::NamedReader &reader) {
Glenn Kasten1c446272017-04-07 09:49:07 -07001385 // FIXME This is called by binder thread in MediaLogService::registerWriter
1386 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001387 mNamedReaders.push_back(reader);
1388}
1389
1390// items placed in priority queue during merge
1391// composed by a timestamp and the index of the snapshot where the timestamp came from
1392struct MergeItem
1393{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001394 int64_t ts;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001395 int index;
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001396 MergeItem(int64_t ts, int index): ts(ts), index(index) {}
Nicolas Roulet40a44982017-02-03 13:39:57 -08001397};
1398
1399// operators needed for priority queue in merge
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001400// bool operator>(const int64_t &t1, const int64_t &t2) {
1401// return t1.tv_sec > t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec);
1402// }
Nicolas Roulet40a44982017-02-03 13:39:57 -08001403
1404bool operator>(const struct MergeItem &i1, const struct MergeItem &i2) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001405 return i1.ts > i2.ts || (i1.ts == i2.ts && i1.index > i2.index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001406}
1407
1408// Merge registered readers, sorted by timestamp
1409void NBLog::Merger::merge() {
Glenn Kasten1c446272017-04-07 09:49:07 -07001410 // FIXME This is called by merge thread
1411 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001412 int nLogs = mNamedReaders.size();
1413 std::vector<std::unique_ptr<NBLog::Reader::Snapshot>> snapshots(nLogs);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001414 std::vector<NBLog::EntryIterator> offsets(nLogs);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001415 for (int i = 0; i < nLogs; ++i) {
1416 snapshots[i] = mNamedReaders[i].reader()->getSnapshot();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001417 offsets[i] = snapshots[i]->begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001418 }
1419 // initialize offsets
Nicolas Roulet40a44982017-02-03 13:39:57 -08001420 // TODO custom heap implementation could allow to update top, improving performance
1421 // for bursty buffers
1422 std::priority_queue<MergeItem, std::vector<MergeItem>, std::greater<MergeItem>> timestamps;
1423 for (int i = 0; i < nLogs; ++i)
1424 {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001425 if (offsets[i] != snapshots[i]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001426 int64_t ts = AbstractEntry::buildEntry(offsets[i])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001427 timestamps.emplace(ts, i);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001428 }
1429 }
1430
1431 while (!timestamps.empty()) {
1432 // find minimum timestamp
1433 int index = timestamps.top().index;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001434 // copy it to the log, increasing offset
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001435 offsets[index] = AbstractEntry::buildEntry(offsets[index])->copyWithAuthor(mFifoWriter,
1436 index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001437 // update data structures
Nicolas Roulet40a44982017-02-03 13:39:57 -08001438 timestamps.pop();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001439 if (offsets[index] != snapshots[index]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001440 int64_t ts = AbstractEntry::buildEntry(offsets[index])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001441 timestamps.emplace(ts, index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001442 }
1443 }
1444}
1445
Glenn Kasten1c446272017-04-07 09:49:07 -07001446const std::vector<NBLog::NamedReader>& NBLog::Merger::getNamedReaders() const {
1447 // FIXME This is returning a reference to a shared variable that needs a lock
1448 return mNamedReaders;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001449}
1450
Glenn Kasten1c446272017-04-07 09:49:07 -07001451// ---------------------------------------------------------------------------
1452
Nicolas Roulet40a44982017-02-03 13:39:57 -08001453NBLog::MergeReader::MergeReader(const void *shared, size_t size, Merger &merger)
1454 : Reader(shared, size), mNamedReaders(merger.getNamedReaders()) {}
1455
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001456void NBLog::MergeReader::handleAuthor(const NBLog::AbstractEntry &entry, String8 *body) {
1457 int author = entry.author();
Glenn Kasten1c446272017-04-07 09:49:07 -07001458 // FIXME Needs a lock
1459 const char* name = mNamedReaders[author].name();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001460 body->appendFormat("%s: ", name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001461}
1462
Glenn Kasten1c446272017-04-07 09:49:07 -07001463// ---------------------------------------------------------------------------
1464
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001465NBLog::MergeThread::MergeThread(NBLog::Merger &merger)
1466 : mMerger(merger),
1467 mTimeoutUs(0) {}
1468
1469NBLog::MergeThread::~MergeThread() {
1470 // set exit flag, set timeout to 0 to force threadLoop to exit and wait for the thread to join
1471 requestExit();
1472 setTimeoutUs(0);
1473 join();
1474}
1475
1476bool NBLog::MergeThread::threadLoop() {
1477 bool doMerge;
1478 {
1479 AutoMutex _l(mMutex);
1480 // If mTimeoutUs is negative, wait on the condition variable until it's positive.
1481 // If it's positive, wait kThreadSleepPeriodUs and then merge
1482 nsecs_t waitTime = mTimeoutUs > 0 ? kThreadSleepPeriodUs * 1000 : LLONG_MAX;
1483 mCond.waitRelative(mMutex, waitTime);
1484 doMerge = mTimeoutUs > 0;
1485 mTimeoutUs -= kThreadSleepPeriodUs;
1486 }
1487 if (doMerge) {
1488 mMerger.merge();
1489 }
1490 return true;
1491}
1492
1493void NBLog::MergeThread::wakeup() {
1494 setTimeoutUs(kThreadWakeupPeriodUs);
1495}
1496
1497void NBLog::MergeThread::setTimeoutUs(int time) {
1498 AutoMutex _l(mMutex);
1499 mTimeoutUs = time;
1500 mCond.signal();
1501}
1502
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001503} // namespace android