blob: f90d7fcf37507fa82af046babaf0591248979425 [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 Wager2d1631e2017-05-30 16:12:36 -0700111// #include <utils/CallStack.h> // used to print callstack
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800112#include <utils/Log.h>
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700113#include <utils/String8.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800114
Nicolas Roulet40a44982017-02-03 13:39:57 -0800115#include <queue>
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700116#include <utility>
Nicolas Roulet40a44982017-02-03 13:39:57 -0800117
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800118namespace android {
119
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700120int NBLog::Entry::copyEntryDataAt(size_t offset) const
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800121{
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700122 // FIXME This is too slow
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800123 if (offset == 0)
124 return mEvent;
125 else if (offset == 1)
126 return mLength;
127 else if (offset < (size_t) (mLength + 2))
128 return ((char *) mData)[offset - 2];
129 else if (offset == (size_t) (mLength + 2))
130 return mLength;
131 else
132 return 0;
133}
134
135// ---------------------------------------------------------------------------
136
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700137/*static*/
138std::unique_ptr<NBLog::AbstractEntry> NBLog::AbstractEntry::buildEntry(const uint8_t *ptr) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -0700139 const uint8_t type = EntryIterator(ptr)->type;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700140 switch (type) {
141 case EVENT_START_FMT:
142 return std::make_unique<FormatEntry>(FormatEntry(ptr));
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700143 case EVENT_AUDIO_STATE:
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700144 case EVENT_HISTOGRAM_ENTRY_TS:
145 return std::make_unique<HistogramEntry>(HistogramEntry(ptr));
146 default:
147 ALOGW("Tried to create AbstractEntry of type %d", type);
148 return nullptr;
149 }
Nicolas Roulet40a44982017-02-03 13:39:57 -0800150}
151
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700152NBLog::AbstractEntry::AbstractEntry(const uint8_t *entry) : mEntry(entry) {
153}
154
155// ---------------------------------------------------------------------------
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800156
Sanna Catherine de Treville Wagerdd92d7e2017-05-15 14:56:53 -0700157NBLog::EntryIterator NBLog::FormatEntry::begin() const {
158 return EntryIterator(mEntry);
159}
160
Nicolas Roulet40a44982017-02-03 13:39:57 -0800161const char *NBLog::FormatEntry::formatString() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800162 return (const char*) mEntry + offsetof(entry, data);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800163}
164
165size_t NBLog::FormatEntry::formatStringLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800166 return mEntry[offsetof(entry, length)];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800167}
168
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700169NBLog::EntryIterator NBLog::FormatEntry::args() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800170 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700171 // skip start fmt
172 ++it;
173 // skip timestamp
174 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700175 // skip hash
176 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700177 // Skip author if present
178 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800179 ++it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800180 }
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700181 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800182}
183
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700184int64_t NBLog::FormatEntry::timestamp() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800185 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700186 // skip start fmt
187 ++it;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700188 return it.payload<int64_t>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800189}
190
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700191NBLog::log_hash_t NBLog::FormatEntry::hash() const {
192 auto it = begin();
193 // skip start fmt
194 ++it;
195 // skip timestamp
196 ++it;
197 // unaligned 64-bit read not supported
198 log_hash_t hash;
199 memcpy(&hash, it->data, sizeof(hash));
200 return hash;
201}
202
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700203int NBLog::FormatEntry::author() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800204 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700205 // skip start fmt
206 ++it;
207 // skip timestamp
208 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700209 // skip hash
210 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700211 // if there is an author entry, return it, return -1 otherwise
212 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800213 return it.payload<int>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800214 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800215 return -1;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800216}
217
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700218NBLog::EntryIterator NBLog::FormatEntry::copyWithAuthor(
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800219 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
220 auto it = begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800221 // copy fmt start entry
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800222 it.copyTo(dst);
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700223 // copy timestamp
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700224 (++it).copyTo(dst); // copy hash
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700225 (++it).copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800226 // insert author entry
227 size_t authorEntrySize = NBLog::Entry::kOverhead + sizeof(author);
228 uint8_t authorEntry[authorEntrySize];
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800229 authorEntry[offsetof(entry, type)] = EVENT_AUTHOR;
230 authorEntry[offsetof(entry, length)] =
231 authorEntry[authorEntrySize + NBLog::Entry::kPreviousLengthOffset] =
232 sizeof(author);
233 *(int*) (&authorEntry[offsetof(entry, data)]) = author;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800234 dst->write(authorEntry, authorEntrySize);
235 // copy rest of entries
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800236 while ((++it)->type != EVENT_END_FMT) {
237 it.copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800238 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800239 it.copyTo(dst);
240 ++it;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800241 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800242}
243
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700244void NBLog::EntryIterator::copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800245 size_t length = ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
246 dst->write(ptr, length);
247}
Nicolas Roulet40a44982017-02-03 13:39:57 -0800248
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700249void NBLog::EntryIterator::copyData(uint8_t *dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800250 memcpy((void*) dst, ptr + offsetof(entry, data), ptr[offsetof(entry, length)]);
251}
252
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700253NBLog::EntryIterator::EntryIterator()
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800254 : ptr(nullptr) {}
255
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700256NBLog::EntryIterator::EntryIterator(const uint8_t *entry)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800257 : ptr(entry) {}
258
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700259NBLog::EntryIterator::EntryIterator(const NBLog::EntryIterator &other)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800260 : ptr(other.ptr) {}
261
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700262const NBLog::entry& NBLog::EntryIterator::operator*() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800263 return *(entry*) ptr;
264}
265
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700266const NBLog::entry* NBLog::EntryIterator::operator->() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800267 return (entry*) ptr;
268}
269
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700270NBLog::EntryIterator& NBLog::EntryIterator::operator++() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800271 ptr += ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
272 return *this;
273}
274
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700275NBLog::EntryIterator& NBLog::EntryIterator::operator--() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800276 ptr -= ptr[NBLog::Entry::kPreviousLengthOffset] + NBLog::Entry::kOverhead;
277 return *this;
278}
279
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700280NBLog::EntryIterator NBLog::EntryIterator::next() const {
281 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800282 return ++aux;
283}
284
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700285NBLog::EntryIterator NBLog::EntryIterator::prev() const {
286 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800287 return --aux;
288}
289
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700290int NBLog::EntryIterator::operator-(const NBLog::EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800291 return ptr - other.ptr;
292}
293
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700294bool NBLog::EntryIterator::operator!=(const EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800295 return ptr != other.ptr;
296}
297
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700298bool NBLog::EntryIterator::hasConsistentLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800299 return ptr[offsetof(entry, length)] == ptr[ptr[offsetof(entry, length)] +
300 NBLog::Entry::kOverhead + NBLog::Entry::kPreviousLengthOffset];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800301}
302
303// ---------------------------------------------------------------------------
304
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700305int64_t NBLog::HistogramEntry::timestamp() const {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700306 return EntryIterator(mEntry).payload<HistTsEntry>().ts;
307}
308
309NBLog::log_hash_t NBLog::HistogramEntry::hash() const {
310 return EntryIterator(mEntry).payload<HistTsEntry>().hash;
311}
312
313int NBLog::HistogramEntry::author() const {
314 EntryIterator it(mEntry);
315 if (it->length == sizeof(HistTsEntryWithAuthor)) {
316 return it.payload<HistTsEntryWithAuthor>().author;
317 } else {
318 return -1;
319 }
320}
321
322NBLog::EntryIterator NBLog::HistogramEntry::copyWithAuthor(
323 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
324 // Current histogram entry has {type, length, struct HistTsEntry, length}.
325 // We now want {type, length, struct HistTsEntryWithAuthor, length}
326 uint8_t buffer[Entry::kOverhead + sizeof(HistTsEntryWithAuthor)];
327 // Copy content until the point we want to add the author
328 memcpy(buffer, mEntry, sizeof(entry) + sizeof(HistTsEntry));
329 // Copy the author
330 *(int*) (buffer + sizeof(entry) + sizeof(HistTsEntry)) = author;
331 // Update lengths
332 buffer[offsetof(entry, length)] = sizeof(HistTsEntryWithAuthor);
333 buffer[sizeof(buffer) + Entry::kPreviousLengthOffset] = sizeof(HistTsEntryWithAuthor);
334 // Write new buffer into FIFO
335 dst->write(buffer, sizeof(buffer));
336 return EntryIterator(mEntry).next();
337}
338
339// ---------------------------------------------------------------------------
340
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800341#if 0 // FIXME see note in NBLog.h
342NBLog::Timeline::Timeline(size_t size, void *shared)
343 : mSize(roundup(size)), mOwn(shared == NULL),
344 mShared((Shared *) (mOwn ? new char[sharedSize(size)] : shared))
345{
346 new (mShared) Shared;
347}
348
349NBLog::Timeline::~Timeline()
350{
351 mShared->~Shared();
352 if (mOwn) {
353 delete[] (char *) mShared;
354 }
355}
356#endif
357
358/*static*/
359size_t NBLog::Timeline::sharedSize(size_t size)
360{
Glenn Kastened99c2b2016-12-12 08:31:24 -0800361 // TODO fifo now supports non-power-of-2 buffer sizes, so could remove the roundup
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800362 return sizeof(Shared) + roundup(size);
363}
364
365// ---------------------------------------------------------------------------
366
367NBLog::Writer::Writer()
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800368 : mShared(NULL), mFifo(NULL), mFifoWriter(NULL), mEnabled(false), mPidTag(NULL), mPidTagSize(0)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800369{
370}
371
Glenn Kasten535e1612016-12-05 12:19:36 -0800372NBLog::Writer::Writer(void *shared, size_t size)
373 : mShared((Shared *) shared),
374 mFifo(mShared != NULL ?
375 new audio_utils_fifo(size, sizeof(uint8_t),
376 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
377 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL),
378 mEnabled(mFifoWriter != NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800379{
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800380 // caching pid and process name
381 pid_t id = ::getpid();
382 char procName[16];
383 int status = prctl(PR_GET_NAME, procName);
384 if (status) { // error getting process name
385 procName[0] = '\0';
386 }
387 size_t length = strlen(procName);
388 mPidTagSize = length + sizeof(pid_t);
389 mPidTag = new char[mPidTagSize];
390 memcpy(mPidTag, &id, sizeof(pid_t));
391 memcpy(mPidTag + sizeof(pid_t), procName, length);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800392}
393
Glenn Kasten535e1612016-12-05 12:19:36 -0800394NBLog::Writer::Writer(const sp<IMemory>& iMemory, size_t size)
395 : Writer(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800396{
Glenn Kasten535e1612016-12-05 12:19:36 -0800397 mIMemory = iMemory;
398}
399
400NBLog::Writer::~Writer()
401{
402 delete mFifoWriter;
403 delete mFifo;
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800404 delete[] mPidTag;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800405}
406
407void NBLog::Writer::log(const char *string)
408{
409 if (!mEnabled) {
410 return;
411 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800412 LOG_ALWAYS_FATAL_IF(string == NULL, "Attempted to log NULL string");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800413 size_t length = strlen(string);
Glenn Kasten535e1612016-12-05 12:19:36 -0800414 if (length > Entry::kMaxLength) {
415 length = Entry::kMaxLength;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800416 }
417 log(EVENT_STRING, string, length);
418}
419
420void NBLog::Writer::logf(const char *fmt, ...)
421{
422 if (!mEnabled) {
423 return;
424 }
425 va_list ap;
426 va_start(ap, fmt);
427 Writer::logvf(fmt, ap); // the Writer:: is needed to avoid virtual dispatch for LockedWriter
428 va_end(ap);
429}
430
431void NBLog::Writer::logvf(const char *fmt, va_list ap)
432{
433 if (!mEnabled) {
434 return;
435 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800436 char buffer[Entry::kMaxLength + 1 /*NUL*/];
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800437 int length = vsnprintf(buffer, sizeof(buffer), fmt, ap);
438 if (length >= (int) sizeof(buffer)) {
439 length = sizeof(buffer) - 1;
440 // NUL termination is not required
441 // buffer[length] = '\0';
442 }
443 if (length >= 0) {
444 log(EVENT_STRING, buffer, length);
445 }
446}
447
448void NBLog::Writer::logTimestamp()
449{
450 if (!mEnabled) {
451 return;
452 }
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700453 int64_t ts = get_monotonic_ns();
454 if (ts > 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800455 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700456 } else {
457 ALOGE("Failed to get timestamp");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800458 }
459}
460
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700461void NBLog::Writer::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800462{
463 if (!mEnabled) {
464 return;
465 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800466 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
467}
468
469void NBLog::Writer::logInteger(const int x)
470{
471 if (!mEnabled) {
472 return;
473 }
474 log(EVENT_INTEGER, &x, sizeof(x));
475}
476
477void NBLog::Writer::logFloat(const float x)
478{
479 if (!mEnabled) {
480 return;
481 }
482 log(EVENT_FLOAT, &x, sizeof(x));
483}
484
485void NBLog::Writer::logPID()
486{
487 if (!mEnabled) {
488 return;
489 }
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800490 log(EVENT_PID, mPidTag, mPidTagSize);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800491}
492
493void NBLog::Writer::logStart(const char *fmt)
494{
495 if (!mEnabled) {
496 return;
497 }
498 size_t length = strlen(fmt);
499 if (length > Entry::kMaxLength) {
500 length = Entry::kMaxLength;
501 }
502 log(EVENT_START_FMT, fmt, length);
503}
504
505void NBLog::Writer::logEnd()
506{
507 if (!mEnabled) {
508 return;
509 }
510 Entry entry = Entry(EVENT_END_FMT, NULL, 0);
511 log(&entry, true);
512}
513
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700514void NBLog::Writer::logHash(log_hash_t hash)
515{
516 if (!mEnabled) {
517 return;
518 }
519 log(EVENT_HASH, &hash, sizeof(hash));
520}
521
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700522void NBLog::Writer::logEventHistTs(Event event, log_hash_t hash)
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700523{
524 if (!mEnabled) {
525 return;
526 }
527 HistTsEntry data;
528 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700529 data.ts = get_monotonic_ns();
530 if (data.ts > 0) {
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700531 log(event, &data, sizeof(data));
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700532 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700533 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700534 }
535}
536
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700537void NBLog::Writer::logFormat(const char *fmt, log_hash_t hash, ...)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800538{
539 if (!mEnabled) {
540 return;
541 }
542
543 va_list ap;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700544 va_start(ap, hash);
545 Writer::logVFormat(fmt, hash, ap);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800546 va_end(ap);
547}
548
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700549void NBLog::Writer::logVFormat(const char *fmt, log_hash_t hash, va_list argp)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800550{
551 if (!mEnabled) {
552 return;
553 }
554 Writer::logStart(fmt);
555 int i;
556 double f;
557 char* s;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700558 int64_t t;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800559 Writer::logTimestamp();
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700560 Writer::logHash(hash);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800561 for (const char *p = fmt; *p != '\0'; p++) {
562 // TODO: implement more complex formatting such as %.3f
563 if (*p != '%') {
564 continue;
565 }
566 switch(*++p) {
567 case 's': // string
568 s = va_arg(argp, char *);
569 Writer::log(s);
570 break;
571
572 case 't': // timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700573 t = va_arg(argp, int64_t);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800574 Writer::logTimestamp(t);
575 break;
576
577 case 'd': // integer
578 i = va_arg(argp, int);
579 Writer::logInteger(i);
580 break;
581
582 case 'f': // float
583 f = va_arg(argp, double); // float arguments are promoted to double in vararg lists
584 Writer::logFloat((float)f);
585 break;
586
587 case 'p': // pid
588 Writer::logPID();
589 break;
590
591 // the "%\0" case finishes parsing
592 case '\0':
593 --p;
594 break;
595
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800596 case '%':
597 break;
598
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800599 default:
600 ALOGW("NBLog Writer parsed invalid format specifier: %c", *p);
601 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800602 }
603 }
604 Writer::logEnd();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800605}
606
607void NBLog::Writer::log(Event event, const void *data, size_t length)
608{
609 if (!mEnabled) {
610 return;
611 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800612 if (data == NULL || length > Entry::kMaxLength) {
613 // TODO Perhaps it makes sense to display truncated data or at least a
614 // message that the data is too long? The current behavior can create
615 // a confusion for a programmer debugging their code.
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800616 return;
617 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700618 // Ignore if invalid event
619 if (event == EVENT_RESERVED || event >= EVENT_UPPER_BOUND) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800620 return;
621 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700622 Entry etr(event, data, length);
623 log(&etr, true /*trusted*/);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800624}
625
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700626void NBLog::Writer::log(const NBLog::Entry *etr, bool trusted)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800627{
628 if (!mEnabled) {
629 return;
630 }
631 if (!trusted) {
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700632 log(etr->mEvent, etr->mData, etr->mLength);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800633 return;
634 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700635 size_t need = etr->mLength + Entry::kOverhead; // mEvent, mLength, data[mLength], mLength
636 // need = number of bytes written to FIFO
Glenn Kasten535e1612016-12-05 12:19:36 -0800637
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800638 // FIXME optimize this using memcpy for the data part of the Entry.
639 // The Entry could have a method copyTo(ptr, offset, size) to optimize the copy.
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700640 // checks size of a single log Entry: type, length, data pointer and ending
Glenn Kasten535e1612016-12-05 12:19:36 -0800641 uint8_t temp[Entry::kMaxLength + Entry::kOverhead];
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700642 // write this data to temp array
Glenn Kasten535e1612016-12-05 12:19:36 -0800643 for (size_t i = 0; i < need; i++) {
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700644 temp[i] = etr->copyEntryDataAt(i);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800645 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700646 // write to circular buffer
Glenn Kasten535e1612016-12-05 12:19:36 -0800647 mFifoWriter->write(temp, need);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800648}
649
650bool NBLog::Writer::isEnabled() const
651{
652 return mEnabled;
653}
654
655bool NBLog::Writer::setEnabled(bool enabled)
656{
657 bool old = mEnabled;
658 mEnabled = enabled && mShared != NULL;
659 return old;
660}
661
662// ---------------------------------------------------------------------------
663
664NBLog::LockedWriter::LockedWriter()
665 : Writer()
666{
667}
668
Glenn Kasten535e1612016-12-05 12:19:36 -0800669NBLog::LockedWriter::LockedWriter(void *shared, size_t size)
670 : Writer(shared, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800671{
672}
673
674void NBLog::LockedWriter::log(const char *string)
675{
676 Mutex::Autolock _l(mLock);
677 Writer::log(string);
678}
679
680void NBLog::LockedWriter::logf(const char *fmt, ...)
681{
682 // FIXME should not take the lock until after formatting is done
683 Mutex::Autolock _l(mLock);
684 va_list ap;
685 va_start(ap, fmt);
686 Writer::logvf(fmt, ap);
687 va_end(ap);
688}
689
690void NBLog::LockedWriter::logvf(const char *fmt, va_list ap)
691{
692 // FIXME should not take the lock until after formatting is done
693 Mutex::Autolock _l(mLock);
694 Writer::logvf(fmt, ap);
695}
696
697void NBLog::LockedWriter::logTimestamp()
698{
699 // FIXME should not take the lock until after the clock_gettime() syscall
700 Mutex::Autolock _l(mLock);
701 Writer::logTimestamp();
702}
703
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700704void NBLog::LockedWriter::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800705{
706 Mutex::Autolock _l(mLock);
707 Writer::logTimestamp(ts);
708}
709
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800710void NBLog::LockedWriter::logInteger(const int x)
711{
712 Mutex::Autolock _l(mLock);
713 Writer::logInteger(x);
714}
715
716void NBLog::LockedWriter::logFloat(const float x)
717{
718 Mutex::Autolock _l(mLock);
719 Writer::logFloat(x);
720}
721
722void NBLog::LockedWriter::logPID()
723{
724 Mutex::Autolock _l(mLock);
725 Writer::logPID();
726}
727
728void NBLog::LockedWriter::logStart(const char *fmt)
729{
730 Mutex::Autolock _l(mLock);
731 Writer::logStart(fmt);
732}
733
734
735void NBLog::LockedWriter::logEnd()
736{
737 Mutex::Autolock _l(mLock);
738 Writer::logEnd();
739}
740
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700741void NBLog::LockedWriter::logHash(log_hash_t hash)
742{
743 Mutex::Autolock _l(mLock);
744 Writer::logHash(hash);
745}
746
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800747bool NBLog::LockedWriter::isEnabled() const
748{
749 Mutex::Autolock _l(mLock);
750 return Writer::isEnabled();
751}
752
753bool NBLog::LockedWriter::setEnabled(bool enabled)
754{
755 Mutex::Autolock _l(mLock);
756 return Writer::setEnabled(enabled);
757}
758
759// ---------------------------------------------------------------------------
760
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700761const std::set<NBLog::Event> NBLog::Reader::startingTypes {NBLog::Event::EVENT_START_FMT,
762 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
763const std::set<NBLog::Event> NBLog::Reader::endingTypes {NBLog::Event::EVENT_END_FMT,
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700764 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
765 NBLog::Event::EVENT_AUDIO_STATE};
766
Glenn Kasten535e1612016-12-05 12:19:36 -0800767NBLog::Reader::Reader(const void *shared, size_t size)
768 : mShared((/*const*/ Shared *) shared), /*mIMemory*/
769 mFd(-1), mIndent(0),
770 mFifo(mShared != NULL ?
771 new audio_utils_fifo(size, sizeof(uint8_t),
772 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700773 mFifoReader(mFifo != NULL ? new audio_utils_fifo_reader(*mFifo) : NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800774{
775}
776
Glenn Kasten535e1612016-12-05 12:19:36 -0800777NBLog::Reader::Reader(const sp<IMemory>& iMemory, size_t size)
778 : Reader(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800779{
Glenn Kasten535e1612016-12-05 12:19:36 -0800780 mIMemory = iMemory;
781}
782
783NBLog::Reader::~Reader()
784{
785 delete mFifoReader;
786 delete mFifo;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800787}
788
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700789const uint8_t *NBLog::Reader::findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
790 const std::set<Event> &types) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800791 while (back + Entry::kPreviousLengthOffset >= front) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700792 const uint8_t *prev = back - back[Entry::kPreviousLengthOffset] - Entry::kOverhead;
793 if (prev < front || prev + prev[offsetof(entry, length)] +
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800794 Entry::kOverhead != back) {
795
796 // prev points to an out of limits or inconsistent entry
797 return nullptr;
798 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700799 if (types.find((const Event) prev[offsetof(entry, type)]) != types.end()) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800800 return prev;
801 }
802 back = prev;
803 }
804 return nullptr; // no entry found
805}
806
Nicolas Roulet40a44982017-02-03 13:39:57 -0800807std::unique_ptr<NBLog::Reader::Snapshot> NBLog::Reader::getSnapshot()
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800808{
Glenn Kasten535e1612016-12-05 12:19:36 -0800809 if (mFifoReader == NULL) {
Nicolas Roulet40a44982017-02-03 13:39:57 -0800810 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800811 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800812 // make a copy to avoid race condition with writer
Glenn Kasten535e1612016-12-05 12:19:36 -0800813 size_t capacity = mFifo->capacity();
814
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800815 // This emulates the behaviour of audio_utils_fifo_reader::read, but without incrementing the
816 // reader index. The index is incremented after handling corruption, to after the last complete
817 // entry of the buffer
818 size_t lost;
819 audio_utils_iovec iovec[2];
820 ssize_t availToRead = mFifoReader->obtain(iovec, capacity, NULL /*timeout*/, &lost);
821 if (availToRead <= 0) {
822 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
823 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800824
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800825 std::unique_ptr<Snapshot> snapshot(new Snapshot(availToRead));
826 memcpy(snapshot->mData, (const char *) mFifo->buffer() + iovec[0].mOffset, iovec[0].mLength);
827 if (iovec[1].mLength > 0) {
828 memcpy(snapshot->mData + (iovec[0].mLength),
829 (const char *) mFifo->buffer() + iovec[1].mOffset, iovec[1].mLength);
830 }
831
832 // Handle corrupted buffer
833 // Potentially, a buffer has corrupted data on both beginning (due to overflow) and end
834 // (due to incomplete format entry). But even if the end format entry is incomplete,
835 // it ends in a complete entry (which is not an END_FMT). So is safe to traverse backwards.
836 // TODO: handle client corruption (in the middle of a buffer)
837
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700838 const uint8_t *back = snapshot->mData + availToRead;
839 const uint8_t *front = snapshot->mData;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800840
841 // Find last END_FMT. <back> is sitting on an entry which might be the middle of a FormatEntry.
842 // We go backwards until we find an EVENT_END_FMT.
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700843 const uint8_t *lastEnd = findLastEntryOfTypes(front, back, endingTypes);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800844 if (lastEnd == nullptr) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700845 snapshot->mEnd = snapshot->mBegin = EntryIterator(front);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800846 } else {
847 // end of snapshot points to after last END_FMT entry
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700848 snapshot->mEnd = EntryIterator(lastEnd).next();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800849 // find first START_FMT
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700850 const uint8_t *firstStart = nullptr;
851 const uint8_t *firstStartTmp = snapshot->mEnd;
852 while ((firstStartTmp = findLastEntryOfTypes(front, firstStartTmp, startingTypes))
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800853 != nullptr) {
854 firstStart = firstStartTmp;
855 }
856 // firstStart is null if no START_FMT entry was found before lastEnd
857 if (firstStart == nullptr) {
858 snapshot->mBegin = snapshot->mEnd;
859 } else {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700860 snapshot->mBegin = EntryIterator(firstStart);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800861 }
862 }
863
864 // advance fifo reader index to after last entry read.
865 mFifoReader->release(snapshot->mEnd - front);
866
867 snapshot->mLost = lost;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800868 return snapshot;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800869
Nicolas Roulet40a44982017-02-03 13:39:57 -0800870}
871
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -0700872// writes sample deltas to file, either truncating or appending
873inline void writeHistToFile(const std::vector<int64_t> &samples, bool append) {
874 // name of file on audioserver
875 static const char* const kName = (char *)"/data/misc/audioserver/sample_results.txt";
876 // stores deltas between the samples
877 std::vector<int64_t> intervals;
878 if (samples.size() == 0) return;
879 for (size_t i = 1; i < samples.size(); ++i) {
880 intervals.push_back(deltaMs(samples[i - 1], samples[i]));
881 }
882 // Deletes maximum value in a histogram. Temp quick fix.
883 // FIXME: need to find root cause of approx. 35th element from the end
884 // consistently being an outlier in the first histogram of a flush
885 // ALOGW("%" PRId64 "before", (int64_t) *(std::max_element(intervals.begin(), intervals.end())));
886 intervals.erase(std::max_element(intervals.begin(), intervals.end()));
887 // ALOGW("%" PRId64 "after", (int64_t) *(std::max_element(intervals.begin(), intervals.end())));
888 std::ofstream ofs;
889 ofs.open(kName, append ? std::ios::app : std::ios::trunc);
890 if (!ofs) {
891 ALOGW("couldn't open file %s", kName);
892 return;
893 }
894 for (size_t i = 0; i < intervals.size(); ++i) {
895 ofs << intervals[i] << "\n";
896 }
897 ofs.close();
898}
899
Nicolas Roulet40a44982017-02-03 13:39:57 -0800900void NBLog::Reader::dump(int fd, size_t indent, NBLog::Reader::Snapshot &snapshot)
901{
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700902 // CallStack cs(LOG_TAG);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700903 mFd = fd;
904 mIndent = indent;
905 String8 timestamp, body;
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700906 // FIXME: this is not thread safe
907 static PerformanceAnalysis performanceAnalysis; // used to store data and to call analysis functions
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700908 size_t lost = snapshot.lost() + (snapshot.begin() - EntryIterator(snapshot.data()));
Glenn Kastenc02c9612013-10-15 09:25:11 -0700909 if (lost > 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700910 body.appendFormat("warning: lost %zu bytes worth of events", lost);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700911 // 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 -0700912 // log to push it out. Consider keeping the timestamp/body between calls to copyEntryDataAt().
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700913 dumpLine(timestamp, body);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800914 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700915
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800916 for (auto entry = snapshot.begin(); entry != snapshot.end();) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800917 switch (entry->type) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800918 case EVENT_START_FMT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800919 entry = handleFormat(FormatEntry(entry), &timestamp, &body);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800920 break;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700921 case EVENT_HISTOGRAM_ENTRY_TS: {
922 HistTsEntryWithAuthor *data = (HistTsEntryWithAuthor *) (entry->data);
923 // TODO This memcpies are here to avoid unaligned memory access crash.
924 // There's probably a more efficient way to do it
925 log_hash_t hash;
926 memcpy(&hash, &(data->hash), sizeof(hash));
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700927 int64_t ts;
928 memcpy(&ts, &data->ts, sizeof(ts));
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700929 performanceAnalysis.logTsEntry(data->author, ts);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700930 ++entry;
931 break;
932 }
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700933 case EVENT_AUDIO_STATE: {
934 StateTsEntryWithAuthor *data = (StateTsEntryWithAuthor *) (entry->data);
935 // TODO This memcpies are here to avoid unaligned memory access crash.
936 // There's probably a more efficient way to do it
937 performanceAnalysis.handleStateChange(data->author);
938 ++entry;
939 break;
940 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800941 case EVENT_END_FMT:
942 body.appendFormat("warning: got to end format event");
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800943 ++entry;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800944 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800945 case EVENT_RESERVED:
946 default:
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800947 body.appendFormat("warning: unexpected event %d", entry->type);
948 ++entry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800949 break;
950 }
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700951 }
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700952 performanceAnalysis.reportPerformance(&body);
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700953 if (!body.isEmpty()) {
954 dumpLine(timestamp, body);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700955 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800956}
957
Nicolas Roulet40a44982017-02-03 13:39:57 -0800958void NBLog::Reader::dump(int fd, size_t indent)
959{
960 // get a snapshot, dump it
961 std::unique_ptr<Snapshot> snap = getSnapshot();
962 dump(fd, indent, *snap);
963}
964
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800965void NBLog::Reader::dumpLine(const String8 &timestamp, String8 &body)
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700966{
967 if (mFd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700968 dprintf(mFd, "%.*s%s %s\n", mIndent, "", timestamp.string(), body.string());
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700969 } else {
970 ALOGI("%.*s%s %s", mIndent, "", timestamp.string(), body.string());
971 }
972 body.clear();
973}
974
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800975bool NBLog::Reader::isIMemory(const sp<IMemory>& iMemory) const
976{
Glenn Kasten481fb672013-09-30 14:39:28 -0700977 return iMemory != 0 && mIMemory != 0 && iMemory->pointer() == mIMemory->pointer();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800978}
979
Glenn Kasten1c446272017-04-07 09:49:07 -0700980// ---------------------------------------------------------------------------
981
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800982void NBLog::appendTimestamp(String8 *body, const void *data) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700983 int64_t ts;
984 memcpy(&ts, data, sizeof(ts));
985 body->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
986 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800987}
988
989void NBLog::appendInt(String8 *body, const void *data) {
990 int x = *((int*) data);
991 body->appendFormat("<%d>", x);
992}
993
994void NBLog::appendFloat(String8 *body, const void *data) {
995 float f;
996 memcpy(&f, data, sizeof(float));
997 body->appendFormat("<%f>", f);
998}
999
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001000void NBLog::appendPID(String8 *body, const void* data, size_t length) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001001 pid_t id = *((pid_t*) data);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001002 char * name = &((char*) data)[sizeof(pid_t)];
1003 body->appendFormat("<PID: %d, name: %.*s>", id, (int) (length - sizeof(pid_t)), name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001004}
1005
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001006String8 NBLog::bufferDump(const uint8_t *buffer, size_t size)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001007{
1008 String8 str;
1009 str.append("[ ");
1010 for(size_t i = 0; i < size; i++)
1011 {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001012 str.appendFormat("%d ", buffer[i]);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001013 }
1014 str.append("]");
1015 return str;
1016}
1017
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001018String8 NBLog::bufferDump(const EntryIterator &it)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001019{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001020 return bufferDump(it, it->length + Entry::kOverhead);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001021}
1022
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001023NBLog::EntryIterator NBLog::Reader::handleFormat(const FormatEntry &fmtEntry,
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001024 String8 *timestamp,
1025 String8 *body) {
Nicolas Roulet40a44982017-02-03 13:39:57 -08001026 // log timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001027 int64_t ts = fmtEntry.timestamp();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001028 timestamp->clear();
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001029 timestamp->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1030 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Roulet40a44982017-02-03 13:39:57 -08001031
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -07001032 // log unique hash
1033 log_hash_t hash = fmtEntry.hash();
1034 // print only lower 16bit of hash as hex and line as int to reduce spam in the log
1035 body->appendFormat("%.4X-%d ", (int)(hash >> 16) & 0xFFFF, (int) hash & 0xFFFF);
1036
Nicolas Roulet40a44982017-02-03 13:39:57 -08001037 // log author (if present)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001038 handleAuthor(fmtEntry, body);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001039
1040 // log string
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001041 NBLog::EntryIterator arg = fmtEntry.args();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001042
1043 const char* fmt = fmtEntry.formatString();
1044 size_t fmt_length = fmtEntry.formatStringLength();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001045
1046 for (size_t fmt_offset = 0; fmt_offset < fmt_length; ++fmt_offset) {
1047 if (fmt[fmt_offset] != '%') {
1048 body->append(&fmt[fmt_offset], 1); // TODO optimize to write consecutive strings at once
1049 continue;
1050 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001051 // case "%%""
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001052 if (fmt[++fmt_offset] == '%') {
1053 body->append("%");
1054 continue;
1055 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001056 // case "%\0"
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001057 if (fmt_offset == fmt_length) {
1058 continue;
1059 }
1060
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001061 NBLog::Event event = (NBLog::Event) arg->type;
1062 size_t length = arg->length;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001063
1064 // TODO check length for event type is correct
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001065
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001066 if (event == EVENT_END_FMT) {
1067 break;
1068 }
1069
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001070 // TODO: implement more complex formatting such as %.3f
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001071 const uint8_t *datum = arg->data; // pointer to the current event args
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001072 switch(fmt[fmt_offset])
1073 {
1074 case 's': // string
Nicolas Roulet4da78202017-02-03 12:53:39 -08001075 ALOGW_IF(event != EVENT_STRING,
1076 "NBLog Reader incompatible event for string specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001077 body->append((const char*) datum, length);
1078 break;
1079
1080 case 't': // timestamp
Nicolas Roulet4da78202017-02-03 12:53:39 -08001081 ALOGW_IF(event != EVENT_TIMESTAMP,
1082 "NBLog Reader incompatible event for timestamp specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001083 appendTimestamp(body, datum);
1084 break;
1085
1086 case 'd': // integer
Nicolas Roulet4da78202017-02-03 12:53:39 -08001087 ALOGW_IF(event != EVENT_INTEGER,
1088 "NBLog Reader incompatible event for integer specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001089 appendInt(body, datum);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001090 break;
1091
1092 case 'f': // float
Nicolas Roulet4da78202017-02-03 12:53:39 -08001093 ALOGW_IF(event != EVENT_FLOAT,
1094 "NBLog Reader incompatible event for float specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001095 appendFloat(body, datum);
1096 break;
1097
1098 case 'p': // pid
Nicolas Roulet4da78202017-02-03 12:53:39 -08001099 ALOGW_IF(event != EVENT_PID,
1100 "NBLog Reader incompatible event for pid specifier: %d", event);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001101 appendPID(body, datum, length);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001102 break;
1103
1104 default:
1105 ALOGW("NBLog Reader encountered unknown character %c", fmt[fmt_offset]);
1106 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001107 ++arg;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001108 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001109 ALOGW_IF(arg->type != EVENT_END_FMT, "Expected end of format, got %d", arg->type);
1110 ++arg;
1111 return arg;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001112}
1113
Nicolas Roulet40a44982017-02-03 13:39:57 -08001114NBLog::Merger::Merger(const void *shared, size_t size):
Nicolas Roulet40a44982017-02-03 13:39:57 -08001115 mShared((Shared *) shared),
1116 mFifo(mShared != NULL ?
1117 new audio_utils_fifo(size, sizeof(uint8_t),
1118 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
1119 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL)
1120 {}
1121
1122void NBLog::Merger::addReader(const NBLog::NamedReader &reader) {
Glenn Kasten1c446272017-04-07 09:49:07 -07001123 // FIXME This is called by binder thread in MediaLogService::registerWriter
1124 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001125 mNamedReaders.push_back(reader);
1126}
1127
1128// items placed in priority queue during merge
1129// composed by a timestamp and the index of the snapshot where the timestamp came from
1130struct MergeItem
1131{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001132 int64_t ts;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001133 int index;
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001134 MergeItem(int64_t ts, int index): ts(ts), index(index) {}
Nicolas Roulet40a44982017-02-03 13:39:57 -08001135};
1136
1137// operators needed for priority queue in merge
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001138// bool operator>(const int64_t &t1, const int64_t &t2) {
1139// return t1.tv_sec > t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec);
1140// }
Nicolas Roulet40a44982017-02-03 13:39:57 -08001141
1142bool operator>(const struct MergeItem &i1, const struct MergeItem &i2) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001143 return i1.ts > i2.ts || (i1.ts == i2.ts && i1.index > i2.index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001144}
1145
1146// Merge registered readers, sorted by timestamp
1147void NBLog::Merger::merge() {
Glenn Kasten1c446272017-04-07 09:49:07 -07001148 // FIXME This is called by merge thread
1149 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001150 int nLogs = mNamedReaders.size();
1151 std::vector<std::unique_ptr<NBLog::Reader::Snapshot>> snapshots(nLogs);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001152 std::vector<NBLog::EntryIterator> offsets(nLogs);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001153 for (int i = 0; i < nLogs; ++i) {
1154 snapshots[i] = mNamedReaders[i].reader()->getSnapshot();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001155 offsets[i] = snapshots[i]->begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001156 }
1157 // initialize offsets
Nicolas Roulet40a44982017-02-03 13:39:57 -08001158 // TODO custom heap implementation could allow to update top, improving performance
1159 // for bursty buffers
1160 std::priority_queue<MergeItem, std::vector<MergeItem>, std::greater<MergeItem>> timestamps;
1161 for (int i = 0; i < nLogs; ++i)
1162 {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001163 if (offsets[i] != snapshots[i]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001164 int64_t ts = AbstractEntry::buildEntry(offsets[i])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001165 timestamps.emplace(ts, i);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001166 }
1167 }
1168
1169 while (!timestamps.empty()) {
1170 // find minimum timestamp
1171 int index = timestamps.top().index;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001172 // copy it to the log, increasing offset
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001173 offsets[index] = AbstractEntry::buildEntry(offsets[index])->copyWithAuthor(mFifoWriter,
1174 index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001175 // update data structures
Nicolas Roulet40a44982017-02-03 13:39:57 -08001176 timestamps.pop();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001177 if (offsets[index] != snapshots[index]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001178 int64_t ts = AbstractEntry::buildEntry(offsets[index])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001179 timestamps.emplace(ts, index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001180 }
1181 }
1182}
1183
Glenn Kasten1c446272017-04-07 09:49:07 -07001184const std::vector<NBLog::NamedReader>& NBLog::Merger::getNamedReaders() const {
1185 // FIXME This is returning a reference to a shared variable that needs a lock
1186 return mNamedReaders;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001187}
1188
Glenn Kasten1c446272017-04-07 09:49:07 -07001189// ---------------------------------------------------------------------------
1190
Nicolas Roulet40a44982017-02-03 13:39:57 -08001191NBLog::MergeReader::MergeReader(const void *shared, size_t size, Merger &merger)
1192 : Reader(shared, size), mNamedReaders(merger.getNamedReaders()) {}
1193
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001194void NBLog::MergeReader::handleAuthor(const NBLog::AbstractEntry &entry, String8 *body) {
1195 int author = entry.author();
Glenn Kasten1c446272017-04-07 09:49:07 -07001196 // FIXME Needs a lock
1197 const char* name = mNamedReaders[author].name();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001198 body->appendFormat("%s: ", name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001199}
1200
Glenn Kasten1c446272017-04-07 09:49:07 -07001201// ---------------------------------------------------------------------------
1202
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001203NBLog::MergeThread::MergeThread(NBLog::Merger &merger)
1204 : mMerger(merger),
1205 mTimeoutUs(0) {}
1206
1207NBLog::MergeThread::~MergeThread() {
1208 // set exit flag, set timeout to 0 to force threadLoop to exit and wait for the thread to join
1209 requestExit();
1210 setTimeoutUs(0);
1211 join();
1212}
1213
1214bool NBLog::MergeThread::threadLoop() {
1215 bool doMerge;
1216 {
1217 AutoMutex _l(mMutex);
1218 // If mTimeoutUs is negative, wait on the condition variable until it's positive.
1219 // If it's positive, wait kThreadSleepPeriodUs and then merge
1220 nsecs_t waitTime = mTimeoutUs > 0 ? kThreadSleepPeriodUs * 1000 : LLONG_MAX;
1221 mCond.waitRelative(mMutex, waitTime);
1222 doMerge = mTimeoutUs > 0;
1223 mTimeoutUs -= kThreadSleepPeriodUs;
1224 }
1225 if (doMerge) {
1226 mMerger.merge();
1227 }
1228 return true;
1229}
1230
1231void NBLog::MergeThread::wakeup() {
1232 setTimeoutUs(kThreadWakeupPeriodUs);
1233}
1234
1235void NBLog::MergeThread::setTimeoutUs(int time) {
1236 AutoMutex _l(mMutex);
1237 mTimeoutUs = time;
1238 mCond.signal();
1239}
1240
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001241} // namespace android