blob: 4516fc4c0e8a195bea2b2bccc45868bdd8fc56ab [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
17#define LOG_TAG "NBLog"
18//#define LOG_NDEBUG 0
19
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -080020#include <climits>
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -070021#include <deque>
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -070022#include <math.h>
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -070023#include <numeric>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080024#include <stdarg.h>
25#include <stdint.h>
26#include <stdio.h>
27#include <string.h>
Nicolas Rouletc20cb502017-02-01 12:35:24 -080028#include <sys/prctl.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080029#include <time.h>
30#include <new>
Glenn Kasten535e1612016-12-05 12:19:36 -080031#include <audio_utils/roundup.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080032#include <media/nbaio/NBLog.h>
33#include <utils/Log.h>
Glenn Kasten4e01ef62013-07-11 14:29:59 -070034#include <utils/String8.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080035
Nicolas Roulet40a44982017-02-03 13:39:57 -080036#include <queue>
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070037#include <utility>
Nicolas Roulet40a44982017-02-03 13:39:57 -080038
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080039namespace android {
40
41int NBLog::Entry::readAt(size_t offset) const
42{
43 // FIXME This is too slow, despite the name it is used during writing
44 if (offset == 0)
45 return mEvent;
46 else if (offset == 1)
47 return mLength;
48 else if (offset < (size_t) (mLength + 2))
49 return ((char *) mData)[offset - 2];
50 else if (offset == (size_t) (mLength + 2))
51 return mLength;
52 else
53 return 0;
54}
55
56// ---------------------------------------------------------------------------
57
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070058/*static*/
59std::unique_ptr<NBLog::AbstractEntry> NBLog::AbstractEntry::buildEntry(const uint8_t *ptr) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -070060 const uint8_t type = EntryIterator(ptr)->type;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070061 switch (type) {
62 case EVENT_START_FMT:
63 return std::make_unique<FormatEntry>(FormatEntry(ptr));
64 case EVENT_HISTOGRAM_FLUSH:
65 case EVENT_HISTOGRAM_ENTRY_TS:
66 return std::make_unique<HistogramEntry>(HistogramEntry(ptr));
67 default:
68 ALOGW("Tried to create AbstractEntry of type %d", type);
69 return nullptr;
70 }
Nicolas Roulet40a44982017-02-03 13:39:57 -080071}
72
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070073NBLog::AbstractEntry::AbstractEntry(const uint8_t *entry) : mEntry(entry) {
74}
75
76// ---------------------------------------------------------------------------
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080077
Nicolas Roulet40a44982017-02-03 13:39:57 -080078const char *NBLog::FormatEntry::formatString() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080079 return (const char*) mEntry + offsetof(entry, data);
Nicolas Roulet40a44982017-02-03 13:39:57 -080080}
81
82size_t NBLog::FormatEntry::formatStringLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080083 return mEntry[offsetof(entry, length)];
Nicolas Roulet40a44982017-02-03 13:39:57 -080084}
85
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070086NBLog::EntryIterator NBLog::FormatEntry::args() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080087 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -070088 // skip start fmt
89 ++it;
90 // skip timestamp
91 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -070092 // skip hash
93 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -070094 // Skip author if present
95 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080096 ++it;
Nicolas Roulet40a44982017-02-03 13:39:57 -080097 }
Nicolas Roulet1ca75122017-03-16 14:19:59 -070098 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -080099}
100
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700101int64_t NBLog::FormatEntry::timestamp() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800102 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700103 // skip start fmt
104 ++it;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700105 return it.payload<int64_t>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800106}
107
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700108NBLog::log_hash_t NBLog::FormatEntry::hash() const {
109 auto it = begin();
110 // skip start fmt
111 ++it;
112 // skip timestamp
113 ++it;
114 // unaligned 64-bit read not supported
115 log_hash_t hash;
116 memcpy(&hash, it->data, sizeof(hash));
117 return hash;
118}
119
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700120int NBLog::FormatEntry::author() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800121 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700122 // skip start fmt
123 ++it;
124 // skip timestamp
125 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700126 // skip hash
127 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700128 // if there is an author entry, return it, return -1 otherwise
129 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800130 return it.payload<int>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800131 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800132 return -1;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800133}
134
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700135NBLog::EntryIterator NBLog::FormatEntry::copyWithAuthor(
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800136 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
137 auto it = begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800138 // copy fmt start entry
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800139 it.copyTo(dst);
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700140 // copy timestamp
141 (++it).copyTo(dst);
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700142 // copy hash
143 (++it).copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800144 // insert author entry
145 size_t authorEntrySize = NBLog::Entry::kOverhead + sizeof(author);
146 uint8_t authorEntry[authorEntrySize];
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800147 authorEntry[offsetof(entry, type)] = EVENT_AUTHOR;
148 authorEntry[offsetof(entry, length)] =
149 authorEntry[authorEntrySize + NBLog::Entry::kPreviousLengthOffset] =
150 sizeof(author);
151 *(int*) (&authorEntry[offsetof(entry, data)]) = author;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800152 dst->write(authorEntry, authorEntrySize);
153 // copy rest of entries
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800154 while ((++it)->type != EVENT_END_FMT) {
155 it.copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800156 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800157 it.copyTo(dst);
158 ++it;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800159 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800160}
161
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700162void NBLog::EntryIterator::copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800163 size_t length = ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
164 dst->write(ptr, length);
165}
Nicolas Roulet40a44982017-02-03 13:39:57 -0800166
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700167void NBLog::EntryIterator::copyData(uint8_t *dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800168 memcpy((void*) dst, ptr + offsetof(entry, data), ptr[offsetof(entry, length)]);
169}
170
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700171NBLog::EntryIterator NBLog::FormatEntry::begin() const {
172 return EntryIterator(mEntry);
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800173}
174
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700175NBLog::EntryIterator::EntryIterator()
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800176 : ptr(nullptr) {}
177
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700178NBLog::EntryIterator::EntryIterator(const uint8_t *entry)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800179 : ptr(entry) {}
180
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700181NBLog::EntryIterator::EntryIterator(const NBLog::EntryIterator &other)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800182 : ptr(other.ptr) {}
183
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700184const NBLog::entry& NBLog::EntryIterator::operator*() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800185 return *(entry*) ptr;
186}
187
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700188const NBLog::entry* NBLog::EntryIterator::operator->() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800189 return (entry*) ptr;
190}
191
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700192NBLog::EntryIterator& NBLog::EntryIterator::operator++() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800193 ptr += ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
194 return *this;
195}
196
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700197NBLog::EntryIterator& NBLog::EntryIterator::operator--() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800198 ptr -= ptr[NBLog::Entry::kPreviousLengthOffset] + NBLog::Entry::kOverhead;
199 return *this;
200}
201
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700202NBLog::EntryIterator NBLog::EntryIterator::next() const {
203 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800204 return ++aux;
205}
206
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700207NBLog::EntryIterator NBLog::EntryIterator::prev() const {
208 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800209 return --aux;
210}
211
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700212int NBLog::EntryIterator::operator-(const NBLog::EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800213 return ptr - other.ptr;
214}
215
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700216bool NBLog::EntryIterator::operator!=(const EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800217 return ptr != other.ptr;
218}
219
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700220bool NBLog::EntryIterator::hasConsistentLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800221 return ptr[offsetof(entry, length)] == ptr[ptr[offsetof(entry, length)] +
222 NBLog::Entry::kOverhead + NBLog::Entry::kPreviousLengthOffset];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800223}
224
225// ---------------------------------------------------------------------------
226
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700227int64_t NBLog::HistogramEntry::timestamp() const {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700228 return EntryIterator(mEntry).payload<HistTsEntry>().ts;
229}
230
231NBLog::log_hash_t NBLog::HistogramEntry::hash() const {
232 return EntryIterator(mEntry).payload<HistTsEntry>().hash;
233}
234
235int NBLog::HistogramEntry::author() const {
236 EntryIterator it(mEntry);
237 if (it->length == sizeof(HistTsEntryWithAuthor)) {
238 return it.payload<HistTsEntryWithAuthor>().author;
239 } else {
240 return -1;
241 }
242}
243
244NBLog::EntryIterator NBLog::HistogramEntry::copyWithAuthor(
245 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
246 // Current histogram entry has {type, length, struct HistTsEntry, length}.
247 // We now want {type, length, struct HistTsEntryWithAuthor, length}
248 uint8_t buffer[Entry::kOverhead + sizeof(HistTsEntryWithAuthor)];
249 // Copy content until the point we want to add the author
250 memcpy(buffer, mEntry, sizeof(entry) + sizeof(HistTsEntry));
251 // Copy the author
252 *(int*) (buffer + sizeof(entry) + sizeof(HistTsEntry)) = author;
253 // Update lengths
254 buffer[offsetof(entry, length)] = sizeof(HistTsEntryWithAuthor);
255 buffer[sizeof(buffer) + Entry::kPreviousLengthOffset] = sizeof(HistTsEntryWithAuthor);
256 // Write new buffer into FIFO
257 dst->write(buffer, sizeof(buffer));
258 return EntryIterator(mEntry).next();
259}
260
261// ---------------------------------------------------------------------------
262
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800263#if 0 // FIXME see note in NBLog.h
264NBLog::Timeline::Timeline(size_t size, void *shared)
265 : mSize(roundup(size)), mOwn(shared == NULL),
266 mShared((Shared *) (mOwn ? new char[sharedSize(size)] : shared))
267{
268 new (mShared) Shared;
269}
270
271NBLog::Timeline::~Timeline()
272{
273 mShared->~Shared();
274 if (mOwn) {
275 delete[] (char *) mShared;
276 }
277}
278#endif
279
280/*static*/
281size_t NBLog::Timeline::sharedSize(size_t size)
282{
Glenn Kastened99c2b2016-12-12 08:31:24 -0800283 // TODO fifo now supports non-power-of-2 buffer sizes, so could remove the roundup
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800284 return sizeof(Shared) + roundup(size);
285}
286
287// ---------------------------------------------------------------------------
288
289NBLog::Writer::Writer()
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800290 : mShared(NULL), mFifo(NULL), mFifoWriter(NULL), mEnabled(false), mPidTag(NULL), mPidTagSize(0)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800291{
292}
293
Glenn Kasten535e1612016-12-05 12:19:36 -0800294NBLog::Writer::Writer(void *shared, size_t size)
295 : mShared((Shared *) shared),
296 mFifo(mShared != NULL ?
297 new audio_utils_fifo(size, sizeof(uint8_t),
298 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
299 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL),
300 mEnabled(mFifoWriter != NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800301{
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800302 // caching pid and process name
303 pid_t id = ::getpid();
304 char procName[16];
305 int status = prctl(PR_GET_NAME, procName);
306 if (status) { // error getting process name
307 procName[0] = '\0';
308 }
309 size_t length = strlen(procName);
310 mPidTagSize = length + sizeof(pid_t);
311 mPidTag = new char[mPidTagSize];
312 memcpy(mPidTag, &id, sizeof(pid_t));
313 memcpy(mPidTag + sizeof(pid_t), procName, length);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800314}
315
Glenn Kasten535e1612016-12-05 12:19:36 -0800316NBLog::Writer::Writer(const sp<IMemory>& iMemory, size_t size)
317 : Writer(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800318{
Glenn Kasten535e1612016-12-05 12:19:36 -0800319 mIMemory = iMemory;
320}
321
322NBLog::Writer::~Writer()
323{
324 delete mFifoWriter;
325 delete mFifo;
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800326 delete[] mPidTag;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800327}
328
329void NBLog::Writer::log(const char *string)
330{
331 if (!mEnabled) {
332 return;
333 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800334 LOG_ALWAYS_FATAL_IF(string == NULL, "Attempted to log NULL string");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800335 size_t length = strlen(string);
Glenn Kasten535e1612016-12-05 12:19:36 -0800336 if (length > Entry::kMaxLength) {
337 length = Entry::kMaxLength;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800338 }
339 log(EVENT_STRING, string, length);
340}
341
342void NBLog::Writer::logf(const char *fmt, ...)
343{
344 if (!mEnabled) {
345 return;
346 }
347 va_list ap;
348 va_start(ap, fmt);
349 Writer::logvf(fmt, ap); // the Writer:: is needed to avoid virtual dispatch for LockedWriter
350 va_end(ap);
351}
352
353void NBLog::Writer::logvf(const char *fmt, va_list ap)
354{
355 if (!mEnabled) {
356 return;
357 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800358 char buffer[Entry::kMaxLength + 1 /*NUL*/];
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800359 int length = vsnprintf(buffer, sizeof(buffer), fmt, ap);
360 if (length >= (int) sizeof(buffer)) {
361 length = sizeof(buffer) - 1;
362 // NUL termination is not required
363 // buffer[length] = '\0';
364 }
365 if (length >= 0) {
366 log(EVENT_STRING, buffer, length);
367 }
368}
369
370void NBLog::Writer::logTimestamp()
371{
372 if (!mEnabled) {
373 return;
374 }
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700375 int64_t ts = get_monotonic_ns();
376 if (ts > 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800377 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700378 } else {
379 ALOGE("Failed to get timestamp");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800380 }
381}
382
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700383void NBLog::Writer::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800384{
385 if (!mEnabled) {
386 return;
387 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800388 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
389}
390
391void NBLog::Writer::logInteger(const int x)
392{
393 if (!mEnabled) {
394 return;
395 }
396 log(EVENT_INTEGER, &x, sizeof(x));
397}
398
399void NBLog::Writer::logFloat(const float x)
400{
401 if (!mEnabled) {
402 return;
403 }
404 log(EVENT_FLOAT, &x, sizeof(x));
405}
406
407void NBLog::Writer::logPID()
408{
409 if (!mEnabled) {
410 return;
411 }
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800412 log(EVENT_PID, mPidTag, mPidTagSize);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800413}
414
415void NBLog::Writer::logStart(const char *fmt)
416{
417 if (!mEnabled) {
418 return;
419 }
420 size_t length = strlen(fmt);
421 if (length > Entry::kMaxLength) {
422 length = Entry::kMaxLength;
423 }
424 log(EVENT_START_FMT, fmt, length);
425}
426
427void NBLog::Writer::logEnd()
428{
429 if (!mEnabled) {
430 return;
431 }
432 Entry entry = Entry(EVENT_END_FMT, NULL, 0);
433 log(&entry, true);
434}
435
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700436void NBLog::Writer::logHash(log_hash_t hash)
437{
438 if (!mEnabled) {
439 return;
440 }
441 log(EVENT_HASH, &hash, sizeof(hash));
442}
443
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700444void NBLog::Writer::logHistTS(log_hash_t hash)
445{
446 if (!mEnabled) {
447 return;
448 }
449 HistTsEntry data;
450 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700451 data.ts = get_monotonic_ns();
452 if (data.ts > 0) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700453 log(EVENT_HISTOGRAM_ENTRY_TS, &data, sizeof(data));
454 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700455 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700456 }
457}
458
459void NBLog::Writer::logHistFlush(log_hash_t hash)
460{
461 if (!mEnabled) {
462 return;
463 }
464 HistTsEntry data;
465 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700466 data.ts = get_monotonic_ns();
467 if (data.ts > 0) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700468 log(EVENT_HISTOGRAM_FLUSH, &data, sizeof(data));
469 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700470 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700471 }
472}
473
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700474void NBLog::Writer::logFormat(const char *fmt, log_hash_t hash, ...)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800475{
476 if (!mEnabled) {
477 return;
478 }
479
480 va_list ap;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700481 va_start(ap, hash);
482 Writer::logVFormat(fmt, hash, ap);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800483 va_end(ap);
484}
485
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700486void NBLog::Writer::logVFormat(const char *fmt, log_hash_t hash, va_list argp)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800487{
488 if (!mEnabled) {
489 return;
490 }
491 Writer::logStart(fmt);
492 int i;
493 double f;
494 char* s;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700495 int64_t t;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800496 Writer::logTimestamp();
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700497 Writer::logHash(hash);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800498 for (const char *p = fmt; *p != '\0'; p++) {
499 // TODO: implement more complex formatting such as %.3f
500 if (*p != '%') {
501 continue;
502 }
503 switch(*++p) {
504 case 's': // string
505 s = va_arg(argp, char *);
506 Writer::log(s);
507 break;
508
509 case 't': // timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700510 t = va_arg(argp, int64_t);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800511 Writer::logTimestamp(t);
512 break;
513
514 case 'd': // integer
515 i = va_arg(argp, int);
516 Writer::logInteger(i);
517 break;
518
519 case 'f': // float
520 f = va_arg(argp, double); // float arguments are promoted to double in vararg lists
521 Writer::logFloat((float)f);
522 break;
523
524 case 'p': // pid
525 Writer::logPID();
526 break;
527
528 // the "%\0" case finishes parsing
529 case '\0':
530 --p;
531 break;
532
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800533 case '%':
534 break;
535
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800536 default:
537 ALOGW("NBLog Writer parsed invalid format specifier: %c", *p);
538 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800539 }
540 }
541 Writer::logEnd();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800542}
543
544void NBLog::Writer::log(Event event, const void *data, size_t length)
545{
546 if (!mEnabled) {
547 return;
548 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800549 if (data == NULL || length > Entry::kMaxLength) {
550 // TODO Perhaps it makes sense to display truncated data or at least a
551 // message that the data is too long? The current behavior can create
552 // a confusion for a programmer debugging their code.
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800553 return;
554 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700555 // Ignore if invalid event
556 if (event == EVENT_RESERVED || event >= EVENT_UPPER_BOUND) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800557 return;
558 }
559 Entry entry(event, data, length);
560 log(&entry, true /*trusted*/);
561}
562
563void NBLog::Writer::log(const NBLog::Entry *entry, bool trusted)
564{
565 if (!mEnabled) {
566 return;
567 }
568 if (!trusted) {
569 log(entry->mEvent, entry->mData, entry->mLength);
570 return;
571 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800572 size_t need = entry->mLength + Entry::kOverhead; // mEvent, mLength, data[length], mLength
573 // need = number of bytes remaining to write
574
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800575 // FIXME optimize this using memcpy for the data part of the Entry.
576 // The Entry could have a method copyTo(ptr, offset, size) to optimize the copy.
Glenn Kasten535e1612016-12-05 12:19:36 -0800577 uint8_t temp[Entry::kMaxLength + Entry::kOverhead];
578 for (size_t i = 0; i < need; i++) {
579 temp[i] = entry->readAt(i);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800580 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800581 mFifoWriter->write(temp, need);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800582}
583
584bool NBLog::Writer::isEnabled() const
585{
586 return mEnabled;
587}
588
589bool NBLog::Writer::setEnabled(bool enabled)
590{
591 bool old = mEnabled;
592 mEnabled = enabled && mShared != NULL;
593 return old;
594}
595
596// ---------------------------------------------------------------------------
597
598NBLog::LockedWriter::LockedWriter()
599 : Writer()
600{
601}
602
Glenn Kasten535e1612016-12-05 12:19:36 -0800603NBLog::LockedWriter::LockedWriter(void *shared, size_t size)
604 : Writer(shared, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800605{
606}
607
608void NBLog::LockedWriter::log(const char *string)
609{
610 Mutex::Autolock _l(mLock);
611 Writer::log(string);
612}
613
614void NBLog::LockedWriter::logf(const char *fmt, ...)
615{
616 // FIXME should not take the lock until after formatting is done
617 Mutex::Autolock _l(mLock);
618 va_list ap;
619 va_start(ap, fmt);
620 Writer::logvf(fmt, ap);
621 va_end(ap);
622}
623
624void NBLog::LockedWriter::logvf(const char *fmt, va_list ap)
625{
626 // FIXME should not take the lock until after formatting is done
627 Mutex::Autolock _l(mLock);
628 Writer::logvf(fmt, ap);
629}
630
631void NBLog::LockedWriter::logTimestamp()
632{
633 // FIXME should not take the lock until after the clock_gettime() syscall
634 Mutex::Autolock _l(mLock);
635 Writer::logTimestamp();
636}
637
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700638void NBLog::LockedWriter::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800639{
640 Mutex::Autolock _l(mLock);
641 Writer::logTimestamp(ts);
642}
643
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800644void NBLog::LockedWriter::logInteger(const int x)
645{
646 Mutex::Autolock _l(mLock);
647 Writer::logInteger(x);
648}
649
650void NBLog::LockedWriter::logFloat(const float x)
651{
652 Mutex::Autolock _l(mLock);
653 Writer::logFloat(x);
654}
655
656void NBLog::LockedWriter::logPID()
657{
658 Mutex::Autolock _l(mLock);
659 Writer::logPID();
660}
661
662void NBLog::LockedWriter::logStart(const char *fmt)
663{
664 Mutex::Autolock _l(mLock);
665 Writer::logStart(fmt);
666}
667
668
669void NBLog::LockedWriter::logEnd()
670{
671 Mutex::Autolock _l(mLock);
672 Writer::logEnd();
673}
674
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700675void NBLog::LockedWriter::logHash(log_hash_t hash)
676{
677 Mutex::Autolock _l(mLock);
678 Writer::logHash(hash);
679}
680
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800681bool NBLog::LockedWriter::isEnabled() const
682{
683 Mutex::Autolock _l(mLock);
684 return Writer::isEnabled();
685}
686
687bool NBLog::LockedWriter::setEnabled(bool enabled)
688{
689 Mutex::Autolock _l(mLock);
690 return Writer::setEnabled(enabled);
691}
692
693// ---------------------------------------------------------------------------
694
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700695const std::set<NBLog::Event> NBLog::Reader::startingTypes {NBLog::Event::EVENT_START_FMT,
696 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
697const std::set<NBLog::Event> NBLog::Reader::endingTypes {NBLog::Event::EVENT_END_FMT,
698 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
699 NBLog::Event::EVENT_HISTOGRAM_FLUSH};
Glenn Kasten535e1612016-12-05 12:19:36 -0800700NBLog::Reader::Reader(const void *shared, size_t size)
701 : mShared((/*const*/ Shared *) shared), /*mIMemory*/
702 mFd(-1), mIndent(0),
703 mFifo(mShared != NULL ?
704 new audio_utils_fifo(size, sizeof(uint8_t),
705 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -0700706 mFifoReader(mFifo != NULL ? new audio_utils_fifo_reader(*mFifo) : NULL),
707 findGlitch(false)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800708{
709}
710
Glenn Kasten535e1612016-12-05 12:19:36 -0800711NBLog::Reader::Reader(const sp<IMemory>& iMemory, size_t size)
712 : Reader(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800713{
Glenn Kasten535e1612016-12-05 12:19:36 -0800714 mIMemory = iMemory;
715}
716
717NBLog::Reader::~Reader()
718{
719 delete mFifoReader;
720 delete mFifo;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800721}
722
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -0700723inline static int deltaMs(int64_t ns1, int64_t ns2) {
724 return (ns2 - ns1) / (1000 * 1000);
725}
726
727// Produces a log warning if the timing of recent buffer periods caused a glitch
728// Computes sum of running window of three buffer periods
729// Checks whether the buffer periods leave enough CPU time for the next one
730// e.g. if a buffer period is expected to be 4 ms and a buffer requires 3 ms of CPU time,
731// here are some glitch cases:
732// 4 + 4 + 6 ; 5 + 4 + 5; 2 + 2 + 10
733// TODO: develop this code to track changes in histogram distribution in addition
734// to / instead of glitches
735void NBLog::Reader::alertIfGlitch(const std::vector<int64_t> &samples) {
736 //TODO: measure kPeriodLen and kRatio from the data as they may change.
737 static const int kPeriodLen = 4; // current period length is ideally 4 ms
738 static const double kRatio = 0.75; // estimate of CPU time as ratio of period length
739 // DAC processing time for 4 ms buffer
740 static const int kPeriodTime = static_cast<int>(round(kPeriodLen * kRatio));
741 static const int kNumBuff = 3; // number of buffers considered in local history
742 std::deque<int> periods(kNumBuff, kPeriodLen);
743 for (size_t i = 2; i < samples.size(); ++i) { // skip first time entry
744 periods.push_front(deltaMs(samples[i - 1], samples[i]));
745 periods.pop_back();
746 // TODO: check that all glitch cases are covered
747 if (std::accumulate(periods.begin(), periods.end(), 0) > kNumBuff * kPeriodLen +
748 kPeriodLen - kPeriodTime) {
749 ALOGW("A glitch occurred");
750 periods.assign(kNumBuff, kPeriodLen);
751 }
752 }
753 return;
754}
755
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700756const uint8_t *NBLog::Reader::findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
757 const std::set<Event> &types) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800758 while (back + Entry::kPreviousLengthOffset >= front) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700759 const uint8_t *prev = back - back[Entry::kPreviousLengthOffset] - Entry::kOverhead;
760 if (prev < front || prev + prev[offsetof(entry, length)] +
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800761 Entry::kOverhead != back) {
762
763 // prev points to an out of limits or inconsistent entry
764 return nullptr;
765 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700766 if (types.find((const Event) prev[offsetof(entry, type)]) != types.end()) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800767 return prev;
768 }
769 back = prev;
770 }
771 return nullptr; // no entry found
772}
773
Nicolas Roulet40a44982017-02-03 13:39:57 -0800774std::unique_ptr<NBLog::Reader::Snapshot> NBLog::Reader::getSnapshot()
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800775{
Glenn Kasten535e1612016-12-05 12:19:36 -0800776 if (mFifoReader == NULL) {
Nicolas Roulet40a44982017-02-03 13:39:57 -0800777 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800778 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800779 // make a copy to avoid race condition with writer
Glenn Kasten535e1612016-12-05 12:19:36 -0800780 size_t capacity = mFifo->capacity();
781
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800782 // This emulates the behaviour of audio_utils_fifo_reader::read, but without incrementing the
783 // reader index. The index is incremented after handling corruption, to after the last complete
784 // entry of the buffer
785 size_t lost;
786 audio_utils_iovec iovec[2];
787 ssize_t availToRead = mFifoReader->obtain(iovec, capacity, NULL /*timeout*/, &lost);
788 if (availToRead <= 0) {
789 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
790 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800791
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800792 std::unique_ptr<Snapshot> snapshot(new Snapshot(availToRead));
793 memcpy(snapshot->mData, (const char *) mFifo->buffer() + iovec[0].mOffset, iovec[0].mLength);
794 if (iovec[1].mLength > 0) {
795 memcpy(snapshot->mData + (iovec[0].mLength),
796 (const char *) mFifo->buffer() + iovec[1].mOffset, iovec[1].mLength);
797 }
798
799 // Handle corrupted buffer
800 // Potentially, a buffer has corrupted data on both beginning (due to overflow) and end
801 // (due to incomplete format entry). But even if the end format entry is incomplete,
802 // it ends in a complete entry (which is not an END_FMT). So is safe to traverse backwards.
803 // TODO: handle client corruption (in the middle of a buffer)
804
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700805 const uint8_t *back = snapshot->mData + availToRead;
806 const uint8_t *front = snapshot->mData;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800807
808 // Find last END_FMT. <back> is sitting on an entry which might be the middle of a FormatEntry.
809 // We go backwards until we find an EVENT_END_FMT.
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700810 const uint8_t *lastEnd = findLastEntryOfTypes(front, back, endingTypes);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800811 if (lastEnd == nullptr) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700812 snapshot->mEnd = snapshot->mBegin = EntryIterator(front);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800813 } else {
814 // end of snapshot points to after last END_FMT entry
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700815 snapshot->mEnd = EntryIterator(lastEnd).next();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800816 // find first START_FMT
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700817 const uint8_t *firstStart = nullptr;
818 const uint8_t *firstStartTmp = snapshot->mEnd;
819 while ((firstStartTmp = findLastEntryOfTypes(front, firstStartTmp, startingTypes))
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800820 != nullptr) {
821 firstStart = firstStartTmp;
822 }
823 // firstStart is null if no START_FMT entry was found before lastEnd
824 if (firstStart == nullptr) {
825 snapshot->mBegin = snapshot->mEnd;
826 } else {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700827 snapshot->mBegin = EntryIterator(firstStart);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800828 }
829 }
830
831 // advance fifo reader index to after last entry read.
832 mFifoReader->release(snapshot->mEnd - front);
833
834 snapshot->mLost = lost;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800835 return snapshot;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800836
Nicolas Roulet40a44982017-02-03 13:39:57 -0800837}
838
839void NBLog::Reader::dump(int fd, size_t indent, NBLog::Reader::Snapshot &snapshot)
840{
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800841#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800842 struct timespec ts;
843 time_t maxSec = -1;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800844 while (entry - start >= (int) Entry::kOverhead) {
845 if (prevEntry - start < 0 || !prevEntry.hasConsistentLength()) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800846 break;
847 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800848 if (prevEntry->type == EVENT_TIMESTAMP) {
849 if (prevEntry->length != sizeof(struct timespec)) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800850 // corrupt
851 break;
852 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800853 prevEntry.copyData((uint8_t*) &ts);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800854 if (ts.tv_sec > maxSec) {
855 maxSec = ts.tv_sec;
856 }
857 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800858 --entry;
859 --prevEntry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800860 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800861#endif
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700862 mFd = fd;
863 mIndent = indent;
864 String8 timestamp, body;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700865 size_t lost = snapshot.lost() + (snapshot.begin() - EntryIterator(snapshot.data()));
Glenn Kastenc02c9612013-10-15 09:25:11 -0700866 if (lost > 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700867 body.appendFormat("warning: lost %zu bytes worth of events", lost);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700868 // TODO timestamp empty here, only other choice to wait for the first timestamp event in the
869 // log to push it out. Consider keeping the timestamp/body between calls to readAt().
870 dumpLine(timestamp, body);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800871 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800872#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800873 size_t width = 1;
874 while (maxSec >= 10) {
875 ++width;
876 maxSec /= 10;
877 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800878 if (maxSec >= 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700879 timestamp.appendFormat("[%*s]", (int) width + 4, "");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800880 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700881 bool deferredTimestamp = false;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800882#endif
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700883
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800884 for (auto entry = snapshot.begin(); entry != snapshot.end();) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800885 switch (entry->type) {
886#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800887 case EVENT_STRING:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800888 body.appendFormat("%.*s", (int) entry.length(), entry.data());
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700889 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800890 case EVENT_TIMESTAMP: {
891 // already checked that length == sizeof(struct timespec);
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800892 entry.copyData((const uint8_t*) &ts);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800893 long prevNsec = ts.tv_nsec;
894 long deltaMin = LONG_MAX;
895 long deltaMax = -1;
896 long deltaTotal = 0;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800897 auto aux(entry);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800898 for (;;) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800899 ++aux;
900 if (end - aux >= 0 || aux.type() != EVENT_TIMESTAMP) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800901 break;
902 }
903 struct timespec tsNext;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800904 aux.copyData((const uint8_t*) &tsNext);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800905 if (tsNext.tv_sec != ts.tv_sec) {
906 break;
907 }
908 long delta = tsNext.tv_nsec - prevNsec;
909 if (delta < 0) {
910 break;
911 }
912 if (delta < deltaMin) {
913 deltaMin = delta;
914 }
915 if (delta > deltaMax) {
916 deltaMax = delta;
917 }
918 deltaTotal += delta;
919 prevNsec = tsNext.tv_nsec;
920 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800921 size_t n = (aux - entry) / (sizeof(struct timespec) + 3 /*Entry::kOverhead?*/);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700922 if (deferredTimestamp) {
923 dumpLine(timestamp, body);
924 deferredTimestamp = false;
925 }
926 timestamp.clear();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800927 if (n >= kSquashTimestamp) {
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700928 timestamp.appendFormat("[%d.%03d to .%.03d by .%.03d to .%.03d]",
929 (int) ts.tv_sec, (int) (ts.tv_nsec / 1000000),
930 (int) ((ts.tv_nsec + deltaTotal) / 1000000),
931 (int) (deltaMin / 1000000), (int) (deltaMax / 1000000));
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800932 entry = aux;
933 // advance = 0;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800934 break;
935 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700936 timestamp.appendFormat("[%d.%03d]", (int) ts.tv_sec,
937 (int) (ts.tv_nsec / 1000000));
938 deferredTimestamp = true;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800939 }
940 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800941 case EVENT_INTEGER:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800942 appendInt(&body, entry.data());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800943 break;
944 case EVENT_FLOAT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800945 appendFloat(&body, entry.data());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800946 break;
947 case EVENT_PID:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800948 appendPID(&body, entry.data(), entry.length());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800949 break;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800950#endif
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800951 case EVENT_START_FMT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800952 entry = handleFormat(FormatEntry(entry), &timestamp, &body);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800953 break;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700954 case EVENT_HISTOGRAM_ENTRY_TS: {
955 HistTsEntryWithAuthor *data = (HistTsEntryWithAuthor *) (entry->data);
956 // TODO This memcpies are here to avoid unaligned memory access crash.
957 // There's probably a more efficient way to do it
958 log_hash_t hash;
959 memcpy(&hash, &(data->hash), sizeof(hash));
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700960 int64_t ts;
961 memcpy(&ts, &data->ts, sizeof(ts));
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700962 const std::pair<log_hash_t, int> key(hash, data->author);
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700963 // TODO might want to filter excessively high outliers, which are usually caused
964 // by the thread being inactive.
965 mHists[key].push_back(ts);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700966 ++entry;
967 break;
968 }
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700969 case EVENT_HISTOGRAM_FLUSH: {
970 HistogramEntry histEntry(entry);
971 // Log timestamp
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -0700972 // Timestamp of call to drawHistogram, not when audio was generated
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -0700973 const int64_t ts = histEntry.timestamp();
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700974 timestamp.clear();
975 timestamp.appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
976 (int) ((ts / (1000 * 1000)) % 1000));
977 // Log histograms
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -0700978 setFindGlitch(true);
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700979 body.appendFormat("Histogram flush - ");
980 handleAuthor(histEntry, &body);
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -0700981 int debug = 0;
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700982 for (auto hist = mHists.begin(); hist != mHists.end();) {
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -0700983 // TODO: "debug" is always 0. Is a for loop necessary here?
984 ALOGW("EVENT_HISTOGRAM_FLUSH case hist: %d", debug++);
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700985 if (hist->first.second == histEntry.author()) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -0700986 body.appendFormat("%X", (int)hist->first.first);
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -0700987 if (findGlitch) {
988 alertIfGlitch(hist->second);
989 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -0700990 drawHistogram(&body, hist->second, true, indent);
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700991 hist = mHists.erase(hist);
992 } else {
993 ++hist;
994 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700995 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700996 ++entry;
997 break;
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700998 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800999 case EVENT_END_FMT:
1000 body.appendFormat("warning: got to end format event");
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001001 ++entry;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001002 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001003 case EVENT_RESERVED:
1004 default:
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001005 body.appendFormat("warning: unexpected event %d", entry->type);
1006 ++entry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001007 break;
1008 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -07001009
1010 if (!body.isEmpty()) {
1011 dumpLine(timestamp, body);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001012 // deferredTimestamp = false;
Glenn Kasten4e01ef62013-07-11 14:29:59 -07001013 }
1014 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001015 // if (deferredTimestamp) {
1016 // dumpLine(timestamp, body);
1017 // }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001018}
1019
Nicolas Roulet40a44982017-02-03 13:39:57 -08001020void NBLog::Reader::dump(int fd, size_t indent)
1021{
1022 // get a snapshot, dump it
1023 std::unique_ptr<Snapshot> snap = getSnapshot();
1024 dump(fd, indent, *snap);
1025}
1026
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001027void NBLog::Reader::dumpLine(const String8 &timestamp, String8 &body)
Glenn Kasten4e01ef62013-07-11 14:29:59 -07001028{
1029 if (mFd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07001030 dprintf(mFd, "%.*s%s %s\n", mIndent, "", timestamp.string(), body.string());
Glenn Kasten4e01ef62013-07-11 14:29:59 -07001031 } else {
1032 ALOGI("%.*s%s %s", mIndent, "", timestamp.string(), body.string());
1033 }
1034 body.clear();
1035}
1036
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001037bool NBLog::Reader::isIMemory(const sp<IMemory>& iMemory) const
1038{
Glenn Kasten481fb672013-09-30 14:39:28 -07001039 return iMemory != 0 && mIMemory != 0 && iMemory->pointer() == mIMemory->pointer();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001040}
1041
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -07001042void NBLog::Reader::setFindGlitch(bool s)
1043{
1044 findGlitch = s;
1045}
1046
1047bool NBLog::Reader::isFindGlitch() const
1048{
1049 return findGlitch;
1050}
1051
Glenn Kasten1c446272017-04-07 09:49:07 -07001052// ---------------------------------------------------------------------------
1053
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001054void NBLog::appendTimestamp(String8 *body, const void *data) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001055 int64_t ts;
1056 memcpy(&ts, data, sizeof(ts));
1057 body->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1058 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001059}
1060
1061void NBLog::appendInt(String8 *body, const void *data) {
1062 int x = *((int*) data);
1063 body->appendFormat("<%d>", x);
1064}
1065
1066void NBLog::appendFloat(String8 *body, const void *data) {
1067 float f;
1068 memcpy(&f, data, sizeof(float));
1069 body->appendFormat("<%f>", f);
1070}
1071
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001072void NBLog::appendPID(String8 *body, const void* data, size_t length) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001073 pid_t id = *((pid_t*) data);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001074 char * name = &((char*) data)[sizeof(pid_t)];
1075 body->appendFormat("<PID: %d, name: %.*s>", id, (int) (length - sizeof(pid_t)), name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001076}
1077
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001078String8 NBLog::bufferDump(const uint8_t *buffer, size_t size)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001079{
1080 String8 str;
1081 str.append("[ ");
1082 for(size_t i = 0; i < size; i++)
1083 {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001084 str.appendFormat("%d ", buffer[i]);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001085 }
1086 str.append("]");
1087 return str;
1088}
1089
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001090String8 NBLog::bufferDump(const EntryIterator &it)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001091{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001092 return bufferDump(it, it->length + Entry::kOverhead);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001093}
1094
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001095NBLog::EntryIterator NBLog::Reader::handleFormat(const FormatEntry &fmtEntry,
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001096 String8 *timestamp,
1097 String8 *body) {
Nicolas Roulet40a44982017-02-03 13:39:57 -08001098 // log timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001099 int64_t ts = fmtEntry.timestamp();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001100 timestamp->clear();
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001101 timestamp->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1102 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Roulet40a44982017-02-03 13:39:57 -08001103
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -07001104 // log unique hash
1105 log_hash_t hash = fmtEntry.hash();
1106 // print only lower 16bit of hash as hex and line as int to reduce spam in the log
1107 body->appendFormat("%.4X-%d ", (int)(hash >> 16) & 0xFFFF, (int) hash & 0xFFFF);
1108
Nicolas Roulet40a44982017-02-03 13:39:57 -08001109 // log author (if present)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001110 handleAuthor(fmtEntry, body);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001111
1112 // log string
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001113 NBLog::EntryIterator arg = fmtEntry.args();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001114
1115 const char* fmt = fmtEntry.formatString();
1116 size_t fmt_length = fmtEntry.formatStringLength();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001117
1118 for (size_t fmt_offset = 0; fmt_offset < fmt_length; ++fmt_offset) {
1119 if (fmt[fmt_offset] != '%') {
1120 body->append(&fmt[fmt_offset], 1); // TODO optimize to write consecutive strings at once
1121 continue;
1122 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001123 // case "%%""
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001124 if (fmt[++fmt_offset] == '%') {
1125 body->append("%");
1126 continue;
1127 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001128 // case "%\0"
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001129 if (fmt_offset == fmt_length) {
1130 continue;
1131 }
1132
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001133 NBLog::Event event = (NBLog::Event) arg->type;
1134 size_t length = arg->length;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001135
1136 // TODO check length for event type is correct
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001137
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001138 if (event == EVENT_END_FMT) {
1139 break;
1140 }
1141
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001142 // TODO: implement more complex formatting such as %.3f
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001143 const uint8_t *datum = arg->data; // pointer to the current event args
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001144 switch(fmt[fmt_offset])
1145 {
1146 case 's': // string
Nicolas Roulet4da78202017-02-03 12:53:39 -08001147 ALOGW_IF(event != EVENT_STRING,
1148 "NBLog Reader incompatible event for string specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001149 body->append((const char*) datum, length);
1150 break;
1151
1152 case 't': // timestamp
Nicolas Roulet4da78202017-02-03 12:53:39 -08001153 ALOGW_IF(event != EVENT_TIMESTAMP,
1154 "NBLog Reader incompatible event for timestamp specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001155 appendTimestamp(body, datum);
1156 break;
1157
1158 case 'd': // integer
Nicolas Roulet4da78202017-02-03 12:53:39 -08001159 ALOGW_IF(event != EVENT_INTEGER,
1160 "NBLog Reader incompatible event for integer specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001161 appendInt(body, datum);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001162 break;
1163
1164 case 'f': // float
Nicolas Roulet4da78202017-02-03 12:53:39 -08001165 ALOGW_IF(event != EVENT_FLOAT,
1166 "NBLog Reader incompatible event for float specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001167 appendFloat(body, datum);
1168 break;
1169
1170 case 'p': // pid
Nicolas Roulet4da78202017-02-03 12:53:39 -08001171 ALOGW_IF(event != EVENT_PID,
1172 "NBLog Reader incompatible event for pid specifier: %d", event);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001173 appendPID(body, datum, length);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001174 break;
1175
1176 default:
1177 ALOGW("NBLog Reader encountered unknown character %c", fmt[fmt_offset]);
1178 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001179 ++arg;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001180 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001181 ALOGW_IF(arg->type != EVENT_END_FMT, "Expected end of format, got %d", arg->type);
1182 ++arg;
1183 return arg;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001184}
1185
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001186static int widthOf(int x) {
1187 int width = 0;
1188 while (x > 0) {
1189 ++width;
1190 x /= 10;
1191 }
1192 return width;
1193}
1194
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001195static std::map<int, int> buildBuckets(const std::vector<int64_t> &samples) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001196 // TODO allow buckets of variable resolution
1197 std::map<int, int> buckets;
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001198 for (size_t i = 1; i < samples.size(); ++i) {
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -07001199 // ALOGW("sample %d ", deltaMs(samples[i - 1], samples[i]));
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001200 ++buckets[deltaMs(samples[i - 1], samples[i])];
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001201 }
1202 return buckets;
1203}
1204
Nicolas Roulet4f033492017-04-03 19:17:03 -07001205static inline uint32_t log2(uint32_t x) {
1206 // This works for x > 0
1207 return 31 - __builtin_clz(x);
1208}
1209
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001210// TODO put this function in separate file. Make it return a std::string instead of modifying body
Nicolas Roulet4f033492017-04-03 19:17:03 -07001211/*
1212Example output:
1213[54.234] Histogram flush - AudioOut_D:
1214Histogram 33640BF1
1215 [ 1][ 1][ 1][ 3][54][69][ 1][ 2][ 1]
1216 64| []
1217 32| [] []
1218 16| [] []
1219 8| [] []
1220 4| [] []
1221 2|______________[]__[]__[]______[]____
1222 4 5 6 8 9 10 11 13 15
1223Notice that all values that fall in the same row have the same height (65 and 127 are displayed
1224identically). That's why exact counts are added at the top.
1225*/
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001226void NBLog::Reader::drawHistogram(String8 *body,
1227 const std::vector<int64_t> &samples,
Nicolas Roulet4f033492017-04-03 19:17:03 -07001228 bool logScale,
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001229 int indent,
1230 int maxHeight) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001231 // this avoids some corner cases
Nicolas Roulet4f033492017-04-03 19:17:03 -07001232 if (samples.size() <= 1) {
1233 return;
1234 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001235 std::map<int, int> buckets = buildBuckets(samples);
Nicolas Roulet4f033492017-04-03 19:17:03 -07001236 // TODO consider changing all ints to uint32_t or uint64_t
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001237
1238 // underscores and spaces length corresponds to maximum width of histogram
1239 static const int kLen = 40;
1240 std::string underscores(kLen, '-');
1241 std::string spaces(kLen, ' ');
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001242
1243 auto it = buckets.begin();
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001244 int maxDelta = it->first;
1245 int maxCount = it->second;
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001246 // Compute maximum values
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001247 while (++it != buckets.end()) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001248 if (it->first > maxDelta) {
1249 maxDelta = it->first;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001250 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001251 if (it->second > maxCount) {
1252 maxCount = it->second;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001253 }
1254 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001255 int height = logScale ? log2(maxCount) + 1 : maxCount; // maxCount > 0, safe to call log2
1256 const int leftPadding = widthOf(logScale ? pow(2, height) : maxCount);
1257 const int colWidth = std::max(std::max(widthOf(maxDelta) + 1, 3), leftPadding + 2);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001258 int scalingFactor = 1;
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001259 // scale data if it exceeds maximum height
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001260 if (height > maxHeight) {
1261 scalingFactor = (height + maxHeight) / maxHeight;
1262 height /= scalingFactor;
1263 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001264 body->appendFormat("\n%*s", leftPadding + 11, "Occurrences");
1265 // write histogram label line with bucket values
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001266 body->appendFormat("\n%*s", indent, " ");
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001267 body->appendFormat("%*s", leftPadding, " ");
1268 for (auto const &x : buckets) {
1269 body->appendFormat("%*d", colWidth, x.second);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001270 }
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001271 // write histogram ascii art
1272 body->appendFormat("\n%*s", indent, " ");
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001273 for (int row = height * scalingFactor; row >= 0; row -= scalingFactor) {
1274 const int value = logScale ? (1 << row) : row;
1275 body->appendFormat("%.*s", leftPadding, spaces.c_str());
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001276 for (auto const &x : buckets) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001277 body->appendFormat("%.*s%s", colWidth - 1, spaces.c_str(), x.second < value ? " " : "|");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001278 }
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001279 body->appendFormat("\n%*s", indent, " ");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001280 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001281 // print x-axis
1282 const int columns = static_cast<int>(buckets.size());
1283 body->appendFormat("%*c", leftPadding, ' ');
1284 body->appendFormat("%.*s", (columns + 1) * colWidth, underscores.c_str());
1285 body->appendFormat("\n%*s", indent, " ");
1286
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001287 // write footer with bucket labels
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001288 body->appendFormat("%*s", leftPadding, " ");
1289 for (auto const &x : buckets) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001290 body->appendFormat("%*d", colWidth, x.first);
1291 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001292 body->appendFormat("%.*s%s", colWidth, spaces.c_str(), "ms\n");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001293}
1294
Nicolas Roulet40a44982017-02-03 13:39:57 -08001295NBLog::Merger::Merger(const void *shared, size_t size):
Nicolas Roulet40a44982017-02-03 13:39:57 -08001296 mShared((Shared *) shared),
1297 mFifo(mShared != NULL ?
1298 new audio_utils_fifo(size, sizeof(uint8_t),
1299 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
1300 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL)
1301 {}
1302
1303void NBLog::Merger::addReader(const NBLog::NamedReader &reader) {
Glenn Kasten1c446272017-04-07 09:49:07 -07001304 // FIXME This is called by binder thread in MediaLogService::registerWriter
1305 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001306 mNamedReaders.push_back(reader);
1307}
1308
1309// items placed in priority queue during merge
1310// composed by a timestamp and the index of the snapshot where the timestamp came from
1311struct MergeItem
1312{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001313 int64_t ts;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001314 int index;
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001315 MergeItem(int64_t ts, int index): ts(ts), index(index) {}
Nicolas Roulet40a44982017-02-03 13:39:57 -08001316};
1317
1318// operators needed for priority queue in merge
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001319// bool operator>(const int64_t &t1, const int64_t &t2) {
1320// return t1.tv_sec > t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec);
1321// }
Nicolas Roulet40a44982017-02-03 13:39:57 -08001322
1323bool operator>(const struct MergeItem &i1, const struct MergeItem &i2) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001324 return i1.ts > i2.ts || (i1.ts == i2.ts && i1.index > i2.index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001325}
1326
1327// Merge registered readers, sorted by timestamp
1328void NBLog::Merger::merge() {
Glenn Kasten1c446272017-04-07 09:49:07 -07001329 // FIXME This is called by merge thread
1330 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001331 int nLogs = mNamedReaders.size();
1332 std::vector<std::unique_ptr<NBLog::Reader::Snapshot>> snapshots(nLogs);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001333 std::vector<NBLog::EntryIterator> offsets(nLogs);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001334 for (int i = 0; i < nLogs; ++i) {
1335 snapshots[i] = mNamedReaders[i].reader()->getSnapshot();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001336 offsets[i] = snapshots[i]->begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001337 }
1338 // initialize offsets
Nicolas Roulet40a44982017-02-03 13:39:57 -08001339 // TODO custom heap implementation could allow to update top, improving performance
1340 // for bursty buffers
1341 std::priority_queue<MergeItem, std::vector<MergeItem>, std::greater<MergeItem>> timestamps;
1342 for (int i = 0; i < nLogs; ++i)
1343 {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001344 if (offsets[i] != snapshots[i]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001345 int64_t ts = AbstractEntry::buildEntry(offsets[i])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001346 timestamps.emplace(ts, i);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001347 }
1348 }
1349
1350 while (!timestamps.empty()) {
1351 // find minimum timestamp
1352 int index = timestamps.top().index;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001353 // copy it to the log, increasing offset
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001354 offsets[index] = AbstractEntry::buildEntry(offsets[index])->copyWithAuthor(mFifoWriter,
1355 index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001356 // update data structures
Nicolas Roulet40a44982017-02-03 13:39:57 -08001357 timestamps.pop();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001358 if (offsets[index] != snapshots[index]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001359 int64_t ts = AbstractEntry::buildEntry(offsets[index])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001360 timestamps.emplace(ts, index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001361 }
1362 }
1363}
1364
Glenn Kasten1c446272017-04-07 09:49:07 -07001365const std::vector<NBLog::NamedReader>& NBLog::Merger::getNamedReaders() const {
1366 // FIXME This is returning a reference to a shared variable that needs a lock
1367 return mNamedReaders;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001368}
1369
Glenn Kasten1c446272017-04-07 09:49:07 -07001370// ---------------------------------------------------------------------------
1371
Nicolas Roulet40a44982017-02-03 13:39:57 -08001372NBLog::MergeReader::MergeReader(const void *shared, size_t size, Merger &merger)
1373 : Reader(shared, size), mNamedReaders(merger.getNamedReaders()) {}
1374
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001375void NBLog::MergeReader::handleAuthor(const NBLog::AbstractEntry &entry, String8 *body) {
1376 int author = entry.author();
Glenn Kasten1c446272017-04-07 09:49:07 -07001377 // FIXME Needs a lock
1378 const char* name = mNamedReaders[author].name();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001379 body->appendFormat("%s: ", name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001380}
1381
Glenn Kasten1c446272017-04-07 09:49:07 -07001382// ---------------------------------------------------------------------------
1383
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001384NBLog::MergeThread::MergeThread(NBLog::Merger &merger)
1385 : mMerger(merger),
1386 mTimeoutUs(0) {}
1387
1388NBLog::MergeThread::~MergeThread() {
1389 // set exit flag, set timeout to 0 to force threadLoop to exit and wait for the thread to join
1390 requestExit();
1391 setTimeoutUs(0);
1392 join();
1393}
1394
1395bool NBLog::MergeThread::threadLoop() {
1396 bool doMerge;
1397 {
1398 AutoMutex _l(mMutex);
1399 // If mTimeoutUs is negative, wait on the condition variable until it's positive.
1400 // If it's positive, wait kThreadSleepPeriodUs and then merge
1401 nsecs_t waitTime = mTimeoutUs > 0 ? kThreadSleepPeriodUs * 1000 : LLONG_MAX;
1402 mCond.waitRelative(mMutex, waitTime);
1403 doMerge = mTimeoutUs > 0;
1404 mTimeoutUs -= kThreadSleepPeriodUs;
1405 }
1406 if (doMerge) {
1407 mMerger.merge();
1408 }
1409 return true;
1410}
1411
1412void NBLog::MergeThread::wakeup() {
1413 setTimeoutUs(kThreadWakeupPeriodUs);
1414}
1415
1416void NBLog::MergeThread::setTimeoutUs(int time) {
1417 AutoMutex _l(mMutex);
1418 mTimeoutUs = time;
1419 mCond.signal();
1420}
1421
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001422} // namespace android