blob: 827cba9a58d1cde71c1ea3169ee2b411911d60d8 [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 Wagera8a8a472017-07-11 09:41:25 -070027* calls NBLOG::Writer::logEventHistTS once
28* NBLOG::Writer::logEventHistTS
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070029* 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
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070047* Similarly, LOG_AUDIO_STATE() is called by onStateChange whenever audio is
48* turned on or off, and writes this notification to the FIFO.
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070049*
Sanna Catherine de Treville Wagerd4a68f62017-06-23 16:09:41 -070050* 2) reading the data from shared memory
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070051* Thread::threadloop()
52* TODO: add description?
53* NBLog::MergeThread::threadLoop()
54* calls NBLog::Merger::merge
55* NBLog::Merger::merge
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070056* Merges snapshots sorted by timestamp
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070057* for each reader in vector of class NamedReader,
58* callsNamedReader::reader()->getSnapshot
59* TODO: check whether the rest of this function is relevant
60* NBLog::Reader::getSnapshot
61* copies snapshot of reader's fifo buffer into its own buffer
62* calls mFifoReader->obtain to find readable data
63* sets snapshot.begin() and .end() iterators to boundaries of valid entries
64* moves the fifo reader index to after the last entry read
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070065* 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 -070066*
Sanna Catherine de Treville Wagerd4a68f62017-06-23 16:09:41 -070067* 3) reading the data from private buffer
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070068* MediaLogService::dump
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -070069* calls NBLog::Reader::dump(CONSOLE)
70* The private buffer contains all logs for all readers in shared memory
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070071* NBLog::Reader::dump(int)
72* calls getSnapshot on the current reader
73* calls dump(int, size_t, Snapshot)
74* NBLog::Reader::dump(int, size, snapshot)
75* iterates through snapshot's events and switches based on their type
76* (string, timestamp, etc...)
77* In the case of EVENT_HISTOGRAM_ENTRY_TS, adds a list of timestamp sequences
78* (histogram entry) to NBLog::mHists
Sanna Catherine de Treville Wagerd4a68f62017-06-23 16:09:41 -070079* TODO: add every HISTOGRAM_ENTRY_TS to two
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070080* circular buffers: one short-term and one long-term (can add even longer-term
81* structures in the future). When dump is called, print everything currently
82* in the buffer.
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070083* NBLog::drawHistogram
84* input: timestamp array
85* buckets this to a histogram and prints
86*
87*/
88
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080089#define LOG_TAG "NBLog"
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070090// #define LOG_NDEBUG 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080091
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -070092#include <algorithm>
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -080093#include <climits>
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -070094#include <deque>
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -070095#include <fstream>
96// #include <inttypes.h>
97#include <iostream>
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -070098#include <math.h>
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -070099#include <numeric>
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -0700100#include <vector>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800101#include <stdarg.h>
102#include <stdint.h>
103#include <stdio.h>
104#include <string.h>
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800105#include <sys/prctl.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800106#include <time.h>
107#include <new>
Glenn Kasten535e1612016-12-05 12:19:36 -0800108#include <audio_utils/roundup.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800109#include <media/nbaio/NBLog.h>
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700110#include <media/nbaio/PerformanceAnalysis.h>
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700111#include <media/nbaio/ReportPerformance.h>
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700112// #include <utils/CallStack.h> // used to print callstack
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800113#include <utils/Log.h>
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700114#include <utils/String8.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800115
Nicolas Roulet40a44982017-02-03 13:39:57 -0800116#include <queue>
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700117#include <utility>
Nicolas Roulet40a44982017-02-03 13:39:57 -0800118
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800119namespace android {
120
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700121int NBLog::Entry::copyEntryDataAt(size_t offset) const
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800122{
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700123 // FIXME This is too slow
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800124 if (offset == 0)
125 return mEvent;
126 else if (offset == 1)
127 return mLength;
128 else if (offset < (size_t) (mLength + 2))
129 return ((char *) mData)[offset - 2];
130 else if (offset == (size_t) (mLength + 2))
131 return mLength;
132 else
133 return 0;
134}
135
136// ---------------------------------------------------------------------------
137
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700138/*static*/
139std::unique_ptr<NBLog::AbstractEntry> NBLog::AbstractEntry::buildEntry(const uint8_t *ptr) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -0700140 const uint8_t type = EntryIterator(ptr)->type;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700141 switch (type) {
142 case EVENT_START_FMT:
143 return std::make_unique<FormatEntry>(FormatEntry(ptr));
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700144 case EVENT_AUDIO_STATE:
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700145 case EVENT_HISTOGRAM_ENTRY_TS:
146 return std::make_unique<HistogramEntry>(HistogramEntry(ptr));
147 default:
148 ALOGW("Tried to create AbstractEntry of type %d", type);
149 return nullptr;
150 }
Nicolas Roulet40a44982017-02-03 13:39:57 -0800151}
152
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700153NBLog::AbstractEntry::AbstractEntry(const uint8_t *entry) : mEntry(entry) {
154}
155
156// ---------------------------------------------------------------------------
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800157
Sanna Catherine de Treville Wagerdd92d7e2017-05-15 14:56:53 -0700158NBLog::EntryIterator NBLog::FormatEntry::begin() const {
159 return EntryIterator(mEntry);
160}
161
Nicolas Roulet40a44982017-02-03 13:39:57 -0800162const char *NBLog::FormatEntry::formatString() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800163 return (const char*) mEntry + offsetof(entry, data);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800164}
165
166size_t NBLog::FormatEntry::formatStringLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800167 return mEntry[offsetof(entry, length)];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800168}
169
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700170NBLog::EntryIterator NBLog::FormatEntry::args() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800171 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700172 // skip start fmt
173 ++it;
174 // skip timestamp
175 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700176 // skip hash
177 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700178 // Skip author if present
179 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800180 ++it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800181 }
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700182 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800183}
184
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700185int64_t NBLog::FormatEntry::timestamp() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800186 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700187 // skip start fmt
188 ++it;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700189 return it.payload<int64_t>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800190}
191
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700192NBLog::log_hash_t NBLog::FormatEntry::hash() const {
193 auto it = begin();
194 // skip start fmt
195 ++it;
196 // skip timestamp
197 ++it;
198 // unaligned 64-bit read not supported
199 log_hash_t hash;
200 memcpy(&hash, it->data, sizeof(hash));
201 return hash;
202}
203
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700204int NBLog::FormatEntry::author() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800205 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700206 // skip start fmt
207 ++it;
208 // skip timestamp
209 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700210 // skip hash
211 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700212 // if there is an author entry, return it, return -1 otherwise
213 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800214 return it.payload<int>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800215 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800216 return -1;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800217}
218
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700219NBLog::EntryIterator NBLog::FormatEntry::copyWithAuthor(
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800220 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
221 auto it = begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800222 // copy fmt start entry
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800223 it.copyTo(dst);
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700224 // copy timestamp
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700225 (++it).copyTo(dst); // copy hash
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700226 (++it).copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800227 // insert author entry
228 size_t authorEntrySize = NBLog::Entry::kOverhead + sizeof(author);
229 uint8_t authorEntry[authorEntrySize];
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800230 authorEntry[offsetof(entry, type)] = EVENT_AUTHOR;
231 authorEntry[offsetof(entry, length)] =
232 authorEntry[authorEntrySize + NBLog::Entry::kPreviousLengthOffset] =
233 sizeof(author);
234 *(int*) (&authorEntry[offsetof(entry, data)]) = author;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800235 dst->write(authorEntry, authorEntrySize);
236 // copy rest of entries
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800237 while ((++it)->type != EVENT_END_FMT) {
238 it.copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800239 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800240 it.copyTo(dst);
241 ++it;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800242 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800243}
244
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700245void NBLog::EntryIterator::copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800246 size_t length = ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
247 dst->write(ptr, length);
248}
Nicolas Roulet40a44982017-02-03 13:39:57 -0800249
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700250void NBLog::EntryIterator::copyData(uint8_t *dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800251 memcpy((void*) dst, ptr + offsetof(entry, data), ptr[offsetof(entry, length)]);
252}
253
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700254NBLog::EntryIterator::EntryIterator()
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800255 : ptr(nullptr) {}
256
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700257NBLog::EntryIterator::EntryIterator(const uint8_t *entry)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800258 : ptr(entry) {}
259
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700260NBLog::EntryIterator::EntryIterator(const NBLog::EntryIterator &other)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800261 : ptr(other.ptr) {}
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 -0700267const NBLog::entry* NBLog::EntryIterator::operator->() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800268 return (entry*) ptr;
269}
270
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700271NBLog::EntryIterator& NBLog::EntryIterator::operator++() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800272 ptr += ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
273 return *this;
274}
275
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700276NBLog::EntryIterator& NBLog::EntryIterator::operator--() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800277 ptr -= ptr[NBLog::Entry::kPreviousLengthOffset] + NBLog::Entry::kOverhead;
278 return *this;
279}
280
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700281NBLog::EntryIterator NBLog::EntryIterator::next() const {
282 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800283 return ++aux;
284}
285
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700286NBLog::EntryIterator NBLog::EntryIterator::prev() const {
287 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800288 return --aux;
289}
290
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700291int NBLog::EntryIterator::operator-(const NBLog::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::operator!=(const EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800296 return ptr != other.ptr;
297}
298
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700299bool NBLog::EntryIterator::hasConsistentLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800300 return ptr[offsetof(entry, length)] == ptr[ptr[offsetof(entry, length)] +
301 NBLog::Entry::kOverhead + NBLog::Entry::kPreviousLengthOffset];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800302}
303
304// ---------------------------------------------------------------------------
305
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700306int64_t NBLog::HistogramEntry::timestamp() const {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700307 return EntryIterator(mEntry).payload<HistTsEntry>().ts;
308}
309
310NBLog::log_hash_t NBLog::HistogramEntry::hash() const {
311 return EntryIterator(mEntry).payload<HistTsEntry>().hash;
312}
313
314int NBLog::HistogramEntry::author() const {
315 EntryIterator it(mEntry);
316 if (it->length == sizeof(HistTsEntryWithAuthor)) {
317 return it.payload<HistTsEntryWithAuthor>().author;
318 } else {
319 return -1;
320 }
321}
322
323NBLog::EntryIterator NBLog::HistogramEntry::copyWithAuthor(
324 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
325 // Current histogram entry has {type, length, struct HistTsEntry, length}.
326 // We now want {type, length, struct HistTsEntryWithAuthor, length}
327 uint8_t buffer[Entry::kOverhead + sizeof(HistTsEntryWithAuthor)];
328 // Copy content until the point we want to add the author
329 memcpy(buffer, mEntry, sizeof(entry) + sizeof(HistTsEntry));
330 // Copy the author
331 *(int*) (buffer + sizeof(entry) + sizeof(HistTsEntry)) = author;
332 // Update lengths
333 buffer[offsetof(entry, length)] = sizeof(HistTsEntryWithAuthor);
Ivan Lozanob303f2e2018-01-08 15:19:09 -0800334 buffer[offsetof(entry, data) + sizeof(HistTsEntryWithAuthor) + offsetof(ending, length)]
335 = sizeof(HistTsEntryWithAuthor);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700336 // Write new buffer into FIFO
337 dst->write(buffer, sizeof(buffer));
338 return EntryIterator(mEntry).next();
339}
340
341// ---------------------------------------------------------------------------
342
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800343#if 0 // FIXME see note in NBLog.h
344NBLog::Timeline::Timeline(size_t size, void *shared)
345 : mSize(roundup(size)), mOwn(shared == NULL),
346 mShared((Shared *) (mOwn ? new char[sharedSize(size)] : shared))
347{
348 new (mShared) Shared;
349}
350
351NBLog::Timeline::~Timeline()
352{
353 mShared->~Shared();
354 if (mOwn) {
355 delete[] (char *) mShared;
356 }
357}
358#endif
359
360/*static*/
361size_t NBLog::Timeline::sharedSize(size_t size)
362{
Glenn Kastened99c2b2016-12-12 08:31:24 -0800363 // TODO fifo now supports non-power-of-2 buffer sizes, so could remove the roundup
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800364 return sizeof(Shared) + roundup(size);
365}
366
367// ---------------------------------------------------------------------------
368
369NBLog::Writer::Writer()
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800370 : mShared(NULL), mFifo(NULL), mFifoWriter(NULL), mEnabled(false), mPidTag(NULL), mPidTagSize(0)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800371{
372}
373
Glenn Kasten535e1612016-12-05 12:19:36 -0800374NBLog::Writer::Writer(void *shared, size_t size)
375 : mShared((Shared *) shared),
376 mFifo(mShared != NULL ?
377 new audio_utils_fifo(size, sizeof(uint8_t),
378 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
379 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL),
380 mEnabled(mFifoWriter != NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800381{
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800382 // caching pid and process name
383 pid_t id = ::getpid();
384 char procName[16];
385 int status = prctl(PR_GET_NAME, procName);
386 if (status) { // error getting process name
387 procName[0] = '\0';
388 }
389 size_t length = strlen(procName);
390 mPidTagSize = length + sizeof(pid_t);
391 mPidTag = new char[mPidTagSize];
392 memcpy(mPidTag, &id, sizeof(pid_t));
393 memcpy(mPidTag + sizeof(pid_t), procName, length);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800394}
395
Glenn Kasten535e1612016-12-05 12:19:36 -0800396NBLog::Writer::Writer(const sp<IMemory>& iMemory, size_t size)
397 : Writer(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800398{
Glenn Kasten535e1612016-12-05 12:19:36 -0800399 mIMemory = iMemory;
400}
401
402NBLog::Writer::~Writer()
403{
404 delete mFifoWriter;
405 delete mFifo;
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800406 delete[] mPidTag;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800407}
408
409void NBLog::Writer::log(const char *string)
410{
411 if (!mEnabled) {
412 return;
413 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800414 LOG_ALWAYS_FATAL_IF(string == NULL, "Attempted to log NULL string");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800415 size_t length = strlen(string);
Glenn Kasten535e1612016-12-05 12:19:36 -0800416 if (length > Entry::kMaxLength) {
417 length = Entry::kMaxLength;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800418 }
419 log(EVENT_STRING, string, length);
420}
421
422void NBLog::Writer::logf(const char *fmt, ...)
423{
424 if (!mEnabled) {
425 return;
426 }
427 va_list ap;
428 va_start(ap, fmt);
429 Writer::logvf(fmt, ap); // the Writer:: is needed to avoid virtual dispatch for LockedWriter
430 va_end(ap);
431}
432
433void NBLog::Writer::logvf(const char *fmt, va_list ap)
434{
435 if (!mEnabled) {
436 return;
437 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800438 char buffer[Entry::kMaxLength + 1 /*NUL*/];
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800439 int length = vsnprintf(buffer, sizeof(buffer), fmt, ap);
440 if (length >= (int) sizeof(buffer)) {
441 length = sizeof(buffer) - 1;
442 // NUL termination is not required
443 // buffer[length] = '\0';
444 }
445 if (length >= 0) {
446 log(EVENT_STRING, buffer, length);
447 }
448}
449
450void NBLog::Writer::logTimestamp()
451{
452 if (!mEnabled) {
453 return;
454 }
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700455 int64_t ts = get_monotonic_ns();
456 if (ts > 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800457 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700458 } else {
459 ALOGE("Failed to get timestamp");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800460 }
461}
462
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700463void NBLog::Writer::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800464{
465 if (!mEnabled) {
466 return;
467 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800468 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
469}
470
471void NBLog::Writer::logInteger(const int x)
472{
473 if (!mEnabled) {
474 return;
475 }
476 log(EVENT_INTEGER, &x, sizeof(x));
477}
478
479void NBLog::Writer::logFloat(const float x)
480{
481 if (!mEnabled) {
482 return;
483 }
484 log(EVENT_FLOAT, &x, sizeof(x));
485}
486
487void NBLog::Writer::logPID()
488{
489 if (!mEnabled) {
490 return;
491 }
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800492 log(EVENT_PID, mPidTag, mPidTagSize);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800493}
494
495void NBLog::Writer::logStart(const char *fmt)
496{
497 if (!mEnabled) {
498 return;
499 }
500 size_t length = strlen(fmt);
501 if (length > Entry::kMaxLength) {
502 length = Entry::kMaxLength;
503 }
504 log(EVENT_START_FMT, fmt, length);
505}
506
507void NBLog::Writer::logEnd()
508{
509 if (!mEnabled) {
510 return;
511 }
512 Entry entry = Entry(EVENT_END_FMT, NULL, 0);
513 log(&entry, true);
514}
515
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700516void NBLog::Writer::logHash(log_hash_t hash)
517{
518 if (!mEnabled) {
519 return;
520 }
521 log(EVENT_HASH, &hash, sizeof(hash));
522}
523
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700524void NBLog::Writer::logEventHistTs(Event event, log_hash_t hash)
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700525{
526 if (!mEnabled) {
527 return;
528 }
529 HistTsEntry data;
530 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700531 data.ts = get_monotonic_ns();
532 if (data.ts > 0) {
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700533 log(event, &data, sizeof(data));
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700534 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700535 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700536 }
537}
538
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700539void NBLog::Writer::logFormat(const char *fmt, log_hash_t hash, ...)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800540{
541 if (!mEnabled) {
542 return;
543 }
544
545 va_list ap;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700546 va_start(ap, hash);
547 Writer::logVFormat(fmt, hash, ap);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800548 va_end(ap);
549}
550
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700551void NBLog::Writer::logVFormat(const char *fmt, log_hash_t hash, va_list argp)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800552{
553 if (!mEnabled) {
554 return;
555 }
556 Writer::logStart(fmt);
557 int i;
558 double f;
559 char* s;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700560 int64_t t;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800561 Writer::logTimestamp();
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700562 Writer::logHash(hash);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800563 for (const char *p = fmt; *p != '\0'; p++) {
564 // TODO: implement more complex formatting such as %.3f
565 if (*p != '%') {
566 continue;
567 }
568 switch(*++p) {
569 case 's': // string
570 s = va_arg(argp, char *);
571 Writer::log(s);
572 break;
573
574 case 't': // timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700575 t = va_arg(argp, int64_t);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800576 Writer::logTimestamp(t);
577 break;
578
579 case 'd': // integer
580 i = va_arg(argp, int);
581 Writer::logInteger(i);
582 break;
583
584 case 'f': // float
585 f = va_arg(argp, double); // float arguments are promoted to double in vararg lists
586 Writer::logFloat((float)f);
587 break;
588
589 case 'p': // pid
590 Writer::logPID();
591 break;
592
593 // the "%\0" case finishes parsing
594 case '\0':
595 --p;
596 break;
597
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800598 case '%':
599 break;
600
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800601 default:
602 ALOGW("NBLog Writer parsed invalid format specifier: %c", *p);
603 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800604 }
605 }
606 Writer::logEnd();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800607}
608
609void NBLog::Writer::log(Event event, const void *data, size_t length)
610{
611 if (!mEnabled) {
612 return;
613 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800614 if (data == NULL || length > Entry::kMaxLength) {
615 // TODO Perhaps it makes sense to display truncated data or at least a
616 // message that the data is too long? The current behavior can create
617 // a confusion for a programmer debugging their code.
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800618 return;
619 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700620 // Ignore if invalid event
621 if (event == EVENT_RESERVED || event >= EVENT_UPPER_BOUND) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800622 return;
623 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700624 Entry etr(event, data, length);
625 log(&etr, true /*trusted*/);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800626}
627
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700628void NBLog::Writer::log(const NBLog::Entry *etr, bool trusted)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800629{
630 if (!mEnabled) {
631 return;
632 }
633 if (!trusted) {
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700634 log(etr->mEvent, etr->mData, etr->mLength);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800635 return;
636 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700637 size_t need = etr->mLength + Entry::kOverhead; // mEvent, mLength, data[mLength], mLength
638 // need = number of bytes written to FIFO
Glenn Kasten535e1612016-12-05 12:19:36 -0800639
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800640 // FIXME optimize this using memcpy for the data part of the Entry.
641 // The Entry could have a method copyTo(ptr, offset, size) to optimize the copy.
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700642 // checks size of a single log Entry: type, length, data pointer and ending
Glenn Kasten535e1612016-12-05 12:19:36 -0800643 uint8_t temp[Entry::kMaxLength + Entry::kOverhead];
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700644 // write this data to temp array
Glenn Kasten535e1612016-12-05 12:19:36 -0800645 for (size_t i = 0; i < need; i++) {
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700646 temp[i] = etr->copyEntryDataAt(i);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800647 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700648 // write to circular buffer
Glenn Kasten535e1612016-12-05 12:19:36 -0800649 mFifoWriter->write(temp, need);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800650}
651
652bool NBLog::Writer::isEnabled() const
653{
654 return mEnabled;
655}
656
657bool NBLog::Writer::setEnabled(bool enabled)
658{
659 bool old = mEnabled;
660 mEnabled = enabled && mShared != NULL;
661 return old;
662}
663
664// ---------------------------------------------------------------------------
665
666NBLog::LockedWriter::LockedWriter()
667 : Writer()
668{
669}
670
Glenn Kasten535e1612016-12-05 12:19:36 -0800671NBLog::LockedWriter::LockedWriter(void *shared, size_t size)
672 : Writer(shared, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800673{
674}
675
676void NBLog::LockedWriter::log(const char *string)
677{
678 Mutex::Autolock _l(mLock);
679 Writer::log(string);
680}
681
682void NBLog::LockedWriter::logf(const char *fmt, ...)
683{
684 // FIXME should not take the lock until after formatting is done
685 Mutex::Autolock _l(mLock);
686 va_list ap;
687 va_start(ap, fmt);
688 Writer::logvf(fmt, ap);
689 va_end(ap);
690}
691
692void NBLog::LockedWriter::logvf(const char *fmt, va_list ap)
693{
694 // FIXME should not take the lock until after formatting is done
695 Mutex::Autolock _l(mLock);
696 Writer::logvf(fmt, ap);
697}
698
699void NBLog::LockedWriter::logTimestamp()
700{
701 // FIXME should not take the lock until after the clock_gettime() syscall
702 Mutex::Autolock _l(mLock);
703 Writer::logTimestamp();
704}
705
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700706void NBLog::LockedWriter::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800707{
708 Mutex::Autolock _l(mLock);
709 Writer::logTimestamp(ts);
710}
711
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800712void NBLog::LockedWriter::logInteger(const int x)
713{
714 Mutex::Autolock _l(mLock);
715 Writer::logInteger(x);
716}
717
718void NBLog::LockedWriter::logFloat(const float x)
719{
720 Mutex::Autolock _l(mLock);
721 Writer::logFloat(x);
722}
723
724void NBLog::LockedWriter::logPID()
725{
726 Mutex::Autolock _l(mLock);
727 Writer::logPID();
728}
729
730void NBLog::LockedWriter::logStart(const char *fmt)
731{
732 Mutex::Autolock _l(mLock);
733 Writer::logStart(fmt);
734}
735
736
737void NBLog::LockedWriter::logEnd()
738{
739 Mutex::Autolock _l(mLock);
740 Writer::logEnd();
741}
742
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700743void NBLog::LockedWriter::logHash(log_hash_t hash)
744{
745 Mutex::Autolock _l(mLock);
746 Writer::logHash(hash);
747}
748
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800749bool NBLog::LockedWriter::isEnabled() const
750{
751 Mutex::Autolock _l(mLock);
752 return Writer::isEnabled();
753}
754
755bool NBLog::LockedWriter::setEnabled(bool enabled)
756{
757 Mutex::Autolock _l(mLock);
758 return Writer::setEnabled(enabled);
759}
760
761// ---------------------------------------------------------------------------
762
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700763const std::set<NBLog::Event> NBLog::Reader::startingTypes {NBLog::Event::EVENT_START_FMT,
764 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
765const std::set<NBLog::Event> NBLog::Reader::endingTypes {NBLog::Event::EVENT_END_FMT,
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700766 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
767 NBLog::Event::EVENT_AUDIO_STATE};
768
Glenn Kasten535e1612016-12-05 12:19:36 -0800769NBLog::Reader::Reader(const void *shared, size_t size)
770 : mShared((/*const*/ Shared *) shared), /*mIMemory*/
771 mFd(-1), mIndent(0),
772 mFifo(mShared != NULL ?
773 new audio_utils_fifo(size, sizeof(uint8_t),
774 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700775 mFifoReader(mFifo != NULL ? new audio_utils_fifo_reader(*mFifo) : NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800776{
777}
778
Glenn Kasten535e1612016-12-05 12:19:36 -0800779NBLog::Reader::Reader(const sp<IMemory>& iMemory, size_t size)
780 : Reader(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800781{
Glenn Kasten535e1612016-12-05 12:19:36 -0800782 mIMemory = iMemory;
783}
784
785NBLog::Reader::~Reader()
786{
787 delete mFifoReader;
788 delete mFifo;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800789}
790
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700791const uint8_t *NBLog::Reader::findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
792 const std::set<Event> &types) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800793 while (back + Entry::kPreviousLengthOffset >= front) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700794 const uint8_t *prev = back - back[Entry::kPreviousLengthOffset] - Entry::kOverhead;
795 if (prev < front || prev + prev[offsetof(entry, length)] +
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800796 Entry::kOverhead != back) {
797
798 // prev points to an out of limits or inconsistent entry
799 return nullptr;
800 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700801 if (types.find((const Event) prev[offsetof(entry, type)]) != types.end()) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800802 return prev;
803 }
804 back = prev;
805 }
806 return nullptr; // no entry found
807}
808
Nicolas Roulet40a44982017-02-03 13:39:57 -0800809std::unique_ptr<NBLog::Reader::Snapshot> NBLog::Reader::getSnapshot()
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800810{
Glenn Kasten535e1612016-12-05 12:19:36 -0800811 if (mFifoReader == NULL) {
Nicolas Roulet40a44982017-02-03 13:39:57 -0800812 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800813 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800814 // make a copy to avoid race condition with writer
Glenn Kasten535e1612016-12-05 12:19:36 -0800815 size_t capacity = mFifo->capacity();
816
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800817 // This emulates the behaviour of audio_utils_fifo_reader::read, but without incrementing the
818 // reader index. The index is incremented after handling corruption, to after the last complete
819 // entry of the buffer
820 size_t lost;
821 audio_utils_iovec iovec[2];
822 ssize_t availToRead = mFifoReader->obtain(iovec, capacity, NULL /*timeout*/, &lost);
823 if (availToRead <= 0) {
824 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
825 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800826
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800827 std::unique_ptr<Snapshot> snapshot(new Snapshot(availToRead));
828 memcpy(snapshot->mData, (const char *) mFifo->buffer() + iovec[0].mOffset, iovec[0].mLength);
829 if (iovec[1].mLength > 0) {
830 memcpy(snapshot->mData + (iovec[0].mLength),
831 (const char *) mFifo->buffer() + iovec[1].mOffset, iovec[1].mLength);
832 }
833
834 // Handle corrupted buffer
835 // Potentially, a buffer has corrupted data on both beginning (due to overflow) and end
836 // (due to incomplete format entry). But even if the end format entry is incomplete,
837 // it ends in a complete entry (which is not an END_FMT). So is safe to traverse backwards.
838 // TODO: handle client corruption (in the middle of a buffer)
839
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700840 const uint8_t *back = snapshot->mData + availToRead;
841 const uint8_t *front = snapshot->mData;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800842
843 // Find last END_FMT. <back> is sitting on an entry which might be the middle of a FormatEntry.
844 // We go backwards until we find an EVENT_END_FMT.
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700845 const uint8_t *lastEnd = findLastEntryOfTypes(front, back, endingTypes);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800846 if (lastEnd == nullptr) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700847 snapshot->mEnd = snapshot->mBegin = EntryIterator(front);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800848 } else {
849 // end of snapshot points to after last END_FMT entry
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700850 snapshot->mEnd = EntryIterator(lastEnd).next();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800851 // find first START_FMT
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700852 const uint8_t *firstStart = nullptr;
853 const uint8_t *firstStartTmp = snapshot->mEnd;
854 while ((firstStartTmp = findLastEntryOfTypes(front, firstStartTmp, startingTypes))
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800855 != nullptr) {
856 firstStart = firstStartTmp;
857 }
858 // firstStart is null if no START_FMT entry was found before lastEnd
859 if (firstStart == nullptr) {
860 snapshot->mBegin = snapshot->mEnd;
861 } else {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700862 snapshot->mBegin = EntryIterator(firstStart);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800863 }
864 }
865
866 // advance fifo reader index to after last entry read.
867 mFifoReader->release(snapshot->mEnd - front);
868
869 snapshot->mLost = lost;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800870 return snapshot;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800871
Nicolas Roulet40a44982017-02-03 13:39:57 -0800872}
873
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700874// TODO: move this to PerformanceAnalysis
875// TODO: make call to dump periodic so that data in shared FIFO does not get overwritten
Nicolas Roulet40a44982017-02-03 13:39:57 -0800876void NBLog::Reader::dump(int fd, size_t indent, NBLog::Reader::Snapshot &snapshot)
877{
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700878 mFd = fd;
879 mIndent = indent;
880 String8 timestamp, body;
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700881 // FIXME: this is not thread safe
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700882 // TODO: need a separate instance of performanceAnalysis for each thread
883 // used to store data and to call analysis functions
884 static ReportPerformance::PerformanceAnalysis performanceAnalysis;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700885 size_t lost = snapshot.lost() + (snapshot.begin() - EntryIterator(snapshot.data()));
Glenn Kastenc02c9612013-10-15 09:25:11 -0700886 if (lost > 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700887 body.appendFormat("warning: lost %zu bytes worth of events", lost);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700888 // 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 -0700889 // log to push it out. Consider keeping the timestamp/body between calls to copyEntryDataAt().
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700890 dumpLine(timestamp, body);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800891 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700892
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800893 for (auto entry = snapshot.begin(); entry != snapshot.end();) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800894 switch (entry->type) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800895 case EVENT_START_FMT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800896 entry = handleFormat(FormatEntry(entry), &timestamp, &body);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800897 break;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700898 case EVENT_HISTOGRAM_ENTRY_TS: {
899 HistTsEntryWithAuthor *data = (HistTsEntryWithAuthor *) (entry->data);
900 // TODO This memcpies are here to avoid unaligned memory access crash.
901 // There's probably a more efficient way to do it
902 log_hash_t hash;
903 memcpy(&hash, &(data->hash), sizeof(hash));
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700904 int64_t ts;
905 memcpy(&ts, &data->ts, sizeof(ts));
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700906 performanceAnalysis.logTsEntry(ts);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700907 ++entry;
908 break;
909 }
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700910 case EVENT_AUDIO_STATE: {
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700911 performanceAnalysis.handleStateChange();
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700912 ++entry;
913 break;
914 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800915 case EVENT_END_FMT:
916 body.appendFormat("warning: got to end format event");
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800917 ++entry;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800918 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800919 case EVENT_RESERVED:
920 default:
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800921 body.appendFormat("warning: unexpected event %d", entry->type);
922 ++entry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800923 break;
924 }
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700925 }
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700926 performanceAnalysis.reportPerformance(&body);
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700927 if (!body.isEmpty()) {
928 dumpLine(timestamp, body);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700929 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800930}
931
Nicolas Roulet40a44982017-02-03 13:39:57 -0800932void NBLog::Reader::dump(int fd, size_t indent)
933{
934 // get a snapshot, dump it
935 std::unique_ptr<Snapshot> snap = getSnapshot();
936 dump(fd, indent, *snap);
937}
938
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800939void NBLog::Reader::dumpLine(const String8 &timestamp, String8 &body)
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700940{
941 if (mFd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700942 dprintf(mFd, "%.*s%s %s\n", mIndent, "", timestamp.string(), body.string());
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700943 } else {
944 ALOGI("%.*s%s %s", mIndent, "", timestamp.string(), body.string());
945 }
946 body.clear();
947}
948
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800949bool NBLog::Reader::isIMemory(const sp<IMemory>& iMemory) const
950{
Glenn Kasten481fb672013-09-30 14:39:28 -0700951 return iMemory != 0 && mIMemory != 0 && iMemory->pointer() == mIMemory->pointer();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800952}
953
Glenn Kasten1c446272017-04-07 09:49:07 -0700954// ---------------------------------------------------------------------------
955
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800956void NBLog::appendTimestamp(String8 *body, const void *data) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700957 int64_t ts;
958 memcpy(&ts, data, sizeof(ts));
959 body->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
960 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800961}
962
963void NBLog::appendInt(String8 *body, const void *data) {
964 int x = *((int*) data);
965 body->appendFormat("<%d>", x);
966}
967
968void NBLog::appendFloat(String8 *body, const void *data) {
969 float f;
970 memcpy(&f, data, sizeof(float));
971 body->appendFormat("<%f>", f);
972}
973
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800974void NBLog::appendPID(String8 *body, const void* data, size_t length) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800975 pid_t id = *((pid_t*) data);
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800976 char * name = &((char*) data)[sizeof(pid_t)];
977 body->appendFormat("<PID: %d, name: %.*s>", id, (int) (length - sizeof(pid_t)), name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800978}
979
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700980String8 NBLog::bufferDump(const uint8_t *buffer, size_t size)
Nicolas Roulet2aedf372017-03-29 11:27:03 -0700981{
982 String8 str;
983 str.append("[ ");
984 for(size_t i = 0; i < size; i++)
985 {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700986 str.appendFormat("%d ", buffer[i]);
Nicolas Roulet2aedf372017-03-29 11:27:03 -0700987 }
988 str.append("]");
989 return str;
990}
991
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700992String8 NBLog::bufferDump(const EntryIterator &it)
Nicolas Roulet2aedf372017-03-29 11:27:03 -0700993{
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700994 return bufferDump(it, it->length + Entry::kOverhead);
Nicolas Roulet2aedf372017-03-29 11:27:03 -0700995}
996
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700997NBLog::EntryIterator NBLog::Reader::handleFormat(const FormatEntry &fmtEntry,
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800998 String8 *timestamp,
999 String8 *body) {
Nicolas Roulet40a44982017-02-03 13:39:57 -08001000 // log timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001001 int64_t ts = fmtEntry.timestamp();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001002 timestamp->clear();
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001003 timestamp->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1004 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Roulet40a44982017-02-03 13:39:57 -08001005
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -07001006 // log unique hash
1007 log_hash_t hash = fmtEntry.hash();
1008 // print only lower 16bit of hash as hex and line as int to reduce spam in the log
1009 body->appendFormat("%.4X-%d ", (int)(hash >> 16) & 0xFFFF, (int) hash & 0xFFFF);
1010
Nicolas Roulet40a44982017-02-03 13:39:57 -08001011 // log author (if present)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001012 handleAuthor(fmtEntry, body);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001013
1014 // log string
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001015 NBLog::EntryIterator arg = fmtEntry.args();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001016
1017 const char* fmt = fmtEntry.formatString();
1018 size_t fmt_length = fmtEntry.formatStringLength();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001019
1020 for (size_t fmt_offset = 0; fmt_offset < fmt_length; ++fmt_offset) {
1021 if (fmt[fmt_offset] != '%') {
1022 body->append(&fmt[fmt_offset], 1); // TODO optimize to write consecutive strings at once
1023 continue;
1024 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001025 // case "%%""
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001026 if (fmt[++fmt_offset] == '%') {
1027 body->append("%");
1028 continue;
1029 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001030 // case "%\0"
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001031 if (fmt_offset == fmt_length) {
1032 continue;
1033 }
1034
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001035 NBLog::Event event = (NBLog::Event) arg->type;
1036 size_t length = arg->length;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001037
1038 // TODO check length for event type is correct
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001039
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001040 if (event == EVENT_END_FMT) {
1041 break;
1042 }
1043
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001044 // TODO: implement more complex formatting such as %.3f
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001045 const uint8_t *datum = arg->data; // pointer to the current event args
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001046 switch(fmt[fmt_offset])
1047 {
1048 case 's': // string
Nicolas Roulet4da78202017-02-03 12:53:39 -08001049 ALOGW_IF(event != EVENT_STRING,
1050 "NBLog Reader incompatible event for string specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001051 body->append((const char*) datum, length);
1052 break;
1053
1054 case 't': // timestamp
Nicolas Roulet4da78202017-02-03 12:53:39 -08001055 ALOGW_IF(event != EVENT_TIMESTAMP,
1056 "NBLog Reader incompatible event for timestamp specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001057 appendTimestamp(body, datum);
1058 break;
1059
1060 case 'd': // integer
Nicolas Roulet4da78202017-02-03 12:53:39 -08001061 ALOGW_IF(event != EVENT_INTEGER,
1062 "NBLog Reader incompatible event for integer specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001063 appendInt(body, datum);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001064 break;
1065
1066 case 'f': // float
Nicolas Roulet4da78202017-02-03 12:53:39 -08001067 ALOGW_IF(event != EVENT_FLOAT,
1068 "NBLog Reader incompatible event for float specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001069 appendFloat(body, datum);
1070 break;
1071
1072 case 'p': // pid
Nicolas Roulet4da78202017-02-03 12:53:39 -08001073 ALOGW_IF(event != EVENT_PID,
1074 "NBLog Reader incompatible event for pid specifier: %d", event);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001075 appendPID(body, datum, length);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001076 break;
1077
1078 default:
1079 ALOGW("NBLog Reader encountered unknown character %c", fmt[fmt_offset]);
1080 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001081 ++arg;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001082 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001083 ALOGW_IF(arg->type != EVENT_END_FMT, "Expected end of format, got %d", arg->type);
1084 ++arg;
1085 return arg;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001086}
1087
Nicolas Roulet40a44982017-02-03 13:39:57 -08001088NBLog::Merger::Merger(const void *shared, size_t size):
Nicolas Roulet40a44982017-02-03 13:39:57 -08001089 mShared((Shared *) shared),
1090 mFifo(mShared != NULL ?
1091 new audio_utils_fifo(size, sizeof(uint8_t),
1092 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
1093 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL)
1094 {}
1095
1096void NBLog::Merger::addReader(const NBLog::NamedReader &reader) {
Glenn Kasten1c446272017-04-07 09:49:07 -07001097 // FIXME This is called by binder thread in MediaLogService::registerWriter
1098 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001099 mNamedReaders.push_back(reader);
1100}
1101
1102// items placed in priority queue during merge
1103// composed by a timestamp and the index of the snapshot where the timestamp came from
1104struct MergeItem
1105{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001106 int64_t ts;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001107 int index;
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001108 MergeItem(int64_t ts, int index): ts(ts), index(index) {}
Nicolas Roulet40a44982017-02-03 13:39:57 -08001109};
1110
1111// operators needed for priority queue in merge
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001112// bool operator>(const int64_t &t1, const int64_t &t2) {
1113// return t1.tv_sec > t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec);
1114// }
Nicolas Roulet40a44982017-02-03 13:39:57 -08001115
1116bool operator>(const struct MergeItem &i1, const struct MergeItem &i2) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001117 return i1.ts > i2.ts || (i1.ts == i2.ts && i1.index > i2.index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001118}
1119
1120// Merge registered readers, sorted by timestamp
1121void NBLog::Merger::merge() {
Glenn Kasten1c446272017-04-07 09:49:07 -07001122 // FIXME This is called by merge thread
1123 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001124 int nLogs = mNamedReaders.size();
1125 std::vector<std::unique_ptr<NBLog::Reader::Snapshot>> snapshots(nLogs);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001126 std::vector<NBLog::EntryIterator> offsets(nLogs);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001127 for (int i = 0; i < nLogs; ++i) {
1128 snapshots[i] = mNamedReaders[i].reader()->getSnapshot();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001129 offsets[i] = snapshots[i]->begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001130 }
1131 // initialize offsets
Nicolas Roulet40a44982017-02-03 13:39:57 -08001132 // TODO custom heap implementation could allow to update top, improving performance
1133 // for bursty buffers
1134 std::priority_queue<MergeItem, std::vector<MergeItem>, std::greater<MergeItem>> timestamps;
1135 for (int i = 0; i < nLogs; ++i)
1136 {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001137 if (offsets[i] != snapshots[i]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001138 int64_t ts = AbstractEntry::buildEntry(offsets[i])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001139 timestamps.emplace(ts, i);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001140 }
1141 }
1142
1143 while (!timestamps.empty()) {
1144 // find minimum timestamp
1145 int index = timestamps.top().index;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001146 // copy it to the log, increasing offset
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001147 offsets[index] = AbstractEntry::buildEntry(offsets[index])->copyWithAuthor(mFifoWriter,
1148 index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001149 // update data structures
Nicolas Roulet40a44982017-02-03 13:39:57 -08001150 timestamps.pop();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001151 if (offsets[index] != snapshots[index]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001152 int64_t ts = AbstractEntry::buildEntry(offsets[index])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001153 timestamps.emplace(ts, index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001154 }
1155 }
1156}
1157
Glenn Kasten1c446272017-04-07 09:49:07 -07001158const std::vector<NBLog::NamedReader>& NBLog::Merger::getNamedReaders() const {
1159 // FIXME This is returning a reference to a shared variable that needs a lock
1160 return mNamedReaders;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001161}
1162
Glenn Kasten1c446272017-04-07 09:49:07 -07001163// ---------------------------------------------------------------------------
1164
Nicolas Roulet40a44982017-02-03 13:39:57 -08001165NBLog::MergeReader::MergeReader(const void *shared, size_t size, Merger &merger)
1166 : Reader(shared, size), mNamedReaders(merger.getNamedReaders()) {}
1167
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001168void NBLog::MergeReader::handleAuthor(const NBLog::AbstractEntry &entry, String8 *body) {
1169 int author = entry.author();
Glenn Kasten1c446272017-04-07 09:49:07 -07001170 // FIXME Needs a lock
1171 const char* name = mNamedReaders[author].name();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001172 body->appendFormat("%s: ", name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001173}
1174
Glenn Kasten1c446272017-04-07 09:49:07 -07001175// ---------------------------------------------------------------------------
1176
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001177NBLog::MergeThread::MergeThread(NBLog::Merger &merger)
1178 : mMerger(merger),
1179 mTimeoutUs(0) {}
1180
1181NBLog::MergeThread::~MergeThread() {
1182 // set exit flag, set timeout to 0 to force threadLoop to exit and wait for the thread to join
1183 requestExit();
1184 setTimeoutUs(0);
1185 join();
1186}
1187
1188bool NBLog::MergeThread::threadLoop() {
1189 bool doMerge;
1190 {
1191 AutoMutex _l(mMutex);
1192 // If mTimeoutUs is negative, wait on the condition variable until it's positive.
1193 // If it's positive, wait kThreadSleepPeriodUs and then merge
1194 nsecs_t waitTime = mTimeoutUs > 0 ? kThreadSleepPeriodUs * 1000 : LLONG_MAX;
1195 mCond.waitRelative(mMutex, waitTime);
1196 doMerge = mTimeoutUs > 0;
1197 mTimeoutUs -= kThreadSleepPeriodUs;
1198 }
1199 if (doMerge) {
1200 mMerger.merge();
1201 }
1202 return true;
1203}
1204
1205void NBLog::MergeThread::wakeup() {
1206 setTimeoutUs(kThreadWakeupPeriodUs);
1207}
1208
1209void NBLog::MergeThread::setTimeoutUs(int time) {
1210 AutoMutex _l(mMutex);
1211 mTimeoutUs = time;
1212 mCond.signal();
1213}
1214
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001215} // namespace android