blob: f698fa28e960eda0dc95cbc0c644c8f65a5a63aa [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080023#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070024#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080025#include <utils/Log.h>
26
27#include <private/media/AudioTrackShared.h>
28
29#include <common_time/cc_helper.h>
30#include <common_time/local_clock.h>
31
32#include "AudioMixer.h"
33#include "AudioFlinger.h"
34#include "ServiceUtilities.h"
35
Glenn Kastenda6ef132013-01-10 12:31:01 -080036#include <media/nbaio/Pipe.h>
37#include <media/nbaio/PipeReader.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070038#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080039
Eric Laurent81784c32012-11-19 14:55:58 -080040// ----------------------------------------------------------------------------
41
42// Note: the following macro is used for extremely verbose logging message. In
43// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
44// 0; but one side effect of this is to turn all LOGV's as well. Some messages
45// are so verbose that we want to suppress them even when we have ALOG_ASSERT
46// turned on. Do not uncomment the #def below unless you really know what you
47// are doing and want to see all of the extremely verbose messages.
48//#define VERY_VERY_VERBOSE_LOGGING
49#ifdef VERY_VERY_VERBOSE_LOGGING
50#define ALOGVV ALOGV
51#else
52#define ALOGVV(a...) do { } while(0)
53#endif
54
55namespace android {
56
57// ----------------------------------------------------------------------------
58// TrackBase
59// ----------------------------------------------------------------------------
60
Glenn Kastenda6ef132013-01-10 12:31:01 -080061static volatile int32_t nextTrackId = 55;
62
Eric Laurent81784c32012-11-19 14:55:58 -080063// TrackBase constructor must be called with AudioFlinger::mLock held
64AudioFlinger::ThreadBase::TrackBase::TrackBase(
65 ThreadBase *thread,
66 const sp<Client>& client,
67 uint32_t sampleRate,
68 audio_format_t format,
69 audio_channel_mask_t channelMask,
70 size_t frameCount,
71 const sp<IMemory>& sharedBuffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080072 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080073 int clientUid,
Glenn Kasten755b0a62014-05-13 11:30:28 -070074 IAudioFlinger::track_flags_t flags,
Glenn Kastend776ac62014-05-07 09:16:09 -070075 bool isOut,
76 bool useReadOnlyHeap)
Eric Laurent81784c32012-11-19 14:55:58 -080077 : RefBase(),
78 mThread(thread),
79 mClient(client),
80 mCblk(NULL),
81 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080082 mState(IDLE),
83 mSampleRate(sampleRate),
84 mFormat(format),
85 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070086 mChannelCount(isOut ?
87 audio_channel_count_from_out_mask(channelMask) :
88 audio_channel_count_from_in_mask(channelMask)),
Eric Laurent81784c32012-11-19 14:55:58 -080089 mFrameSize(audio_is_linear_pcm(format) ?
90 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
91 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080092 mSessionId(sessionId),
Glenn Kasten755b0a62014-05-13 11:30:28 -070093 mFlags(flags),
Glenn Kastene3aa6592012-12-04 12:22:46 -080094 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080095 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080096 mId(android_atomic_inc(&nextTrackId)),
97 mTerminated(false)
Eric Laurent81784c32012-11-19 14:55:58 -080098{
Marco Nelissen462fd2f2013-01-14 14:12:05 -080099 // if the caller is us, trust the specified uid
100 if (IPCThreadState::self()->getCallingPid() != getpid_cached || clientUid == -1) {
101 int newclientUid = IPCThreadState::self()->getCallingUid();
102 if (clientUid != -1 && clientUid != newclientUid) {
103 ALOGW("uid %d tried to pass itself off as %d", newclientUid, clientUid);
104 }
105 clientUid = newclientUid;
106 }
107 // clientUid contains the uid of the app that is responsible for this track, so we can blame
108 // battery usage on it.
109 mUid = clientUid;
110
Eric Laurent81784c32012-11-19 14:55:58 -0800111 // client == 0 implies sharedBuffer == 0
112 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
113
114 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
115 sharedBuffer->size());
116
117 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
118 size_t size = sizeof(audio_track_cblk_t);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800119 size_t bufferSize = (sharedBuffer == 0 ? roundup(frameCount) : frameCount) * mFrameSize;
Glenn Kastend776ac62014-05-07 09:16:09 -0700120 if (sharedBuffer == 0 && !useReadOnlyHeap) {
Eric Laurent81784c32012-11-19 14:55:58 -0800121 size += bufferSize;
122 }
123
124 if (client != 0) {
125 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700126 if (mCblkMemory == 0 ||
127 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800128 ALOGE("not enough memory for AudioTrack size=%u", size);
129 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700130 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800131 return;
132 }
133 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800134 // this syntax avoids calling the audio_track_cblk_t constructor twice
135 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800136 // assume mCblk != NULL
137 }
138
139 // construct the shared structure in-place.
140 if (mCblk != NULL) {
141 new(mCblk) audio_track_cblk_t();
Glenn Kastend776ac62014-05-07 09:16:09 -0700142 if (useReadOnlyHeap) {
143 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
144 if (roHeap == 0 ||
145 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
146 (mBuffer = mBufferMemory->pointer()) == NULL) {
147 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
148 if (roHeap != 0) {
149 roHeap->dump("buffer");
150 }
151 mCblkMemory.clear();
152 mBufferMemory.clear();
153 return;
154 }
Eric Laurent81784c32012-11-19 14:55:58 -0800155 memset(mBuffer, 0, bufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -0800156 } else {
Glenn Kastend776ac62014-05-07 09:16:09 -0700157 // clear all buffers
158 if (sharedBuffer == 0) {
159 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
160 memset(mBuffer, 0, bufferSize);
161 } else {
162 mBuffer = sharedBuffer->pointer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800163#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700164 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800165#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700166 }
Eric Laurent81784c32012-11-19 14:55:58 -0800167 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800168
Glenn Kasten46909e72013-02-26 09:20:22 -0800169#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800170 if (mTeeSinkTrackEnabled) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800171 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800172 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800173 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
174 size_t numCounterOffers = 0;
175 const NBAIO_Format offers[1] = {pipeFormat};
176 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
177 ALOG_ASSERT(index == 0);
178 PipeReader *pipeReader = new PipeReader(*pipe);
179 numCounterOffers = 0;
180 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
181 ALOG_ASSERT(index == 0);
182 mTeeSink = pipe;
183 mTeeSource = pipeReader;
184 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800185 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800186#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800187
Eric Laurent81784c32012-11-19 14:55:58 -0800188 }
189}
190
191AudioFlinger::ThreadBase::TrackBase::~TrackBase()
192{
Glenn Kasten46909e72013-02-26 09:20:22 -0800193#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800194 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800195#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800196 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
197 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800198 if (mCblk != NULL) {
199 if (mClient == 0) {
200 delete mCblk;
201 } else {
202 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
203 }
204 }
205 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
206 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700207 // Client destructor must run with AudioFlinger client mutex locked
208 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800209 // If the client's reference count drops to zero, the associated destructor
210 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
211 // relying on the automatic clear() at end of scope.
212 mClient.clear();
213 }
214}
215
216// AudioBufferProvider interface
217// getNextBuffer() = 0;
218// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
219void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
220{
Glenn Kasten46909e72013-02-26 09:20:22 -0800221#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800222 if (mTeeSink != 0) {
223 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
224 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800225#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800226
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800227 ServerProxy::Buffer buf;
228 buf.mFrameCount = buffer->frameCount;
229 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800230 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800231 buffer->raw = NULL;
232 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800233}
234
Eric Laurent81784c32012-11-19 14:55:58 -0800235status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
236{
237 mSyncEvents.add(event);
238 return NO_ERROR;
239}
240
241// ----------------------------------------------------------------------------
242// Playback
243// ----------------------------------------------------------------------------
244
245AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
246 : BnAudioTrack(),
247 mTrack(track)
248{
249}
250
251AudioFlinger::TrackHandle::~TrackHandle() {
252 // just stop the track on deletion, associated resources
253 // will be freed from the main thread once all pending buffers have
254 // been played. Unless it's not in the active track list, in which
255 // case we free everything now...
256 mTrack->destroy();
257}
258
259sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
260 return mTrack->getCblk();
261}
262
263status_t AudioFlinger::TrackHandle::start() {
264 return mTrack->start();
265}
266
267void AudioFlinger::TrackHandle::stop() {
268 mTrack->stop();
269}
270
271void AudioFlinger::TrackHandle::flush() {
272 mTrack->flush();
273}
274
Eric Laurent81784c32012-11-19 14:55:58 -0800275void AudioFlinger::TrackHandle::pause() {
276 mTrack->pause();
277}
278
279status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
280{
281 return mTrack->attachAuxEffect(EffectId);
282}
283
284status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
285 sp<IMemory>* buffer) {
286 if (!mTrack->isTimedTrack())
287 return INVALID_OPERATION;
288
289 PlaybackThread::TimedTrack* tt =
290 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
291 return tt->allocateTimedBuffer(size, buffer);
292}
293
294status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
295 int64_t pts) {
296 if (!mTrack->isTimedTrack())
297 return INVALID_OPERATION;
298
Glenn Kasten663c2242013-09-24 11:52:37 -0700299 if (buffer == 0 || buffer->pointer() == NULL) {
300 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
301 return BAD_VALUE;
302 }
303
Eric Laurent81784c32012-11-19 14:55:58 -0800304 PlaybackThread::TimedTrack* tt =
305 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
306 return tt->queueTimedBuffer(buffer, pts);
307}
308
309status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
310 const LinearTransform& xform, int target) {
311
312 if (!mTrack->isTimedTrack())
313 return INVALID_OPERATION;
314
315 PlaybackThread::TimedTrack* tt =
316 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
317 return tt->setMediaTimeTransform(
318 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
319}
320
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700321status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
322 return mTrack->setParameters(keyValuePairs);
323}
324
Glenn Kasten53cec222013-08-29 09:01:02 -0700325status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
326{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700327 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700328}
329
Eric Laurent59fe0102013-09-27 18:48:26 -0700330
331void AudioFlinger::TrackHandle::signal()
332{
333 return mTrack->signal();
334}
335
Eric Laurent81784c32012-11-19 14:55:58 -0800336status_t AudioFlinger::TrackHandle::onTransact(
337 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
338{
339 return BnAudioTrack::onTransact(code, data, reply, flags);
340}
341
342// ----------------------------------------------------------------------------
343
344// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
345AudioFlinger::PlaybackThread::Track::Track(
346 PlaybackThread *thread,
347 const sp<Client>& client,
348 audio_stream_type_t streamType,
349 uint32_t sampleRate,
350 audio_format_t format,
351 audio_channel_mask_t channelMask,
352 size_t frameCount,
353 const sp<IMemory>& sharedBuffer,
354 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800355 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -0800356 IAudioFlinger::track_flags_t flags)
357 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
Glenn Kasten755b0a62014-05-13 11:30:28 -0700358 sessionId, uid, flags, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800359 mFillingUpStatus(FS_INVALID),
360 // mRetryCount initialized later when needed
361 mSharedBuffer(sharedBuffer),
362 mStreamType(streamType),
363 mName(-1), // see note below
364 mMainBuffer(thread->mixBuffer()),
365 mAuxBuffer(NULL),
366 mAuxEffectId(0), mHasVolumeController(false),
367 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800368 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800369 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800370 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800371 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800372 mResumeToStopping(false),
373 mFlushHwPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800374{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700375 if (mCblk == NULL) {
376 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800377 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700378
379 if (sharedBuffer == 0) {
380 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
381 mFrameSize);
382 } else {
383 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
384 mFrameSize);
385 }
386 mServerProxy = mAudioTrackServerProxy;
387
388 mName = thread->getTrackName_l(channelMask, sessionId);
389 if (mName < 0) {
390 ALOGE("no more track names available");
391 return;
392 }
393 // only allocate a fast track index if we were able to allocate a normal track name
394 if (flags & IAudioFlinger::TRACK_FAST) {
395 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
396 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
397 int i = __builtin_ctz(thread->mFastTrackAvailMask);
398 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
399 // FIXME This is too eager. We allocate a fast track index before the
400 // fast track becomes active. Since fast tracks are a scarce resource,
401 // this means we are potentially denying other more important fast tracks from
402 // being created. It would be better to allocate the index dynamically.
403 mFastIndex = i;
404 // Read the initial underruns because this field is never cleared by the fast mixer
405 mObservedUnderruns = thread->getFastTrackUnderruns(i);
406 thread->mFastTrackAvailMask &= ~(1 << i);
407 }
Eric Laurent81784c32012-11-19 14:55:58 -0800408}
409
410AudioFlinger::PlaybackThread::Track::~Track()
411{
412 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700413
414 // The destructor would clear mSharedBuffer,
415 // but it will not push the decremented reference count,
416 // leaving the client's IMemory dangling indefinitely.
417 // This prevents that leak.
418 if (mSharedBuffer != 0) {
419 mSharedBuffer.clear();
420 // flush the binder command buffer
421 IPCThreadState::self()->flushCommands();
422 }
Eric Laurent81784c32012-11-19 14:55:58 -0800423}
424
Glenn Kasten03003332013-08-06 15:40:54 -0700425status_t AudioFlinger::PlaybackThread::Track::initCheck() const
426{
427 status_t status = TrackBase::initCheck();
428 if (status == NO_ERROR && mName < 0) {
429 status = NO_MEMORY;
430 }
431 return status;
432}
433
Eric Laurent81784c32012-11-19 14:55:58 -0800434void AudioFlinger::PlaybackThread::Track::destroy()
435{
436 // NOTE: destroyTrack_l() can remove a strong reference to this Track
437 // by removing it from mTracks vector, so there is a risk that this Tracks's
438 // destructor is called. As the destructor needs to lock mLock,
439 // we must acquire a strong reference on this Track before locking mLock
440 // here so that the destructor is called only when exiting this function.
441 // On the other hand, as long as Track::destroy() is only called by
442 // TrackHandle destructor, the TrackHandle still holds a strong ref on
443 // this Track with its member mTrack.
444 sp<Track> keep(this);
445 { // scope for mLock
446 sp<ThreadBase> thread = mThread.promote();
447 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800448 Mutex::Autolock _l(thread->mLock);
449 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800450 bool wasActive = playbackThread->destroyTrack_l(this);
451 if (!isOutputTrack() && !wasActive) {
452 AudioSystem::releaseOutput(thread->id());
453 }
Eric Laurent81784c32012-11-19 14:55:58 -0800454 }
455 }
456}
457
458/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
459{
Marco Nelissenb2208842014-02-07 14:00:50 -0800460 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700461 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800462}
463
Marco Nelissenb2208842014-02-07 14:00:50 -0800464void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800465{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700466 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800467 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800468 sprintf(buffer, " F %2d", mFastIndex);
469 } else if (mName >= AudioMixer::TRACK0) {
470 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800471 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800472 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800473 }
474 track_state state = mState;
475 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800476 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800477 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800478 } else {
479 switch (state) {
480 case IDLE:
481 stateChar = 'I';
482 break;
483 case STOPPING_1:
484 stateChar = 's';
485 break;
486 case STOPPING_2:
487 stateChar = '5';
488 break;
489 case STOPPED:
490 stateChar = 'S';
491 break;
492 case RESUMING:
493 stateChar = 'R';
494 break;
495 case ACTIVE:
496 stateChar = 'A';
497 break;
498 case PAUSING:
499 stateChar = 'p';
500 break;
501 case PAUSED:
502 stateChar = 'P';
503 break;
504 case FLUSHED:
505 stateChar = 'F';
506 break;
507 default:
508 stateChar = '?';
509 break;
510 }
Eric Laurent81784c32012-11-19 14:55:58 -0800511 }
512 char nowInUnderrun;
513 switch (mObservedUnderruns.mBitFields.mMostRecent) {
514 case UNDERRUN_FULL:
515 nowInUnderrun = ' ';
516 break;
517 case UNDERRUN_PARTIAL:
518 nowInUnderrun = '<';
519 break;
520 case UNDERRUN_EMPTY:
521 nowInUnderrun = '*';
522 break;
523 default:
524 nowInUnderrun = '?';
525 break;
526 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000527 snprintf(&buffer[8], size-8, " %6s %6u %4u %08X %08X %7u %6zu %1c %1d %5u %5.2g %5.2g "
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000528 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800529 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800530 (mClient == 0) ? getpid_cached : mClient->pid(),
531 mStreamType,
532 mFormat,
533 mChannelMask,
534 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800535 mFrameCount,
536 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800537 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800538 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700539 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
540 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700541 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000542 mMainBuffer,
543 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700544 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700545 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800546 nowInUnderrun);
547}
548
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800549uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
550 return mAudioTrackServerProxy->getSampleRate();
551}
552
Eric Laurent81784c32012-11-19 14:55:58 -0800553// AudioBufferProvider interface
554status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800555 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800556{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800557 ServerProxy::Buffer buf;
558 size_t desiredFrames = buffer->frameCount;
559 buf.mFrameCount = desiredFrames;
560 status_t status = mServerProxy->obtainBuffer(&buf);
561 buffer->frameCount = buf.mFrameCount;
562 buffer->raw = buf.mRaw;
563 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700564 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800565 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800566 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800567}
568
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700569// releaseBuffer() is not overridden
570
571// ExtendedAudioBufferProvider interface
572
Eric Laurent81784c32012-11-19 14:55:58 -0800573// Note that framesReady() takes a mutex on the control block using tryLock().
574// This could result in priority inversion if framesReady() is called by the normal mixer,
575// as the normal mixer thread runs at lower
576// priority than the client's callback thread: there is a short window within framesReady()
577// during which the normal mixer could be preempted, and the client callback would block.
578// Another problem can occur if framesReady() is called by the fast mixer:
579// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
580// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
581size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800582 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800583}
584
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700585size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
586{
587 return mAudioTrackServerProxy->framesReleased();
588}
589
Eric Laurent81784c32012-11-19 14:55:58 -0800590// Don't call for fast tracks; the framesReady() could result in priority inversion
591bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800592 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
593 return true;
594 }
595
Eric Laurent16498512014-03-17 17:22:08 -0700596 if (isStopping()) {
597 if (framesReady() > 0) {
598 mFillingUpStatus = FS_FILLED;
599 }
Eric Laurent81784c32012-11-19 14:55:58 -0800600 return true;
601 }
602
603 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700604 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800605 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700606 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800607 return true;
608 }
609 return false;
610}
611
Glenn Kasten0f11b512014-01-31 16:18:54 -0800612status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
613 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800614{
615 status_t status = NO_ERROR;
616 ALOGV("start(%d), calling pid %d session %d",
617 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
618
619 sp<ThreadBase> thread = mThread.promote();
620 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700621 if (isOffloaded()) {
622 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
623 Mutex::Autolock _lth(thread->mLock);
624 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700625 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
626 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700627 invalidate();
628 return PERMISSION_DENIED;
629 }
630 }
631 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800632 track_state state = mState;
633 // here the track could be either new, or restarted
634 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800635
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800636 // initial state-stopping. next state-pausing.
637 // What if resume is called ?
638
639 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800640 if (mResumeToStopping) {
641 // happened we need to resume to STOPPING_1
642 mState = TrackBase::STOPPING_1;
643 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
644 } else {
645 mState = TrackBase::RESUMING;
646 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
647 }
Eric Laurent81784c32012-11-19 14:55:58 -0800648 } else {
649 mState = TrackBase::ACTIVE;
650 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
651 }
652
Eric Laurentbfb1b832013-01-07 09:53:42 -0800653 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
654 status = playbackThread->addTrack_l(this);
655 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800656 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800657 // restore previous state if start was rejected by policy manager
658 if (status == PERMISSION_DENIED) {
659 mState = state;
660 }
661 }
662 // track was already in the active list, not a problem
663 if (status == ALREADY_EXISTS) {
664 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700665 } else {
666 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
667 // It is usually unsafe to access the server proxy from a binder thread.
668 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
669 // isn't looking at this track yet: we still hold the normal mixer thread lock,
670 // and for fast tracks the track is not yet in the fast mixer thread's active set.
671 ServerProxy::Buffer buffer;
672 buffer.mFrameCount = 1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700673 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800674 }
675 } else {
676 status = BAD_VALUE;
677 }
678 return status;
679}
680
681void AudioFlinger::PlaybackThread::Track::stop()
682{
683 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
684 sp<ThreadBase> thread = mThread.promote();
685 if (thread != 0) {
686 Mutex::Autolock _l(thread->mLock);
687 track_state state = mState;
688 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
689 // If the track is not active (PAUSED and buffers full), flush buffers
690 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
691 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
692 reset();
693 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800694 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800695 mState = STOPPED;
696 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800697 // For fast tracks prepareTracks_l() will set state to STOPPING_2
698 // presentation is complete
699 // For an offloaded track this starts a drain and state will
700 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800701 mState = STOPPING_1;
702 }
703 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
704 playbackThread);
705 }
Eric Laurent81784c32012-11-19 14:55:58 -0800706 }
707}
708
709void AudioFlinger::PlaybackThread::Track::pause()
710{
711 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
712 sp<ThreadBase> thread = mThread.promote();
713 if (thread != 0) {
714 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800715 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
716 switch (mState) {
717 case STOPPING_1:
718 case STOPPING_2:
719 if (!isOffloaded()) {
720 /* nothing to do if track is not offloaded */
721 break;
722 }
723
724 // Offloaded track was draining, we need to carry on draining when resumed
725 mResumeToStopping = true;
726 // fall through...
727 case ACTIVE:
728 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800729 mState = PAUSING;
730 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700731 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800732 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800733
Eric Laurentbfb1b832013-01-07 09:53:42 -0800734 default:
735 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800736 }
737 }
738}
739
740void AudioFlinger::PlaybackThread::Track::flush()
741{
742 ALOGV("flush(%d)", mName);
743 sp<ThreadBase> thread = mThread.promote();
744 if (thread != 0) {
745 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800746 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800747
748 if (isOffloaded()) {
749 // If offloaded we allow flush during any state except terminated
750 // and keep the track active to avoid problems if user is seeking
751 // rapidly and underlying hardware has a significant delay handling
752 // a pause
753 if (isTerminated()) {
754 return;
755 }
756
757 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800758 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800759
760 if (mState == STOPPING_1 || mState == STOPPING_2) {
761 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
762 mState = ACTIVE;
763 }
764
765 if (mState == ACTIVE) {
766 ALOGV("flush called in active state, resetting buffer time out retry count");
767 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
768 }
769
Haynes Mathew George7844f672014-01-15 12:32:55 -0800770 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800771 mResumeToStopping = false;
772 } else {
773 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
774 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
775 return;
776 }
777 // No point remaining in PAUSED state after a flush => go to
778 // FLUSHED state
779 mState = FLUSHED;
780 // do not reset the track if it is still in the process of being stopped or paused.
781 // this will be done by prepareTracks_l() when the track is stopped.
782 // prepareTracks_l() will see mState == FLUSHED, then
783 // remove from active track list, reset(), and trigger presentation complete
784 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
785 reset();
786 }
Eric Laurent81784c32012-11-19 14:55:58 -0800787 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800788 // Prevent flush being lost if the track is flushed and then resumed
789 // before mixer thread can run. This is important when offloading
790 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700791 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800792 }
793}
794
Haynes Mathew George7844f672014-01-15 12:32:55 -0800795// must be called with thread lock held
796void AudioFlinger::PlaybackThread::Track::flushAck()
797{
798 if (!isOffloaded())
799 return;
800
801 mFlushHwPending = false;
802}
803
Eric Laurent81784c32012-11-19 14:55:58 -0800804void AudioFlinger::PlaybackThread::Track::reset()
805{
806 // Do not reset twice to avoid discarding data written just after a flush and before
807 // the audioflinger thread detects the track is stopped.
808 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800809 // Force underrun condition to avoid false underrun callback until first data is
810 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700811 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800812 mFillingUpStatus = FS_FILLING;
813 mResetDone = true;
814 if (mState == FLUSHED) {
815 mState = IDLE;
816 }
817 }
818}
819
Eric Laurentbfb1b832013-01-07 09:53:42 -0800820status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
821{
822 sp<ThreadBase> thread = mThread.promote();
823 if (thread == 0) {
824 ALOGE("thread is dead");
825 return FAILED_TRANSACTION;
826 } else if ((thread->type() == ThreadBase::DIRECT) ||
827 (thread->type() == ThreadBase::OFFLOAD)) {
828 return thread->setParameters(keyValuePairs);
829 } else {
830 return PERMISSION_DENIED;
831 }
832}
833
Glenn Kasten573d80a2013-08-26 09:36:23 -0700834status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
835{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700836 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
837 if (isFastTrack()) {
838 return INVALID_OPERATION;
839 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700840 sp<ThreadBase> thread = mThread.promote();
841 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700842 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700843 }
844 Mutex::Autolock _l(thread->mLock);
845 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaccc1472013-09-20 09:36:34 -0700846 if (!isOffloaded()) {
847 if (!playbackThread->mLatchQValid) {
848 return INVALID_OPERATION;
849 }
850 uint32_t unpresentedFrames =
851 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
852 playbackThread->mSampleRate;
853 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
854 if (framesWritten < unpresentedFrames) {
855 return INVALID_OPERATION;
856 }
857 timestamp.mPosition = framesWritten - unpresentedFrames;
858 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
859 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700860 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700861
862 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700863}
864
Eric Laurent81784c32012-11-19 14:55:58 -0800865status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
866{
867 status_t status = DEAD_OBJECT;
868 sp<ThreadBase> thread = mThread.promote();
869 if (thread != 0) {
870 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
871 sp<AudioFlinger> af = mClient->audioFlinger();
872
873 Mutex::Autolock _l(af->mLock);
874
875 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
876
877 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
878 Mutex::Autolock _dl(playbackThread->mLock);
879 Mutex::Autolock _sl(srcThread->mLock);
880 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
881 if (chain == 0) {
882 return INVALID_OPERATION;
883 }
884
885 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
886 if (effect == 0) {
887 return INVALID_OPERATION;
888 }
889 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700890 status = playbackThread->addEffect_l(effect);
891 if (status != NO_ERROR) {
892 srcThread->addEffect_l(effect);
893 return INVALID_OPERATION;
894 }
Eric Laurent81784c32012-11-19 14:55:58 -0800895 // removeEffect_l() has stopped the effect if it was active so it must be restarted
896 if (effect->state() == EffectModule::ACTIVE ||
897 effect->state() == EffectModule::STOPPING) {
898 effect->start();
899 }
900
901 sp<EffectChain> dstChain = effect->chain().promote();
902 if (dstChain == 0) {
903 srcThread->addEffect_l(effect);
904 return INVALID_OPERATION;
905 }
906 AudioSystem::unregisterEffect(effect->id());
907 AudioSystem::registerEffect(&effect->desc(),
908 srcThread->id(),
909 dstChain->strategy(),
910 AUDIO_SESSION_OUTPUT_MIX,
911 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700912 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800913 }
914 status = playbackThread->attachAuxEffect(this, EffectId);
915 }
916 return status;
917}
918
919void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
920{
921 mAuxEffectId = EffectId;
922 mAuxBuffer = buffer;
923}
924
925bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
926 size_t audioHalFrames)
927{
928 // a track is considered presented when the total number of frames written to audio HAL
929 // corresponds to the number of frames written when presentationComplete() is called for the
930 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800931 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
932 // to detect when all frames have been played. In this case framesWritten isn't
933 // useful because it doesn't always reflect whether there is data in the h/w
934 // buffers, particularly if a track has been paused and resumed during draining
935 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
936 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800937 if (mPresentationCompleteFrames == 0) {
938 mPresentationCompleteFrames = framesWritten + audioHalFrames;
939 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
940 mPresentationCompleteFrames, audioHalFrames);
941 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800942
943 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800944 ALOGV("presentationComplete() session %d complete: framesWritten %d",
945 mSessionId, framesWritten);
946 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800947 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800948 return true;
949 }
950 return false;
951}
952
953void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
954{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700955 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -0800956 if (mSyncEvents[i]->type() == type) {
957 mSyncEvents[i]->trigger();
958 mSyncEvents.removeAt(i);
959 i--;
960 }
961 }
962}
963
964// implement VolumeBufferProvider interface
965
Glenn Kastenc56f3422014-03-21 17:53:17 -0700966gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -0800967{
968 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
969 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -0700970 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
971 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
972 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -0800973 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -0700974 if (vl > GAIN_FLOAT_UNITY) {
975 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -0800976 }
Glenn Kastenc56f3422014-03-21 17:53:17 -0700977 if (vr > GAIN_FLOAT_UNITY) {
978 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -0800979 }
980 // now apply the cached master volume and stream type volume;
981 // this is trusted but lacks any synchronization or barrier so may be stale
982 float v = mCachedVolume;
983 vl *= v;
984 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -0700985 // re-combine into packed minifloat
986 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -0800987 // FIXME look at mute, pause, and stop flags
988 return vlr;
989}
990
991status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
992{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800993 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800994 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
995 (mState == STOPPED)))) {
996 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
997 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
998 event->cancel();
999 return INVALID_OPERATION;
1000 }
1001 (void) TrackBase::setSyncEvent(event);
1002 return NO_ERROR;
1003}
1004
Glenn Kasten5736c352012-12-04 12:12:34 -08001005void AudioFlinger::PlaybackThread::Track::invalidate()
1006{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001007 // FIXME should use proxy, and needs work
1008 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001009 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001010 android_atomic_release_store(0x40000000, &cblk->mFutex);
1011 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001012 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001013 mIsInvalid = true;
1014}
1015
Eric Laurent59fe0102013-09-27 18:48:26 -07001016void AudioFlinger::PlaybackThread::Track::signal()
1017{
1018 sp<ThreadBase> thread = mThread.promote();
1019 if (thread != 0) {
1020 PlaybackThread *t = (PlaybackThread *)thread.get();
1021 Mutex::Autolock _l(t->mLock);
1022 t->broadcast_l();
1023 }
1024}
1025
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001026//To be called with thread lock held
1027bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1028
1029 if (mState == RESUMING)
1030 return true;
1031 /* Resume is pending if track was stopping before pause was called */
1032 if (mState == STOPPING_1 &&
1033 mResumeToStopping)
1034 return true;
1035
1036 return false;
1037}
1038
1039//To be called with thread lock held
1040void AudioFlinger::PlaybackThread::Track::resumeAck() {
1041
1042
1043 if (mState == RESUMING)
1044 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001045
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001046 // Other possibility of pending resume is stopping_1 state
1047 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001048 // drain being called.
1049 if (mState == STOPPING_1) {
1050 mResumeToStopping = false;
1051 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001052}
Eric Laurent81784c32012-11-19 14:55:58 -08001053// ----------------------------------------------------------------------------
1054
1055sp<AudioFlinger::PlaybackThread::TimedTrack>
1056AudioFlinger::PlaybackThread::TimedTrack::create(
1057 PlaybackThread *thread,
1058 const sp<Client>& client,
1059 audio_stream_type_t streamType,
1060 uint32_t sampleRate,
1061 audio_format_t format,
1062 audio_channel_mask_t channelMask,
1063 size_t frameCount,
1064 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001065 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001066 int uid)
1067{
Eric Laurent81784c32012-11-19 14:55:58 -08001068 if (!client->reserveTimedTrack())
1069 return 0;
1070
1071 return new TimedTrack(
1072 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001073 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001074}
1075
1076AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1077 PlaybackThread *thread,
1078 const sp<Client>& client,
1079 audio_stream_type_t streamType,
1080 uint32_t sampleRate,
1081 audio_format_t format,
1082 audio_channel_mask_t channelMask,
1083 size_t frameCount,
1084 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001085 int sessionId,
1086 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001087 : Track(thread, client, streamType, sampleRate, format, channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001088 frameCount, sharedBuffer, sessionId, uid, IAudioFlinger::TRACK_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001089 mQueueHeadInFlight(false),
1090 mTrimQueueHeadOnRelease(false),
1091 mFramesPendingInQueue(0),
1092 mTimedSilenceBuffer(NULL),
1093 mTimedSilenceBufferSize(0),
1094 mTimedAudioOutputOnTime(false),
1095 mMediaTimeTransformValid(false)
1096{
1097 LocalClock lc;
1098 mLocalTimeFreq = lc.getLocalFreq();
1099
1100 mLocalTimeToSampleTransform.a_zero = 0;
1101 mLocalTimeToSampleTransform.b_zero = 0;
1102 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1103 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1104 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1105 &mLocalTimeToSampleTransform.a_to_b_denom);
1106
1107 mMediaTimeToSampleTransform.a_zero = 0;
1108 mMediaTimeToSampleTransform.b_zero = 0;
1109 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1110 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1111 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1112 &mMediaTimeToSampleTransform.a_to_b_denom);
1113}
1114
1115AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1116 mClient->releaseTimedTrack();
1117 delete [] mTimedSilenceBuffer;
1118}
1119
1120status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1121 size_t size, sp<IMemory>* buffer) {
1122
1123 Mutex::Autolock _l(mTimedBufferQueueLock);
1124
1125 trimTimedBufferQueue_l();
1126
1127 // lazily initialize the shared memory heap for timed buffers
1128 if (mTimedMemoryDealer == NULL) {
1129 const int kTimedBufferHeapSize = 512 << 10;
1130
1131 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1132 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001133 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001134 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001135 }
Eric Laurent81784c32012-11-19 14:55:58 -08001136 }
1137
1138 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001139 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001140 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001141 }
1142
1143 *buffer = newBuffer;
1144 return NO_ERROR;
1145}
1146
1147// caller must hold mTimedBufferQueueLock
1148void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1149 int64_t mediaTimeNow;
1150 {
1151 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1152 if (!mMediaTimeTransformValid)
1153 return;
1154
1155 int64_t targetTimeNow;
1156 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1157 ? mCCHelper.getCommonTime(&targetTimeNow)
1158 : mCCHelper.getLocalTime(&targetTimeNow);
1159
1160 if (OK != res)
1161 return;
1162
1163 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1164 &mediaTimeNow)) {
1165 return;
1166 }
1167 }
1168
1169 size_t trimEnd;
1170 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1171 int64_t bufEnd;
1172
1173 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1174 // We have a next buffer. Just use its PTS as the PTS of the frame
1175 // following the last frame in this buffer. If the stream is sparse
1176 // (ie, there are deliberate gaps left in the stream which should be
1177 // filled with silence by the TimedAudioTrack), then this can result
1178 // in one extra buffer being left un-trimmed when it could have
1179 // been. In general, this is not typical, and we would rather
1180 // optimized away the TS calculation below for the more common case
1181 // where PTSes are contiguous.
1182 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1183 } else {
1184 // We have no next buffer. Compute the PTS of the frame following
1185 // the last frame in this buffer by computing the duration of of
1186 // this frame in media time units and adding it to the PTS of the
1187 // buffer.
1188 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1189 / mFrameSize;
1190
1191 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1192 &bufEnd)) {
1193 ALOGE("Failed to convert frame count of %lld to media time"
1194 " duration" " (scale factor %d/%u) in %s",
1195 frameCount,
1196 mMediaTimeToSampleTransform.a_to_b_numer,
1197 mMediaTimeToSampleTransform.a_to_b_denom,
1198 __PRETTY_FUNCTION__);
1199 break;
1200 }
1201 bufEnd += mTimedBufferQueue[trimEnd].pts();
1202 }
1203
1204 if (bufEnd > mediaTimeNow)
1205 break;
1206
1207 // Is the buffer we want to use in the middle of a mix operation right
1208 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1209 // from the mixer which should be coming back shortly.
1210 if (!trimEnd && mQueueHeadInFlight) {
1211 mTrimQueueHeadOnRelease = true;
1212 }
1213 }
1214
1215 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1216 if (trimStart < trimEnd) {
1217 // Update the bookkeeping for framesReady()
1218 for (size_t i = trimStart; i < trimEnd; ++i) {
1219 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1220 }
1221
1222 // Now actually remove the buffers from the queue.
1223 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1224 }
1225}
1226
1227void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1228 const char* logTag) {
1229 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1230 "%s called (reason \"%s\"), but timed buffer queue has no"
1231 " elements to trim.", __FUNCTION__, logTag);
1232
1233 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1234 mTimedBufferQueue.removeAt(0);
1235}
1236
1237void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1238 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001239 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001240 uint32_t bufBytes = buf.buffer()->size();
1241 uint32_t consumedAlready = buf.position();
1242
1243 ALOG_ASSERT(consumedAlready <= bufBytes,
1244 "Bad bookkeeping while updating frames pending. Timed buffer is"
1245 " only %u bytes long, but claims to have consumed %u"
1246 " bytes. (update reason: \"%s\")",
1247 bufBytes, consumedAlready, logTag);
1248
1249 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1250 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1251 "Bad bookkeeping while updating frames pending. Should have at"
1252 " least %u queued frames, but we think we have only %u. (update"
1253 " reason: \"%s\")",
1254 bufFrames, mFramesPendingInQueue, logTag);
1255
1256 mFramesPendingInQueue -= bufFrames;
1257}
1258
1259status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1260 const sp<IMemory>& buffer, int64_t pts) {
1261
1262 {
1263 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1264 if (!mMediaTimeTransformValid)
1265 return INVALID_OPERATION;
1266 }
1267
1268 Mutex::Autolock _l(mTimedBufferQueueLock);
1269
1270 uint32_t bufFrames = buffer->size() / mFrameSize;
1271 mFramesPendingInQueue += bufFrames;
1272 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1273
1274 return NO_ERROR;
1275}
1276
1277status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1278 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1279
1280 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1281 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1282 target);
1283
1284 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1285 target == TimedAudioTrack::COMMON_TIME)) {
1286 return BAD_VALUE;
1287 }
1288
1289 Mutex::Autolock lock(mMediaTimeTransformLock);
1290 mMediaTimeTransform = xform;
1291 mMediaTimeTransformTarget = target;
1292 mMediaTimeTransformValid = true;
1293
1294 return NO_ERROR;
1295}
1296
1297#define min(a, b) ((a) < (b) ? (a) : (b))
1298
1299// implementation of getNextBuffer for tracks whose buffers have timestamps
1300status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1301 AudioBufferProvider::Buffer* buffer, int64_t pts)
1302{
1303 if (pts == AudioBufferProvider::kInvalidPTS) {
1304 buffer->raw = NULL;
1305 buffer->frameCount = 0;
1306 mTimedAudioOutputOnTime = false;
1307 return INVALID_OPERATION;
1308 }
1309
1310 Mutex::Autolock _l(mTimedBufferQueueLock);
1311
1312 ALOG_ASSERT(!mQueueHeadInFlight,
1313 "getNextBuffer called without releaseBuffer!");
1314
1315 while (true) {
1316
1317 // if we have no timed buffers, then fail
1318 if (mTimedBufferQueue.isEmpty()) {
1319 buffer->raw = NULL;
1320 buffer->frameCount = 0;
1321 return NOT_ENOUGH_DATA;
1322 }
1323
1324 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1325
1326 // calculate the PTS of the head of the timed buffer queue expressed in
1327 // local time
1328 int64_t headLocalPTS;
1329 {
1330 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1331
1332 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1333
1334 if (mMediaTimeTransform.a_to_b_denom == 0) {
1335 // the transform represents a pause, so yield silence
1336 timedYieldSilence_l(buffer->frameCount, buffer);
1337 return NO_ERROR;
1338 }
1339
1340 int64_t transformedPTS;
1341 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1342 &transformedPTS)) {
1343 // the transform failed. this shouldn't happen, but if it does
1344 // then just drop this buffer
1345 ALOGW("timedGetNextBuffer transform failed");
1346 buffer->raw = NULL;
1347 buffer->frameCount = 0;
1348 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1349 return NO_ERROR;
1350 }
1351
1352 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1353 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1354 &headLocalPTS)) {
1355 buffer->raw = NULL;
1356 buffer->frameCount = 0;
1357 return INVALID_OPERATION;
1358 }
1359 } else {
1360 headLocalPTS = transformedPTS;
1361 }
1362 }
1363
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001364 uint32_t sr = sampleRate();
1365
Eric Laurent81784c32012-11-19 14:55:58 -08001366 // adjust the head buffer's PTS to reflect the portion of the head buffer
1367 // that has already been consumed
1368 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001369 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001370
1371 // Calculate the delta in samples between the head of the input buffer
1372 // queue and the start of the next output buffer that will be written.
1373 // If the transformation fails because of over or underflow, it means
1374 // that the sample's position in the output stream is so far out of
1375 // whack that it should just be dropped.
1376 int64_t sampleDelta;
1377 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1378 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1379 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1380 " mix");
1381 continue;
1382 }
1383 if (!mLocalTimeToSampleTransform.doForwardTransform(
1384 (effectivePTS - pts) << 32, &sampleDelta)) {
1385 ALOGV("*** too late during sample rate transform: dropped buffer");
1386 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1387 continue;
1388 }
1389
1390 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1391 " sampleDelta=[%d.%08x]",
1392 head.pts(), head.position(), pts,
1393 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1394 + (sampleDelta >> 32)),
1395 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1396
1397 // if the delta between the ideal placement for the next input sample and
1398 // the current output position is within this threshold, then we will
1399 // concatenate the next input samples to the previous output
1400 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001401 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001402
1403 // if this is the first buffer of audio that we're emitting from this track
1404 // then it should be almost exactly on time.
1405 const int64_t kSampleStartupThreshold = 1LL << 32;
1406
1407 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1408 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1409 // the next input is close enough to being on time, so concatenate it
1410 // with the last output
1411 timedYieldSamples_l(buffer);
1412
1413 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1414 head.position(), buffer->frameCount);
1415 return NO_ERROR;
1416 }
1417
1418 // Looks like our output is not on time. Reset our on timed status.
1419 // Next time we mix samples from our input queue, then should be within
1420 // the StartupThreshold.
1421 mTimedAudioOutputOnTime = false;
1422 if (sampleDelta > 0) {
1423 // the gap between the current output position and the proper start of
1424 // the next input sample is too big, so fill it with silence
1425 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1426
1427 timedYieldSilence_l(framesUntilNextInput, buffer);
1428 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1429 return NO_ERROR;
1430 } else {
1431 // the next input sample is late
1432 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1433 size_t onTimeSamplePosition =
1434 head.position() + lateFrames * mFrameSize;
1435
1436 if (onTimeSamplePosition > head.buffer()->size()) {
1437 // all the remaining samples in the head are too late, so
1438 // drop it and move on
1439 ALOGV("*** too late: dropped buffer");
1440 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1441 continue;
1442 } else {
1443 // skip over the late samples
1444 head.setPosition(onTimeSamplePosition);
1445
1446 // yield the available samples
1447 timedYieldSamples_l(buffer);
1448
1449 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1450 return NO_ERROR;
1451 }
1452 }
1453 }
1454}
1455
1456// Yield samples from the timed buffer queue head up to the given output
1457// buffer's capacity.
1458//
1459// Caller must hold mTimedBufferQueueLock
1460void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1461 AudioBufferProvider::Buffer* buffer) {
1462
1463 const TimedBuffer& head = mTimedBufferQueue[0];
1464
1465 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1466 head.position());
1467
1468 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1469 mFrameSize);
1470 size_t framesRequested = buffer->frameCount;
1471 buffer->frameCount = min(framesLeftInHead, framesRequested);
1472
1473 mQueueHeadInFlight = true;
1474 mTimedAudioOutputOnTime = true;
1475}
1476
1477// Yield samples of silence up to the given output buffer's capacity
1478//
1479// Caller must hold mTimedBufferQueueLock
1480void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1481 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1482
1483 // lazily allocate a buffer filled with silence
1484 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1485 delete [] mTimedSilenceBuffer;
1486 mTimedSilenceBufferSize = numFrames * mFrameSize;
1487 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1488 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1489 }
1490
1491 buffer->raw = mTimedSilenceBuffer;
1492 size_t framesRequested = buffer->frameCount;
1493 buffer->frameCount = min(numFrames, framesRequested);
1494
1495 mTimedAudioOutputOnTime = false;
1496}
1497
1498// AudioBufferProvider interface
1499void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1500 AudioBufferProvider::Buffer* buffer) {
1501
1502 Mutex::Autolock _l(mTimedBufferQueueLock);
1503
1504 // If the buffer which was just released is part of the buffer at the head
1505 // of the queue, be sure to update the amt of the buffer which has been
1506 // consumed. If the buffer being returned is not part of the head of the
1507 // queue, its either because the buffer is part of the silence buffer, or
1508 // because the head of the timed queue was trimmed after the mixer called
1509 // getNextBuffer but before the mixer called releaseBuffer.
1510 if (buffer->raw == mTimedSilenceBuffer) {
1511 ALOG_ASSERT(!mQueueHeadInFlight,
1512 "Queue head in flight during release of silence buffer!");
1513 goto done;
1514 }
1515
1516 ALOG_ASSERT(mQueueHeadInFlight,
1517 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1518 " head in flight.");
1519
1520 if (mTimedBufferQueue.size()) {
1521 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1522
1523 void* start = head.buffer()->pointer();
1524 void* end = reinterpret_cast<void*>(
1525 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1526 + head.buffer()->size());
1527
1528 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1529 "released buffer not within the head of the timed buffer"
1530 " queue; qHead = [%p, %p], released buffer = %p",
1531 start, end, buffer->raw);
1532
1533 head.setPosition(head.position() +
1534 (buffer->frameCount * mFrameSize));
1535 mQueueHeadInFlight = false;
1536
1537 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1538 "Bad bookkeeping during releaseBuffer! Should have at"
1539 " least %u queued frames, but we think we have only %u",
1540 buffer->frameCount, mFramesPendingInQueue);
1541
1542 mFramesPendingInQueue -= buffer->frameCount;
1543
1544 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1545 || mTrimQueueHeadOnRelease) {
1546 trimTimedBufferQueueHead_l("releaseBuffer");
1547 mTrimQueueHeadOnRelease = false;
1548 }
1549 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001550 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001551 " buffers in the timed buffer queue");
1552 }
1553
1554done:
1555 buffer->raw = 0;
1556 buffer->frameCount = 0;
1557}
1558
1559size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1560 Mutex::Autolock _l(mTimedBufferQueueLock);
1561 return mFramesPendingInQueue;
1562}
1563
1564AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1565 : mPTS(0), mPosition(0) {}
1566
1567AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1568 const sp<IMemory>& buffer, int64_t pts)
1569 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1570
1571
1572// ----------------------------------------------------------------------------
1573
1574AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1575 PlaybackThread *playbackThread,
1576 DuplicatingThread *sourceThread,
1577 uint32_t sampleRate,
1578 audio_format_t format,
1579 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001580 size_t frameCount,
1581 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001582 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001583 NULL, 0, uid, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001584 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001585{
1586
1587 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001588 mOutBuffer.frameCount = 0;
1589 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001590 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001591 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001592 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001593 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001594 // since client and server are in the same process,
1595 // the buffer has the same virtual address on both sides
1596 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001597 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001598 mClientProxy->setSendLevel(0.0);
1599 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001600 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1601 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001602 } else {
1603 ALOGW("Error creating output track on thread %p", playbackThread);
1604 }
1605}
1606
1607AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1608{
1609 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001610 delete mClientProxy;
1611 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001612}
1613
1614status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1615 int triggerSession)
1616{
1617 status_t status = Track::start(event, triggerSession);
1618 if (status != NO_ERROR) {
1619 return status;
1620 }
1621
1622 mActive = true;
1623 mRetryCount = 127;
1624 return status;
1625}
1626
1627void AudioFlinger::PlaybackThread::OutputTrack::stop()
1628{
1629 Track::stop();
1630 clearBufferQueue();
1631 mOutBuffer.frameCount = 0;
1632 mActive = false;
1633}
1634
1635bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1636{
1637 Buffer *pInBuffer;
1638 Buffer inBuffer;
1639 uint32_t channelCount = mChannelCount;
1640 bool outputBufferFull = false;
1641 inBuffer.frameCount = frames;
1642 inBuffer.i16 = data;
1643
1644 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1645
1646 if (!mActive && frames != 0) {
1647 start();
1648 sp<ThreadBase> thread = mThread.promote();
1649 if (thread != 0) {
1650 MixerThread *mixerThread = (MixerThread *)thread.get();
1651 if (mFrameCount > frames) {
1652 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1653 uint32_t startFrames = (mFrameCount - frames);
1654 pInBuffer = new Buffer;
1655 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1656 pInBuffer->frameCount = startFrames;
1657 pInBuffer->i16 = pInBuffer->mBuffer;
1658 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1659 mBufferQueue.add(pInBuffer);
1660 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001661 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001662 }
1663 }
1664 }
1665 }
1666
1667 while (waitTimeLeftMs) {
1668 // First write pending buffers, then new data
1669 if (mBufferQueue.size()) {
1670 pInBuffer = mBufferQueue.itemAt(0);
1671 } else {
1672 pInBuffer = &inBuffer;
1673 }
1674
1675 if (pInBuffer->frameCount == 0) {
1676 break;
1677 }
1678
1679 if (mOutBuffer.frameCount == 0) {
1680 mOutBuffer.frameCount = pInBuffer->frameCount;
1681 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001682 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1683 if (status != NO_ERROR) {
1684 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1685 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001686 outputBufferFull = true;
1687 break;
1688 }
1689 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1690 if (waitTimeLeftMs >= waitTimeMs) {
1691 waitTimeLeftMs -= waitTimeMs;
1692 } else {
1693 waitTimeLeftMs = 0;
1694 }
1695 }
1696
1697 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1698 pInBuffer->frameCount;
1699 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001700 Proxy::Buffer buf;
1701 buf.mFrameCount = outFrames;
1702 buf.mRaw = NULL;
1703 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001704 pInBuffer->frameCount -= outFrames;
1705 pInBuffer->i16 += outFrames * channelCount;
1706 mOutBuffer.frameCount -= outFrames;
1707 mOutBuffer.i16 += outFrames * channelCount;
1708
1709 if (pInBuffer->frameCount == 0) {
1710 if (mBufferQueue.size()) {
1711 mBufferQueue.removeAt(0);
1712 delete [] pInBuffer->mBuffer;
1713 delete pInBuffer;
1714 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1715 mThread.unsafe_get(), mBufferQueue.size());
1716 } else {
1717 break;
1718 }
1719 }
1720 }
1721
1722 // If we could not write all frames, allocate a buffer and queue it for next time.
1723 if (inBuffer.frameCount) {
1724 sp<ThreadBase> thread = mThread.promote();
1725 if (thread != 0 && !thread->standby()) {
1726 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1727 pInBuffer = new Buffer;
1728 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1729 pInBuffer->frameCount = inBuffer.frameCount;
1730 pInBuffer->i16 = pInBuffer->mBuffer;
1731 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1732 sizeof(int16_t));
1733 mBufferQueue.add(pInBuffer);
1734 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1735 mThread.unsafe_get(), mBufferQueue.size());
1736 } else {
1737 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1738 mThread.unsafe_get(), this);
1739 }
1740 }
1741 }
1742
1743 // Calling write() with a 0 length buffer, means that no more data will be written:
1744 // If no more buffers are pending, fill output track buffer to make sure it is started
1745 // by output mixer.
1746 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001747 // FIXME borken, replace by getting framesReady() from proxy
1748 size_t user = 0; // was mCblk->user
1749 if (user < mFrameCount) {
1750 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001751 pInBuffer = new Buffer;
1752 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1753 pInBuffer->frameCount = frames;
1754 pInBuffer->i16 = pInBuffer->mBuffer;
1755 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1756 mBufferQueue.add(pInBuffer);
1757 } else if (mActive) {
1758 stop();
1759 }
1760 }
1761
1762 return outputBufferFull;
1763}
1764
1765status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1766 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1767{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001768 ClientProxy::Buffer buf;
1769 buf.mFrameCount = buffer->frameCount;
1770 struct timespec timeout;
1771 timeout.tv_sec = waitTimeMs / 1000;
1772 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1773 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1774 buffer->frameCount = buf.mFrameCount;
1775 buffer->raw = buf.mRaw;
1776 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001777}
1778
Eric Laurent81784c32012-11-19 14:55:58 -08001779void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1780{
1781 size_t size = mBufferQueue.size();
1782
1783 for (size_t i = 0; i < size; i++) {
1784 Buffer *pBuffer = mBufferQueue.itemAt(i);
1785 delete [] pBuffer->mBuffer;
1786 delete pBuffer;
1787 }
1788 mBufferQueue.clear();
1789}
1790
1791
1792// ----------------------------------------------------------------------------
1793// Record
1794// ----------------------------------------------------------------------------
1795
1796AudioFlinger::RecordHandle::RecordHandle(
1797 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1798 : BnAudioRecord(),
1799 mRecordTrack(recordTrack)
1800{
1801}
1802
1803AudioFlinger::RecordHandle::~RecordHandle() {
1804 stop_nonvirtual();
1805 mRecordTrack->destroy();
1806}
1807
Eric Laurent81784c32012-11-19 14:55:58 -08001808status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1809 int triggerSession) {
1810 ALOGV("RecordHandle::start()");
1811 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1812}
1813
1814void AudioFlinger::RecordHandle::stop() {
1815 stop_nonvirtual();
1816}
1817
1818void AudioFlinger::RecordHandle::stop_nonvirtual() {
1819 ALOGV("RecordHandle::stop()");
1820 mRecordTrack->stop();
1821}
1822
1823status_t AudioFlinger::RecordHandle::onTransact(
1824 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1825{
1826 return BnAudioRecord::onTransact(code, data, reply, flags);
1827}
1828
1829// ----------------------------------------------------------------------------
1830
Glenn Kasten05997e22014-03-13 15:08:33 -07001831// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001832AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1833 RecordThread *thread,
1834 const sp<Client>& client,
1835 uint32_t sampleRate,
1836 audio_format_t format,
1837 audio_channel_mask_t channelMask,
1838 size_t frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001839 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001840 int uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001841 IAudioFlinger::track_flags_t flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001842 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001843 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, uid,
1844 flags, false /*isOut*/,
1845 (flags & IAudioFlinger::TRACK_FAST) != 0 /*useReadOnlyHeap*/),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001846 mOverflow(false), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0),
1847 // See real initialization of mRsmpInFront at RecordThread::start()
1848 mRsmpInUnrel(0), mRsmpInFront(0), mFramesToDrop(0), mResamplerBufferProvider(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001849{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001850 if (mCblk == NULL) {
1851 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001852 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001853
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001854 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount, mFrameSize);
1855
Andy Hunge5412692014-05-16 11:25:07 -07001856 uint32_t channelCount = audio_channel_count_from_in_mask(channelMask);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001857 // FIXME I don't understand either of the channel count checks
1858 if (thread->mSampleRate != sampleRate && thread->mChannelCount <= FCC_2 &&
1859 channelCount <= FCC_2) {
1860 // sink SR
1861 mResampler = AudioResampler::create(16, thread->mChannelCount, sampleRate);
1862 // source SR
1863 mResampler->setSampleRate(thread->mSampleRate);
1864 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
1865 mResamplerBufferProvider = new ResamplerBufferProvider(this);
1866 }
Eric Laurent81784c32012-11-19 14:55:58 -08001867}
1868
1869AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1870{
1871 ALOGV("%s", __func__);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001872 delete mResampler;
1873 delete[] mRsmpOutBuffer;
1874 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001875}
1876
1877// AudioBufferProvider interface
1878status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001879 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001880{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001881 ServerProxy::Buffer buf;
1882 buf.mFrameCount = buffer->frameCount;
1883 status_t status = mServerProxy->obtainBuffer(&buf);
1884 buffer->frameCount = buf.mFrameCount;
1885 buffer->raw = buf.mRaw;
1886 if (buf.mFrameCount == 0) {
1887 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001888 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001889 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001890 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001891}
1892
1893status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1894 int triggerSession)
1895{
1896 sp<ThreadBase> thread = mThread.promote();
1897 if (thread != 0) {
1898 RecordThread *recordThread = (RecordThread *)thread.get();
1899 return recordThread->start(this, event, triggerSession);
1900 } else {
1901 return BAD_VALUE;
1902 }
1903}
1904
1905void AudioFlinger::RecordThread::RecordTrack::stop()
1906{
1907 sp<ThreadBase> thread = mThread.promote();
1908 if (thread != 0) {
1909 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001910 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001911 AudioSystem::stopInput(recordThread->id());
1912 }
1913 }
1914}
1915
1916void AudioFlinger::RecordThread::RecordTrack::destroy()
1917{
1918 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1919 sp<RecordTrack> keep(this);
1920 {
1921 sp<ThreadBase> thread = mThread.promote();
1922 if (thread != 0) {
1923 if (mState == ACTIVE || mState == RESUMING) {
1924 AudioSystem::stopInput(thread->id());
1925 }
1926 AudioSystem::releaseInput(thread->id());
1927 Mutex::Autolock _l(thread->mLock);
1928 RecordThread *recordThread = (RecordThread *) thread.get();
1929 recordThread->destroyTrack_l(this);
1930 }
1931 }
1932}
1933
Eric Laurent9a54bc22013-09-09 09:08:44 -07001934void AudioFlinger::RecordThread::RecordTrack::invalidate()
1935{
1936 // FIXME should use proxy, and needs work
1937 audio_track_cblk_t* cblk = mCblk;
1938 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1939 android_atomic_release_store(0x40000000, &cblk->mFutex);
1940 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001941 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001942}
1943
Eric Laurent81784c32012-11-19 14:55:58 -08001944
1945/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1946{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001947 result.append(" Active Client Fmt Chn mask Session S Server fCount Resampling\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001948}
1949
Marco Nelissenb2208842014-02-07 14:00:50 -08001950void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001951{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001952 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %10d\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001953 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001954 (mClient == 0) ? getpid_cached : mClient->pid(),
1955 mFormat,
1956 mChannelMask,
1957 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001958 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001959 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001960 mFrameCount,
1961 mResampler != NULL);
1962
Eric Laurent81784c32012-11-19 14:55:58 -08001963}
1964
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001965void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1966{
1967 if (event == mSyncStartEvent) {
1968 ssize_t framesToDrop = 0;
1969 sp<ThreadBase> threadBase = mThread.promote();
1970 if (threadBase != 0) {
1971 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1972 // from audio HAL
1973 framesToDrop = threadBase->mFrameCount * 2;
1974 }
1975 mFramesToDrop = framesToDrop;
1976 }
1977}
1978
1979void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1980{
1981 if (mSyncStartEvent != 0) {
1982 mSyncStartEvent->cancel();
1983 mSyncStartEvent.clear();
1984 }
1985 mFramesToDrop = 0;
1986}
1987
Eric Laurent81784c32012-11-19 14:55:58 -08001988}; // namespace android