blob: 73adff64cccca66178c66e6f8904137c85274332 [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
26* Hashes file name and line number
27* calls NBLOG::Writer::logHistTS once
28* NBLOG::Writer::logHistTS
29* calls NBLOG::Writer::log on hash and current timestamp
30* time is in CLOCK_MONOTONIC converted to ns
31* NBLOG::Writer::log(Event, const void*, size_t)
32* Initializes Entry, a struct containing one log entry
33* Entry contains the event type (mEvent), data length (mLength),
34* and data pointer (mData)
35* TODO: why mLength (max length of buffer data) must be <= kMaxLength = 255?
36* calls NBLOG::Writer::log(Entry *, bool)
37* NBLog::Writer::log(Entry *, bool)
38* Calls copyEntryDataAt to format data as follows in temp array:
39* [type][length][data ... ][length]
40* calls audio_utils_fifo_writer.write on temp
41* audio_utils_fifo_writer.write
42* calls obtain(), memcpy (reference in doxygen)
43* returns number of frames written
44* ssize_t audio_utils_fifo_reader::obtain
45* Determines readable buffer section via pointer arithmetic on reader
46* and writer pointers
47*
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070048* 2) Writing LOG_HIST_FLUSH event to console when audio is turned on or off
49* When this event is found when reading from the buffer, all histograms are
50* printed to the console
51* TODO: remove this: always write data to another data structure or the console
52* FastMixer::onStateChange()
53* is called when audio is turned on/off
54* calls LOG_HIST_FLUSH()
55* LOG_HIST_FLUSH()
56* calls logHistFlush
57* NBLog::Writer::logHistFlush
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -070058* records current timestamp
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070059* calls log(EVENT_HISTOGRAM_FLUSH)
60* From here, everything is the same as in 1), resulting in call to fifo write
61*
62* 3) reading the data from shared memory
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070063* Thread::threadloop()
64* TODO: add description?
65* NBLog::MergeThread::threadLoop()
66* calls NBLog::Merger::merge
67* NBLog::Merger::merge
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070068* Merges snapshots sorted by timestamp
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070069* for each reader in vector of class NamedReader,
70* callsNamedReader::reader()->getSnapshot
71* TODO: check whether the rest of this function is relevant
72* NBLog::Reader::getSnapshot
73* copies snapshot of reader's fifo buffer into its own buffer
74* calls mFifoReader->obtain to find readable data
75* sets snapshot.begin() and .end() iterators to boundaries of valid entries
76* moves the fifo reader index to after the last entry read
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070077* 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 -070078*
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070079* 4) reading the data from private buffer
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070080* MediaLogService::dump
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -070081* calls NBLog::Reader::dump(CONSOLE)
82* The private buffer contains all logs for all readers in shared memory
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070083* NBLog::Reader::dump(int)
84* calls getSnapshot on the current reader
85* calls dump(int, size_t, Snapshot)
86* NBLog::Reader::dump(int, size, snapshot)
87* iterates through snapshot's events and switches based on their type
88* (string, timestamp, etc...)
89* In the case of EVENT_HISTOGRAM_ENTRY_TS, adds a list of timestamp sequences
90* (histogram entry) to NBLog::mHists
91* In the case of EVENT_HISTOGRAM_FLUSH, calls drawHistogram on each element in
92* the list and erases it
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070093* TODO: get rid of the FLUSH, instead add every HISTOGRAM_ENTRY_TS to two
94* circular buffers: one short-term and one long-term (can add even longer-term
95* structures in the future). When dump is called, print everything currently
96* in the buffer.
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070097* NBLog::drawHistogram
98* input: timestamp array
99* buckets this to a histogram and prints
100*
101*/
102
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800103#define LOG_TAG "NBLog"
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -0700104// #define LOG_NDEBUG 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800105
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -0700106#include <algorithm>
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800107#include <climits>
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -0700108#include <deque>
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -0700109#include <fstream>
110// #include <inttypes.h>
111#include <iostream>
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -0700112#include <math.h>
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -0700113#include <numeric>
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -0700114#include <vector>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800115#include <stdarg.h>
116#include <stdint.h>
117#include <stdio.h>
118#include <string.h>
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800119#include <sys/prctl.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800120#include <time.h>
121#include <new>
Glenn Kasten535e1612016-12-05 12:19:36 -0800122#include <audio_utils/roundup.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800123#include <media/nbaio/NBLog.h>
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700124#include <media/nbaio/PerformanceAnalysis.h>
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700125// #include <utils/CallStack.h> // used to print callstack
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800126#include <utils/Log.h>
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700127#include <utils/String8.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800128
Nicolas Roulet40a44982017-02-03 13:39:57 -0800129#include <queue>
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700130#include <utility>
Nicolas Roulet40a44982017-02-03 13:39:57 -0800131
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800132namespace android {
133
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700134int NBLog::Entry::copyEntryDataAt(size_t offset) const
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800135{
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700136 // FIXME This is too slow
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800137 if (offset == 0)
138 return mEvent;
139 else if (offset == 1)
140 return mLength;
141 else if (offset < (size_t) (mLength + 2))
142 return ((char *) mData)[offset - 2];
143 else if (offset == (size_t) (mLength + 2))
144 return mLength;
145 else
146 return 0;
147}
148
149// ---------------------------------------------------------------------------
150
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700151/*static*/
152std::unique_ptr<NBLog::AbstractEntry> NBLog::AbstractEntry::buildEntry(const uint8_t *ptr) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -0700153 const uint8_t type = EntryIterator(ptr)->type;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700154 switch (type) {
155 case EVENT_START_FMT:
156 return std::make_unique<FormatEntry>(FormatEntry(ptr));
157 case EVENT_HISTOGRAM_FLUSH:
158 case EVENT_HISTOGRAM_ENTRY_TS:
159 return std::make_unique<HistogramEntry>(HistogramEntry(ptr));
160 default:
161 ALOGW("Tried to create AbstractEntry of type %d", type);
162 return nullptr;
163 }
Nicolas Roulet40a44982017-02-03 13:39:57 -0800164}
165
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700166NBLog::AbstractEntry::AbstractEntry(const uint8_t *entry) : mEntry(entry) {
167}
168
169// ---------------------------------------------------------------------------
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800170
Sanna Catherine de Treville Wagerdd92d7e2017-05-15 14:56:53 -0700171NBLog::EntryIterator NBLog::FormatEntry::begin() const {
172 return EntryIterator(mEntry);
173}
174
Nicolas Roulet40a44982017-02-03 13:39:57 -0800175const char *NBLog::FormatEntry::formatString() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800176 return (const char*) mEntry + offsetof(entry, data);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800177}
178
179size_t NBLog::FormatEntry::formatStringLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800180 return mEntry[offsetof(entry, length)];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800181}
182
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700183NBLog::EntryIterator NBLog::FormatEntry::args() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800184 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700185 // skip start fmt
186 ++it;
187 // skip timestamp
188 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700189 // skip hash
190 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700191 // Skip author if present
192 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800193 ++it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800194 }
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700195 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800196}
197
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700198int64_t NBLog::FormatEntry::timestamp() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800199 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700200 // skip start fmt
201 ++it;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700202 return it.payload<int64_t>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800203}
204
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700205NBLog::log_hash_t NBLog::FormatEntry::hash() const {
206 auto it = begin();
207 // skip start fmt
208 ++it;
209 // skip timestamp
210 ++it;
211 // unaligned 64-bit read not supported
212 log_hash_t hash;
213 memcpy(&hash, it->data, sizeof(hash));
214 return hash;
215}
216
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700217int NBLog::FormatEntry::author() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800218 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700219 // skip start fmt
220 ++it;
221 // skip timestamp
222 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700223 // skip hash
224 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700225 // if there is an author entry, return it, return -1 otherwise
226 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800227 return it.payload<int>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800228 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800229 return -1;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800230}
231
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700232NBLog::EntryIterator NBLog::FormatEntry::copyWithAuthor(
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800233 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
234 auto it = begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800235 // copy fmt start entry
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800236 it.copyTo(dst);
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700237 // copy timestamp
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700238 (++it).copyTo(dst); // copy hash
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700239 (++it).copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800240 // insert author entry
241 size_t authorEntrySize = NBLog::Entry::kOverhead + sizeof(author);
242 uint8_t authorEntry[authorEntrySize];
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800243 authorEntry[offsetof(entry, type)] = EVENT_AUTHOR;
244 authorEntry[offsetof(entry, length)] =
245 authorEntry[authorEntrySize + NBLog::Entry::kPreviousLengthOffset] =
246 sizeof(author);
247 *(int*) (&authorEntry[offsetof(entry, data)]) = author;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800248 dst->write(authorEntry, authorEntrySize);
249 // copy rest of entries
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800250 while ((++it)->type != EVENT_END_FMT) {
251 it.copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800252 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800253 it.copyTo(dst);
254 ++it;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800255 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800256}
257
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700258void NBLog::EntryIterator::copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800259 size_t length = ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
260 dst->write(ptr, length);
261}
Nicolas Roulet40a44982017-02-03 13:39:57 -0800262
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700263void NBLog::EntryIterator::copyData(uint8_t *dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800264 memcpy((void*) dst, ptr + offsetof(entry, data), ptr[offsetof(entry, length)]);
265}
266
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700267NBLog::EntryIterator::EntryIterator()
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800268 : ptr(nullptr) {}
269
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700270NBLog::EntryIterator::EntryIterator(const uint8_t *entry)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800271 : ptr(entry) {}
272
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700273NBLog::EntryIterator::EntryIterator(const NBLog::EntryIterator &other)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800274 : ptr(other.ptr) {}
275
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700276const NBLog::entry& NBLog::EntryIterator::operator*() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800277 return *(entry*) ptr;
278}
279
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700280const NBLog::entry* NBLog::EntryIterator::operator->() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800281 return (entry*) ptr;
282}
283
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700284NBLog::EntryIterator& NBLog::EntryIterator::operator++() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800285 ptr += ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
286 return *this;
287}
288
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700289NBLog::EntryIterator& NBLog::EntryIterator::operator--() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800290 ptr -= ptr[NBLog::Entry::kPreviousLengthOffset] + NBLog::Entry::kOverhead;
291 return *this;
292}
293
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700294NBLog::EntryIterator NBLog::EntryIterator::next() const {
295 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800296 return ++aux;
297}
298
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700299NBLog::EntryIterator NBLog::EntryIterator::prev() const {
300 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800301 return --aux;
302}
303
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700304int NBLog::EntryIterator::operator-(const NBLog::EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800305 return ptr - other.ptr;
306}
307
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700308bool NBLog::EntryIterator::operator!=(const EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800309 return ptr != other.ptr;
310}
311
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700312bool NBLog::EntryIterator::hasConsistentLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800313 return ptr[offsetof(entry, length)] == ptr[ptr[offsetof(entry, length)] +
314 NBLog::Entry::kOverhead + NBLog::Entry::kPreviousLengthOffset];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800315}
316
317// ---------------------------------------------------------------------------
318
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700319int64_t NBLog::HistogramEntry::timestamp() const {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700320 return EntryIterator(mEntry).payload<HistTsEntry>().ts;
321}
322
323NBLog::log_hash_t NBLog::HistogramEntry::hash() const {
324 return EntryIterator(mEntry).payload<HistTsEntry>().hash;
325}
326
327int NBLog::HistogramEntry::author() const {
328 EntryIterator it(mEntry);
329 if (it->length == sizeof(HistTsEntryWithAuthor)) {
330 return it.payload<HistTsEntryWithAuthor>().author;
331 } else {
332 return -1;
333 }
334}
335
336NBLog::EntryIterator NBLog::HistogramEntry::copyWithAuthor(
337 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
338 // Current histogram entry has {type, length, struct HistTsEntry, length}.
339 // We now want {type, length, struct HistTsEntryWithAuthor, length}
340 uint8_t buffer[Entry::kOverhead + sizeof(HistTsEntryWithAuthor)];
341 // Copy content until the point we want to add the author
342 memcpy(buffer, mEntry, sizeof(entry) + sizeof(HistTsEntry));
343 // Copy the author
344 *(int*) (buffer + sizeof(entry) + sizeof(HistTsEntry)) = author;
345 // Update lengths
346 buffer[offsetof(entry, length)] = sizeof(HistTsEntryWithAuthor);
347 buffer[sizeof(buffer) + Entry::kPreviousLengthOffset] = sizeof(HistTsEntryWithAuthor);
348 // Write new buffer into FIFO
349 dst->write(buffer, sizeof(buffer));
350 return EntryIterator(mEntry).next();
351}
352
353// ---------------------------------------------------------------------------
354
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800355#if 0 // FIXME see note in NBLog.h
356NBLog::Timeline::Timeline(size_t size, void *shared)
357 : mSize(roundup(size)), mOwn(shared == NULL),
358 mShared((Shared *) (mOwn ? new char[sharedSize(size)] : shared))
359{
360 new (mShared) Shared;
361}
362
363NBLog::Timeline::~Timeline()
364{
365 mShared->~Shared();
366 if (mOwn) {
367 delete[] (char *) mShared;
368 }
369}
370#endif
371
372/*static*/
373size_t NBLog::Timeline::sharedSize(size_t size)
374{
Glenn Kastened99c2b2016-12-12 08:31:24 -0800375 // TODO fifo now supports non-power-of-2 buffer sizes, so could remove the roundup
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800376 return sizeof(Shared) + roundup(size);
377}
378
379// ---------------------------------------------------------------------------
380
381NBLog::Writer::Writer()
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800382 : mShared(NULL), mFifo(NULL), mFifoWriter(NULL), mEnabled(false), mPidTag(NULL), mPidTagSize(0)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800383{
384}
385
Glenn Kasten535e1612016-12-05 12:19:36 -0800386NBLog::Writer::Writer(void *shared, size_t size)
387 : mShared((Shared *) shared),
388 mFifo(mShared != NULL ?
389 new audio_utils_fifo(size, sizeof(uint8_t),
390 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
391 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL),
392 mEnabled(mFifoWriter != NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800393{
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800394 // caching pid and process name
395 pid_t id = ::getpid();
396 char procName[16];
397 int status = prctl(PR_GET_NAME, procName);
398 if (status) { // error getting process name
399 procName[0] = '\0';
400 }
401 size_t length = strlen(procName);
402 mPidTagSize = length + sizeof(pid_t);
403 mPidTag = new char[mPidTagSize];
404 memcpy(mPidTag, &id, sizeof(pid_t));
405 memcpy(mPidTag + sizeof(pid_t), procName, length);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800406}
407
Glenn Kasten535e1612016-12-05 12:19:36 -0800408NBLog::Writer::Writer(const sp<IMemory>& iMemory, size_t size)
409 : Writer(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800410{
Glenn Kasten535e1612016-12-05 12:19:36 -0800411 mIMemory = iMemory;
412}
413
414NBLog::Writer::~Writer()
415{
416 delete mFifoWriter;
417 delete mFifo;
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800418 delete[] mPidTag;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800419}
420
421void NBLog::Writer::log(const char *string)
422{
423 if (!mEnabled) {
424 return;
425 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800426 LOG_ALWAYS_FATAL_IF(string == NULL, "Attempted to log NULL string");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800427 size_t length = strlen(string);
Glenn Kasten535e1612016-12-05 12:19:36 -0800428 if (length > Entry::kMaxLength) {
429 length = Entry::kMaxLength;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800430 }
431 log(EVENT_STRING, string, length);
432}
433
434void NBLog::Writer::logf(const char *fmt, ...)
435{
436 if (!mEnabled) {
437 return;
438 }
439 va_list ap;
440 va_start(ap, fmt);
441 Writer::logvf(fmt, ap); // the Writer:: is needed to avoid virtual dispatch for LockedWriter
442 va_end(ap);
443}
444
445void NBLog::Writer::logvf(const char *fmt, va_list ap)
446{
447 if (!mEnabled) {
448 return;
449 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800450 char buffer[Entry::kMaxLength + 1 /*NUL*/];
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800451 int length = vsnprintf(buffer, sizeof(buffer), fmt, ap);
452 if (length >= (int) sizeof(buffer)) {
453 length = sizeof(buffer) - 1;
454 // NUL termination is not required
455 // buffer[length] = '\0';
456 }
457 if (length >= 0) {
458 log(EVENT_STRING, buffer, length);
459 }
460}
461
462void NBLog::Writer::logTimestamp()
463{
464 if (!mEnabled) {
465 return;
466 }
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700467 int64_t ts = get_monotonic_ns();
468 if (ts > 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800469 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700470 } else {
471 ALOGE("Failed to get timestamp");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800472 }
473}
474
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700475void NBLog::Writer::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800476{
477 if (!mEnabled) {
478 return;
479 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800480 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
481}
482
483void NBLog::Writer::logInteger(const int x)
484{
485 if (!mEnabled) {
486 return;
487 }
488 log(EVENT_INTEGER, &x, sizeof(x));
489}
490
491void NBLog::Writer::logFloat(const float x)
492{
493 if (!mEnabled) {
494 return;
495 }
496 log(EVENT_FLOAT, &x, sizeof(x));
497}
498
499void NBLog::Writer::logPID()
500{
501 if (!mEnabled) {
502 return;
503 }
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800504 log(EVENT_PID, mPidTag, mPidTagSize);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800505}
506
507void NBLog::Writer::logStart(const char *fmt)
508{
509 if (!mEnabled) {
510 return;
511 }
512 size_t length = strlen(fmt);
513 if (length > Entry::kMaxLength) {
514 length = Entry::kMaxLength;
515 }
516 log(EVENT_START_FMT, fmt, length);
517}
518
519void NBLog::Writer::logEnd()
520{
521 if (!mEnabled) {
522 return;
523 }
524 Entry entry = Entry(EVENT_END_FMT, NULL, 0);
525 log(&entry, true);
526}
527
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700528void NBLog::Writer::logHash(log_hash_t hash)
529{
530 if (!mEnabled) {
531 return;
532 }
533 log(EVENT_HASH, &hash, sizeof(hash));
534}
535
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700536void NBLog::Writer::logHistTS(log_hash_t hash)
537{
538 if (!mEnabled) {
539 return;
540 }
541 HistTsEntry data;
542 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700543 data.ts = get_monotonic_ns();
544 if (data.ts > 0) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700545 log(EVENT_HISTOGRAM_ENTRY_TS, &data, sizeof(data));
546 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700547 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700548 }
549}
550
551void NBLog::Writer::logHistFlush(log_hash_t hash)
552{
553 if (!mEnabled) {
554 return;
555 }
556 HistTsEntry data;
557 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700558 data.ts = get_monotonic_ns();
559 if (data.ts > 0) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700560 log(EVENT_HISTOGRAM_FLUSH, &data, sizeof(data));
561 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700562 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700563 }
564}
565
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700566void NBLog::Writer::logFormat(const char *fmt, log_hash_t hash, ...)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800567{
568 if (!mEnabled) {
569 return;
570 }
571
572 va_list ap;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700573 va_start(ap, hash);
574 Writer::logVFormat(fmt, hash, ap);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800575 va_end(ap);
576}
577
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700578void NBLog::Writer::logVFormat(const char *fmt, log_hash_t hash, va_list argp)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800579{
580 if (!mEnabled) {
581 return;
582 }
583 Writer::logStart(fmt);
584 int i;
585 double f;
586 char* s;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700587 int64_t t;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800588 Writer::logTimestamp();
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700589 Writer::logHash(hash);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800590 for (const char *p = fmt; *p != '\0'; p++) {
591 // TODO: implement more complex formatting such as %.3f
592 if (*p != '%') {
593 continue;
594 }
595 switch(*++p) {
596 case 's': // string
597 s = va_arg(argp, char *);
598 Writer::log(s);
599 break;
600
601 case 't': // timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700602 t = va_arg(argp, int64_t);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800603 Writer::logTimestamp(t);
604 break;
605
606 case 'd': // integer
607 i = va_arg(argp, int);
608 Writer::logInteger(i);
609 break;
610
611 case 'f': // float
612 f = va_arg(argp, double); // float arguments are promoted to double in vararg lists
613 Writer::logFloat((float)f);
614 break;
615
616 case 'p': // pid
617 Writer::logPID();
618 break;
619
620 // the "%\0" case finishes parsing
621 case '\0':
622 --p;
623 break;
624
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800625 case '%':
626 break;
627
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800628 default:
629 ALOGW("NBLog Writer parsed invalid format specifier: %c", *p);
630 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800631 }
632 }
633 Writer::logEnd();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800634}
635
636void NBLog::Writer::log(Event event, const void *data, size_t length)
637{
638 if (!mEnabled) {
639 return;
640 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800641 if (data == NULL || length > Entry::kMaxLength) {
642 // TODO Perhaps it makes sense to display truncated data or at least a
643 // message that the data is too long? The current behavior can create
644 // a confusion for a programmer debugging their code.
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800645 return;
646 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700647 // Ignore if invalid event
648 if (event == EVENT_RESERVED || event >= EVENT_UPPER_BOUND) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800649 return;
650 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700651 Entry etr(event, data, length);
652 log(&etr, true /*trusted*/);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800653}
654
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700655void NBLog::Writer::log(const NBLog::Entry *etr, bool trusted)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800656{
657 if (!mEnabled) {
658 return;
659 }
660 if (!trusted) {
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700661 log(etr->mEvent, etr->mData, etr->mLength);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800662 return;
663 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700664 size_t need = etr->mLength + Entry::kOverhead; // mEvent, mLength, data[mLength], mLength
665 // need = number of bytes written to FIFO
Glenn Kasten535e1612016-12-05 12:19:36 -0800666
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800667 // FIXME optimize this using memcpy for the data part of the Entry.
668 // The Entry could have a method copyTo(ptr, offset, size) to optimize the copy.
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700669 // checks size of a single log Entry: type, length, data pointer and ending
Glenn Kasten535e1612016-12-05 12:19:36 -0800670 uint8_t temp[Entry::kMaxLength + Entry::kOverhead];
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700671 // write this data to temp array
Glenn Kasten535e1612016-12-05 12:19:36 -0800672 for (size_t i = 0; i < need; i++) {
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700673 temp[i] = etr->copyEntryDataAt(i);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800674 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700675 // write to circular buffer
Glenn Kasten535e1612016-12-05 12:19:36 -0800676 mFifoWriter->write(temp, need);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800677}
678
679bool NBLog::Writer::isEnabled() const
680{
681 return mEnabled;
682}
683
684bool NBLog::Writer::setEnabled(bool enabled)
685{
686 bool old = mEnabled;
687 mEnabled = enabled && mShared != NULL;
688 return old;
689}
690
691// ---------------------------------------------------------------------------
692
693NBLog::LockedWriter::LockedWriter()
694 : Writer()
695{
696}
697
Glenn Kasten535e1612016-12-05 12:19:36 -0800698NBLog::LockedWriter::LockedWriter(void *shared, size_t size)
699 : Writer(shared, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800700{
701}
702
703void NBLog::LockedWriter::log(const char *string)
704{
705 Mutex::Autolock _l(mLock);
706 Writer::log(string);
707}
708
709void NBLog::LockedWriter::logf(const char *fmt, ...)
710{
711 // FIXME should not take the lock until after formatting is done
712 Mutex::Autolock _l(mLock);
713 va_list ap;
714 va_start(ap, fmt);
715 Writer::logvf(fmt, ap);
716 va_end(ap);
717}
718
719void NBLog::LockedWriter::logvf(const char *fmt, va_list ap)
720{
721 // FIXME should not take the lock until after formatting is done
722 Mutex::Autolock _l(mLock);
723 Writer::logvf(fmt, ap);
724}
725
726void NBLog::LockedWriter::logTimestamp()
727{
728 // FIXME should not take the lock until after the clock_gettime() syscall
729 Mutex::Autolock _l(mLock);
730 Writer::logTimestamp();
731}
732
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700733void NBLog::LockedWriter::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800734{
735 Mutex::Autolock _l(mLock);
736 Writer::logTimestamp(ts);
737}
738
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800739void NBLog::LockedWriter::logInteger(const int x)
740{
741 Mutex::Autolock _l(mLock);
742 Writer::logInteger(x);
743}
744
745void NBLog::LockedWriter::logFloat(const float x)
746{
747 Mutex::Autolock _l(mLock);
748 Writer::logFloat(x);
749}
750
751void NBLog::LockedWriter::logPID()
752{
753 Mutex::Autolock _l(mLock);
754 Writer::logPID();
755}
756
757void NBLog::LockedWriter::logStart(const char *fmt)
758{
759 Mutex::Autolock _l(mLock);
760 Writer::logStart(fmt);
761}
762
763
764void NBLog::LockedWriter::logEnd()
765{
766 Mutex::Autolock _l(mLock);
767 Writer::logEnd();
768}
769
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700770void NBLog::LockedWriter::logHash(log_hash_t hash)
771{
772 Mutex::Autolock _l(mLock);
773 Writer::logHash(hash);
774}
775
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800776bool NBLog::LockedWriter::isEnabled() const
777{
778 Mutex::Autolock _l(mLock);
779 return Writer::isEnabled();
780}
781
782bool NBLog::LockedWriter::setEnabled(bool enabled)
783{
784 Mutex::Autolock _l(mLock);
785 return Writer::setEnabled(enabled);
786}
787
788// ---------------------------------------------------------------------------
789
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700790const std::set<NBLog::Event> NBLog::Reader::startingTypes {NBLog::Event::EVENT_START_FMT,
791 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
792const std::set<NBLog::Event> NBLog::Reader::endingTypes {NBLog::Event::EVENT_END_FMT,
793 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
794 NBLog::Event::EVENT_HISTOGRAM_FLUSH};
Glenn Kasten535e1612016-12-05 12:19:36 -0800795NBLog::Reader::Reader(const void *shared, size_t size)
796 : mShared((/*const*/ Shared *) shared), /*mIMemory*/
797 mFd(-1), mIndent(0),
798 mFifo(mShared != NULL ?
799 new audio_utils_fifo(size, sizeof(uint8_t),
800 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700801 mFifoReader(mFifo != NULL ? new audio_utils_fifo_reader(*mFifo) : NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800802{
803}
804
Glenn Kasten535e1612016-12-05 12:19:36 -0800805NBLog::Reader::Reader(const sp<IMemory>& iMemory, size_t size)
806 : Reader(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800807{
Glenn Kasten535e1612016-12-05 12:19:36 -0800808 mIMemory = iMemory;
809}
810
811NBLog::Reader::~Reader()
812{
813 delete mFifoReader;
814 delete mFifo;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800815}
816
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700817const uint8_t *NBLog::Reader::findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
818 const std::set<Event> &types) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800819 while (back + Entry::kPreviousLengthOffset >= front) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700820 const uint8_t *prev = back - back[Entry::kPreviousLengthOffset] - Entry::kOverhead;
821 if (prev < front || prev + prev[offsetof(entry, length)] +
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800822 Entry::kOverhead != back) {
823
824 // prev points to an out of limits or inconsistent entry
825 return nullptr;
826 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700827 if (types.find((const Event) prev[offsetof(entry, type)]) != types.end()) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800828 return prev;
829 }
830 back = prev;
831 }
832 return nullptr; // no entry found
833}
834
Nicolas Roulet40a44982017-02-03 13:39:57 -0800835std::unique_ptr<NBLog::Reader::Snapshot> NBLog::Reader::getSnapshot()
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800836{
Glenn Kasten535e1612016-12-05 12:19:36 -0800837 if (mFifoReader == NULL) {
Nicolas Roulet40a44982017-02-03 13:39:57 -0800838 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800839 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800840 // make a copy to avoid race condition with writer
Glenn Kasten535e1612016-12-05 12:19:36 -0800841 size_t capacity = mFifo->capacity();
842
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800843 // This emulates the behaviour of audio_utils_fifo_reader::read, but without incrementing the
844 // reader index. The index is incremented after handling corruption, to after the last complete
845 // entry of the buffer
846 size_t lost;
847 audio_utils_iovec iovec[2];
848 ssize_t availToRead = mFifoReader->obtain(iovec, capacity, NULL /*timeout*/, &lost);
849 if (availToRead <= 0) {
850 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
851 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800852
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800853 std::unique_ptr<Snapshot> snapshot(new Snapshot(availToRead));
854 memcpy(snapshot->mData, (const char *) mFifo->buffer() + iovec[0].mOffset, iovec[0].mLength);
855 if (iovec[1].mLength > 0) {
856 memcpy(snapshot->mData + (iovec[0].mLength),
857 (const char *) mFifo->buffer() + iovec[1].mOffset, iovec[1].mLength);
858 }
859
860 // Handle corrupted buffer
861 // Potentially, a buffer has corrupted data on both beginning (due to overflow) and end
862 // (due to incomplete format entry). But even if the end format entry is incomplete,
863 // it ends in a complete entry (which is not an END_FMT). So is safe to traverse backwards.
864 // TODO: handle client corruption (in the middle of a buffer)
865
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700866 const uint8_t *back = snapshot->mData + availToRead;
867 const uint8_t *front = snapshot->mData;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800868
869 // Find last END_FMT. <back> is sitting on an entry which might be the middle of a FormatEntry.
870 // We go backwards until we find an EVENT_END_FMT.
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700871 const uint8_t *lastEnd = findLastEntryOfTypes(front, back, endingTypes);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800872 if (lastEnd == nullptr) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700873 snapshot->mEnd = snapshot->mBegin = EntryIterator(front);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800874 } else {
875 // end of snapshot points to after last END_FMT entry
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700876 snapshot->mEnd = EntryIterator(lastEnd).next();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800877 // find first START_FMT
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700878 const uint8_t *firstStart = nullptr;
879 const uint8_t *firstStartTmp = snapshot->mEnd;
880 while ((firstStartTmp = findLastEntryOfTypes(front, firstStartTmp, startingTypes))
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800881 != nullptr) {
882 firstStart = firstStartTmp;
883 }
884 // firstStart is null if no START_FMT entry was found before lastEnd
885 if (firstStart == nullptr) {
886 snapshot->mBegin = snapshot->mEnd;
887 } else {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700888 snapshot->mBegin = EntryIterator(firstStart);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800889 }
890 }
891
892 // advance fifo reader index to after last entry read.
893 mFifoReader->release(snapshot->mEnd - front);
894
895 snapshot->mLost = lost;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800896 return snapshot;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800897
Nicolas Roulet40a44982017-02-03 13:39:57 -0800898}
899
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -0700900// writes sample deltas to file, either truncating or appending
901inline void writeHistToFile(const std::vector<int64_t> &samples, bool append) {
902 // name of file on audioserver
903 static const char* const kName = (char *)"/data/misc/audioserver/sample_results.txt";
904 // stores deltas between the samples
905 std::vector<int64_t> intervals;
906 if (samples.size() == 0) return;
907 for (size_t i = 1; i < samples.size(); ++i) {
908 intervals.push_back(deltaMs(samples[i - 1], samples[i]));
909 }
910 // Deletes maximum value in a histogram. Temp quick fix.
911 // FIXME: need to find root cause of approx. 35th element from the end
912 // consistently being an outlier in the first histogram of a flush
913 // ALOGW("%" PRId64 "before", (int64_t) *(std::max_element(intervals.begin(), intervals.end())));
914 intervals.erase(std::max_element(intervals.begin(), intervals.end()));
915 // ALOGW("%" PRId64 "after", (int64_t) *(std::max_element(intervals.begin(), intervals.end())));
916 std::ofstream ofs;
917 ofs.open(kName, append ? std::ios::app : std::ios::trunc);
918 if (!ofs) {
919 ALOGW("couldn't open file %s", kName);
920 return;
921 }
922 for (size_t i = 0; i < intervals.size(); ++i) {
923 ofs << intervals[i] << "\n";
924 }
925 ofs.close();
926}
927
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700928// converts a time series into a map. key: buffer period length. value: count
929static std::map<int, int> buildBuckets(const std::vector<int64_t> &samples) {
930 // TODO allow buckets of variable resolution
931 std::map<int, int> buckets;
932 for (size_t i = 1; i < samples.size(); ++i) {
933 ++buckets[deltaMs(samples[i - 1], samples[i])];
934 }
935 return buckets;
936}
937
Nicolas Roulet40a44982017-02-03 13:39:57 -0800938void NBLog::Reader::dump(int fd, size_t indent, NBLog::Reader::Snapshot &snapshot)
939{
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700940 // CallStack cs(LOG_TAG);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700941 mFd = fd;
942 mIndent = indent;
943 String8 timestamp, body;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700944 size_t lost = snapshot.lost() + (snapshot.begin() - EntryIterator(snapshot.data()));
Glenn Kastenc02c9612013-10-15 09:25:11 -0700945 if (lost > 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700946 body.appendFormat("warning: lost %zu bytes worth of events", lost);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700947 // 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 -0700948 // log to push it out. Consider keeping the timestamp/body between calls to copyEntryDataAt().
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700949 dumpLine(timestamp, body);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800950 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700951
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800952 for (auto entry = snapshot.begin(); entry != snapshot.end();) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800953 switch (entry->type) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800954 case EVENT_START_FMT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800955 entry = handleFormat(FormatEntry(entry), &timestamp, &body);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800956 break;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700957 case EVENT_HISTOGRAM_ENTRY_TS: {
958 HistTsEntryWithAuthor *data = (HistTsEntryWithAuthor *) (entry->data);
959 // TODO This memcpies are here to avoid unaligned memory access crash.
960 // There's probably a more efficient way to do it
961 log_hash_t hash;
962 memcpy(&hash, &(data->hash), sizeof(hash));
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700963 int64_t ts;
964 memcpy(&ts, &data->ts, sizeof(ts));
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700965 const std::pair<log_hash_t, int> key(hash, data->author);
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700966 // TODO might want to filter excessively high outliers, which are usually caused
967 // by the thread being inactive.
968 mHists[key].push_back(ts);
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700969 // store time series data for each reader in order to bucket it once there
970 // is enough data. Then, it is written to recentHists as a histogram.
971 mTimeStampSeries[data->author].push_back(ts);
972 // if length of the time series has reached kShortHistSize samples,
973 // compute its histogram, append this to mRecentHists and erase the time series
974 if (mTimeStampSeries[data->author].size() >= kShortHistSize) {
975 mRecentHists.emplace_front(data->author,
976 buildBuckets(mTimeStampSeries[data->author]));
977 // do not let mRecentHists exceed capacity
978 // TODO: turn the FIFO queue into a circular buffer
979 if (mRecentHists.size() >= kRecentHistsCapacity) {
980 mRecentHists.pop_back();
981 }
982 mTimeStampSeries.erase(data->author);
983 }
984 // if an element in mHists has not grown for a long time, delete
985 // TODO copy histogram data only to mRecentHistsBuffer and pop oldest
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700986 ++entry;
987 break;
988 }
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700989 case EVENT_HISTOGRAM_FLUSH: {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700990 ++entry;
991 break;
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700992 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800993 case EVENT_END_FMT:
994 body.appendFormat("warning: got to end format event");
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800995 ++entry;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800996 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800997 case EVENT_RESERVED:
998 default:
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800999 body.appendFormat("warning: unexpected event %d", entry->type);
1000 ++entry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001001 break;
1002 }
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -07001003 }
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -07001004 PerformanceAnalysis performanceAnalyzer;
1005 performanceAnalyzer.reportPerformance(&body, mRecentHists);
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -07001006 if (!body.isEmpty()) {
1007 dumpLine(timestamp, body);
Glenn Kasten4e01ef62013-07-11 14:29:59 -07001008 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001009}
1010
Nicolas Roulet40a44982017-02-03 13:39:57 -08001011void NBLog::Reader::dump(int fd, size_t indent)
1012{
1013 // get a snapshot, dump it
1014 std::unique_ptr<Snapshot> snap = getSnapshot();
1015 dump(fd, indent, *snap);
1016}
1017
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001018void NBLog::Reader::dumpLine(const String8 &timestamp, String8 &body)
Glenn Kasten4e01ef62013-07-11 14:29:59 -07001019{
1020 if (mFd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07001021 dprintf(mFd, "%.*s%s %s\n", mIndent, "", timestamp.string(), body.string());
Glenn Kasten4e01ef62013-07-11 14:29:59 -07001022 } else {
1023 ALOGI("%.*s%s %s", mIndent, "", timestamp.string(), body.string());
1024 }
1025 body.clear();
1026}
1027
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001028bool NBLog::Reader::isIMemory(const sp<IMemory>& iMemory) const
1029{
Glenn Kasten481fb672013-09-30 14:39:28 -07001030 return iMemory != 0 && mIMemory != 0 && iMemory->pointer() == mIMemory->pointer();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001031}
1032
Glenn Kasten1c446272017-04-07 09:49:07 -07001033// ---------------------------------------------------------------------------
1034
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001035void NBLog::appendTimestamp(String8 *body, const void *data) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001036 int64_t ts;
1037 memcpy(&ts, data, sizeof(ts));
1038 body->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1039 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001040}
1041
1042void NBLog::appendInt(String8 *body, const void *data) {
1043 int x = *((int*) data);
1044 body->appendFormat("<%d>", x);
1045}
1046
1047void NBLog::appendFloat(String8 *body, const void *data) {
1048 float f;
1049 memcpy(&f, data, sizeof(float));
1050 body->appendFormat("<%f>", f);
1051}
1052
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001053void NBLog::appendPID(String8 *body, const void* data, size_t length) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001054 pid_t id = *((pid_t*) data);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001055 char * name = &((char*) data)[sizeof(pid_t)];
1056 body->appendFormat("<PID: %d, name: %.*s>", id, (int) (length - sizeof(pid_t)), name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001057}
1058
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001059String8 NBLog::bufferDump(const uint8_t *buffer, size_t size)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001060{
1061 String8 str;
1062 str.append("[ ");
1063 for(size_t i = 0; i < size; i++)
1064 {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001065 str.appendFormat("%d ", buffer[i]);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001066 }
1067 str.append("]");
1068 return str;
1069}
1070
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001071String8 NBLog::bufferDump(const EntryIterator &it)
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001072{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001073 return bufferDump(it, it->length + Entry::kOverhead);
Nicolas Roulet2aedf372017-03-29 11:27:03 -07001074}
1075
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001076NBLog::EntryIterator NBLog::Reader::handleFormat(const FormatEntry &fmtEntry,
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001077 String8 *timestamp,
1078 String8 *body) {
Nicolas Roulet40a44982017-02-03 13:39:57 -08001079 // log timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001080 int64_t ts = fmtEntry.timestamp();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001081 timestamp->clear();
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001082 timestamp->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1083 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Roulet40a44982017-02-03 13:39:57 -08001084
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -07001085 // log unique hash
1086 log_hash_t hash = fmtEntry.hash();
1087 // print only lower 16bit of hash as hex and line as int to reduce spam in the log
1088 body->appendFormat("%.4X-%d ", (int)(hash >> 16) & 0xFFFF, (int) hash & 0xFFFF);
1089
Nicolas Roulet40a44982017-02-03 13:39:57 -08001090 // log author (if present)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001091 handleAuthor(fmtEntry, body);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001092
1093 // log string
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001094 NBLog::EntryIterator arg = fmtEntry.args();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001095
1096 const char* fmt = fmtEntry.formatString();
1097 size_t fmt_length = fmtEntry.formatStringLength();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001098
1099 for (size_t fmt_offset = 0; fmt_offset < fmt_length; ++fmt_offset) {
1100 if (fmt[fmt_offset] != '%') {
1101 body->append(&fmt[fmt_offset], 1); // TODO optimize to write consecutive strings at once
1102 continue;
1103 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001104 // case "%%""
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001105 if (fmt[++fmt_offset] == '%') {
1106 body->append("%");
1107 continue;
1108 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001109 // case "%\0"
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001110 if (fmt_offset == fmt_length) {
1111 continue;
1112 }
1113
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001114 NBLog::Event event = (NBLog::Event) arg->type;
1115 size_t length = arg->length;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001116
1117 // TODO check length for event type is correct
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001118
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001119 if (event == EVENT_END_FMT) {
1120 break;
1121 }
1122
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001123 // TODO: implement more complex formatting such as %.3f
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001124 const uint8_t *datum = arg->data; // pointer to the current event args
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001125 switch(fmt[fmt_offset])
1126 {
1127 case 's': // string
Nicolas Roulet4da78202017-02-03 12:53:39 -08001128 ALOGW_IF(event != EVENT_STRING,
1129 "NBLog Reader incompatible event for string specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001130 body->append((const char*) datum, length);
1131 break;
1132
1133 case 't': // timestamp
Nicolas Roulet4da78202017-02-03 12:53:39 -08001134 ALOGW_IF(event != EVENT_TIMESTAMP,
1135 "NBLog Reader incompatible event for timestamp specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001136 appendTimestamp(body, datum);
1137 break;
1138
1139 case 'd': // integer
Nicolas Roulet4da78202017-02-03 12:53:39 -08001140 ALOGW_IF(event != EVENT_INTEGER,
1141 "NBLog Reader incompatible event for integer specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001142 appendInt(body, datum);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001143 break;
1144
1145 case 'f': // float
Nicolas Roulet4da78202017-02-03 12:53:39 -08001146 ALOGW_IF(event != EVENT_FLOAT,
1147 "NBLog Reader incompatible event for float specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001148 appendFloat(body, datum);
1149 break;
1150
1151 case 'p': // pid
Nicolas Roulet4da78202017-02-03 12:53:39 -08001152 ALOGW_IF(event != EVENT_PID,
1153 "NBLog Reader incompatible event for pid specifier: %d", event);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001154 appendPID(body, datum, length);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001155 break;
1156
1157 default:
1158 ALOGW("NBLog Reader encountered unknown character %c", fmt[fmt_offset]);
1159 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001160 ++arg;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001161 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001162 ALOGW_IF(arg->type != EVENT_END_FMT, "Expected end of format, got %d", arg->type);
1163 ++arg;
1164 return arg;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001165}
1166
Nicolas Roulet40a44982017-02-03 13:39:57 -08001167NBLog::Merger::Merger(const void *shared, size_t size):
Nicolas Roulet40a44982017-02-03 13:39:57 -08001168 mShared((Shared *) shared),
1169 mFifo(mShared != NULL ?
1170 new audio_utils_fifo(size, sizeof(uint8_t),
1171 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
1172 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL)
1173 {}
1174
1175void NBLog::Merger::addReader(const NBLog::NamedReader &reader) {
Glenn Kasten1c446272017-04-07 09:49:07 -07001176 // FIXME This is called by binder thread in MediaLogService::registerWriter
1177 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001178 mNamedReaders.push_back(reader);
1179}
1180
1181// items placed in priority queue during merge
1182// composed by a timestamp and the index of the snapshot where the timestamp came from
1183struct MergeItem
1184{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001185 int64_t ts;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001186 int index;
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001187 MergeItem(int64_t ts, int index): ts(ts), index(index) {}
Nicolas Roulet40a44982017-02-03 13:39:57 -08001188};
1189
1190// operators needed for priority queue in merge
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001191// bool operator>(const int64_t &t1, const int64_t &t2) {
1192// return t1.tv_sec > t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec);
1193// }
Nicolas Roulet40a44982017-02-03 13:39:57 -08001194
1195bool operator>(const struct MergeItem &i1, const struct MergeItem &i2) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001196 return i1.ts > i2.ts || (i1.ts == i2.ts && i1.index > i2.index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001197}
1198
1199// Merge registered readers, sorted by timestamp
1200void NBLog::Merger::merge() {
Glenn Kasten1c446272017-04-07 09:49:07 -07001201 // FIXME This is called by merge thread
1202 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001203 int nLogs = mNamedReaders.size();
1204 std::vector<std::unique_ptr<NBLog::Reader::Snapshot>> snapshots(nLogs);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001205 std::vector<NBLog::EntryIterator> offsets(nLogs);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001206 for (int i = 0; i < nLogs; ++i) {
1207 snapshots[i] = mNamedReaders[i].reader()->getSnapshot();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001208 offsets[i] = snapshots[i]->begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001209 }
1210 // initialize offsets
Nicolas Roulet40a44982017-02-03 13:39:57 -08001211 // TODO custom heap implementation could allow to update top, improving performance
1212 // for bursty buffers
1213 std::priority_queue<MergeItem, std::vector<MergeItem>, std::greater<MergeItem>> timestamps;
1214 for (int i = 0; i < nLogs; ++i)
1215 {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001216 if (offsets[i] != snapshots[i]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001217 int64_t ts = AbstractEntry::buildEntry(offsets[i])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001218 timestamps.emplace(ts, i);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001219 }
1220 }
1221
1222 while (!timestamps.empty()) {
1223 // find minimum timestamp
1224 int index = timestamps.top().index;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001225 // copy it to the log, increasing offset
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001226 offsets[index] = AbstractEntry::buildEntry(offsets[index])->copyWithAuthor(mFifoWriter,
1227 index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001228 // update data structures
Nicolas Roulet40a44982017-02-03 13:39:57 -08001229 timestamps.pop();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001230 if (offsets[index] != snapshots[index]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001231 int64_t ts = AbstractEntry::buildEntry(offsets[index])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001232 timestamps.emplace(ts, index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001233 }
1234 }
1235}
1236
Glenn Kasten1c446272017-04-07 09:49:07 -07001237const std::vector<NBLog::NamedReader>& NBLog::Merger::getNamedReaders() const {
1238 // FIXME This is returning a reference to a shared variable that needs a lock
1239 return mNamedReaders;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001240}
1241
Glenn Kasten1c446272017-04-07 09:49:07 -07001242// ---------------------------------------------------------------------------
1243
Nicolas Roulet40a44982017-02-03 13:39:57 -08001244NBLog::MergeReader::MergeReader(const void *shared, size_t size, Merger &merger)
1245 : Reader(shared, size), mNamedReaders(merger.getNamedReaders()) {}
1246
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001247void NBLog::MergeReader::handleAuthor(const NBLog::AbstractEntry &entry, String8 *body) {
1248 int author = entry.author();
Glenn Kasten1c446272017-04-07 09:49:07 -07001249 // FIXME Needs a lock
1250 const char* name = mNamedReaders[author].name();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001251 body->appendFormat("%s: ", name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001252}
1253
Glenn Kasten1c446272017-04-07 09:49:07 -07001254// ---------------------------------------------------------------------------
1255
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001256NBLog::MergeThread::MergeThread(NBLog::Merger &merger)
1257 : mMerger(merger),
1258 mTimeoutUs(0) {}
1259
1260NBLog::MergeThread::~MergeThread() {
1261 // set exit flag, set timeout to 0 to force threadLoop to exit and wait for the thread to join
1262 requestExit();
1263 setTimeoutUs(0);
1264 join();
1265}
1266
1267bool NBLog::MergeThread::threadLoop() {
1268 bool doMerge;
1269 {
1270 AutoMutex _l(mMutex);
1271 // If mTimeoutUs is negative, wait on the condition variable until it's positive.
1272 // If it's positive, wait kThreadSleepPeriodUs and then merge
1273 nsecs_t waitTime = mTimeoutUs > 0 ? kThreadSleepPeriodUs * 1000 : LLONG_MAX;
1274 mCond.waitRelative(mMutex, waitTime);
1275 doMerge = mTimeoutUs > 0;
1276 mTimeoutUs -= kThreadSleepPeriodUs;
1277 }
1278 if (doMerge) {
1279 mMerger.merge();
1280 }
1281 return true;
1282}
1283
1284void NBLog::MergeThread::wakeup() {
1285 setTimeoutUs(kThreadWakeupPeriodUs);
1286}
1287
1288void NBLog::MergeThread::setTimeoutUs(int time) {
1289 AutoMutex _l(mMutex);
1290 mTimeoutUs = time;
1291 mCond.signal();
1292}
1293
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001294} // namespace android