blob: 3888bd99b6f2a56d146c7751b14fb1e9e27bc047 [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 Wagercced6742017-05-10 14:42:54 -070021#include <math.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080022#include <stdarg.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <string.h>
Nicolas Rouletc20cb502017-02-01 12:35:24 -080026#include <sys/prctl.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080027#include <time.h>
28#include <new>
Glenn Kasten535e1612016-12-05 12:19:36 -080029#include <audio_utils/roundup.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080030#include <media/nbaio/NBLog.h>
31#include <utils/Log.h>
Glenn Kasten4e01ef62013-07-11 14:29:59 -070032#include <utils/String8.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080033
Nicolas Roulet40a44982017-02-03 13:39:57 -080034#include <queue>
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070035#include <utility>
Nicolas Roulet40a44982017-02-03 13:39:57 -080036
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080037namespace android {
38
39int NBLog::Entry::readAt(size_t offset) const
40{
41 // FIXME This is too slow, despite the name it is used during writing
42 if (offset == 0)
43 return mEvent;
44 else if (offset == 1)
45 return mLength;
46 else if (offset < (size_t) (mLength + 2))
47 return ((char *) mData)[offset - 2];
48 else if (offset == (size_t) (mLength + 2))
49 return mLength;
50 else
51 return 0;
52}
53
54// ---------------------------------------------------------------------------
55
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070056/*static*/
57std::unique_ptr<NBLog::AbstractEntry> NBLog::AbstractEntry::buildEntry(const uint8_t *ptr) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -070058 const uint8_t type = EntryIterator(ptr)->type;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070059 switch (type) {
60 case EVENT_START_FMT:
61 return std::make_unique<FormatEntry>(FormatEntry(ptr));
62 case EVENT_HISTOGRAM_FLUSH:
63 case EVENT_HISTOGRAM_ENTRY_TS:
64 return std::make_unique<HistogramEntry>(HistogramEntry(ptr));
65 default:
66 ALOGW("Tried to create AbstractEntry of type %d", type);
67 return nullptr;
68 }
Nicolas Roulet40a44982017-02-03 13:39:57 -080069}
70
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070071NBLog::AbstractEntry::AbstractEntry(const uint8_t *entry) : mEntry(entry) {
72}
73
74// ---------------------------------------------------------------------------
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080075
Nicolas Roulet40a44982017-02-03 13:39:57 -080076const char *NBLog::FormatEntry::formatString() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080077 return (const char*) mEntry + offsetof(entry, data);
Nicolas Roulet40a44982017-02-03 13:39:57 -080078}
79
80size_t NBLog::FormatEntry::formatStringLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080081 return mEntry[offsetof(entry, length)];
Nicolas Roulet40a44982017-02-03 13:39:57 -080082}
83
Nicolas Roulet537ad7d2017-03-21 16:24:30 -070084NBLog::EntryIterator NBLog::FormatEntry::args() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080085 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -070086 // skip start fmt
87 ++it;
88 // skip timestamp
89 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -070090 // skip hash
91 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -070092 // Skip author if present
93 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -080094 ++it;
Nicolas Roulet40a44982017-02-03 13:39:57 -080095 }
Nicolas Roulet1ca75122017-03-16 14:19:59 -070096 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -080097}
98
Nicolas Rouletf42f1562017-03-30 19:16:22 -070099int64_t NBLog::FormatEntry::timestamp() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800100 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700101 // skip start fmt
102 ++it;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700103 return it.payload<int64_t>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800104}
105
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700106NBLog::log_hash_t NBLog::FormatEntry::hash() const {
107 auto it = begin();
108 // skip start fmt
109 ++it;
110 // skip timestamp
111 ++it;
112 // unaligned 64-bit read not supported
113 log_hash_t hash;
114 memcpy(&hash, it->data, sizeof(hash));
115 return hash;
116}
117
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700118int NBLog::FormatEntry::author() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800119 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700120 // skip start fmt
121 ++it;
122 // skip timestamp
123 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700124 // skip hash
125 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700126 // if there is an author entry, return it, return -1 otherwise
127 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800128 return it.payload<int>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800129 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800130 return -1;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800131}
132
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700133NBLog::EntryIterator NBLog::FormatEntry::copyWithAuthor(
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800134 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
135 auto it = begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800136 // copy fmt start entry
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800137 it.copyTo(dst);
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700138 // copy timestamp
139 (++it).copyTo(dst);
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700140 // copy hash
141 (++it).copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800142 // insert author entry
143 size_t authorEntrySize = NBLog::Entry::kOverhead + sizeof(author);
144 uint8_t authorEntry[authorEntrySize];
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800145 authorEntry[offsetof(entry, type)] = EVENT_AUTHOR;
146 authorEntry[offsetof(entry, length)] =
147 authorEntry[authorEntrySize + NBLog::Entry::kPreviousLengthOffset] =
148 sizeof(author);
149 *(int*) (&authorEntry[offsetof(entry, data)]) = author;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800150 dst->write(authorEntry, authorEntrySize);
151 // copy rest of entries
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800152 while ((++it)->type != EVENT_END_FMT) {
153 it.copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800154 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800155 it.copyTo(dst);
156 ++it;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800157 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800158}
159
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700160void NBLog::EntryIterator::copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800161 size_t length = ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
162 dst->write(ptr, length);
163}
Nicolas Roulet40a44982017-02-03 13:39:57 -0800164
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700165void NBLog::EntryIterator::copyData(uint8_t *dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800166 memcpy((void*) dst, ptr + offsetof(entry, data), ptr[offsetof(entry, length)]);
167}
168
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700169NBLog::EntryIterator NBLog::FormatEntry::begin() const {
170 return EntryIterator(mEntry);
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800171}
172
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700173NBLog::EntryIterator::EntryIterator()
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800174 : ptr(nullptr) {}
175
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700176NBLog::EntryIterator::EntryIterator(const uint8_t *entry)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800177 : ptr(entry) {}
178
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700179NBLog::EntryIterator::EntryIterator(const NBLog::EntryIterator &other)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800180 : ptr(other.ptr) {}
181
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700182const NBLog::entry& NBLog::EntryIterator::operator*() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800183 return *(entry*) ptr;
184}
185
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700186const NBLog::entry* NBLog::EntryIterator::operator->() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800187 return (entry*) ptr;
188}
189
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700190NBLog::EntryIterator& NBLog::EntryIterator::operator++() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800191 ptr += ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
192 return *this;
193}
194
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700195NBLog::EntryIterator& NBLog::EntryIterator::operator--() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800196 ptr -= ptr[NBLog::Entry::kPreviousLengthOffset] + NBLog::Entry::kOverhead;
197 return *this;
198}
199
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700200NBLog::EntryIterator NBLog::EntryIterator::next() const {
201 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800202 return ++aux;
203}
204
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700205NBLog::EntryIterator NBLog::EntryIterator::prev() const {
206 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800207 return --aux;
208}
209
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700210int NBLog::EntryIterator::operator-(const NBLog::EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800211 return ptr - other.ptr;
212}
213
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700214bool NBLog::EntryIterator::operator!=(const EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800215 return ptr != other.ptr;
216}
217
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700218bool NBLog::EntryIterator::hasConsistentLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800219 return ptr[offsetof(entry, length)] == ptr[ptr[offsetof(entry, length)] +
220 NBLog::Entry::kOverhead + NBLog::Entry::kPreviousLengthOffset];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800221}
222
223// ---------------------------------------------------------------------------
224
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700225int64_t NBLog::HistogramEntry::timestamp() const {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700226 return EntryIterator(mEntry).payload<HistTsEntry>().ts;
227}
228
229NBLog::log_hash_t NBLog::HistogramEntry::hash() const {
230 return EntryIterator(mEntry).payload<HistTsEntry>().hash;
231}
232
233int NBLog::HistogramEntry::author() const {
234 EntryIterator it(mEntry);
235 if (it->length == sizeof(HistTsEntryWithAuthor)) {
236 return it.payload<HistTsEntryWithAuthor>().author;
237 } else {
238 return -1;
239 }
240}
241
242NBLog::EntryIterator NBLog::HistogramEntry::copyWithAuthor(
243 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
244 // Current histogram entry has {type, length, struct HistTsEntry, length}.
245 // We now want {type, length, struct HistTsEntryWithAuthor, length}
246 uint8_t buffer[Entry::kOverhead + sizeof(HistTsEntryWithAuthor)];
247 // Copy content until the point we want to add the author
248 memcpy(buffer, mEntry, sizeof(entry) + sizeof(HistTsEntry));
249 // Copy the author
250 *(int*) (buffer + sizeof(entry) + sizeof(HistTsEntry)) = author;
251 // Update lengths
252 buffer[offsetof(entry, length)] = sizeof(HistTsEntryWithAuthor);
253 buffer[sizeof(buffer) + Entry::kPreviousLengthOffset] = sizeof(HistTsEntryWithAuthor);
254 // Write new buffer into FIFO
255 dst->write(buffer, sizeof(buffer));
256 return EntryIterator(mEntry).next();
257}
258
259// ---------------------------------------------------------------------------
260
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800261#if 0 // FIXME see note in NBLog.h
262NBLog::Timeline::Timeline(size_t size, void *shared)
263 : mSize(roundup(size)), mOwn(shared == NULL),
264 mShared((Shared *) (mOwn ? new char[sharedSize(size)] : shared))
265{
266 new (mShared) Shared;
267}
268
269NBLog::Timeline::~Timeline()
270{
271 mShared->~Shared();
272 if (mOwn) {
273 delete[] (char *) mShared;
274 }
275}
276#endif
277
278/*static*/
279size_t NBLog::Timeline::sharedSize(size_t size)
280{
Glenn Kastened99c2b2016-12-12 08:31:24 -0800281 // TODO fifo now supports non-power-of-2 buffer sizes, so could remove the roundup
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800282 return sizeof(Shared) + roundup(size);
283}
284
285// ---------------------------------------------------------------------------
286
287NBLog::Writer::Writer()
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800288 : mShared(NULL), mFifo(NULL), mFifoWriter(NULL), mEnabled(false), mPidTag(NULL), mPidTagSize(0)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800289{
290}
291
Glenn Kasten535e1612016-12-05 12:19:36 -0800292NBLog::Writer::Writer(void *shared, size_t size)
293 : mShared((Shared *) shared),
294 mFifo(mShared != NULL ?
295 new audio_utils_fifo(size, sizeof(uint8_t),
296 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
297 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL),
298 mEnabled(mFifoWriter != NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800299{
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800300 // caching pid and process name
301 pid_t id = ::getpid();
302 char procName[16];
303 int status = prctl(PR_GET_NAME, procName);
304 if (status) { // error getting process name
305 procName[0] = '\0';
306 }
307 size_t length = strlen(procName);
308 mPidTagSize = length + sizeof(pid_t);
309 mPidTag = new char[mPidTagSize];
310 memcpy(mPidTag, &id, sizeof(pid_t));
311 memcpy(mPidTag + sizeof(pid_t), procName, length);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800312}
313
Glenn Kasten535e1612016-12-05 12:19:36 -0800314NBLog::Writer::Writer(const sp<IMemory>& iMemory, size_t size)
315 : Writer(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800316{
Glenn Kasten535e1612016-12-05 12:19:36 -0800317 mIMemory = iMemory;
318}
319
320NBLog::Writer::~Writer()
321{
322 delete mFifoWriter;
323 delete mFifo;
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800324 delete[] mPidTag;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800325}
326
327void NBLog::Writer::log(const char *string)
328{
329 if (!mEnabled) {
330 return;
331 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800332 LOG_ALWAYS_FATAL_IF(string == NULL, "Attempted to log NULL string");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800333 size_t length = strlen(string);
Glenn Kasten535e1612016-12-05 12:19:36 -0800334 if (length > Entry::kMaxLength) {
335 length = Entry::kMaxLength;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800336 }
337 log(EVENT_STRING, string, length);
338}
339
340void NBLog::Writer::logf(const char *fmt, ...)
341{
342 if (!mEnabled) {
343 return;
344 }
345 va_list ap;
346 va_start(ap, fmt);
347 Writer::logvf(fmt, ap); // the Writer:: is needed to avoid virtual dispatch for LockedWriter
348 va_end(ap);
349}
350
351void NBLog::Writer::logvf(const char *fmt, va_list ap)
352{
353 if (!mEnabled) {
354 return;
355 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800356 char buffer[Entry::kMaxLength + 1 /*NUL*/];
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800357 int length = vsnprintf(buffer, sizeof(buffer), fmt, ap);
358 if (length >= (int) sizeof(buffer)) {
359 length = sizeof(buffer) - 1;
360 // NUL termination is not required
361 // buffer[length] = '\0';
362 }
363 if (length >= 0) {
364 log(EVENT_STRING, buffer, length);
365 }
366}
367
368void NBLog::Writer::logTimestamp()
369{
370 if (!mEnabled) {
371 return;
372 }
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700373 int64_t ts = get_monotonic_ns();
374 if (ts > 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800375 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700376 } else {
377 ALOGE("Failed to get timestamp");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800378 }
379}
380
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700381void NBLog::Writer::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800382{
383 if (!mEnabled) {
384 return;
385 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800386 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
387}
388
389void NBLog::Writer::logInteger(const int x)
390{
391 if (!mEnabled) {
392 return;
393 }
394 log(EVENT_INTEGER, &x, sizeof(x));
395}
396
397void NBLog::Writer::logFloat(const float x)
398{
399 if (!mEnabled) {
400 return;
401 }
402 log(EVENT_FLOAT, &x, sizeof(x));
403}
404
405void NBLog::Writer::logPID()
406{
407 if (!mEnabled) {
408 return;
409 }
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800410 log(EVENT_PID, mPidTag, mPidTagSize);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800411}
412
413void NBLog::Writer::logStart(const char *fmt)
414{
415 if (!mEnabled) {
416 return;
417 }
418 size_t length = strlen(fmt);
419 if (length > Entry::kMaxLength) {
420 length = Entry::kMaxLength;
421 }
422 log(EVENT_START_FMT, fmt, length);
423}
424
425void NBLog::Writer::logEnd()
426{
427 if (!mEnabled) {
428 return;
429 }
430 Entry entry = Entry(EVENT_END_FMT, NULL, 0);
431 log(&entry, true);
432}
433
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700434void NBLog::Writer::logHash(log_hash_t hash)
435{
436 if (!mEnabled) {
437 return;
438 }
439 log(EVENT_HASH, &hash, sizeof(hash));
440}
441
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700442void NBLog::Writer::logHistTS(log_hash_t hash)
443{
444 if (!mEnabled) {
445 return;
446 }
447 HistTsEntry data;
448 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700449 data.ts = get_monotonic_ns();
450 if (data.ts > 0) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700451 log(EVENT_HISTOGRAM_ENTRY_TS, &data, sizeof(data));
452 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700453 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700454 }
455}
456
457void NBLog::Writer::logHistFlush(log_hash_t hash)
458{
459 if (!mEnabled) {
460 return;
461 }
462 HistTsEntry data;
463 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700464 data.ts = get_monotonic_ns();
465 if (data.ts > 0) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700466 log(EVENT_HISTOGRAM_FLUSH, &data, sizeof(data));
467 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700468 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700469 }
470}
471
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700472void NBLog::Writer::logFormat(const char *fmt, log_hash_t hash, ...)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800473{
474 if (!mEnabled) {
475 return;
476 }
477
478 va_list ap;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700479 va_start(ap, hash);
480 Writer::logVFormat(fmt, hash, ap);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800481 va_end(ap);
482}
483
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700484void NBLog::Writer::logVFormat(const char *fmt, log_hash_t hash, va_list argp)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800485{
486 if (!mEnabled) {
487 return;
488 }
489 Writer::logStart(fmt);
490 int i;
491 double f;
492 char* s;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700493 int64_t t;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800494 Writer::logTimestamp();
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700495 Writer::logHash(hash);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800496 for (const char *p = fmt; *p != '\0'; p++) {
497 // TODO: implement more complex formatting such as %.3f
498 if (*p != '%') {
499 continue;
500 }
501 switch(*++p) {
502 case 's': // string
503 s = va_arg(argp, char *);
504 Writer::log(s);
505 break;
506
507 case 't': // timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700508 t = va_arg(argp, int64_t);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800509 Writer::logTimestamp(t);
510 break;
511
512 case 'd': // integer
513 i = va_arg(argp, int);
514 Writer::logInteger(i);
515 break;
516
517 case 'f': // float
518 f = va_arg(argp, double); // float arguments are promoted to double in vararg lists
519 Writer::logFloat((float)f);
520 break;
521
522 case 'p': // pid
523 Writer::logPID();
524 break;
525
526 // the "%\0" case finishes parsing
527 case '\0':
528 --p;
529 break;
530
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800531 case '%':
532 break;
533
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800534 default:
535 ALOGW("NBLog Writer parsed invalid format specifier: %c", *p);
536 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800537 }
538 }
539 Writer::logEnd();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800540}
541
542void NBLog::Writer::log(Event event, const void *data, size_t length)
543{
544 if (!mEnabled) {
545 return;
546 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800547 if (data == NULL || length > Entry::kMaxLength) {
548 // TODO Perhaps it makes sense to display truncated data or at least a
549 // message that the data is too long? The current behavior can create
550 // a confusion for a programmer debugging their code.
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800551 return;
552 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700553 // Ignore if invalid event
554 if (event == EVENT_RESERVED || event >= EVENT_UPPER_BOUND) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800555 return;
556 }
557 Entry entry(event, data, length);
558 log(&entry, true /*trusted*/);
559}
560
561void NBLog::Writer::log(const NBLog::Entry *entry, bool trusted)
562{
563 if (!mEnabled) {
564 return;
565 }
566 if (!trusted) {
567 log(entry->mEvent, entry->mData, entry->mLength);
568 return;
569 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800570 size_t need = entry->mLength + Entry::kOverhead; // mEvent, mLength, data[length], mLength
571 // need = number of bytes remaining to write
572
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800573 // FIXME optimize this using memcpy for the data part of the Entry.
574 // The Entry could have a method copyTo(ptr, offset, size) to optimize the copy.
Glenn Kasten535e1612016-12-05 12:19:36 -0800575 uint8_t temp[Entry::kMaxLength + Entry::kOverhead];
576 for (size_t i = 0; i < need; i++) {
577 temp[i] = entry->readAt(i);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800578 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800579 mFifoWriter->write(temp, need);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800580}
581
582bool NBLog::Writer::isEnabled() const
583{
584 return mEnabled;
585}
586
587bool NBLog::Writer::setEnabled(bool enabled)
588{
589 bool old = mEnabled;
590 mEnabled = enabled && mShared != NULL;
591 return old;
592}
593
594// ---------------------------------------------------------------------------
595
596NBLog::LockedWriter::LockedWriter()
597 : Writer()
598{
599}
600
Glenn Kasten535e1612016-12-05 12:19:36 -0800601NBLog::LockedWriter::LockedWriter(void *shared, size_t size)
602 : Writer(shared, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800603{
604}
605
606void NBLog::LockedWriter::log(const char *string)
607{
608 Mutex::Autolock _l(mLock);
609 Writer::log(string);
610}
611
612void NBLog::LockedWriter::logf(const char *fmt, ...)
613{
614 // FIXME should not take the lock until after formatting is done
615 Mutex::Autolock _l(mLock);
616 va_list ap;
617 va_start(ap, fmt);
618 Writer::logvf(fmt, ap);
619 va_end(ap);
620}
621
622void NBLog::LockedWriter::logvf(const char *fmt, va_list ap)
623{
624 // FIXME should not take the lock until after formatting is done
625 Mutex::Autolock _l(mLock);
626 Writer::logvf(fmt, ap);
627}
628
629void NBLog::LockedWriter::logTimestamp()
630{
631 // FIXME should not take the lock until after the clock_gettime() syscall
632 Mutex::Autolock _l(mLock);
633 Writer::logTimestamp();
634}
635
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700636void NBLog::LockedWriter::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800637{
638 Mutex::Autolock _l(mLock);
639 Writer::logTimestamp(ts);
640}
641
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800642void NBLog::LockedWriter::logInteger(const int x)
643{
644 Mutex::Autolock _l(mLock);
645 Writer::logInteger(x);
646}
647
648void NBLog::LockedWriter::logFloat(const float x)
649{
650 Mutex::Autolock _l(mLock);
651 Writer::logFloat(x);
652}
653
654void NBLog::LockedWriter::logPID()
655{
656 Mutex::Autolock _l(mLock);
657 Writer::logPID();
658}
659
660void NBLog::LockedWriter::logStart(const char *fmt)
661{
662 Mutex::Autolock _l(mLock);
663 Writer::logStart(fmt);
664}
665
666
667void NBLog::LockedWriter::logEnd()
668{
669 Mutex::Autolock _l(mLock);
670 Writer::logEnd();
671}
672
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700673void NBLog::LockedWriter::logHash(log_hash_t hash)
674{
675 Mutex::Autolock _l(mLock);
676 Writer::logHash(hash);
677}
678
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800679bool NBLog::LockedWriter::isEnabled() const
680{
681 Mutex::Autolock _l(mLock);
682 return Writer::isEnabled();
683}
684
685bool NBLog::LockedWriter::setEnabled(bool enabled)
686{
687 Mutex::Autolock _l(mLock);
688 return Writer::setEnabled(enabled);
689}
690
691// ---------------------------------------------------------------------------
692
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700693const std::set<NBLog::Event> NBLog::Reader::startingTypes {NBLog::Event::EVENT_START_FMT,
694 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
695const std::set<NBLog::Event> NBLog::Reader::endingTypes {NBLog::Event::EVENT_END_FMT,
696 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
697 NBLog::Event::EVENT_HISTOGRAM_FLUSH};
Glenn Kasten535e1612016-12-05 12:19:36 -0800698NBLog::Reader::Reader(const void *shared, size_t size)
699 : mShared((/*const*/ Shared *) shared), /*mIMemory*/
700 mFd(-1), mIndent(0),
701 mFifo(mShared != NULL ?
702 new audio_utils_fifo(size, sizeof(uint8_t),
703 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
704 mFifoReader(mFifo != NULL ? new audio_utils_fifo_reader(*mFifo) : NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800705{
706}
707
Glenn Kasten535e1612016-12-05 12:19:36 -0800708NBLog::Reader::Reader(const sp<IMemory>& iMemory, size_t size)
709 : Reader(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800710{
Glenn Kasten535e1612016-12-05 12:19:36 -0800711 mIMemory = iMemory;
712}
713
714NBLog::Reader::~Reader()
715{
716 delete mFifoReader;
717 delete mFifo;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800718}
719
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700720const uint8_t *NBLog::Reader::findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
721 const std::set<Event> &types) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800722 while (back + Entry::kPreviousLengthOffset >= front) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700723 const uint8_t *prev = back - back[Entry::kPreviousLengthOffset] - Entry::kOverhead;
724 if (prev < front || prev + prev[offsetof(entry, length)] +
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800725 Entry::kOverhead != back) {
726
727 // prev points to an out of limits or inconsistent entry
728 return nullptr;
729 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700730 if (types.find((const Event) prev[offsetof(entry, type)]) != types.end()) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800731 return prev;
732 }
733 back = prev;
734 }
735 return nullptr; // no entry found
736}
737
Nicolas Roulet40a44982017-02-03 13:39:57 -0800738std::unique_ptr<NBLog::Reader::Snapshot> NBLog::Reader::getSnapshot()
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800739{
Glenn Kasten535e1612016-12-05 12:19:36 -0800740 if (mFifoReader == NULL) {
Nicolas Roulet40a44982017-02-03 13:39:57 -0800741 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800742 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800743 // make a copy to avoid race condition with writer
Glenn Kasten535e1612016-12-05 12:19:36 -0800744 size_t capacity = mFifo->capacity();
745
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800746 // This emulates the behaviour of audio_utils_fifo_reader::read, but without incrementing the
747 // reader index. The index is incremented after handling corruption, to after the last complete
748 // entry of the buffer
749 size_t lost;
750 audio_utils_iovec iovec[2];
751 ssize_t availToRead = mFifoReader->obtain(iovec, capacity, NULL /*timeout*/, &lost);
752 if (availToRead <= 0) {
753 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
754 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800755
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800756 std::unique_ptr<Snapshot> snapshot(new Snapshot(availToRead));
757 memcpy(snapshot->mData, (const char *) mFifo->buffer() + iovec[0].mOffset, iovec[0].mLength);
758 if (iovec[1].mLength > 0) {
759 memcpy(snapshot->mData + (iovec[0].mLength),
760 (const char *) mFifo->buffer() + iovec[1].mOffset, iovec[1].mLength);
761 }
762
763 // Handle corrupted buffer
764 // Potentially, a buffer has corrupted data on both beginning (due to overflow) and end
765 // (due to incomplete format entry). But even if the end format entry is incomplete,
766 // it ends in a complete entry (which is not an END_FMT). So is safe to traverse backwards.
767 // TODO: handle client corruption (in the middle of a buffer)
768
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700769 const uint8_t *back = snapshot->mData + availToRead;
770 const uint8_t *front = snapshot->mData;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800771
772 // Find last END_FMT. <back> is sitting on an entry which might be the middle of a FormatEntry.
773 // We go backwards until we find an EVENT_END_FMT.
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700774 const uint8_t *lastEnd = findLastEntryOfTypes(front, back, endingTypes);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800775 if (lastEnd == nullptr) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700776 snapshot->mEnd = snapshot->mBegin = EntryIterator(front);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800777 } else {
778 // end of snapshot points to after last END_FMT entry
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700779 snapshot->mEnd = EntryIterator(lastEnd).next();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800780 // find first START_FMT
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700781 const uint8_t *firstStart = nullptr;
782 const uint8_t *firstStartTmp = snapshot->mEnd;
783 while ((firstStartTmp = findLastEntryOfTypes(front, firstStartTmp, startingTypes))
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800784 != nullptr) {
785 firstStart = firstStartTmp;
786 }
787 // firstStart is null if no START_FMT entry was found before lastEnd
788 if (firstStart == nullptr) {
789 snapshot->mBegin = snapshot->mEnd;
790 } else {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700791 snapshot->mBegin = EntryIterator(firstStart);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800792 }
793 }
794
795 // advance fifo reader index to after last entry read.
796 mFifoReader->release(snapshot->mEnd - front);
797
798 snapshot->mLost = lost;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800799 return snapshot;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800800
Nicolas Roulet40a44982017-02-03 13:39:57 -0800801}
802
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700803inline static int deltaMs(int64_t t1, int64_t t2) {
804 return (t2 - t1) / (1000 * 1000);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700805}
806
Nicolas Roulet40a44982017-02-03 13:39:57 -0800807void NBLog::Reader::dump(int fd, size_t indent, NBLog::Reader::Snapshot &snapshot)
808{
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800809#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800810 struct timespec ts;
811 time_t maxSec = -1;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800812 while (entry - start >= (int) Entry::kOverhead) {
813 if (prevEntry - start < 0 || !prevEntry.hasConsistentLength()) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800814 break;
815 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800816 if (prevEntry->type == EVENT_TIMESTAMP) {
817 if (prevEntry->length != sizeof(struct timespec)) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800818 // corrupt
819 break;
820 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800821 prevEntry.copyData((uint8_t*) &ts);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800822 if (ts.tv_sec > maxSec) {
823 maxSec = ts.tv_sec;
824 }
825 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800826 --entry;
827 --prevEntry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800828 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800829#endif
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700830 mFd = fd;
831 mIndent = indent;
832 String8 timestamp, body;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700833 size_t lost = snapshot.lost() + (snapshot.begin() - EntryIterator(snapshot.data()));
Glenn Kastenc02c9612013-10-15 09:25:11 -0700834 if (lost > 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700835 body.appendFormat("warning: lost %zu bytes worth of events", lost);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700836 // TODO timestamp empty here, only other choice to wait for the first timestamp event in the
837 // log to push it out. Consider keeping the timestamp/body between calls to readAt().
838 dumpLine(timestamp, body);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800839 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800840#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800841 size_t width = 1;
842 while (maxSec >= 10) {
843 ++width;
844 maxSec /= 10;
845 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800846 if (maxSec >= 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700847 timestamp.appendFormat("[%*s]", (int) width + 4, "");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800848 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700849 bool deferredTimestamp = false;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800850#endif
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700851
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800852 for (auto entry = snapshot.begin(); entry != snapshot.end();) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800853 switch (entry->type) {
854#if 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800855 case EVENT_STRING:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800856 body.appendFormat("%.*s", (int) entry.length(), entry.data());
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700857 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800858 case EVENT_TIMESTAMP: {
859 // already checked that length == sizeof(struct timespec);
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800860 entry.copyData((const uint8_t*) &ts);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800861 long prevNsec = ts.tv_nsec;
862 long deltaMin = LONG_MAX;
863 long deltaMax = -1;
864 long deltaTotal = 0;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800865 auto aux(entry);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800866 for (;;) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800867 ++aux;
868 if (end - aux >= 0 || aux.type() != EVENT_TIMESTAMP) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800869 break;
870 }
871 struct timespec tsNext;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800872 aux.copyData((const uint8_t*) &tsNext);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800873 if (tsNext.tv_sec != ts.tv_sec) {
874 break;
875 }
876 long delta = tsNext.tv_nsec - prevNsec;
877 if (delta < 0) {
878 break;
879 }
880 if (delta < deltaMin) {
881 deltaMin = delta;
882 }
883 if (delta > deltaMax) {
884 deltaMax = delta;
885 }
886 deltaTotal += delta;
887 prevNsec = tsNext.tv_nsec;
888 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800889 size_t n = (aux - entry) / (sizeof(struct timespec) + 3 /*Entry::kOverhead?*/);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700890 if (deferredTimestamp) {
891 dumpLine(timestamp, body);
892 deferredTimestamp = false;
893 }
894 timestamp.clear();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800895 if (n >= kSquashTimestamp) {
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700896 timestamp.appendFormat("[%d.%03d to .%.03d by .%.03d to .%.03d]",
897 (int) ts.tv_sec, (int) (ts.tv_nsec / 1000000),
898 (int) ((ts.tv_nsec + deltaTotal) / 1000000),
899 (int) (deltaMin / 1000000), (int) (deltaMax / 1000000));
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800900 entry = aux;
901 // advance = 0;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800902 break;
903 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700904 timestamp.appendFormat("[%d.%03d]", (int) ts.tv_sec,
905 (int) (ts.tv_nsec / 1000000));
906 deferredTimestamp = true;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800907 }
908 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800909 case EVENT_INTEGER:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800910 appendInt(&body, entry.data());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800911 break;
912 case EVENT_FLOAT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800913 appendFloat(&body, entry.data());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800914 break;
915 case EVENT_PID:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800916 appendPID(&body, entry.data(), entry.length());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800917 break;
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800918#endif
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800919 case EVENT_START_FMT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800920 // right now, this is the only supported case
921 entry = handleFormat(FormatEntry(entry), &timestamp, &body);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800922 break;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700923 case EVENT_HISTOGRAM_ENTRY_TS: {
924 HistTsEntryWithAuthor *data = (HistTsEntryWithAuthor *) (entry->data);
925 // TODO This memcpies are here to avoid unaligned memory access crash.
926 // There's probably a more efficient way to do it
927 log_hash_t hash;
928 memcpy(&hash, &(data->hash), sizeof(hash));
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700929 int64_t ts;
930 memcpy(&ts, &data->ts, sizeof(ts));
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700931 const std::pair<log_hash_t, int> key(hash, data->author);
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700932 // TODO might want to filter excessively high outliers, which are usually caused
933 // by the thread being inactive.
934 mHists[key].push_back(ts);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700935 ++entry;
936 break;
937 }
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700938 case EVENT_HISTOGRAM_FLUSH: {
939 HistogramEntry histEntry(entry);
940 // Log timestamp
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -0700941 const int64_t ts = histEntry.timestamp();
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700942 timestamp.clear();
943 timestamp.appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
944 (int) ((ts / (1000 * 1000)) % 1000));
945 // Log histograms
946 body.appendFormat("Histogram flush - ");
947 handleAuthor(histEntry, &body);
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700948 for (auto hist = mHists.begin(); hist != mHists.end();) {
949 if (hist->first.second == histEntry.author()) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -0700950 body.appendFormat("%X", (int)hist->first.first);
951 drawHistogram(&body, hist->second, true, indent);
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700952 hist = mHists.erase(hist);
953 } else {
954 ++hist;
955 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700956 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700957 ++entry;
958 break;
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700959 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800960 case EVENT_END_FMT:
961 body.appendFormat("warning: got to end format event");
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800962 ++entry;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800963 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800964 case EVENT_RESERVED:
965 default:
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800966 body.appendFormat("warning: unexpected event %d", entry->type);
967 ++entry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800968 break;
969 }
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700970
971 if (!body.isEmpty()) {
972 dumpLine(timestamp, body);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800973 // deferredTimestamp = false;
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700974 }
975 }
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800976 // if (deferredTimestamp) {
977 // dumpLine(timestamp, body);
978 // }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800979}
980
Nicolas Roulet40a44982017-02-03 13:39:57 -0800981void NBLog::Reader::dump(int fd, size_t indent)
982{
983 // get a snapshot, dump it
984 std::unique_ptr<Snapshot> snap = getSnapshot();
985 dump(fd, indent, *snap);
986}
987
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800988void NBLog::Reader::dumpLine(const String8 &timestamp, String8 &body)
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700989{
990 if (mFd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700991 dprintf(mFd, "%.*s%s %s\n", mIndent, "", timestamp.string(), body.string());
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700992 } else {
993 ALOGI("%.*s%s %s", mIndent, "", timestamp.string(), body.string());
994 }
995 body.clear();
996}
997
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800998bool NBLog::Reader::isIMemory(const sp<IMemory>& iMemory) const
999{
Glenn Kasten481fb672013-09-30 14:39:28 -07001000 return iMemory != 0 && mIMemory != 0 && iMemory->pointer() == mIMemory->pointer();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001001}
1002
Glenn Kasten1c446272017-04-07 09:49:07 -07001003// ---------------------------------------------------------------------------
1004
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001005void NBLog::appendTimestamp(String8 *body, const void *data) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001006 int64_t ts;
1007 memcpy(&ts, data, sizeof(ts));
1008 body->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1009 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001010}
1011
1012void NBLog::appendInt(String8 *body, const void *data) {
1013 int x = *((int*) data);
1014 body->appendFormat("<%d>", x);
1015}
1016
1017void NBLog::appendFloat(String8 *body, const void *data) {
1018 float f;
1019 memcpy(&f, data, sizeof(float));
1020 body->appendFormat("<%f>", f);
1021}
1022
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001023void NBLog::appendPID(String8 *body, const void* data, size_t length) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001024 pid_t id = *((pid_t*) data);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001025 char * name = &((char*) data)[sizeof(pid_t)];
1026 body->appendFormat("<PID: %d, name: %.*s>", id, (int) (length - sizeof(pid_t)), name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001027}
1028
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001029String8 NBLog::bufferDump(const uint8_t *buffer, size_t size)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001030{
1031 String8 str;
1032 str.append("[ ");
1033 for(size_t i = 0; i < size; i++)
1034 {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001035 str.appendFormat("%d ", buffer[i]);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001036 }
1037 str.append("]");
1038 return str;
1039}
1040
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001041String8 NBLog::bufferDump(const EntryIterator &it)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001042{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001043 return bufferDump(it, it->length + Entry::kOverhead);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001044}
1045
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001046NBLog::EntryIterator NBLog::Reader::handleFormat(const FormatEntry &fmtEntry,
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001047 String8 *timestamp,
1048 String8 *body) {
Nicolas Roulet40a44982017-02-03 13:39:57 -08001049 // log timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001050 int64_t ts = fmtEntry.timestamp();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001051 timestamp->clear();
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001052 timestamp->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1053 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Roulet40a44982017-02-03 13:39:57 -08001054
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -07001055 // log unique hash
1056 log_hash_t hash = fmtEntry.hash();
1057 // print only lower 16bit of hash as hex and line as int to reduce spam in the log
1058 body->appendFormat("%.4X-%d ", (int)(hash >> 16) & 0xFFFF, (int) hash & 0xFFFF);
1059
Nicolas Roulet40a44982017-02-03 13:39:57 -08001060 // log author (if present)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001061 handleAuthor(fmtEntry, body);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001062
1063 // log string
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001064 NBLog::EntryIterator arg = fmtEntry.args();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001065
1066 const char* fmt = fmtEntry.formatString();
1067 size_t fmt_length = fmtEntry.formatStringLength();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001068
1069 for (size_t fmt_offset = 0; fmt_offset < fmt_length; ++fmt_offset) {
1070 if (fmt[fmt_offset] != '%') {
1071 body->append(&fmt[fmt_offset], 1); // TODO optimize to write consecutive strings at once
1072 continue;
1073 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001074 // case "%%""
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001075 if (fmt[++fmt_offset] == '%') {
1076 body->append("%");
1077 continue;
1078 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001079 // case "%\0"
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001080 if (fmt_offset == fmt_length) {
1081 continue;
1082 }
1083
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001084 NBLog::Event event = (NBLog::Event) arg->type;
1085 size_t length = arg->length;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001086
1087 // TODO check length for event type is correct
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001088
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001089 if (event == EVENT_END_FMT) {
1090 break;
1091 }
1092
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001093 // TODO: implement more complex formatting such as %.3f
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001094 const uint8_t *datum = arg->data; // pointer to the current event args
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001095 switch(fmt[fmt_offset])
1096 {
1097 case 's': // string
Nicolas Roulet4da78202017-02-03 12:53:39 -08001098 ALOGW_IF(event != EVENT_STRING,
1099 "NBLog Reader incompatible event for string specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001100 body->append((const char*) datum, length);
1101 break;
1102
1103 case 't': // timestamp
Nicolas Roulet4da78202017-02-03 12:53:39 -08001104 ALOGW_IF(event != EVENT_TIMESTAMP,
1105 "NBLog Reader incompatible event for timestamp specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001106 appendTimestamp(body, datum);
1107 break;
1108
1109 case 'd': // integer
Nicolas Roulet4da78202017-02-03 12:53:39 -08001110 ALOGW_IF(event != EVENT_INTEGER,
1111 "NBLog Reader incompatible event for integer specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001112 appendInt(body, datum);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001113 break;
1114
1115 case 'f': // float
Nicolas Roulet4da78202017-02-03 12:53:39 -08001116 ALOGW_IF(event != EVENT_FLOAT,
1117 "NBLog Reader incompatible event for float specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001118 appendFloat(body, datum);
1119 break;
1120
1121 case 'p': // pid
Nicolas Roulet4da78202017-02-03 12:53:39 -08001122 ALOGW_IF(event != EVENT_PID,
1123 "NBLog Reader incompatible event for pid specifier: %d", event);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001124 appendPID(body, datum, length);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001125 break;
1126
1127 default:
1128 ALOGW("NBLog Reader encountered unknown character %c", fmt[fmt_offset]);
1129 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001130 ++arg;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001131 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001132 ALOGW_IF(arg->type != EVENT_END_FMT, "Expected end of format, got %d", arg->type);
1133 ++arg;
1134 return arg;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001135}
1136
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001137static int widthOf(int x) {
1138 int width = 0;
1139 while (x > 0) {
1140 ++width;
1141 x /= 10;
1142 }
1143 return width;
1144}
1145
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001146static std::map<int, int> buildBuckets(const std::vector<int64_t> &samples) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001147 // TODO allow buckets of variable resolution
1148 std::map<int, int> buckets;
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001149 for (size_t i = 1; i < samples.size(); ++i) {
1150 ++buckets[deltaMs(samples[i - 1], samples[i])];
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001151 }
1152 return buckets;
1153}
1154
Nicolas Roulet4f033492017-04-03 19:17:03 -07001155static inline uint32_t log2(uint32_t x) {
1156 // This works for x > 0
1157 return 31 - __builtin_clz(x);
1158}
1159
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001160// TODO put this function in separate file. Make it return a std::string instead of modifying body
Nicolas Roulet4f033492017-04-03 19:17:03 -07001161/*
1162Example output:
1163[54.234] Histogram flush - AudioOut_D:
1164Histogram 33640BF1
1165 [ 1][ 1][ 1][ 3][54][69][ 1][ 2][ 1]
1166 64| []
1167 32| [] []
1168 16| [] []
1169 8| [] []
1170 4| [] []
1171 2|______________[]__[]__[]______[]____
1172 4 5 6 8 9 10 11 13 15
1173Notice that all values that fall in the same row have the same height (65 and 127 are displayed
1174identically). That's why exact counts are added at the top.
1175*/
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001176void NBLog::Reader::drawHistogram(String8 *body,
1177 const std::vector<int64_t> &samples,
Nicolas Roulet4f033492017-04-03 19:17:03 -07001178 bool logScale,
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001179 int indent,
1180 int maxHeight) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001181 // this avoids some corner cases
Nicolas Roulet4f033492017-04-03 19:17:03 -07001182 if (samples.size() <= 1) {
1183 return;
1184 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001185 std::map<int, int> buckets = buildBuckets(samples);
Nicolas Roulet4f033492017-04-03 19:17:03 -07001186 // TODO consider changing all ints to uint32_t or uint64_t
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001187
1188 // underscores and spaces length corresponds to maximum width of histogram
1189 static const int kLen = 40;
1190 std::string underscores(kLen, '-');
1191 std::string spaces(kLen, ' ');
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001192
1193 auto it = buckets.begin();
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001194 int maxDelta = it->first;
1195 int maxCount = it->second;
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001196 // Compute maximum values
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001197 while (++it != buckets.end()) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001198 if (it->first > maxDelta) {
1199 maxDelta = it->first;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001200 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001201 if (it->second > maxCount) {
1202 maxCount = it->second;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001203 }
1204 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001205 int height = logScale ? log2(maxCount) + 1 : maxCount; // maxCount > 0, safe to call log2
1206 const int leftPadding = widthOf(logScale ? pow(2, height) : maxCount);
1207 const int colWidth = std::max(std::max(widthOf(maxDelta) + 1, 3), leftPadding + 2);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001208 int scalingFactor = 1;
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001209 // scale data if it exceeds maximum height
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001210 if (height > maxHeight) {
1211 scalingFactor = (height + maxHeight) / maxHeight;
1212 height /= scalingFactor;
1213 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001214 body->appendFormat("\n%*s", leftPadding + 11, "Occurrences");
1215 // write histogram label line with bucket values
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001216 body->appendFormat("\n%*s", indent, " ");
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001217 body->appendFormat("%*s", leftPadding, " ");
1218 for (auto const &x : buckets) {
1219 body->appendFormat("%*d", colWidth, x.second);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001220 }
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001221 // write histogram ascii art
1222 body->appendFormat("\n%*s", indent, " ");
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001223 for (int row = height * scalingFactor; row >= 0; row -= scalingFactor) {
1224 const int value = logScale ? (1 << row) : row;
1225 body->appendFormat("%.*s", leftPadding, spaces.c_str());
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001226 for (auto const &x : buckets) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001227 body->appendFormat("%.*s%s", colWidth - 1, spaces.c_str(), x.second < value ? " " : "|");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001228 }
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001229 body->appendFormat("\n%*s", indent, " ");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001230 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001231 // print x-axis
1232 const int columns = static_cast<int>(buckets.size());
1233 body->appendFormat("%*c", leftPadding, ' ');
1234 body->appendFormat("%.*s", (columns + 1) * colWidth, underscores.c_str());
1235 body->appendFormat("\n%*s", indent, " ");
1236
Nicolas Rouletad82aa62017-04-03 19:15:20 -07001237 // write footer with bucket labels
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001238 body->appendFormat("%*s", leftPadding, " ");
1239 for (auto const &x : buckets) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001240 body->appendFormat("%*d", colWidth, x.first);
1241 }
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -07001242 body->appendFormat("%.*s%s", colWidth, spaces.c_str(), "ms\n");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001243}
1244
Nicolas Roulet40a44982017-02-03 13:39:57 -08001245NBLog::Merger::Merger(const void *shared, size_t size):
Nicolas Roulet40a44982017-02-03 13:39:57 -08001246 mShared((Shared *) shared),
1247 mFifo(mShared != NULL ?
1248 new audio_utils_fifo(size, sizeof(uint8_t),
1249 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
1250 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL)
1251 {}
1252
1253void NBLog::Merger::addReader(const NBLog::NamedReader &reader) {
Glenn Kasten1c446272017-04-07 09:49:07 -07001254 // FIXME This is called by binder thread in MediaLogService::registerWriter
1255 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001256 mNamedReaders.push_back(reader);
1257}
1258
1259// items placed in priority queue during merge
1260// composed by a timestamp and the index of the snapshot where the timestamp came from
1261struct MergeItem
1262{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001263 int64_t ts;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001264 int index;
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001265 MergeItem(int64_t ts, int index): ts(ts), index(index) {}
Nicolas Roulet40a44982017-02-03 13:39:57 -08001266};
1267
1268// operators needed for priority queue in merge
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001269// bool operator>(const int64_t &t1, const int64_t &t2) {
1270// return t1.tv_sec > t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec);
1271// }
Nicolas Roulet40a44982017-02-03 13:39:57 -08001272
1273bool operator>(const struct MergeItem &i1, const struct MergeItem &i2) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001274 return i1.ts > i2.ts || (i1.ts == i2.ts && i1.index > i2.index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001275}
1276
1277// Merge registered readers, sorted by timestamp
1278void NBLog::Merger::merge() {
Glenn Kasten1c446272017-04-07 09:49:07 -07001279 // FIXME This is called by merge thread
1280 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001281 int nLogs = mNamedReaders.size();
1282 std::vector<std::unique_ptr<NBLog::Reader::Snapshot>> snapshots(nLogs);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001283 std::vector<NBLog::EntryIterator> offsets(nLogs);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001284 for (int i = 0; i < nLogs; ++i) {
1285 snapshots[i] = mNamedReaders[i].reader()->getSnapshot();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001286 offsets[i] = snapshots[i]->begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001287 }
1288 // initialize offsets
Nicolas Roulet40a44982017-02-03 13:39:57 -08001289 // TODO custom heap implementation could allow to update top, improving performance
1290 // for bursty buffers
1291 std::priority_queue<MergeItem, std::vector<MergeItem>, std::greater<MergeItem>> timestamps;
1292 for (int i = 0; i < nLogs; ++i)
1293 {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001294 if (offsets[i] != snapshots[i]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001295 int64_t ts = AbstractEntry::buildEntry(offsets[i])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001296 timestamps.emplace(ts, i);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001297 }
1298 }
1299
1300 while (!timestamps.empty()) {
1301 // find minimum timestamp
1302 int index = timestamps.top().index;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001303 // copy it to the log, increasing offset
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001304 offsets[index] = AbstractEntry::buildEntry(offsets[index])->copyWithAuthor(mFifoWriter,
1305 index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001306 // update data structures
Nicolas Roulet40a44982017-02-03 13:39:57 -08001307 timestamps.pop();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001308 if (offsets[index] != snapshots[index]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001309 int64_t ts = AbstractEntry::buildEntry(offsets[index])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001310 timestamps.emplace(ts, index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001311 }
1312 }
1313}
1314
Glenn Kasten1c446272017-04-07 09:49:07 -07001315const std::vector<NBLog::NamedReader>& NBLog::Merger::getNamedReaders() const {
1316 // FIXME This is returning a reference to a shared variable that needs a lock
1317 return mNamedReaders;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001318}
1319
Glenn Kasten1c446272017-04-07 09:49:07 -07001320// ---------------------------------------------------------------------------
1321
Nicolas Roulet40a44982017-02-03 13:39:57 -08001322NBLog::MergeReader::MergeReader(const void *shared, size_t size, Merger &merger)
1323 : Reader(shared, size), mNamedReaders(merger.getNamedReaders()) {}
1324
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001325void NBLog::MergeReader::handleAuthor(const NBLog::AbstractEntry &entry, String8 *body) {
1326 int author = entry.author();
Glenn Kasten1c446272017-04-07 09:49:07 -07001327 // FIXME Needs a lock
1328 const char* name = mNamedReaders[author].name();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001329 body->appendFormat("%s: ", name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001330}
1331
Glenn Kasten1c446272017-04-07 09:49:07 -07001332// ---------------------------------------------------------------------------
1333
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001334NBLog::MergeThread::MergeThread(NBLog::Merger &merger)
1335 : mMerger(merger),
1336 mTimeoutUs(0) {}
1337
1338NBLog::MergeThread::~MergeThread() {
1339 // set exit flag, set timeout to 0 to force threadLoop to exit and wait for the thread to join
1340 requestExit();
1341 setTimeoutUs(0);
1342 join();
1343}
1344
1345bool NBLog::MergeThread::threadLoop() {
1346 bool doMerge;
1347 {
1348 AutoMutex _l(mMutex);
1349 // If mTimeoutUs is negative, wait on the condition variable until it's positive.
1350 // If it's positive, wait kThreadSleepPeriodUs and then merge
1351 nsecs_t waitTime = mTimeoutUs > 0 ? kThreadSleepPeriodUs * 1000 : LLONG_MAX;
1352 mCond.waitRelative(mMutex, waitTime);
1353 doMerge = mTimeoutUs > 0;
1354 mTimeoutUs -= kThreadSleepPeriodUs;
1355 }
1356 if (doMerge) {
1357 mMerger.merge();
1358 }
1359 return true;
1360}
1361
1362void NBLog::MergeThread::wakeup() {
1363 setTimeoutUs(kThreadWakeupPeriodUs);
1364}
1365
1366void NBLog::MergeThread::setTimeoutUs(int time) {
1367 AutoMutex _l(mMutex);
1368 mTimeoutUs = time;
1369 mCond.signal();
1370}
1371
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001372} // namespace android