blob: 7ddc71c775b6feb9dd3bc5f69ed9aa38a47f52fa [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,
Glenn Kasten6181ffd2014-05-13 10:41:52 -070076 alloc_type alloc)
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 Kasten6181ffd2014-05-13 10:41:52 -0700120 if (sharedBuffer == 0 && alloc == ALLOC_CBLK) {
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 Kasten6181ffd2014-05-13 10:41:52 -0700142 switch (alloc) {
143 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700144 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
145 if (roHeap == 0 ||
146 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
147 (mBuffer = mBufferMemory->pointer()) == NULL) {
148 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
149 if (roHeap != 0) {
150 roHeap->dump("buffer");
151 }
152 mCblkMemory.clear();
153 mBufferMemory.clear();
154 return;
155 }
Eric Laurent81784c32012-11-19 14:55:58 -0800156 memset(mBuffer, 0, bufferSize);
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700157 } break;
158 case ALLOC_PIPE:
159 mBufferMemory = thread->pipeMemory();
160 // mBuffer is the virtual address as seen from current process (mediaserver),
161 // and should normally be coming from mBufferMemory->pointer().
162 // However in this case the TrackBase does not reference the buffer directly.
163 // It should references the buffer via the pipe.
164 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
165 mBuffer = NULL;
166 break;
167 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700168 // clear all buffers
169 if (sharedBuffer == 0) {
170 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
171 memset(mBuffer, 0, bufferSize);
172 } else {
173 mBuffer = sharedBuffer->pointer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800174#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700175 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800176#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700177 }
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700178 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800179 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800180
Glenn Kasten46909e72013-02-26 09:20:22 -0800181#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800182 if (mTeeSinkTrackEnabled) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800183 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800184 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800185 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
186 size_t numCounterOffers = 0;
187 const NBAIO_Format offers[1] = {pipeFormat};
188 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
189 ALOG_ASSERT(index == 0);
190 PipeReader *pipeReader = new PipeReader(*pipe);
191 numCounterOffers = 0;
192 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
193 ALOG_ASSERT(index == 0);
194 mTeeSink = pipe;
195 mTeeSource = pipeReader;
196 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800197 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800198#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800199
Eric Laurent81784c32012-11-19 14:55:58 -0800200 }
201}
202
203AudioFlinger::ThreadBase::TrackBase::~TrackBase()
204{
Glenn Kasten46909e72013-02-26 09:20:22 -0800205#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800206 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800207#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800208 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
209 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800210 if (mCblk != NULL) {
211 if (mClient == 0) {
212 delete mCblk;
213 } else {
214 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
215 }
216 }
217 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
218 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700219 // Client destructor must run with AudioFlinger client mutex locked
220 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800221 // If the client's reference count drops to zero, the associated destructor
222 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
223 // relying on the automatic clear() at end of scope.
224 mClient.clear();
225 }
226}
227
228// AudioBufferProvider interface
229// getNextBuffer() = 0;
230// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
231void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
232{
Glenn Kasten46909e72013-02-26 09:20:22 -0800233#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800234 if (mTeeSink != 0) {
235 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
236 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800237#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800238
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800239 ServerProxy::Buffer buf;
240 buf.mFrameCount = buffer->frameCount;
241 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800242 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800243 buffer->raw = NULL;
244 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800245}
246
Eric Laurent81784c32012-11-19 14:55:58 -0800247status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
248{
249 mSyncEvents.add(event);
250 return NO_ERROR;
251}
252
253// ----------------------------------------------------------------------------
254// Playback
255// ----------------------------------------------------------------------------
256
257AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
258 : BnAudioTrack(),
259 mTrack(track)
260{
261}
262
263AudioFlinger::TrackHandle::~TrackHandle() {
264 // just stop the track on deletion, associated resources
265 // will be freed from the main thread once all pending buffers have
266 // been played. Unless it's not in the active track list, in which
267 // case we free everything now...
268 mTrack->destroy();
269}
270
271sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
272 return mTrack->getCblk();
273}
274
275status_t AudioFlinger::TrackHandle::start() {
276 return mTrack->start();
277}
278
279void AudioFlinger::TrackHandle::stop() {
280 mTrack->stop();
281}
282
283void AudioFlinger::TrackHandle::flush() {
284 mTrack->flush();
285}
286
Eric Laurent81784c32012-11-19 14:55:58 -0800287void AudioFlinger::TrackHandle::pause() {
288 mTrack->pause();
289}
290
291status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
292{
293 return mTrack->attachAuxEffect(EffectId);
294}
295
296status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
297 sp<IMemory>* buffer) {
298 if (!mTrack->isTimedTrack())
299 return INVALID_OPERATION;
300
301 PlaybackThread::TimedTrack* tt =
302 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
303 return tt->allocateTimedBuffer(size, buffer);
304}
305
306status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
307 int64_t pts) {
308 if (!mTrack->isTimedTrack())
309 return INVALID_OPERATION;
310
Glenn Kasten663c2242013-09-24 11:52:37 -0700311 if (buffer == 0 || buffer->pointer() == NULL) {
312 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
313 return BAD_VALUE;
314 }
315
Eric Laurent81784c32012-11-19 14:55:58 -0800316 PlaybackThread::TimedTrack* tt =
317 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
318 return tt->queueTimedBuffer(buffer, pts);
319}
320
321status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
322 const LinearTransform& xform, int target) {
323
324 if (!mTrack->isTimedTrack())
325 return INVALID_OPERATION;
326
327 PlaybackThread::TimedTrack* tt =
328 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
329 return tt->setMediaTimeTransform(
330 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
331}
332
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700333status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
334 return mTrack->setParameters(keyValuePairs);
335}
336
Glenn Kasten53cec222013-08-29 09:01:02 -0700337status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
338{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700339 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700340}
341
Eric Laurent59fe0102013-09-27 18:48:26 -0700342
343void AudioFlinger::TrackHandle::signal()
344{
345 return mTrack->signal();
346}
347
Eric Laurent81784c32012-11-19 14:55:58 -0800348status_t AudioFlinger::TrackHandle::onTransact(
349 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
350{
351 return BnAudioTrack::onTransact(code, data, reply, flags);
352}
353
354// ----------------------------------------------------------------------------
355
356// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
357AudioFlinger::PlaybackThread::Track::Track(
358 PlaybackThread *thread,
359 const sp<Client>& client,
360 audio_stream_type_t streamType,
361 uint32_t sampleRate,
362 audio_format_t format,
363 audio_channel_mask_t channelMask,
364 size_t frameCount,
365 const sp<IMemory>& sharedBuffer,
366 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800367 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -0800368 IAudioFlinger::track_flags_t flags)
369 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
Glenn Kasten755b0a62014-05-13 11:30:28 -0700370 sessionId, uid, flags, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800371 mFillingUpStatus(FS_INVALID),
372 // mRetryCount initialized later when needed
373 mSharedBuffer(sharedBuffer),
374 mStreamType(streamType),
375 mName(-1), // see note below
376 mMainBuffer(thread->mixBuffer()),
377 mAuxBuffer(NULL),
378 mAuxEffectId(0), mHasVolumeController(false),
379 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800380 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800381 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800382 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800383 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800384 mResumeToStopping(false),
385 mFlushHwPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800386{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700387 if (mCblk == NULL) {
388 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800389 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700390
391 if (sharedBuffer == 0) {
392 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
393 mFrameSize);
394 } else {
395 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
396 mFrameSize);
397 }
398 mServerProxy = mAudioTrackServerProxy;
399
Andy Hunge8a1ced2014-05-09 15:02:21 -0700400 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700401 if (mName < 0) {
402 ALOGE("no more track names available");
403 return;
404 }
405 // only allocate a fast track index if we were able to allocate a normal track name
406 if (flags & IAudioFlinger::TRACK_FAST) {
407 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
408 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
409 int i = __builtin_ctz(thread->mFastTrackAvailMask);
410 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
411 // FIXME This is too eager. We allocate a fast track index before the
412 // fast track becomes active. Since fast tracks are a scarce resource,
413 // this means we are potentially denying other more important fast tracks from
414 // being created. It would be better to allocate the index dynamically.
415 mFastIndex = i;
416 // Read the initial underruns because this field is never cleared by the fast mixer
417 mObservedUnderruns = thread->getFastTrackUnderruns(i);
418 thread->mFastTrackAvailMask &= ~(1 << i);
419 }
Eric Laurent81784c32012-11-19 14:55:58 -0800420}
421
422AudioFlinger::PlaybackThread::Track::~Track()
423{
424 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700425
426 // The destructor would clear mSharedBuffer,
427 // but it will not push the decremented reference count,
428 // leaving the client's IMemory dangling indefinitely.
429 // This prevents that leak.
430 if (mSharedBuffer != 0) {
431 mSharedBuffer.clear();
432 // flush the binder command buffer
433 IPCThreadState::self()->flushCommands();
434 }
Eric Laurent81784c32012-11-19 14:55:58 -0800435}
436
Glenn Kasten03003332013-08-06 15:40:54 -0700437status_t AudioFlinger::PlaybackThread::Track::initCheck() const
438{
439 status_t status = TrackBase::initCheck();
440 if (status == NO_ERROR && mName < 0) {
441 status = NO_MEMORY;
442 }
443 return status;
444}
445
Eric Laurent81784c32012-11-19 14:55:58 -0800446void AudioFlinger::PlaybackThread::Track::destroy()
447{
448 // NOTE: destroyTrack_l() can remove a strong reference to this Track
449 // by removing it from mTracks vector, so there is a risk that this Tracks's
450 // destructor is called. As the destructor needs to lock mLock,
451 // we must acquire a strong reference on this Track before locking mLock
452 // here so that the destructor is called only when exiting this function.
453 // On the other hand, as long as Track::destroy() is only called by
454 // TrackHandle destructor, the TrackHandle still holds a strong ref on
455 // this Track with its member mTrack.
456 sp<Track> keep(this);
457 { // scope for mLock
458 sp<ThreadBase> thread = mThread.promote();
459 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800460 Mutex::Autolock _l(thread->mLock);
461 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800462 bool wasActive = playbackThread->destroyTrack_l(this);
463 if (!isOutputTrack() && !wasActive) {
464 AudioSystem::releaseOutput(thread->id());
465 }
Eric Laurent81784c32012-11-19 14:55:58 -0800466 }
467 }
468}
469
470/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
471{
Marco Nelissenb2208842014-02-07 14:00:50 -0800472 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700473 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800474}
475
Marco Nelissenb2208842014-02-07 14:00:50 -0800476void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800477{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700478 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800479 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800480 sprintf(buffer, " F %2d", mFastIndex);
481 } else if (mName >= AudioMixer::TRACK0) {
482 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800483 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800484 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800485 }
486 track_state state = mState;
487 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800488 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800489 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800490 } else {
491 switch (state) {
492 case IDLE:
493 stateChar = 'I';
494 break;
495 case STOPPING_1:
496 stateChar = 's';
497 break;
498 case STOPPING_2:
499 stateChar = '5';
500 break;
501 case STOPPED:
502 stateChar = 'S';
503 break;
504 case RESUMING:
505 stateChar = 'R';
506 break;
507 case ACTIVE:
508 stateChar = 'A';
509 break;
510 case PAUSING:
511 stateChar = 'p';
512 break;
513 case PAUSED:
514 stateChar = 'P';
515 break;
516 case FLUSHED:
517 stateChar = 'F';
518 break;
519 default:
520 stateChar = '?';
521 break;
522 }
Eric Laurent81784c32012-11-19 14:55:58 -0800523 }
524 char nowInUnderrun;
525 switch (mObservedUnderruns.mBitFields.mMostRecent) {
526 case UNDERRUN_FULL:
527 nowInUnderrun = ' ';
528 break;
529 case UNDERRUN_PARTIAL:
530 nowInUnderrun = '<';
531 break;
532 case UNDERRUN_EMPTY:
533 nowInUnderrun = '*';
534 break;
535 default:
536 nowInUnderrun = '?';
537 break;
538 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000539 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 +0000540 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800541 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800542 (mClient == 0) ? getpid_cached : mClient->pid(),
543 mStreamType,
544 mFormat,
545 mChannelMask,
546 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800547 mFrameCount,
548 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800549 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800550 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700551 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
552 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700553 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000554 mMainBuffer,
555 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700556 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700557 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800558 nowInUnderrun);
559}
560
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800561uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
562 return mAudioTrackServerProxy->getSampleRate();
563}
564
Eric Laurent81784c32012-11-19 14:55:58 -0800565// AudioBufferProvider interface
566status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800567 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800568{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800569 ServerProxy::Buffer buf;
570 size_t desiredFrames = buffer->frameCount;
571 buf.mFrameCount = desiredFrames;
572 status_t status = mServerProxy->obtainBuffer(&buf);
573 buffer->frameCount = buf.mFrameCount;
574 buffer->raw = buf.mRaw;
575 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700576 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800577 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800578 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800579}
580
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700581// releaseBuffer() is not overridden
582
583// ExtendedAudioBufferProvider interface
584
Eric Laurent81784c32012-11-19 14:55:58 -0800585// Note that framesReady() takes a mutex on the control block using tryLock().
586// This could result in priority inversion if framesReady() is called by the normal mixer,
587// as the normal mixer thread runs at lower
588// priority than the client's callback thread: there is a short window within framesReady()
589// during which the normal mixer could be preempted, and the client callback would block.
590// Another problem can occur if framesReady() is called by the fast mixer:
591// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
592// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
593size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800594 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800595}
596
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700597size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
598{
599 return mAudioTrackServerProxy->framesReleased();
600}
601
Eric Laurent81784c32012-11-19 14:55:58 -0800602// Don't call for fast tracks; the framesReady() could result in priority inversion
603bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800604 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
605 return true;
606 }
607
Eric Laurent16498512014-03-17 17:22:08 -0700608 if (isStopping()) {
609 if (framesReady() > 0) {
610 mFillingUpStatus = FS_FILLED;
611 }
Eric Laurent81784c32012-11-19 14:55:58 -0800612 return true;
613 }
614
615 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700616 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800617 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700618 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800619 return true;
620 }
621 return false;
622}
623
Glenn Kasten0f11b512014-01-31 16:18:54 -0800624status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
625 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800626{
627 status_t status = NO_ERROR;
628 ALOGV("start(%d), calling pid %d session %d",
629 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
630
631 sp<ThreadBase> thread = mThread.promote();
632 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700633 if (isOffloaded()) {
634 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
635 Mutex::Autolock _lth(thread->mLock);
636 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700637 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
638 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700639 invalidate();
640 return PERMISSION_DENIED;
641 }
642 }
643 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800644 track_state state = mState;
645 // here the track could be either new, or restarted
646 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800647
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800648 // initial state-stopping. next state-pausing.
649 // What if resume is called ?
650
651 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800652 if (mResumeToStopping) {
653 // happened we need to resume to STOPPING_1
654 mState = TrackBase::STOPPING_1;
655 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
656 } else {
657 mState = TrackBase::RESUMING;
658 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
659 }
Eric Laurent81784c32012-11-19 14:55:58 -0800660 } else {
661 mState = TrackBase::ACTIVE;
662 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
663 }
664
Eric Laurentbfb1b832013-01-07 09:53:42 -0800665 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
666 status = playbackThread->addTrack_l(this);
667 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800668 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800669 // restore previous state if start was rejected by policy manager
670 if (status == PERMISSION_DENIED) {
671 mState = state;
672 }
673 }
674 // track was already in the active list, not a problem
675 if (status == ALREADY_EXISTS) {
676 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700677 } else {
678 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
679 // It is usually unsafe to access the server proxy from a binder thread.
680 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
681 // isn't looking at this track yet: we still hold the normal mixer thread lock,
682 // and for fast tracks the track is not yet in the fast mixer thread's active set.
683 ServerProxy::Buffer buffer;
684 buffer.mFrameCount = 1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700685 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800686 }
687 } else {
688 status = BAD_VALUE;
689 }
690 return status;
691}
692
693void AudioFlinger::PlaybackThread::Track::stop()
694{
695 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
696 sp<ThreadBase> thread = mThread.promote();
697 if (thread != 0) {
698 Mutex::Autolock _l(thread->mLock);
699 track_state state = mState;
700 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
701 // If the track is not active (PAUSED and buffers full), flush buffers
702 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
703 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
704 reset();
705 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800706 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800707 mState = STOPPED;
708 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800709 // For fast tracks prepareTracks_l() will set state to STOPPING_2
710 // presentation is complete
711 // For an offloaded track this starts a drain and state will
712 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800713 mState = STOPPING_1;
714 }
715 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
716 playbackThread);
717 }
Eric Laurent81784c32012-11-19 14:55:58 -0800718 }
719}
720
721void AudioFlinger::PlaybackThread::Track::pause()
722{
723 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
724 sp<ThreadBase> thread = mThread.promote();
725 if (thread != 0) {
726 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800727 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
728 switch (mState) {
729 case STOPPING_1:
730 case STOPPING_2:
731 if (!isOffloaded()) {
732 /* nothing to do if track is not offloaded */
733 break;
734 }
735
736 // Offloaded track was draining, we need to carry on draining when resumed
737 mResumeToStopping = true;
738 // fall through...
739 case ACTIVE:
740 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800741 mState = PAUSING;
742 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700743 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800744 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800745
Eric Laurentbfb1b832013-01-07 09:53:42 -0800746 default:
747 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800748 }
749 }
750}
751
752void AudioFlinger::PlaybackThread::Track::flush()
753{
754 ALOGV("flush(%d)", mName);
755 sp<ThreadBase> thread = mThread.promote();
756 if (thread != 0) {
757 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800758 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800759
760 if (isOffloaded()) {
761 // If offloaded we allow flush during any state except terminated
762 // and keep the track active to avoid problems if user is seeking
763 // rapidly and underlying hardware has a significant delay handling
764 // a pause
765 if (isTerminated()) {
766 return;
767 }
768
769 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800770 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800771
772 if (mState == STOPPING_1 || mState == STOPPING_2) {
773 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
774 mState = ACTIVE;
775 }
776
777 if (mState == ACTIVE) {
778 ALOGV("flush called in active state, resetting buffer time out retry count");
779 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
780 }
781
Haynes Mathew George7844f672014-01-15 12:32:55 -0800782 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800783 mResumeToStopping = false;
784 } else {
785 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
786 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
787 return;
788 }
789 // No point remaining in PAUSED state after a flush => go to
790 // FLUSHED state
791 mState = FLUSHED;
792 // do not reset the track if it is still in the process of being stopped or paused.
793 // this will be done by prepareTracks_l() when the track is stopped.
794 // prepareTracks_l() will see mState == FLUSHED, then
795 // remove from active track list, reset(), and trigger presentation complete
796 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
797 reset();
798 }
Eric Laurent81784c32012-11-19 14:55:58 -0800799 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800800 // Prevent flush being lost if the track is flushed and then resumed
801 // before mixer thread can run. This is important when offloading
802 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700803 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800804 }
805}
806
Haynes Mathew George7844f672014-01-15 12:32:55 -0800807// must be called with thread lock held
808void AudioFlinger::PlaybackThread::Track::flushAck()
809{
810 if (!isOffloaded())
811 return;
812
813 mFlushHwPending = false;
814}
815
Eric Laurent81784c32012-11-19 14:55:58 -0800816void AudioFlinger::PlaybackThread::Track::reset()
817{
818 // Do not reset twice to avoid discarding data written just after a flush and before
819 // the audioflinger thread detects the track is stopped.
820 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800821 // Force underrun condition to avoid false underrun callback until first data is
822 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700823 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800824 mFillingUpStatus = FS_FILLING;
825 mResetDone = true;
826 if (mState == FLUSHED) {
827 mState = IDLE;
828 }
829 }
830}
831
Eric Laurentbfb1b832013-01-07 09:53:42 -0800832status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
833{
834 sp<ThreadBase> thread = mThread.promote();
835 if (thread == 0) {
836 ALOGE("thread is dead");
837 return FAILED_TRANSACTION;
838 } else if ((thread->type() == ThreadBase::DIRECT) ||
839 (thread->type() == ThreadBase::OFFLOAD)) {
840 return thread->setParameters(keyValuePairs);
841 } else {
842 return PERMISSION_DENIED;
843 }
844}
845
Glenn Kasten573d80a2013-08-26 09:36:23 -0700846status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
847{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700848 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
849 if (isFastTrack()) {
850 return INVALID_OPERATION;
851 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700852 sp<ThreadBase> thread = mThread.promote();
853 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700854 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700855 }
856 Mutex::Autolock _l(thread->mLock);
857 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaccc1472013-09-20 09:36:34 -0700858 if (!isOffloaded()) {
859 if (!playbackThread->mLatchQValid) {
860 return INVALID_OPERATION;
861 }
862 uint32_t unpresentedFrames =
863 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
864 playbackThread->mSampleRate;
865 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
866 if (framesWritten < unpresentedFrames) {
867 return INVALID_OPERATION;
868 }
869 timestamp.mPosition = framesWritten - unpresentedFrames;
870 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
871 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700872 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700873
874 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700875}
876
Eric Laurent81784c32012-11-19 14:55:58 -0800877status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
878{
879 status_t status = DEAD_OBJECT;
880 sp<ThreadBase> thread = mThread.promote();
881 if (thread != 0) {
882 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
883 sp<AudioFlinger> af = mClient->audioFlinger();
884
885 Mutex::Autolock _l(af->mLock);
886
887 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
888
889 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
890 Mutex::Autolock _dl(playbackThread->mLock);
891 Mutex::Autolock _sl(srcThread->mLock);
892 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
893 if (chain == 0) {
894 return INVALID_OPERATION;
895 }
896
897 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
898 if (effect == 0) {
899 return INVALID_OPERATION;
900 }
901 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700902 status = playbackThread->addEffect_l(effect);
903 if (status != NO_ERROR) {
904 srcThread->addEffect_l(effect);
905 return INVALID_OPERATION;
906 }
Eric Laurent81784c32012-11-19 14:55:58 -0800907 // removeEffect_l() has stopped the effect if it was active so it must be restarted
908 if (effect->state() == EffectModule::ACTIVE ||
909 effect->state() == EffectModule::STOPPING) {
910 effect->start();
911 }
912
913 sp<EffectChain> dstChain = effect->chain().promote();
914 if (dstChain == 0) {
915 srcThread->addEffect_l(effect);
916 return INVALID_OPERATION;
917 }
918 AudioSystem::unregisterEffect(effect->id());
919 AudioSystem::registerEffect(&effect->desc(),
920 srcThread->id(),
921 dstChain->strategy(),
922 AUDIO_SESSION_OUTPUT_MIX,
923 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700924 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800925 }
926 status = playbackThread->attachAuxEffect(this, EffectId);
927 }
928 return status;
929}
930
931void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
932{
933 mAuxEffectId = EffectId;
934 mAuxBuffer = buffer;
935}
936
937bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
938 size_t audioHalFrames)
939{
940 // a track is considered presented when the total number of frames written to audio HAL
941 // corresponds to the number of frames written when presentationComplete() is called for the
942 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800943 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
944 // to detect when all frames have been played. In this case framesWritten isn't
945 // useful because it doesn't always reflect whether there is data in the h/w
946 // buffers, particularly if a track has been paused and resumed during draining
947 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
948 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800949 if (mPresentationCompleteFrames == 0) {
950 mPresentationCompleteFrames = framesWritten + audioHalFrames;
951 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
952 mPresentationCompleteFrames, audioHalFrames);
953 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800954
955 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800956 ALOGV("presentationComplete() session %d complete: framesWritten %d",
957 mSessionId, framesWritten);
958 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800959 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800960 return true;
961 }
962 return false;
963}
964
965void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
966{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700967 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -0800968 if (mSyncEvents[i]->type() == type) {
969 mSyncEvents[i]->trigger();
970 mSyncEvents.removeAt(i);
971 i--;
972 }
973 }
974}
975
976// implement VolumeBufferProvider interface
977
Glenn Kastenc56f3422014-03-21 17:53:17 -0700978gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -0800979{
980 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
981 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -0700982 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
983 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
984 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -0800985 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -0700986 if (vl > GAIN_FLOAT_UNITY) {
987 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -0800988 }
Glenn Kastenc56f3422014-03-21 17:53:17 -0700989 if (vr > GAIN_FLOAT_UNITY) {
990 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -0800991 }
992 // now apply the cached master volume and stream type volume;
993 // this is trusted but lacks any synchronization or barrier so may be stale
994 float v = mCachedVolume;
995 vl *= v;
996 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -0700997 // re-combine into packed minifloat
998 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -0800999 // FIXME look at mute, pause, and stop flags
1000 return vlr;
1001}
1002
1003status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1004{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001005 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001006 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1007 (mState == STOPPED)))) {
1008 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1009 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1010 event->cancel();
1011 return INVALID_OPERATION;
1012 }
1013 (void) TrackBase::setSyncEvent(event);
1014 return NO_ERROR;
1015}
1016
Glenn Kasten5736c352012-12-04 12:12:34 -08001017void AudioFlinger::PlaybackThread::Track::invalidate()
1018{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001019 // FIXME should use proxy, and needs work
1020 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001021 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001022 android_atomic_release_store(0x40000000, &cblk->mFutex);
1023 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001024 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001025 mIsInvalid = true;
1026}
1027
Eric Laurent59fe0102013-09-27 18:48:26 -07001028void AudioFlinger::PlaybackThread::Track::signal()
1029{
1030 sp<ThreadBase> thread = mThread.promote();
1031 if (thread != 0) {
1032 PlaybackThread *t = (PlaybackThread *)thread.get();
1033 Mutex::Autolock _l(t->mLock);
1034 t->broadcast_l();
1035 }
1036}
1037
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001038//To be called with thread lock held
1039bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1040
1041 if (mState == RESUMING)
1042 return true;
1043 /* Resume is pending if track was stopping before pause was called */
1044 if (mState == STOPPING_1 &&
1045 mResumeToStopping)
1046 return true;
1047
1048 return false;
1049}
1050
1051//To be called with thread lock held
1052void AudioFlinger::PlaybackThread::Track::resumeAck() {
1053
1054
1055 if (mState == RESUMING)
1056 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001057
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001058 // Other possibility of pending resume is stopping_1 state
1059 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001060 // drain being called.
1061 if (mState == STOPPING_1) {
1062 mResumeToStopping = false;
1063 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001064}
Eric Laurent81784c32012-11-19 14:55:58 -08001065// ----------------------------------------------------------------------------
1066
1067sp<AudioFlinger::PlaybackThread::TimedTrack>
1068AudioFlinger::PlaybackThread::TimedTrack::create(
1069 PlaybackThread *thread,
1070 const sp<Client>& client,
1071 audio_stream_type_t streamType,
1072 uint32_t sampleRate,
1073 audio_format_t format,
1074 audio_channel_mask_t channelMask,
1075 size_t frameCount,
1076 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001077 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001078 int uid)
1079{
Eric Laurent81784c32012-11-19 14:55:58 -08001080 if (!client->reserveTimedTrack())
1081 return 0;
1082
1083 return new TimedTrack(
1084 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001085 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001086}
1087
1088AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1089 PlaybackThread *thread,
1090 const sp<Client>& client,
1091 audio_stream_type_t streamType,
1092 uint32_t sampleRate,
1093 audio_format_t format,
1094 audio_channel_mask_t channelMask,
1095 size_t frameCount,
1096 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001097 int sessionId,
1098 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001099 : Track(thread, client, streamType, sampleRate, format, channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001100 frameCount, sharedBuffer, sessionId, uid, IAudioFlinger::TRACK_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001101 mQueueHeadInFlight(false),
1102 mTrimQueueHeadOnRelease(false),
1103 mFramesPendingInQueue(0),
1104 mTimedSilenceBuffer(NULL),
1105 mTimedSilenceBufferSize(0),
1106 mTimedAudioOutputOnTime(false),
1107 mMediaTimeTransformValid(false)
1108{
1109 LocalClock lc;
1110 mLocalTimeFreq = lc.getLocalFreq();
1111
1112 mLocalTimeToSampleTransform.a_zero = 0;
1113 mLocalTimeToSampleTransform.b_zero = 0;
1114 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1115 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1116 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1117 &mLocalTimeToSampleTransform.a_to_b_denom);
1118
1119 mMediaTimeToSampleTransform.a_zero = 0;
1120 mMediaTimeToSampleTransform.b_zero = 0;
1121 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1122 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1123 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1124 &mMediaTimeToSampleTransform.a_to_b_denom);
1125}
1126
1127AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1128 mClient->releaseTimedTrack();
1129 delete [] mTimedSilenceBuffer;
1130}
1131
1132status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1133 size_t size, sp<IMemory>* buffer) {
1134
1135 Mutex::Autolock _l(mTimedBufferQueueLock);
1136
1137 trimTimedBufferQueue_l();
1138
1139 // lazily initialize the shared memory heap for timed buffers
1140 if (mTimedMemoryDealer == NULL) {
1141 const int kTimedBufferHeapSize = 512 << 10;
1142
1143 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1144 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001145 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001146 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001147 }
Eric Laurent81784c32012-11-19 14:55:58 -08001148 }
1149
1150 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001151 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001152 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001153 }
1154
1155 *buffer = newBuffer;
1156 return NO_ERROR;
1157}
1158
1159// caller must hold mTimedBufferQueueLock
1160void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1161 int64_t mediaTimeNow;
1162 {
1163 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1164 if (!mMediaTimeTransformValid)
1165 return;
1166
1167 int64_t targetTimeNow;
1168 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1169 ? mCCHelper.getCommonTime(&targetTimeNow)
1170 : mCCHelper.getLocalTime(&targetTimeNow);
1171
1172 if (OK != res)
1173 return;
1174
1175 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1176 &mediaTimeNow)) {
1177 return;
1178 }
1179 }
1180
1181 size_t trimEnd;
1182 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1183 int64_t bufEnd;
1184
1185 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1186 // We have a next buffer. Just use its PTS as the PTS of the frame
1187 // following the last frame in this buffer. If the stream is sparse
1188 // (ie, there are deliberate gaps left in the stream which should be
1189 // filled with silence by the TimedAudioTrack), then this can result
1190 // in one extra buffer being left un-trimmed when it could have
1191 // been. In general, this is not typical, and we would rather
1192 // optimized away the TS calculation below for the more common case
1193 // where PTSes are contiguous.
1194 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1195 } else {
1196 // We have no next buffer. Compute the PTS of the frame following
1197 // the last frame in this buffer by computing the duration of of
1198 // this frame in media time units and adding it to the PTS of the
1199 // buffer.
1200 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1201 / mFrameSize;
1202
1203 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1204 &bufEnd)) {
1205 ALOGE("Failed to convert frame count of %lld to media time"
1206 " duration" " (scale factor %d/%u) in %s",
1207 frameCount,
1208 mMediaTimeToSampleTransform.a_to_b_numer,
1209 mMediaTimeToSampleTransform.a_to_b_denom,
1210 __PRETTY_FUNCTION__);
1211 break;
1212 }
1213 bufEnd += mTimedBufferQueue[trimEnd].pts();
1214 }
1215
1216 if (bufEnd > mediaTimeNow)
1217 break;
1218
1219 // Is the buffer we want to use in the middle of a mix operation right
1220 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1221 // from the mixer which should be coming back shortly.
1222 if (!trimEnd && mQueueHeadInFlight) {
1223 mTrimQueueHeadOnRelease = true;
1224 }
1225 }
1226
1227 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1228 if (trimStart < trimEnd) {
1229 // Update the bookkeeping for framesReady()
1230 for (size_t i = trimStart; i < trimEnd; ++i) {
1231 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1232 }
1233
1234 // Now actually remove the buffers from the queue.
1235 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1236 }
1237}
1238
1239void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1240 const char* logTag) {
1241 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1242 "%s called (reason \"%s\"), but timed buffer queue has no"
1243 " elements to trim.", __FUNCTION__, logTag);
1244
1245 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1246 mTimedBufferQueue.removeAt(0);
1247}
1248
1249void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1250 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001251 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001252 uint32_t bufBytes = buf.buffer()->size();
1253 uint32_t consumedAlready = buf.position();
1254
1255 ALOG_ASSERT(consumedAlready <= bufBytes,
1256 "Bad bookkeeping while updating frames pending. Timed buffer is"
1257 " only %u bytes long, but claims to have consumed %u"
1258 " bytes. (update reason: \"%s\")",
1259 bufBytes, consumedAlready, logTag);
1260
1261 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1262 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1263 "Bad bookkeeping while updating frames pending. Should have at"
1264 " least %u queued frames, but we think we have only %u. (update"
1265 " reason: \"%s\")",
1266 bufFrames, mFramesPendingInQueue, logTag);
1267
1268 mFramesPendingInQueue -= bufFrames;
1269}
1270
1271status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1272 const sp<IMemory>& buffer, int64_t pts) {
1273
1274 {
1275 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1276 if (!mMediaTimeTransformValid)
1277 return INVALID_OPERATION;
1278 }
1279
1280 Mutex::Autolock _l(mTimedBufferQueueLock);
1281
1282 uint32_t bufFrames = buffer->size() / mFrameSize;
1283 mFramesPendingInQueue += bufFrames;
1284 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1285
1286 return NO_ERROR;
1287}
1288
1289status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1290 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1291
1292 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1293 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1294 target);
1295
1296 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1297 target == TimedAudioTrack::COMMON_TIME)) {
1298 return BAD_VALUE;
1299 }
1300
1301 Mutex::Autolock lock(mMediaTimeTransformLock);
1302 mMediaTimeTransform = xform;
1303 mMediaTimeTransformTarget = target;
1304 mMediaTimeTransformValid = true;
1305
1306 return NO_ERROR;
1307}
1308
1309#define min(a, b) ((a) < (b) ? (a) : (b))
1310
1311// implementation of getNextBuffer for tracks whose buffers have timestamps
1312status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1313 AudioBufferProvider::Buffer* buffer, int64_t pts)
1314{
1315 if (pts == AudioBufferProvider::kInvalidPTS) {
1316 buffer->raw = NULL;
1317 buffer->frameCount = 0;
1318 mTimedAudioOutputOnTime = false;
1319 return INVALID_OPERATION;
1320 }
1321
1322 Mutex::Autolock _l(mTimedBufferQueueLock);
1323
1324 ALOG_ASSERT(!mQueueHeadInFlight,
1325 "getNextBuffer called without releaseBuffer!");
1326
1327 while (true) {
1328
1329 // if we have no timed buffers, then fail
1330 if (mTimedBufferQueue.isEmpty()) {
1331 buffer->raw = NULL;
1332 buffer->frameCount = 0;
1333 return NOT_ENOUGH_DATA;
1334 }
1335
1336 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1337
1338 // calculate the PTS of the head of the timed buffer queue expressed in
1339 // local time
1340 int64_t headLocalPTS;
1341 {
1342 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1343
1344 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1345
1346 if (mMediaTimeTransform.a_to_b_denom == 0) {
1347 // the transform represents a pause, so yield silence
1348 timedYieldSilence_l(buffer->frameCount, buffer);
1349 return NO_ERROR;
1350 }
1351
1352 int64_t transformedPTS;
1353 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1354 &transformedPTS)) {
1355 // the transform failed. this shouldn't happen, but if it does
1356 // then just drop this buffer
1357 ALOGW("timedGetNextBuffer transform failed");
1358 buffer->raw = NULL;
1359 buffer->frameCount = 0;
1360 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1361 return NO_ERROR;
1362 }
1363
1364 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1365 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1366 &headLocalPTS)) {
1367 buffer->raw = NULL;
1368 buffer->frameCount = 0;
1369 return INVALID_OPERATION;
1370 }
1371 } else {
1372 headLocalPTS = transformedPTS;
1373 }
1374 }
1375
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001376 uint32_t sr = sampleRate();
1377
Eric Laurent81784c32012-11-19 14:55:58 -08001378 // adjust the head buffer's PTS to reflect the portion of the head buffer
1379 // that has already been consumed
1380 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001381 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001382
1383 // Calculate the delta in samples between the head of the input buffer
1384 // queue and the start of the next output buffer that will be written.
1385 // If the transformation fails because of over or underflow, it means
1386 // that the sample's position in the output stream is so far out of
1387 // whack that it should just be dropped.
1388 int64_t sampleDelta;
1389 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1390 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1391 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1392 " mix");
1393 continue;
1394 }
1395 if (!mLocalTimeToSampleTransform.doForwardTransform(
1396 (effectivePTS - pts) << 32, &sampleDelta)) {
1397 ALOGV("*** too late during sample rate transform: dropped buffer");
1398 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1399 continue;
1400 }
1401
1402 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1403 " sampleDelta=[%d.%08x]",
1404 head.pts(), head.position(), pts,
1405 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1406 + (sampleDelta >> 32)),
1407 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1408
1409 // if the delta between the ideal placement for the next input sample and
1410 // the current output position is within this threshold, then we will
1411 // concatenate the next input samples to the previous output
1412 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001413 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001414
1415 // if this is the first buffer of audio that we're emitting from this track
1416 // then it should be almost exactly on time.
1417 const int64_t kSampleStartupThreshold = 1LL << 32;
1418
1419 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1420 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1421 // the next input is close enough to being on time, so concatenate it
1422 // with the last output
1423 timedYieldSamples_l(buffer);
1424
1425 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1426 head.position(), buffer->frameCount);
1427 return NO_ERROR;
1428 }
1429
1430 // Looks like our output is not on time. Reset our on timed status.
1431 // Next time we mix samples from our input queue, then should be within
1432 // the StartupThreshold.
1433 mTimedAudioOutputOnTime = false;
1434 if (sampleDelta > 0) {
1435 // the gap between the current output position and the proper start of
1436 // the next input sample is too big, so fill it with silence
1437 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1438
1439 timedYieldSilence_l(framesUntilNextInput, buffer);
1440 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1441 return NO_ERROR;
1442 } else {
1443 // the next input sample is late
1444 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1445 size_t onTimeSamplePosition =
1446 head.position() + lateFrames * mFrameSize;
1447
1448 if (onTimeSamplePosition > head.buffer()->size()) {
1449 // all the remaining samples in the head are too late, so
1450 // drop it and move on
1451 ALOGV("*** too late: dropped buffer");
1452 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1453 continue;
1454 } else {
1455 // skip over the late samples
1456 head.setPosition(onTimeSamplePosition);
1457
1458 // yield the available samples
1459 timedYieldSamples_l(buffer);
1460
1461 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1462 return NO_ERROR;
1463 }
1464 }
1465 }
1466}
1467
1468// Yield samples from the timed buffer queue head up to the given output
1469// buffer's capacity.
1470//
1471// Caller must hold mTimedBufferQueueLock
1472void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1473 AudioBufferProvider::Buffer* buffer) {
1474
1475 const TimedBuffer& head = mTimedBufferQueue[0];
1476
1477 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1478 head.position());
1479
1480 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1481 mFrameSize);
1482 size_t framesRequested = buffer->frameCount;
1483 buffer->frameCount = min(framesLeftInHead, framesRequested);
1484
1485 mQueueHeadInFlight = true;
1486 mTimedAudioOutputOnTime = true;
1487}
1488
1489// Yield samples of silence up to the given output buffer's capacity
1490//
1491// Caller must hold mTimedBufferQueueLock
1492void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1493 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1494
1495 // lazily allocate a buffer filled with silence
1496 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1497 delete [] mTimedSilenceBuffer;
1498 mTimedSilenceBufferSize = numFrames * mFrameSize;
1499 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1500 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1501 }
1502
1503 buffer->raw = mTimedSilenceBuffer;
1504 size_t framesRequested = buffer->frameCount;
1505 buffer->frameCount = min(numFrames, framesRequested);
1506
1507 mTimedAudioOutputOnTime = false;
1508}
1509
1510// AudioBufferProvider interface
1511void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1512 AudioBufferProvider::Buffer* buffer) {
1513
1514 Mutex::Autolock _l(mTimedBufferQueueLock);
1515
1516 // If the buffer which was just released is part of the buffer at the head
1517 // of the queue, be sure to update the amt of the buffer which has been
1518 // consumed. If the buffer being returned is not part of the head of the
1519 // queue, its either because the buffer is part of the silence buffer, or
1520 // because the head of the timed queue was trimmed after the mixer called
1521 // getNextBuffer but before the mixer called releaseBuffer.
1522 if (buffer->raw == mTimedSilenceBuffer) {
1523 ALOG_ASSERT(!mQueueHeadInFlight,
1524 "Queue head in flight during release of silence buffer!");
1525 goto done;
1526 }
1527
1528 ALOG_ASSERT(mQueueHeadInFlight,
1529 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1530 " head in flight.");
1531
1532 if (mTimedBufferQueue.size()) {
1533 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1534
1535 void* start = head.buffer()->pointer();
1536 void* end = reinterpret_cast<void*>(
1537 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1538 + head.buffer()->size());
1539
1540 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1541 "released buffer not within the head of the timed buffer"
1542 " queue; qHead = [%p, %p], released buffer = %p",
1543 start, end, buffer->raw);
1544
1545 head.setPosition(head.position() +
1546 (buffer->frameCount * mFrameSize));
1547 mQueueHeadInFlight = false;
1548
1549 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1550 "Bad bookkeeping during releaseBuffer! Should have at"
1551 " least %u queued frames, but we think we have only %u",
1552 buffer->frameCount, mFramesPendingInQueue);
1553
1554 mFramesPendingInQueue -= buffer->frameCount;
1555
1556 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1557 || mTrimQueueHeadOnRelease) {
1558 trimTimedBufferQueueHead_l("releaseBuffer");
1559 mTrimQueueHeadOnRelease = false;
1560 }
1561 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001562 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001563 " buffers in the timed buffer queue");
1564 }
1565
1566done:
1567 buffer->raw = 0;
1568 buffer->frameCount = 0;
1569}
1570
1571size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1572 Mutex::Autolock _l(mTimedBufferQueueLock);
1573 return mFramesPendingInQueue;
1574}
1575
1576AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1577 : mPTS(0), mPosition(0) {}
1578
1579AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1580 const sp<IMemory>& buffer, int64_t pts)
1581 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1582
1583
1584// ----------------------------------------------------------------------------
1585
1586AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1587 PlaybackThread *playbackThread,
1588 DuplicatingThread *sourceThread,
1589 uint32_t sampleRate,
1590 audio_format_t format,
1591 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001592 size_t frameCount,
1593 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001594 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001595 NULL, 0, uid, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001596 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001597{
1598
1599 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001600 mOutBuffer.frameCount = 0;
1601 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001602 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001603 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001604 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001605 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001606 // since client and server are in the same process,
1607 // the buffer has the same virtual address on both sides
1608 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001609 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001610 mClientProxy->setSendLevel(0.0);
1611 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001612 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1613 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001614 } else {
1615 ALOGW("Error creating output track on thread %p", playbackThread);
1616 }
1617}
1618
1619AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1620{
1621 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001622 delete mClientProxy;
1623 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001624}
1625
1626status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1627 int triggerSession)
1628{
1629 status_t status = Track::start(event, triggerSession);
1630 if (status != NO_ERROR) {
1631 return status;
1632 }
1633
1634 mActive = true;
1635 mRetryCount = 127;
1636 return status;
1637}
1638
1639void AudioFlinger::PlaybackThread::OutputTrack::stop()
1640{
1641 Track::stop();
1642 clearBufferQueue();
1643 mOutBuffer.frameCount = 0;
1644 mActive = false;
1645}
1646
1647bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1648{
1649 Buffer *pInBuffer;
1650 Buffer inBuffer;
1651 uint32_t channelCount = mChannelCount;
1652 bool outputBufferFull = false;
1653 inBuffer.frameCount = frames;
1654 inBuffer.i16 = data;
1655
1656 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1657
1658 if (!mActive && frames != 0) {
1659 start();
1660 sp<ThreadBase> thread = mThread.promote();
1661 if (thread != 0) {
1662 MixerThread *mixerThread = (MixerThread *)thread.get();
1663 if (mFrameCount > frames) {
1664 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1665 uint32_t startFrames = (mFrameCount - frames);
1666 pInBuffer = new Buffer;
1667 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1668 pInBuffer->frameCount = startFrames;
1669 pInBuffer->i16 = pInBuffer->mBuffer;
1670 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1671 mBufferQueue.add(pInBuffer);
1672 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001673 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001674 }
1675 }
1676 }
1677 }
1678
1679 while (waitTimeLeftMs) {
1680 // First write pending buffers, then new data
1681 if (mBufferQueue.size()) {
1682 pInBuffer = mBufferQueue.itemAt(0);
1683 } else {
1684 pInBuffer = &inBuffer;
1685 }
1686
1687 if (pInBuffer->frameCount == 0) {
1688 break;
1689 }
1690
1691 if (mOutBuffer.frameCount == 0) {
1692 mOutBuffer.frameCount = pInBuffer->frameCount;
1693 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001694 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1695 if (status != NO_ERROR) {
1696 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1697 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001698 outputBufferFull = true;
1699 break;
1700 }
1701 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1702 if (waitTimeLeftMs >= waitTimeMs) {
1703 waitTimeLeftMs -= waitTimeMs;
1704 } else {
1705 waitTimeLeftMs = 0;
1706 }
1707 }
1708
1709 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1710 pInBuffer->frameCount;
1711 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001712 Proxy::Buffer buf;
1713 buf.mFrameCount = outFrames;
1714 buf.mRaw = NULL;
1715 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001716 pInBuffer->frameCount -= outFrames;
1717 pInBuffer->i16 += outFrames * channelCount;
1718 mOutBuffer.frameCount -= outFrames;
1719 mOutBuffer.i16 += outFrames * channelCount;
1720
1721 if (pInBuffer->frameCount == 0) {
1722 if (mBufferQueue.size()) {
1723 mBufferQueue.removeAt(0);
1724 delete [] pInBuffer->mBuffer;
1725 delete pInBuffer;
1726 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1727 mThread.unsafe_get(), mBufferQueue.size());
1728 } else {
1729 break;
1730 }
1731 }
1732 }
1733
1734 // If we could not write all frames, allocate a buffer and queue it for next time.
1735 if (inBuffer.frameCount) {
1736 sp<ThreadBase> thread = mThread.promote();
1737 if (thread != 0 && !thread->standby()) {
1738 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1739 pInBuffer = new Buffer;
1740 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1741 pInBuffer->frameCount = inBuffer.frameCount;
1742 pInBuffer->i16 = pInBuffer->mBuffer;
1743 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1744 sizeof(int16_t));
1745 mBufferQueue.add(pInBuffer);
1746 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1747 mThread.unsafe_get(), mBufferQueue.size());
1748 } else {
1749 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1750 mThread.unsafe_get(), this);
1751 }
1752 }
1753 }
1754
1755 // Calling write() with a 0 length buffer, means that no more data will be written:
1756 // If no more buffers are pending, fill output track buffer to make sure it is started
1757 // by output mixer.
1758 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001759 // FIXME borken, replace by getting framesReady() from proxy
1760 size_t user = 0; // was mCblk->user
1761 if (user < mFrameCount) {
1762 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001763 pInBuffer = new Buffer;
1764 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1765 pInBuffer->frameCount = frames;
1766 pInBuffer->i16 = pInBuffer->mBuffer;
1767 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1768 mBufferQueue.add(pInBuffer);
1769 } else if (mActive) {
1770 stop();
1771 }
1772 }
1773
1774 return outputBufferFull;
1775}
1776
1777status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1778 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1779{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001780 ClientProxy::Buffer buf;
1781 buf.mFrameCount = buffer->frameCount;
1782 struct timespec timeout;
1783 timeout.tv_sec = waitTimeMs / 1000;
1784 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1785 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1786 buffer->frameCount = buf.mFrameCount;
1787 buffer->raw = buf.mRaw;
1788 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001789}
1790
Eric Laurent81784c32012-11-19 14:55:58 -08001791void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1792{
1793 size_t size = mBufferQueue.size();
1794
1795 for (size_t i = 0; i < size; i++) {
1796 Buffer *pBuffer = mBufferQueue.itemAt(i);
1797 delete [] pBuffer->mBuffer;
1798 delete pBuffer;
1799 }
1800 mBufferQueue.clear();
1801}
1802
1803
1804// ----------------------------------------------------------------------------
1805// Record
1806// ----------------------------------------------------------------------------
1807
1808AudioFlinger::RecordHandle::RecordHandle(
1809 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1810 : BnAudioRecord(),
1811 mRecordTrack(recordTrack)
1812{
1813}
1814
1815AudioFlinger::RecordHandle::~RecordHandle() {
1816 stop_nonvirtual();
1817 mRecordTrack->destroy();
1818}
1819
Eric Laurent81784c32012-11-19 14:55:58 -08001820status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1821 int triggerSession) {
1822 ALOGV("RecordHandle::start()");
1823 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1824}
1825
1826void AudioFlinger::RecordHandle::stop() {
1827 stop_nonvirtual();
1828}
1829
1830void AudioFlinger::RecordHandle::stop_nonvirtual() {
1831 ALOGV("RecordHandle::stop()");
1832 mRecordTrack->stop();
1833}
1834
1835status_t AudioFlinger::RecordHandle::onTransact(
1836 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1837{
1838 return BnAudioRecord::onTransact(code, data, reply, flags);
1839}
1840
1841// ----------------------------------------------------------------------------
1842
Glenn Kasten05997e22014-03-13 15:08:33 -07001843// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001844AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1845 RecordThread *thread,
1846 const sp<Client>& client,
1847 uint32_t sampleRate,
1848 audio_format_t format,
1849 audio_channel_mask_t channelMask,
1850 size_t frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001851 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001852 int uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001853 IAudioFlinger::track_flags_t flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001854 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001855 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, uid,
1856 flags, false /*isOut*/,
Glenn Kasten6181ffd2014-05-13 10:41:52 -07001857 (flags & IAudioFlinger::TRACK_FAST) != 0 ? ALLOC_READONLY : ALLOC_CBLK),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001858 mOverflow(false), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0),
1859 // See real initialization of mRsmpInFront at RecordThread::start()
1860 mRsmpInUnrel(0), mRsmpInFront(0), mFramesToDrop(0), mResamplerBufferProvider(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001861{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001862 if (mCblk == NULL) {
1863 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001864 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001865
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001866 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount, mFrameSize);
1867
Andy Hunge5412692014-05-16 11:25:07 -07001868 uint32_t channelCount = audio_channel_count_from_in_mask(channelMask);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001869 // FIXME I don't understand either of the channel count checks
1870 if (thread->mSampleRate != sampleRate && thread->mChannelCount <= FCC_2 &&
1871 channelCount <= FCC_2) {
1872 // sink SR
1873 mResampler = AudioResampler::create(16, thread->mChannelCount, sampleRate);
1874 // source SR
1875 mResampler->setSampleRate(thread->mSampleRate);
1876 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
1877 mResamplerBufferProvider = new ResamplerBufferProvider(this);
1878 }
Eric Laurent81784c32012-11-19 14:55:58 -08001879}
1880
1881AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1882{
1883 ALOGV("%s", __func__);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001884 delete mResampler;
1885 delete[] mRsmpOutBuffer;
1886 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001887}
1888
1889// AudioBufferProvider interface
1890status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001891 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001892{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001893 ServerProxy::Buffer buf;
1894 buf.mFrameCount = buffer->frameCount;
1895 status_t status = mServerProxy->obtainBuffer(&buf);
1896 buffer->frameCount = buf.mFrameCount;
1897 buffer->raw = buf.mRaw;
1898 if (buf.mFrameCount == 0) {
1899 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001900 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001901 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001902 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001903}
1904
1905status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1906 int triggerSession)
1907{
1908 sp<ThreadBase> thread = mThread.promote();
1909 if (thread != 0) {
1910 RecordThread *recordThread = (RecordThread *)thread.get();
1911 return recordThread->start(this, event, triggerSession);
1912 } else {
1913 return BAD_VALUE;
1914 }
1915}
1916
1917void AudioFlinger::RecordThread::RecordTrack::stop()
1918{
1919 sp<ThreadBase> thread = mThread.promote();
1920 if (thread != 0) {
1921 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001922 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001923 AudioSystem::stopInput(recordThread->id());
1924 }
1925 }
1926}
1927
1928void AudioFlinger::RecordThread::RecordTrack::destroy()
1929{
1930 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1931 sp<RecordTrack> keep(this);
1932 {
1933 sp<ThreadBase> thread = mThread.promote();
1934 if (thread != 0) {
1935 if (mState == ACTIVE || mState == RESUMING) {
1936 AudioSystem::stopInput(thread->id());
1937 }
1938 AudioSystem::releaseInput(thread->id());
1939 Mutex::Autolock _l(thread->mLock);
1940 RecordThread *recordThread = (RecordThread *) thread.get();
1941 recordThread->destroyTrack_l(this);
1942 }
1943 }
1944}
1945
Eric Laurent9a54bc22013-09-09 09:08:44 -07001946void AudioFlinger::RecordThread::RecordTrack::invalidate()
1947{
1948 // FIXME should use proxy, and needs work
1949 audio_track_cblk_t* cblk = mCblk;
1950 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1951 android_atomic_release_store(0x40000000, &cblk->mFutex);
1952 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001953 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001954}
1955
Eric Laurent81784c32012-11-19 14:55:58 -08001956
1957/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1958{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001959 result.append(" Active Client Fmt Chn mask Session S Server fCount Resampling\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001960}
1961
Marco Nelissenb2208842014-02-07 14:00:50 -08001962void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001963{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001964 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %10d\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001965 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001966 (mClient == 0) ? getpid_cached : mClient->pid(),
1967 mFormat,
1968 mChannelMask,
1969 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001970 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001971 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001972 mFrameCount,
1973 mResampler != NULL);
1974
Eric Laurent81784c32012-11-19 14:55:58 -08001975}
1976
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001977void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1978{
1979 if (event == mSyncStartEvent) {
1980 ssize_t framesToDrop = 0;
1981 sp<ThreadBase> threadBase = mThread.promote();
1982 if (threadBase != 0) {
1983 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1984 // from audio HAL
1985 framesToDrop = threadBase->mFrameCount * 2;
1986 }
1987 mFramesToDrop = framesToDrop;
1988 }
1989}
1990
1991void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1992{
1993 if (mSyncStartEvent != 0) {
1994 mSyncStartEvent->cancel();
1995 mSyncStartEvent.clear();
1996 }
1997 mFramesToDrop = 0;
1998}
1999
Eric Laurent81784c32012-11-19 14:55:58 -08002000}; // namespace android