blob: 3cbd06fe39954b11b28395e6ef7230b31075a210 [file] [log] [blame]
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070017/*
18* Documentation: Workflow summary for histogram data processing:
19* For more details on FIFO, please see system/media/audio_utils; doxygen
20* TODO: add this documentation to doxygen once it is further developed
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070021* 1) Writing buffer period timestamp to the circular buffer
22* onWork()
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070023* Called every period length (e.g., 4ms)
24* Calls LOG_HIST_TS
25* LOG_HIST_TS
Sanna Catherine de Treville Wagerd4a68f62017-06-23 16:09:41 -070026* Hashes file name and line number, and writes single timestamp to buffer
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070027* calls NBLOG::Writer::logHistTS once
28* NBLOG::Writer::logHistTS
29* calls NBLOG::Writer::log on hash and current timestamp
30* time is in CLOCK_MONOTONIC converted to ns
31* NBLOG::Writer::log(Event, const void*, size_t)
32* Initializes Entry, a struct containing one log entry
33* Entry contains the event type (mEvent), data length (mLength),
34* and data pointer (mData)
35* TODO: why mLength (max length of buffer data) must be <= kMaxLength = 255?
36* calls NBLOG::Writer::log(Entry *, bool)
37* NBLog::Writer::log(Entry *, bool)
38* Calls copyEntryDataAt to format data as follows in temp array:
39* [type][length][data ... ][length]
40* calls audio_utils_fifo_writer.write on temp
41* audio_utils_fifo_writer.write
42* calls obtain(), memcpy (reference in doxygen)
43* returns number of frames written
44* ssize_t audio_utils_fifo_reader::obtain
45* Determines readable buffer section via pointer arithmetic on reader
46* and writer pointers
47*
Sanna Catherine de Treville Wagerd4a68f62017-06-23 16:09:41 -070048* 2) reading the data from shared memory
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070049* Thread::threadloop()
50* TODO: add description?
51* NBLog::MergeThread::threadLoop()
52* calls NBLog::Merger::merge
53* NBLog::Merger::merge
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070054* Merges snapshots sorted by timestamp
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070055* for each reader in vector of class NamedReader,
56* callsNamedReader::reader()->getSnapshot
57* TODO: check whether the rest of this function is relevant
58* NBLog::Reader::getSnapshot
59* copies snapshot of reader's fifo buffer into its own buffer
60* calls mFifoReader->obtain to find readable data
61* sets snapshot.begin() and .end() iterators to boundaries of valid entries
62* moves the fifo reader index to after the last entry read
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070063* in this case, the buffer is in shared memory. in (4), the buffer is private
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070064*
Sanna Catherine de Treville Wagerd4a68f62017-06-23 16:09:41 -070065* 3) reading the data from private buffer
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070066* MediaLogService::dump
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -070067* calls NBLog::Reader::dump(CONSOLE)
68* The private buffer contains all logs for all readers in shared memory
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070069* NBLog::Reader::dump(int)
70* calls getSnapshot on the current reader
71* calls dump(int, size_t, Snapshot)
72* NBLog::Reader::dump(int, size, snapshot)
73* iterates through snapshot's events and switches based on their type
74* (string, timestamp, etc...)
75* In the case of EVENT_HISTOGRAM_ENTRY_TS, adds a list of timestamp sequences
76* (histogram entry) to NBLog::mHists
Sanna Catherine de Treville Wagerd4a68f62017-06-23 16:09:41 -070077* TODO: add every HISTOGRAM_ENTRY_TS to two
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070078* circular buffers: one short-term and one long-term (can add even longer-term
79* structures in the future). When dump is called, print everything currently
80* in the buffer.
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070081* NBLog::drawHistogram
82* input: timestamp array
83* buckets this to a histogram and prints
84*
85*/
86
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080087#define LOG_TAG "NBLog"
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070088// #define LOG_NDEBUG 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080089
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -070090#include <algorithm>
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -080091#include <climits>
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -070092#include <deque>
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -070093#include <fstream>
94// #include <inttypes.h>
95#include <iostream>
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -070096#include <math.h>
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -070097#include <numeric>
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -070098#include <vector>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080099#include <stdarg.h>
100#include <stdint.h>
101#include <stdio.h>
102#include <string.h>
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800103#include <sys/prctl.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800104#include <time.h>
105#include <new>
Glenn Kasten535e1612016-12-05 12:19:36 -0800106#include <audio_utils/roundup.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800107#include <media/nbaio/NBLog.h>
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700108#include <media/nbaio/PerformanceAnalysis.h>
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700109// #include <utils/CallStack.h> // used to print callstack
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800110#include <utils/Log.h>
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700111#include <utils/String8.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800112
Nicolas Roulet40a44982017-02-03 13:39:57 -0800113#include <queue>
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700114#include <utility>
Nicolas Roulet40a44982017-02-03 13:39:57 -0800115
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800116namespace android {
117
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700118int NBLog::Entry::copyEntryDataAt(size_t offset) const
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800119{
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700120 // FIXME This is too slow
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800121 if (offset == 0)
122 return mEvent;
123 else if (offset == 1)
124 return mLength;
125 else if (offset < (size_t) (mLength + 2))
126 return ((char *) mData)[offset - 2];
127 else if (offset == (size_t) (mLength + 2))
128 return mLength;
129 else
130 return 0;
131}
132
133// ---------------------------------------------------------------------------
134
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700135/*static*/
136std::unique_ptr<NBLog::AbstractEntry> NBLog::AbstractEntry::buildEntry(const uint8_t *ptr) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -0700137 const uint8_t type = EntryIterator(ptr)->type;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700138 switch (type) {
139 case EVENT_START_FMT:
140 return std::make_unique<FormatEntry>(FormatEntry(ptr));
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700141 case EVENT_HISTOGRAM_ENTRY_TS:
142 return std::make_unique<HistogramEntry>(HistogramEntry(ptr));
143 default:
144 ALOGW("Tried to create AbstractEntry of type %d", type);
145 return nullptr;
146 }
Nicolas Roulet40a44982017-02-03 13:39:57 -0800147}
148
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700149NBLog::AbstractEntry::AbstractEntry(const uint8_t *entry) : mEntry(entry) {
150}
151
152// ---------------------------------------------------------------------------
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800153
Sanna Catherine de Treville Wagerdd92d7e2017-05-15 14:56:53 -0700154NBLog::EntryIterator NBLog::FormatEntry::begin() const {
155 return EntryIterator(mEntry);
156}
157
Nicolas Roulet40a44982017-02-03 13:39:57 -0800158const char *NBLog::FormatEntry::formatString() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800159 return (const char*) mEntry + offsetof(entry, data);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800160}
161
162size_t NBLog::FormatEntry::formatStringLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800163 return mEntry[offsetof(entry, length)];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800164}
165
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700166NBLog::EntryIterator NBLog::FormatEntry::args() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800167 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700168 // skip start fmt
169 ++it;
170 // skip timestamp
171 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700172 // skip hash
173 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700174 // Skip author if present
175 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800176 ++it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800177 }
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700178 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800179}
180
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700181int64_t NBLog::FormatEntry::timestamp() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800182 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700183 // skip start fmt
184 ++it;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700185 return it.payload<int64_t>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800186}
187
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700188NBLog::log_hash_t NBLog::FormatEntry::hash() const {
189 auto it = begin();
190 // skip start fmt
191 ++it;
192 // skip timestamp
193 ++it;
194 // unaligned 64-bit read not supported
195 log_hash_t hash;
196 memcpy(&hash, it->data, sizeof(hash));
197 return hash;
198}
199
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700200int NBLog::FormatEntry::author() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800201 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700202 // skip start fmt
203 ++it;
204 // skip timestamp
205 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700206 // skip hash
207 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700208 // if there is an author entry, return it, return -1 otherwise
209 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800210 return it.payload<int>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800211 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800212 return -1;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800213}
214
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700215NBLog::EntryIterator NBLog::FormatEntry::copyWithAuthor(
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800216 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
217 auto it = begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800218 // copy fmt start entry
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800219 it.copyTo(dst);
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700220 // copy timestamp
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700221 (++it).copyTo(dst); // copy hash
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700222 (++it).copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800223 // insert author entry
224 size_t authorEntrySize = NBLog::Entry::kOverhead + sizeof(author);
225 uint8_t authorEntry[authorEntrySize];
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800226 authorEntry[offsetof(entry, type)] = EVENT_AUTHOR;
227 authorEntry[offsetof(entry, length)] =
228 authorEntry[authorEntrySize + NBLog::Entry::kPreviousLengthOffset] =
229 sizeof(author);
230 *(int*) (&authorEntry[offsetof(entry, data)]) = author;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800231 dst->write(authorEntry, authorEntrySize);
232 // copy rest of entries
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800233 while ((++it)->type != EVENT_END_FMT) {
234 it.copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800235 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800236 it.copyTo(dst);
237 ++it;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800238 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800239}
240
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700241void NBLog::EntryIterator::copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800242 size_t length = ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
243 dst->write(ptr, length);
244}
Nicolas Roulet40a44982017-02-03 13:39:57 -0800245
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700246void NBLog::EntryIterator::copyData(uint8_t *dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800247 memcpy((void*) dst, ptr + offsetof(entry, data), ptr[offsetof(entry, length)]);
248}
249
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700250NBLog::EntryIterator::EntryIterator()
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800251 : ptr(nullptr) {}
252
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700253NBLog::EntryIterator::EntryIterator(const uint8_t *entry)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800254 : ptr(entry) {}
255
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700256NBLog::EntryIterator::EntryIterator(const NBLog::EntryIterator &other)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800257 : ptr(other.ptr) {}
258
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700259const NBLog::entry& NBLog::EntryIterator::operator*() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800260 return *(entry*) ptr;
261}
262
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700263const NBLog::entry* NBLog::EntryIterator::operator->() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800264 return (entry*) ptr;
265}
266
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700267NBLog::EntryIterator& NBLog::EntryIterator::operator++() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800268 ptr += ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
269 return *this;
270}
271
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700272NBLog::EntryIterator& NBLog::EntryIterator::operator--() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800273 ptr -= ptr[NBLog::Entry::kPreviousLengthOffset] + NBLog::Entry::kOverhead;
274 return *this;
275}
276
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700277NBLog::EntryIterator NBLog::EntryIterator::next() const {
278 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800279 return ++aux;
280}
281
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700282NBLog::EntryIterator NBLog::EntryIterator::prev() const {
283 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800284 return --aux;
285}
286
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700287int NBLog::EntryIterator::operator-(const NBLog::EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800288 return ptr - other.ptr;
289}
290
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700291bool NBLog::EntryIterator::operator!=(const EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800292 return ptr != other.ptr;
293}
294
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700295bool NBLog::EntryIterator::hasConsistentLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800296 return ptr[offsetof(entry, length)] == ptr[ptr[offsetof(entry, length)] +
297 NBLog::Entry::kOverhead + NBLog::Entry::kPreviousLengthOffset];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800298}
299
300// ---------------------------------------------------------------------------
301
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700302int64_t NBLog::HistogramEntry::timestamp() const {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700303 return EntryIterator(mEntry).payload<HistTsEntry>().ts;
304}
305
306NBLog::log_hash_t NBLog::HistogramEntry::hash() const {
307 return EntryIterator(mEntry).payload<HistTsEntry>().hash;
308}
309
310int NBLog::HistogramEntry::author() const {
311 EntryIterator it(mEntry);
312 if (it->length == sizeof(HistTsEntryWithAuthor)) {
313 return it.payload<HistTsEntryWithAuthor>().author;
314 } else {
315 return -1;
316 }
317}
318
319NBLog::EntryIterator NBLog::HistogramEntry::copyWithAuthor(
320 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
321 // Current histogram entry has {type, length, struct HistTsEntry, length}.
322 // We now want {type, length, struct HistTsEntryWithAuthor, length}
323 uint8_t buffer[Entry::kOverhead + sizeof(HistTsEntryWithAuthor)];
324 // Copy content until the point we want to add the author
325 memcpy(buffer, mEntry, sizeof(entry) + sizeof(HistTsEntry));
326 // Copy the author
327 *(int*) (buffer + sizeof(entry) + sizeof(HistTsEntry)) = author;
328 // Update lengths
329 buffer[offsetof(entry, length)] = sizeof(HistTsEntryWithAuthor);
330 buffer[sizeof(buffer) + Entry::kPreviousLengthOffset] = sizeof(HistTsEntryWithAuthor);
331 // Write new buffer into FIFO
332 dst->write(buffer, sizeof(buffer));
333 return EntryIterator(mEntry).next();
334}
335
336// ---------------------------------------------------------------------------
337
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800338#if 0 // FIXME see note in NBLog.h
339NBLog::Timeline::Timeline(size_t size, void *shared)
340 : mSize(roundup(size)), mOwn(shared == NULL),
341 mShared((Shared *) (mOwn ? new char[sharedSize(size)] : shared))
342{
343 new (mShared) Shared;
344}
345
346NBLog::Timeline::~Timeline()
347{
348 mShared->~Shared();
349 if (mOwn) {
350 delete[] (char *) mShared;
351 }
352}
353#endif
354
355/*static*/
356size_t NBLog::Timeline::sharedSize(size_t size)
357{
Glenn Kastened99c2b2016-12-12 08:31:24 -0800358 // TODO fifo now supports non-power-of-2 buffer sizes, so could remove the roundup
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800359 return sizeof(Shared) + roundup(size);
360}
361
362// ---------------------------------------------------------------------------
363
364NBLog::Writer::Writer()
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800365 : mShared(NULL), mFifo(NULL), mFifoWriter(NULL), mEnabled(false), mPidTag(NULL), mPidTagSize(0)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800366{
367}
368
Glenn Kasten535e1612016-12-05 12:19:36 -0800369NBLog::Writer::Writer(void *shared, size_t size)
370 : mShared((Shared *) shared),
371 mFifo(mShared != NULL ?
372 new audio_utils_fifo(size, sizeof(uint8_t),
373 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
374 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL),
375 mEnabled(mFifoWriter != NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800376{
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800377 // caching pid and process name
378 pid_t id = ::getpid();
379 char procName[16];
380 int status = prctl(PR_GET_NAME, procName);
381 if (status) { // error getting process name
382 procName[0] = '\0';
383 }
384 size_t length = strlen(procName);
385 mPidTagSize = length + sizeof(pid_t);
386 mPidTag = new char[mPidTagSize];
387 memcpy(mPidTag, &id, sizeof(pid_t));
388 memcpy(mPidTag + sizeof(pid_t), procName, length);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800389}
390
Glenn Kasten535e1612016-12-05 12:19:36 -0800391NBLog::Writer::Writer(const sp<IMemory>& iMemory, size_t size)
392 : Writer(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800393{
Glenn Kasten535e1612016-12-05 12:19:36 -0800394 mIMemory = iMemory;
395}
396
397NBLog::Writer::~Writer()
398{
399 delete mFifoWriter;
400 delete mFifo;
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800401 delete[] mPidTag;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800402}
403
404void NBLog::Writer::log(const char *string)
405{
406 if (!mEnabled) {
407 return;
408 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800409 LOG_ALWAYS_FATAL_IF(string == NULL, "Attempted to log NULL string");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800410 size_t length = strlen(string);
Glenn Kasten535e1612016-12-05 12:19:36 -0800411 if (length > Entry::kMaxLength) {
412 length = Entry::kMaxLength;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800413 }
414 log(EVENT_STRING, string, length);
415}
416
417void NBLog::Writer::logf(const char *fmt, ...)
418{
419 if (!mEnabled) {
420 return;
421 }
422 va_list ap;
423 va_start(ap, fmt);
424 Writer::logvf(fmt, ap); // the Writer:: is needed to avoid virtual dispatch for LockedWriter
425 va_end(ap);
426}
427
428void NBLog::Writer::logvf(const char *fmt, va_list ap)
429{
430 if (!mEnabled) {
431 return;
432 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800433 char buffer[Entry::kMaxLength + 1 /*NUL*/];
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800434 int length = vsnprintf(buffer, sizeof(buffer), fmt, ap);
435 if (length >= (int) sizeof(buffer)) {
436 length = sizeof(buffer) - 1;
437 // NUL termination is not required
438 // buffer[length] = '\0';
439 }
440 if (length >= 0) {
441 log(EVENT_STRING, buffer, length);
442 }
443}
444
445void NBLog::Writer::logTimestamp()
446{
447 if (!mEnabled) {
448 return;
449 }
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700450 int64_t ts = get_monotonic_ns();
451 if (ts > 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800452 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700453 } else {
454 ALOGE("Failed to get timestamp");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800455 }
456}
457
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700458void NBLog::Writer::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800459{
460 if (!mEnabled) {
461 return;
462 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800463 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
464}
465
466void NBLog::Writer::logInteger(const int x)
467{
468 if (!mEnabled) {
469 return;
470 }
471 log(EVENT_INTEGER, &x, sizeof(x));
472}
473
474void NBLog::Writer::logFloat(const float x)
475{
476 if (!mEnabled) {
477 return;
478 }
479 log(EVENT_FLOAT, &x, sizeof(x));
480}
481
482void NBLog::Writer::logPID()
483{
484 if (!mEnabled) {
485 return;
486 }
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800487 log(EVENT_PID, mPidTag, mPidTagSize);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800488}
489
490void NBLog::Writer::logStart(const char *fmt)
491{
492 if (!mEnabled) {
493 return;
494 }
495 size_t length = strlen(fmt);
496 if (length > Entry::kMaxLength) {
497 length = Entry::kMaxLength;
498 }
499 log(EVENT_START_FMT, fmt, length);
500}
501
502void NBLog::Writer::logEnd()
503{
504 if (!mEnabled) {
505 return;
506 }
507 Entry entry = Entry(EVENT_END_FMT, NULL, 0);
508 log(&entry, true);
509}
510
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700511void NBLog::Writer::logHash(log_hash_t hash)
512{
513 if (!mEnabled) {
514 return;
515 }
516 log(EVENT_HASH, &hash, sizeof(hash));
517}
518
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700519void NBLog::Writer::logHistTS(log_hash_t hash)
520{
521 if (!mEnabled) {
522 return;
523 }
524 HistTsEntry data;
525 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700526 data.ts = get_monotonic_ns();
527 if (data.ts > 0) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700528 log(EVENT_HISTOGRAM_ENTRY_TS, &data, sizeof(data));
529 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700530 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700531 }
532}
533
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700534void NBLog::Writer::logFormat(const char *fmt, log_hash_t hash, ...)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800535{
536 if (!mEnabled) {
537 return;
538 }
539
540 va_list ap;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700541 va_start(ap, hash);
542 Writer::logVFormat(fmt, hash, ap);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800543 va_end(ap);
544}
545
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700546void NBLog::Writer::logVFormat(const char *fmt, log_hash_t hash, va_list argp)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800547{
548 if (!mEnabled) {
549 return;
550 }
551 Writer::logStart(fmt);
552 int i;
553 double f;
554 char* s;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700555 int64_t t;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800556 Writer::logTimestamp();
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700557 Writer::logHash(hash);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800558 for (const char *p = fmt; *p != '\0'; p++) {
559 // TODO: implement more complex formatting such as %.3f
560 if (*p != '%') {
561 continue;
562 }
563 switch(*++p) {
564 case 's': // string
565 s = va_arg(argp, char *);
566 Writer::log(s);
567 break;
568
569 case 't': // timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700570 t = va_arg(argp, int64_t);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800571 Writer::logTimestamp(t);
572 break;
573
574 case 'd': // integer
575 i = va_arg(argp, int);
576 Writer::logInteger(i);
577 break;
578
579 case 'f': // float
580 f = va_arg(argp, double); // float arguments are promoted to double in vararg lists
581 Writer::logFloat((float)f);
582 break;
583
584 case 'p': // pid
585 Writer::logPID();
586 break;
587
588 // the "%\0" case finishes parsing
589 case '\0':
590 --p;
591 break;
592
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800593 case '%':
594 break;
595
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800596 default:
597 ALOGW("NBLog Writer parsed invalid format specifier: %c", *p);
598 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800599 }
600 }
601 Writer::logEnd();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800602}
603
604void NBLog::Writer::log(Event event, const void *data, size_t length)
605{
606 if (!mEnabled) {
607 return;
608 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800609 if (data == NULL || length > Entry::kMaxLength) {
610 // TODO Perhaps it makes sense to display truncated data or at least a
611 // message that the data is too long? The current behavior can create
612 // a confusion for a programmer debugging their code.
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800613 return;
614 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700615 // Ignore if invalid event
616 if (event == EVENT_RESERVED || event >= EVENT_UPPER_BOUND) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800617 return;
618 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700619 Entry etr(event, data, length);
620 log(&etr, true /*trusted*/);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800621}
622
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700623void NBLog::Writer::log(const NBLog::Entry *etr, bool trusted)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800624{
625 if (!mEnabled) {
626 return;
627 }
628 if (!trusted) {
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700629 log(etr->mEvent, etr->mData, etr->mLength);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800630 return;
631 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700632 size_t need = etr->mLength + Entry::kOverhead; // mEvent, mLength, data[mLength], mLength
633 // need = number of bytes written to FIFO
Glenn Kasten535e1612016-12-05 12:19:36 -0800634
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800635 // FIXME optimize this using memcpy for the data part of the Entry.
636 // The Entry could have a method copyTo(ptr, offset, size) to optimize the copy.
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700637 // checks size of a single log Entry: type, length, data pointer and ending
Glenn Kasten535e1612016-12-05 12:19:36 -0800638 uint8_t temp[Entry::kMaxLength + Entry::kOverhead];
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700639 // write this data to temp array
Glenn Kasten535e1612016-12-05 12:19:36 -0800640 for (size_t i = 0; i < need; i++) {
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700641 temp[i] = etr->copyEntryDataAt(i);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800642 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700643 // write to circular buffer
Glenn Kasten535e1612016-12-05 12:19:36 -0800644 mFifoWriter->write(temp, need);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800645}
646
647bool NBLog::Writer::isEnabled() const
648{
649 return mEnabled;
650}
651
652bool NBLog::Writer::setEnabled(bool enabled)
653{
654 bool old = mEnabled;
655 mEnabled = enabled && mShared != NULL;
656 return old;
657}
658
659// ---------------------------------------------------------------------------
660
661NBLog::LockedWriter::LockedWriter()
662 : Writer()
663{
664}
665
Glenn Kasten535e1612016-12-05 12:19:36 -0800666NBLog::LockedWriter::LockedWriter(void *shared, size_t size)
667 : Writer(shared, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800668{
669}
670
671void NBLog::LockedWriter::log(const char *string)
672{
673 Mutex::Autolock _l(mLock);
674 Writer::log(string);
675}
676
677void NBLog::LockedWriter::logf(const char *fmt, ...)
678{
679 // FIXME should not take the lock until after formatting is done
680 Mutex::Autolock _l(mLock);
681 va_list ap;
682 va_start(ap, fmt);
683 Writer::logvf(fmt, ap);
684 va_end(ap);
685}
686
687void NBLog::LockedWriter::logvf(const char *fmt, va_list ap)
688{
689 // FIXME should not take the lock until after formatting is done
690 Mutex::Autolock _l(mLock);
691 Writer::logvf(fmt, ap);
692}
693
694void NBLog::LockedWriter::logTimestamp()
695{
696 // FIXME should not take the lock until after the clock_gettime() syscall
697 Mutex::Autolock _l(mLock);
698 Writer::logTimestamp();
699}
700
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700701void NBLog::LockedWriter::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800702{
703 Mutex::Autolock _l(mLock);
704 Writer::logTimestamp(ts);
705}
706
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800707void NBLog::LockedWriter::logInteger(const int x)
708{
709 Mutex::Autolock _l(mLock);
710 Writer::logInteger(x);
711}
712
713void NBLog::LockedWriter::logFloat(const float x)
714{
715 Mutex::Autolock _l(mLock);
716 Writer::logFloat(x);
717}
718
719void NBLog::LockedWriter::logPID()
720{
721 Mutex::Autolock _l(mLock);
722 Writer::logPID();
723}
724
725void NBLog::LockedWriter::logStart(const char *fmt)
726{
727 Mutex::Autolock _l(mLock);
728 Writer::logStart(fmt);
729}
730
731
732void NBLog::LockedWriter::logEnd()
733{
734 Mutex::Autolock _l(mLock);
735 Writer::logEnd();
736}
737
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700738void NBLog::LockedWriter::logHash(log_hash_t hash)
739{
740 Mutex::Autolock _l(mLock);
741 Writer::logHash(hash);
742}
743
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800744bool NBLog::LockedWriter::isEnabled() const
745{
746 Mutex::Autolock _l(mLock);
747 return Writer::isEnabled();
748}
749
750bool NBLog::LockedWriter::setEnabled(bool enabled)
751{
752 Mutex::Autolock _l(mLock);
753 return Writer::setEnabled(enabled);
754}
755
756// ---------------------------------------------------------------------------
757
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700758const std::set<NBLog::Event> NBLog::Reader::startingTypes {NBLog::Event::EVENT_START_FMT,
759 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
760const std::set<NBLog::Event> NBLog::Reader::endingTypes {NBLog::Event::EVENT_END_FMT,
Sanna Catherine de Treville Wagerd4a68f62017-06-23 16:09:41 -0700761 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
Glenn Kasten535e1612016-12-05 12:19:36 -0800762NBLog::Reader::Reader(const void *shared, size_t size)
763 : mShared((/*const*/ Shared *) shared), /*mIMemory*/
764 mFd(-1), mIndent(0),
765 mFifo(mShared != NULL ?
766 new audio_utils_fifo(size, sizeof(uint8_t),
767 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700768 mFifoReader(mFifo != NULL ? new audio_utils_fifo_reader(*mFifo) : NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800769{
770}
771
Glenn Kasten535e1612016-12-05 12:19:36 -0800772NBLog::Reader::Reader(const sp<IMemory>& iMemory, size_t size)
773 : Reader(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800774{
Glenn Kasten535e1612016-12-05 12:19:36 -0800775 mIMemory = iMemory;
776}
777
778NBLog::Reader::~Reader()
779{
780 delete mFifoReader;
781 delete mFifo;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800782}
783
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700784const uint8_t *NBLog::Reader::findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
785 const std::set<Event> &types) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800786 while (back + Entry::kPreviousLengthOffset >= front) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700787 const uint8_t *prev = back - back[Entry::kPreviousLengthOffset] - Entry::kOverhead;
788 if (prev < front || prev + prev[offsetof(entry, length)] +
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800789 Entry::kOverhead != back) {
790
791 // prev points to an out of limits or inconsistent entry
792 return nullptr;
793 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700794 if (types.find((const Event) prev[offsetof(entry, type)]) != types.end()) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800795 return prev;
796 }
797 back = prev;
798 }
799 return nullptr; // no entry found
800}
801
Nicolas Roulet40a44982017-02-03 13:39:57 -0800802std::unique_ptr<NBLog::Reader::Snapshot> NBLog::Reader::getSnapshot()
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800803{
Glenn Kasten535e1612016-12-05 12:19:36 -0800804 if (mFifoReader == NULL) {
Nicolas Roulet40a44982017-02-03 13:39:57 -0800805 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800806 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800807 // make a copy to avoid race condition with writer
Glenn Kasten535e1612016-12-05 12:19:36 -0800808 size_t capacity = mFifo->capacity();
809
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800810 // This emulates the behaviour of audio_utils_fifo_reader::read, but without incrementing the
811 // reader index. The index is incremented after handling corruption, to after the last complete
812 // entry of the buffer
813 size_t lost;
814 audio_utils_iovec iovec[2];
815 ssize_t availToRead = mFifoReader->obtain(iovec, capacity, NULL /*timeout*/, &lost);
816 if (availToRead <= 0) {
817 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
818 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800819
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800820 std::unique_ptr<Snapshot> snapshot(new Snapshot(availToRead));
821 memcpy(snapshot->mData, (const char *) mFifo->buffer() + iovec[0].mOffset, iovec[0].mLength);
822 if (iovec[1].mLength > 0) {
823 memcpy(snapshot->mData + (iovec[0].mLength),
824 (const char *) mFifo->buffer() + iovec[1].mOffset, iovec[1].mLength);
825 }
826
827 // Handle corrupted buffer
828 // Potentially, a buffer has corrupted data on both beginning (due to overflow) and end
829 // (due to incomplete format entry). But even if the end format entry is incomplete,
830 // it ends in a complete entry (which is not an END_FMT). So is safe to traverse backwards.
831 // TODO: handle client corruption (in the middle of a buffer)
832
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700833 const uint8_t *back = snapshot->mData + availToRead;
834 const uint8_t *front = snapshot->mData;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800835
836 // Find last END_FMT. <back> is sitting on an entry which might be the middle of a FormatEntry.
837 // We go backwards until we find an EVENT_END_FMT.
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700838 const uint8_t *lastEnd = findLastEntryOfTypes(front, back, endingTypes);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800839 if (lastEnd == nullptr) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700840 snapshot->mEnd = snapshot->mBegin = EntryIterator(front);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800841 } else {
842 // end of snapshot points to after last END_FMT entry
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700843 snapshot->mEnd = EntryIterator(lastEnd).next();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800844 // find first START_FMT
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700845 const uint8_t *firstStart = nullptr;
846 const uint8_t *firstStartTmp = snapshot->mEnd;
847 while ((firstStartTmp = findLastEntryOfTypes(front, firstStartTmp, startingTypes))
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800848 != nullptr) {
849 firstStart = firstStartTmp;
850 }
851 // firstStart is null if no START_FMT entry was found before lastEnd
852 if (firstStart == nullptr) {
853 snapshot->mBegin = snapshot->mEnd;
854 } else {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700855 snapshot->mBegin = EntryIterator(firstStart);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800856 }
857 }
858
859 // advance fifo reader index to after last entry read.
860 mFifoReader->release(snapshot->mEnd - front);
861
862 snapshot->mLost = lost;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800863 return snapshot;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800864
Nicolas Roulet40a44982017-02-03 13:39:57 -0800865}
866
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -0700867// writes sample deltas to file, either truncating or appending
868inline void writeHistToFile(const std::vector<int64_t> &samples, bool append) {
869 // name of file on audioserver
870 static const char* const kName = (char *)"/data/misc/audioserver/sample_results.txt";
871 // stores deltas between the samples
872 std::vector<int64_t> intervals;
873 if (samples.size() == 0) return;
874 for (size_t i = 1; i < samples.size(); ++i) {
875 intervals.push_back(deltaMs(samples[i - 1], samples[i]));
876 }
877 // Deletes maximum value in a histogram. Temp quick fix.
878 // FIXME: need to find root cause of approx. 35th element from the end
879 // consistently being an outlier in the first histogram of a flush
880 // ALOGW("%" PRId64 "before", (int64_t) *(std::max_element(intervals.begin(), intervals.end())));
881 intervals.erase(std::max_element(intervals.begin(), intervals.end()));
882 // ALOGW("%" PRId64 "after", (int64_t) *(std::max_element(intervals.begin(), intervals.end())));
883 std::ofstream ofs;
884 ofs.open(kName, append ? std::ios::app : std::ios::trunc);
885 if (!ofs) {
886 ALOGW("couldn't open file %s", kName);
887 return;
888 }
889 for (size_t i = 0; i < intervals.size(); ++i) {
890 ofs << intervals[i] << "\n";
891 }
892 ofs.close();
893}
894
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700895// converts a time series into a map. key: buffer period length. value: count
896static std::map<int, int> buildBuckets(const std::vector<int64_t> &samples) {
897 // TODO allow buckets of variable resolution
898 std::map<int, int> buckets;
899 for (size_t i = 1; i < samples.size(); ++i) {
900 ++buckets[deltaMs(samples[i - 1], samples[i])];
901 }
902 return buckets;
903}
904
Nicolas Roulet40a44982017-02-03 13:39:57 -0800905void NBLog::Reader::dump(int fd, size_t indent, NBLog::Reader::Snapshot &snapshot)
906{
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700907 // CallStack cs(LOG_TAG);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700908 mFd = fd;
909 mIndent = indent;
910 String8 timestamp, body;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700911 size_t lost = snapshot.lost() + (snapshot.begin() - EntryIterator(snapshot.data()));
Glenn Kastenc02c9612013-10-15 09:25:11 -0700912 if (lost > 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700913 body.appendFormat("warning: lost %zu bytes worth of events", lost);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700914 // TODO timestamp empty here, only other choice to wait for the first timestamp event in the
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700915 // log to push it out. Consider keeping the timestamp/body between calls to copyEntryDataAt().
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700916 dumpLine(timestamp, body);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800917 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700918
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800919 for (auto entry = snapshot.begin(); entry != snapshot.end();) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800920 switch (entry->type) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800921 case EVENT_START_FMT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800922 entry = handleFormat(FormatEntry(entry), &timestamp, &body);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800923 break;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700924 case EVENT_HISTOGRAM_ENTRY_TS: {
925 HistTsEntryWithAuthor *data = (HistTsEntryWithAuthor *) (entry->data);
926 // TODO This memcpies are here to avoid unaligned memory access crash.
927 // There's probably a more efficient way to do it
928 log_hash_t hash;
929 memcpy(&hash, &(data->hash), sizeof(hash));
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700930 int64_t ts;
931 memcpy(&ts, &data->ts, sizeof(ts));
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700932 const std::pair<log_hash_t, int> key(hash, data->author);
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700933 // TODO might want to filter excessively high outliers, which are usually caused
934 // by the thread being inactive.
935 mHists[key].push_back(ts);
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700936 // store time series data for each reader in order to bucket it once there
937 // is enough data. Then, it is written to recentHists as a histogram.
938 mTimeStampSeries[data->author].push_back(ts);
939 // if length of the time series has reached kShortHistSize samples,
940 // compute its histogram, append this to mRecentHists and erase the time series
941 if (mTimeStampSeries[data->author].size() >= kShortHistSize) {
942 mRecentHists.emplace_front(data->author,
943 buildBuckets(mTimeStampSeries[data->author]));
944 // do not let mRecentHists exceed capacity
945 // TODO: turn the FIFO queue into a circular buffer
946 if (mRecentHists.size() >= kRecentHistsCapacity) {
947 mRecentHists.pop_back();
948 }
949 mTimeStampSeries.erase(data->author);
950 }
951 // if an element in mHists has not grown for a long time, delete
952 // TODO copy histogram data only to mRecentHistsBuffer and pop oldest
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700953 ++entry;
954 break;
955 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800956 case EVENT_END_FMT:
957 body.appendFormat("warning: got to end format event");
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800958 ++entry;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800959 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800960 case EVENT_RESERVED:
961 default:
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800962 body.appendFormat("warning: unexpected event %d", entry->type);
963 ++entry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800964 break;
965 }
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700966 }
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700967 PerformanceAnalysis performanceAnalyzer;
968 performanceAnalyzer.reportPerformance(&body, mRecentHists);
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700969 if (!body.isEmpty()) {
970 dumpLine(timestamp, body);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700971 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800972}
973
Nicolas Roulet40a44982017-02-03 13:39:57 -0800974void NBLog::Reader::dump(int fd, size_t indent)
975{
976 // get a snapshot, dump it
977 std::unique_ptr<Snapshot> snap = getSnapshot();
978 dump(fd, indent, *snap);
979}
980
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800981void NBLog::Reader::dumpLine(const String8 &timestamp, String8 &body)
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700982{
983 if (mFd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700984 dprintf(mFd, "%.*s%s %s\n", mIndent, "", timestamp.string(), body.string());
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700985 } else {
986 ALOGI("%.*s%s %s", mIndent, "", timestamp.string(), body.string());
987 }
988 body.clear();
989}
990
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800991bool NBLog::Reader::isIMemory(const sp<IMemory>& iMemory) const
992{
Glenn Kasten481fb672013-09-30 14:39:28 -0700993 return iMemory != 0 && mIMemory != 0 && iMemory->pointer() == mIMemory->pointer();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800994}
995
Glenn Kasten1c446272017-04-07 09:49:07 -0700996// ---------------------------------------------------------------------------
997
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800998void NBLog::appendTimestamp(String8 *body, const void *data) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700999 int64_t ts;
1000 memcpy(&ts, data, sizeof(ts));
1001 body->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1002 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001003}
1004
1005void NBLog::appendInt(String8 *body, const void *data) {
1006 int x = *((int*) data);
1007 body->appendFormat("<%d>", x);
1008}
1009
1010void NBLog::appendFloat(String8 *body, const void *data) {
1011 float f;
1012 memcpy(&f, data, sizeof(float));
1013 body->appendFormat("<%f>", f);
1014}
1015
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001016void NBLog::appendPID(String8 *body, const void* data, size_t length) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001017 pid_t id = *((pid_t*) data);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001018 char * name = &((char*) data)[sizeof(pid_t)];
1019 body->appendFormat("<PID: %d, name: %.*s>", id, (int) (length - sizeof(pid_t)), name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001020}
1021
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001022String8 NBLog::bufferDump(const uint8_t *buffer, size_t size)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001023{
1024 String8 str;
1025 str.append("[ ");
1026 for(size_t i = 0; i < size; i++)
1027 {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001028 str.appendFormat("%d ", buffer[i]);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001029 }
1030 str.append("]");
1031 return str;
1032}
1033
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001034String8 NBLog::bufferDump(const EntryIterator &it)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001035{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001036 return bufferDump(it, it->length + Entry::kOverhead);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001037}
1038
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001039NBLog::EntryIterator NBLog::Reader::handleFormat(const FormatEntry &fmtEntry,
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001040 String8 *timestamp,
1041 String8 *body) {
Nicolas Roulet40a44982017-02-03 13:39:57 -08001042 // log timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001043 int64_t ts = fmtEntry.timestamp();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001044 timestamp->clear();
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001045 timestamp->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1046 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Roulet40a44982017-02-03 13:39:57 -08001047
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -07001048 // log unique hash
1049 log_hash_t hash = fmtEntry.hash();
1050 // print only lower 16bit of hash as hex and line as int to reduce spam in the log
1051 body->appendFormat("%.4X-%d ", (int)(hash >> 16) & 0xFFFF, (int) hash & 0xFFFF);
1052
Nicolas Roulet40a44982017-02-03 13:39:57 -08001053 // log author (if present)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001054 handleAuthor(fmtEntry, body);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001055
1056 // log string
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001057 NBLog::EntryIterator arg = fmtEntry.args();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001058
1059 const char* fmt = fmtEntry.formatString();
1060 size_t fmt_length = fmtEntry.formatStringLength();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001061
1062 for (size_t fmt_offset = 0; fmt_offset < fmt_length; ++fmt_offset) {
1063 if (fmt[fmt_offset] != '%') {
1064 body->append(&fmt[fmt_offset], 1); // TODO optimize to write consecutive strings at once
1065 continue;
1066 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001067 // case "%%""
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001068 if (fmt[++fmt_offset] == '%') {
1069 body->append("%");
1070 continue;
1071 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001072 // case "%\0"
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001073 if (fmt_offset == fmt_length) {
1074 continue;
1075 }
1076
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001077 NBLog::Event event = (NBLog::Event) arg->type;
1078 size_t length = arg->length;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001079
1080 // TODO check length for event type is correct
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001081
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001082 if (event == EVENT_END_FMT) {
1083 break;
1084 }
1085
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001086 // TODO: implement more complex formatting such as %.3f
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001087 const uint8_t *datum = arg->data; // pointer to the current event args
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001088 switch(fmt[fmt_offset])
1089 {
1090 case 's': // string
Nicolas Roulet4da78202017-02-03 12:53:39 -08001091 ALOGW_IF(event != EVENT_STRING,
1092 "NBLog Reader incompatible event for string specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001093 body->append((const char*) datum, length);
1094 break;
1095
1096 case 't': // timestamp
Nicolas Roulet4da78202017-02-03 12:53:39 -08001097 ALOGW_IF(event != EVENT_TIMESTAMP,
1098 "NBLog Reader incompatible event for timestamp specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001099 appendTimestamp(body, datum);
1100 break;
1101
1102 case 'd': // integer
Nicolas Roulet4da78202017-02-03 12:53:39 -08001103 ALOGW_IF(event != EVENT_INTEGER,
1104 "NBLog Reader incompatible event for integer specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001105 appendInt(body, datum);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001106 break;
1107
1108 case 'f': // float
Nicolas Roulet4da78202017-02-03 12:53:39 -08001109 ALOGW_IF(event != EVENT_FLOAT,
1110 "NBLog Reader incompatible event for float specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001111 appendFloat(body, datum);
1112 break;
1113
1114 case 'p': // pid
Nicolas Roulet4da78202017-02-03 12:53:39 -08001115 ALOGW_IF(event != EVENT_PID,
1116 "NBLog Reader incompatible event for pid specifier: %d", event);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001117 appendPID(body, datum, length);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001118 break;
1119
1120 default:
1121 ALOGW("NBLog Reader encountered unknown character %c", fmt[fmt_offset]);
1122 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001123 ++arg;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001124 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001125 ALOGW_IF(arg->type != EVENT_END_FMT, "Expected end of format, got %d", arg->type);
1126 ++arg;
1127 return arg;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001128}
1129
Nicolas Roulet40a44982017-02-03 13:39:57 -08001130NBLog::Merger::Merger(const void *shared, size_t size):
Nicolas Roulet40a44982017-02-03 13:39:57 -08001131 mShared((Shared *) shared),
1132 mFifo(mShared != NULL ?
1133 new audio_utils_fifo(size, sizeof(uint8_t),
1134 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
1135 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL)
1136 {}
1137
1138void NBLog::Merger::addReader(const NBLog::NamedReader &reader) {
Glenn Kasten1c446272017-04-07 09:49:07 -07001139 // FIXME This is called by binder thread in MediaLogService::registerWriter
1140 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001141 mNamedReaders.push_back(reader);
1142}
1143
1144// items placed in priority queue during merge
1145// composed by a timestamp and the index of the snapshot where the timestamp came from
1146struct MergeItem
1147{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001148 int64_t ts;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001149 int index;
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001150 MergeItem(int64_t ts, int index): ts(ts), index(index) {}
Nicolas Roulet40a44982017-02-03 13:39:57 -08001151};
1152
1153// operators needed for priority queue in merge
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001154// bool operator>(const int64_t &t1, const int64_t &t2) {
1155// return t1.tv_sec > t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec);
1156// }
Nicolas Roulet40a44982017-02-03 13:39:57 -08001157
1158bool operator>(const struct MergeItem &i1, const struct MergeItem &i2) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001159 return i1.ts > i2.ts || (i1.ts == i2.ts && i1.index > i2.index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001160}
1161
1162// Merge registered readers, sorted by timestamp
1163void NBLog::Merger::merge() {
Glenn Kasten1c446272017-04-07 09:49:07 -07001164 // FIXME This is called by merge thread
1165 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001166 int nLogs = mNamedReaders.size();
1167 std::vector<std::unique_ptr<NBLog::Reader::Snapshot>> snapshots(nLogs);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001168 std::vector<NBLog::EntryIterator> offsets(nLogs);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001169 for (int i = 0; i < nLogs; ++i) {
1170 snapshots[i] = mNamedReaders[i].reader()->getSnapshot();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001171 offsets[i] = snapshots[i]->begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001172 }
1173 // initialize offsets
Nicolas Roulet40a44982017-02-03 13:39:57 -08001174 // TODO custom heap implementation could allow to update top, improving performance
1175 // for bursty buffers
1176 std::priority_queue<MergeItem, std::vector<MergeItem>, std::greater<MergeItem>> timestamps;
1177 for (int i = 0; i < nLogs; ++i)
1178 {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001179 if (offsets[i] != snapshots[i]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001180 int64_t ts = AbstractEntry::buildEntry(offsets[i])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001181 timestamps.emplace(ts, i);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001182 }
1183 }
1184
1185 while (!timestamps.empty()) {
1186 // find minimum timestamp
1187 int index = timestamps.top().index;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001188 // copy it to the log, increasing offset
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001189 offsets[index] = AbstractEntry::buildEntry(offsets[index])->copyWithAuthor(mFifoWriter,
1190 index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001191 // update data structures
Nicolas Roulet40a44982017-02-03 13:39:57 -08001192 timestamps.pop();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001193 if (offsets[index] != snapshots[index]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001194 int64_t ts = AbstractEntry::buildEntry(offsets[index])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001195 timestamps.emplace(ts, index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001196 }
1197 }
1198}
1199
Glenn Kasten1c446272017-04-07 09:49:07 -07001200const std::vector<NBLog::NamedReader>& NBLog::Merger::getNamedReaders() const {
1201 // FIXME This is returning a reference to a shared variable that needs a lock
1202 return mNamedReaders;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001203}
1204
Glenn Kasten1c446272017-04-07 09:49:07 -07001205// ---------------------------------------------------------------------------
1206
Nicolas Roulet40a44982017-02-03 13:39:57 -08001207NBLog::MergeReader::MergeReader(const void *shared, size_t size, Merger &merger)
1208 : Reader(shared, size), mNamedReaders(merger.getNamedReaders()) {}
1209
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001210void NBLog::MergeReader::handleAuthor(const NBLog::AbstractEntry &entry, String8 *body) {
1211 int author = entry.author();
Glenn Kasten1c446272017-04-07 09:49:07 -07001212 // FIXME Needs a lock
1213 const char* name = mNamedReaders[author].name();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001214 body->appendFormat("%s: ", name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001215}
1216
Glenn Kasten1c446272017-04-07 09:49:07 -07001217// ---------------------------------------------------------------------------
1218
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001219NBLog::MergeThread::MergeThread(NBLog::Merger &merger)
1220 : mMerger(merger),
1221 mTimeoutUs(0) {}
1222
1223NBLog::MergeThread::~MergeThread() {
1224 // set exit flag, set timeout to 0 to force threadLoop to exit and wait for the thread to join
1225 requestExit();
1226 setTimeoutUs(0);
1227 join();
1228}
1229
1230bool NBLog::MergeThread::threadLoop() {
1231 bool doMerge;
1232 {
1233 AutoMutex _l(mMutex);
1234 // If mTimeoutUs is negative, wait on the condition variable until it's positive.
1235 // If it's positive, wait kThreadSleepPeriodUs and then merge
1236 nsecs_t waitTime = mTimeoutUs > 0 ? kThreadSleepPeriodUs * 1000 : LLONG_MAX;
1237 mCond.waitRelative(mMutex, waitTime);
1238 doMerge = mTimeoutUs > 0;
1239 mTimeoutUs -= kThreadSleepPeriodUs;
1240 }
1241 if (doMerge) {
1242 mMerger.merge();
1243 }
1244 return true;
1245}
1246
1247void NBLog::MergeThread::wakeup() {
1248 setTimeoutUs(kThreadWakeupPeriodUs);
1249}
1250
1251void NBLog::MergeThread::setTimeoutUs(int time) {
1252 AutoMutex _l(mMutex);
1253 mTimeoutUs = time;
1254 mCond.signal();
1255}
1256
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001257} // namespace android