blob: 1a48e07521d92a8ee55753a9bfc9c45f69d194e4 [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"
Glenn Kastenad8510a2015-02-17 16:24:07 -080023#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070025#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080026#include <utils/Log.h>
27
28#include <private/media/AudioTrackShared.h>
29
Eric Laurent81784c32012-11-19 14:55:58 -080030#include "AudioMixer.h"
31#include "AudioFlinger.h"
32#include "ServiceUtilities.h"
33
Glenn Kastenda6ef132013-01-10 12:31:01 -080034#include <media/nbaio/Pipe.h>
35#include <media/nbaio/PipeReader.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070036#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080037
Eric Laurent81784c32012-11-19 14:55:58 -080038// ----------------------------------------------------------------------------
39
40// Note: the following macro is used for extremely verbose logging message. In
41// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
42// 0; but one side effect of this is to turn all LOGV's as well. Some messages
43// are so verbose that we want to suppress them even when we have ALOG_ASSERT
44// turned on. Do not uncomment the #def below unless you really know what you
45// are doing and want to see all of the extremely verbose messages.
46//#define VERY_VERY_VERBOSE_LOGGING
47#ifdef VERY_VERY_VERBOSE_LOGGING
48#define ALOGVV ALOGV
49#else
50#define ALOGVV(a...) do { } while(0)
51#endif
52
Andy Hunge10393e2015-06-12 13:59:33 -070053// TODO move to a common header (Also shared with AudioTrack.cpp)
54#define NANOS_PER_SECOND 1000000000
55#define TIME_TO_NANOS(time) ((uint64_t)time.tv_sec * NANOS_PER_SECOND + time.tv_nsec)
56
Eric Laurent81784c32012-11-19 14:55:58 -080057namespace android {
58
59// ----------------------------------------------------------------------------
60// TrackBase
61// ----------------------------------------------------------------------------
62
Glenn Kastenda6ef132013-01-10 12:31:01 -080063static volatile int32_t nextTrackId = 55;
64
Eric Laurent81784c32012-11-19 14:55:58 -080065// TrackBase constructor must be called with AudioFlinger::mLock held
66AudioFlinger::ThreadBase::TrackBase::TrackBase(
67 ThreadBase *thread,
68 const sp<Client>& client,
69 uint32_t sampleRate,
70 audio_format_t format,
71 audio_channel_mask_t channelMask,
72 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070073 void *buffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080074 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080075 int clientUid,
Glenn Kasten755b0a62014-05-13 11:30:28 -070076 IAudioFlinger::track_flags_t flags,
Glenn Kastend776ac62014-05-07 09:16:09 -070077 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070078 alloc_type alloc,
79 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -080080 : RefBase(),
81 mThread(thread),
82 mClient(client),
83 mCblk(NULL),
84 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080085 mState(IDLE),
86 mSampleRate(sampleRate),
87 mFormat(format),
88 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070089 mChannelCount(isOut ?
90 audio_channel_count_from_out_mask(channelMask) :
91 audio_channel_count_from_in_mask(channelMask)),
Phil Burkfdb3c072016-02-09 10:47:02 -080092 mFrameSize(audio_has_proportional_frames(format) ?
Eric Laurent81784c32012-11-19 14:55:58 -080093 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
94 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080095 mSessionId(sessionId),
Glenn Kasten755b0a62014-05-13 11:30:28 -070096 mFlags(flags),
Glenn Kastene3aa6592012-12-04 12:22:46 -080097 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080098 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080099 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -0700100 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -0700101 mType(type),
102 mThreadIoHandle(thread->id())
Eric Laurent81784c32012-11-19 14:55:58 -0800103{
Marco Nelissendcb346b2015-09-09 10:47:29 -0700104 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
105 if (!isTrustedCallingUid(callingUid) || clientUid == -1) {
106 ALOGW_IF(clientUid != -1 && clientUid != (int)callingUid,
107 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
108 clientUid = (int)callingUid;
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800109 }
110 // clientUid contains the uid of the app that is responsible for this track, so we can blame
111 // battery usage on it.
112 mUid = clientUid;
113
Eric Laurent81784c32012-11-19 14:55:58 -0800114 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
115 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700116 size_t bufferSize = (buffer == NULL ? roundup(frameCount) : frameCount) * mFrameSize;
117 if (buffer == NULL && alloc == ALLOC_CBLK) {
Eric Laurent81784c32012-11-19 14:55:58 -0800118 size += bufferSize;
119 }
120
121 if (client != 0) {
122 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700123 if (mCblkMemory == 0 ||
124 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800125 ALOGE("not enough memory for AudioTrack size=%u", size);
126 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700127 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800128 return;
129 }
130 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800131 // this syntax avoids calling the audio_track_cblk_t constructor twice
132 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800133 // assume mCblk != NULL
134 }
135
136 // construct the shared structure in-place.
137 if (mCblk != NULL) {
138 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700139 switch (alloc) {
140 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700141 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
142 if (roHeap == 0 ||
143 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
144 (mBuffer = mBufferMemory->pointer()) == NULL) {
145 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
146 if (roHeap != 0) {
147 roHeap->dump("buffer");
148 }
149 mCblkMemory.clear();
150 mBufferMemory.clear();
151 return;
152 }
Eric Laurent81784c32012-11-19 14:55:58 -0800153 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700154 } break;
155 case ALLOC_PIPE:
156 mBufferMemory = thread->pipeMemory();
157 // mBuffer is the virtual address as seen from current process (mediaserver),
158 // and should normally be coming from mBufferMemory->pointer().
159 // However in this case the TrackBase does not reference the buffer directly.
160 // It should references the buffer via the pipe.
161 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
162 mBuffer = NULL;
163 break;
164 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700165 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700166 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700167 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
168 memset(mBuffer, 0, bufferSize);
169 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700170 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800171#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700172 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800173#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700174 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700175 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700176 case ALLOC_LOCAL:
177 mBuffer = calloc(1, bufferSize);
178 break;
179 case ALLOC_NONE:
180 mBuffer = buffer;
181 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800182 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800183
Glenn Kasten46909e72013-02-26 09:20:22 -0800184#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800185 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700186 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800187 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800188 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
189 size_t numCounterOffers = 0;
190 const NBAIO_Format offers[1] = {pipeFormat};
191 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
192 ALOG_ASSERT(index == 0);
193 PipeReader *pipeReader = new PipeReader(*pipe);
194 numCounterOffers = 0;
195 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
196 ALOG_ASSERT(index == 0);
197 mTeeSink = pipe;
198 mTeeSource = pipeReader;
199 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800200 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800201#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800202
Eric Laurent81784c32012-11-19 14:55:58 -0800203 }
204}
205
Eric Laurent83b88082014-06-20 18:31:16 -0700206status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
207{
208 status_t status;
209 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
210 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
211 } else {
212 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
213 }
214 return status;
215}
216
Eric Laurent81784c32012-11-19 14:55:58 -0800217AudioFlinger::ThreadBase::TrackBase::~TrackBase()
218{
Glenn Kasten46909e72013-02-26 09:20:22 -0800219#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800220 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800221#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800222 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
223 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800224 if (mCblk != NULL) {
225 if (mClient == 0) {
226 delete mCblk;
227 } else {
228 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
229 }
230 }
231 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
232 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700233 // Client destructor must run with AudioFlinger client mutex locked
234 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800235 // If the client's reference count drops to zero, the associated destructor
236 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
237 // relying on the automatic clear() at end of scope.
238 mClient.clear();
239 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700240 // flush the binder command buffer
241 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800242}
243
244// AudioBufferProvider interface
245// getNextBuffer() = 0;
Glenn Kastend79072e2016-01-06 08:41:20 -0800246// This implementation of releaseBuffer() is used by Track and RecordTrack
Eric Laurent81784c32012-11-19 14:55:58 -0800247void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
248{
Glenn Kasten46909e72013-02-26 09:20:22 -0800249#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800250 if (mTeeSink != 0) {
251 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
252 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800253#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800254
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800255 ServerProxy::Buffer buf;
256 buf.mFrameCount = buffer->frameCount;
257 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800258 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800259 buffer->raw = NULL;
260 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800261}
262
Eric Laurent81784c32012-11-19 14:55:58 -0800263status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
264{
265 mSyncEvents.add(event);
266 return NO_ERROR;
267}
268
269// ----------------------------------------------------------------------------
270// Playback
271// ----------------------------------------------------------------------------
272
273AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
274 : BnAudioTrack(),
275 mTrack(track)
276{
277}
278
279AudioFlinger::TrackHandle::~TrackHandle() {
280 // just stop the track on deletion, associated resources
281 // will be freed from the main thread once all pending buffers have
282 // been played. Unless it's not in the active track list, in which
283 // case we free everything now...
284 mTrack->destroy();
285}
286
287sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
288 return mTrack->getCblk();
289}
290
291status_t AudioFlinger::TrackHandle::start() {
292 return mTrack->start();
293}
294
295void AudioFlinger::TrackHandle::stop() {
296 mTrack->stop();
297}
298
299void AudioFlinger::TrackHandle::flush() {
300 mTrack->flush();
301}
302
Eric Laurent81784c32012-11-19 14:55:58 -0800303void AudioFlinger::TrackHandle::pause() {
304 mTrack->pause();
305}
306
307status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
308{
309 return mTrack->attachAuxEffect(EffectId);
310}
311
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700312status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
313 return mTrack->setParameters(keyValuePairs);
314}
315
Glenn Kasten53cec222013-08-29 09:01:02 -0700316status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
317{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700318 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700319}
320
Eric Laurent59fe0102013-09-27 18:48:26 -0700321
322void AudioFlinger::TrackHandle::signal()
323{
324 return mTrack->signal();
325}
326
Eric Laurent81784c32012-11-19 14:55:58 -0800327status_t AudioFlinger::TrackHandle::onTransact(
328 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
329{
330 return BnAudioTrack::onTransact(code, data, reply, flags);
331}
332
333// ----------------------------------------------------------------------------
334
335// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
336AudioFlinger::PlaybackThread::Track::Track(
337 PlaybackThread *thread,
338 const sp<Client>& client,
339 audio_stream_type_t streamType,
340 uint32_t sampleRate,
341 audio_format_t format,
342 audio_channel_mask_t channelMask,
343 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700344 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800345 const sp<IMemory>& sharedBuffer,
346 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800347 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -0700348 IAudioFlinger::track_flags_t flags,
349 track_type type)
350 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
351 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
352 sessionId, uid, flags, true /*isOut*/,
353 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
354 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800355 mFillingUpStatus(FS_INVALID),
356 // mRetryCount initialized later when needed
357 mSharedBuffer(sharedBuffer),
358 mStreamType(streamType),
359 mName(-1), // see note below
360 mMainBuffer(thread->mixBuffer()),
361 mAuxBuffer(NULL),
362 mAuxEffectId(0), mHasVolumeController(false),
363 mPresentationCompleteFrames(0),
Andy Hunge10393e2015-06-12 13:59:33 -0700364 mFrameMap(16 /* sink-frame-to-track-frame map memory */),
365 mSinkTimestampValid(false),
366 // mSinkTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800367 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800368 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800369 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800370 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800371 mResumeToStopping(false),
Phil Burk1b420972015-04-22 10:52:21 -0700372 mFlushHwPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800373{
Eric Laurent83b88082014-06-20 18:31:16 -0700374 // client == 0 implies sharedBuffer == 0
375 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
376
377 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
378 sharedBuffer->size());
379
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700380 if (mCblk == NULL) {
381 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800382 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700383
384 if (sharedBuffer == 0) {
385 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700386 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700387 } else {
388 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
389 mFrameSize);
390 }
391 mServerProxy = mAudioTrackServerProxy;
392
Glenn Kastenc263ca02014-06-04 20:31:46 -0700393 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700394 if (mName < 0) {
395 ALOGE("no more track names available");
396 return;
397 }
398 // only allocate a fast track index if we were able to allocate a normal track name
399 if (flags & IAudioFlinger::TRACK_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700400 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
401 // race with setSyncEvent(). However, if we call it, we cannot properly start
402 // static fast tracks (SoundPool) immediately after stopping.
403 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700404 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
405 int i = __builtin_ctz(thread->mFastTrackAvailMask);
406 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
407 // FIXME This is too eager. We allocate a fast track index before the
408 // fast track becomes active. Since fast tracks are a scarce resource,
409 // this means we are potentially denying other more important fast tracks from
410 // being created. It would be better to allocate the index dynamically.
411 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700412 thread->mFastTrackAvailMask &= ~(1 << i);
413 }
Eric Laurent81784c32012-11-19 14:55:58 -0800414}
415
416AudioFlinger::PlaybackThread::Track::~Track()
417{
418 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700419
420 // The destructor would clear mSharedBuffer,
421 // but it will not push the decremented reference count,
422 // leaving the client's IMemory dangling indefinitely.
423 // This prevents that leak.
424 if (mSharedBuffer != 0) {
425 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700426 }
Eric Laurent81784c32012-11-19 14:55:58 -0800427}
428
Glenn Kasten03003332013-08-06 15:40:54 -0700429status_t AudioFlinger::PlaybackThread::Track::initCheck() const
430{
431 status_t status = TrackBase::initCheck();
432 if (status == NO_ERROR && mName < 0) {
433 status = NO_MEMORY;
434 }
435 return status;
436}
437
Eric Laurent81784c32012-11-19 14:55:58 -0800438void AudioFlinger::PlaybackThread::Track::destroy()
439{
440 // NOTE: destroyTrack_l() can remove a strong reference to this Track
441 // by removing it from mTracks vector, so there is a risk that this Tracks's
442 // destructor is called. As the destructor needs to lock mLock,
443 // we must acquire a strong reference on this Track before locking mLock
444 // here so that the destructor is called only when exiting this function.
445 // On the other hand, as long as Track::destroy() is only called by
446 // TrackHandle destructor, the TrackHandle still holds a strong ref on
447 // this Track with its member mTrack.
448 sp<Track> keep(this);
449 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700450 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800451 sp<ThreadBase> thread = mThread.promote();
452 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800453 Mutex::Autolock _l(thread->mLock);
454 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700455 wasActive = playbackThread->destroyTrack_l(this);
456 }
457 if (isExternalTrack() && !wasActive) {
Eric Laurente83b55d2014-11-14 10:06:21 -0800458 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800459 }
460 }
461}
462
463/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
464{
Marco Nelissenb2208842014-02-07 14:00:50 -0800465 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700466 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800467}
468
Marco Nelissenb2208842014-02-07 14:00:50 -0800469void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800470{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700471 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800472 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800473 sprintf(buffer, " F %2d", mFastIndex);
474 } else if (mName >= AudioMixer::TRACK0) {
475 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800476 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800477 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800478 }
479 track_state state = mState;
480 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800481 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800482 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800483 } else {
484 switch (state) {
485 case IDLE:
486 stateChar = 'I';
487 break;
488 case STOPPING_1:
489 stateChar = 's';
490 break;
491 case STOPPING_2:
492 stateChar = '5';
493 break;
494 case STOPPED:
495 stateChar = 'S';
496 break;
497 case RESUMING:
498 stateChar = 'R';
499 break;
500 case ACTIVE:
501 stateChar = 'A';
502 break;
503 case PAUSING:
504 stateChar = 'p';
505 break;
506 case PAUSED:
507 stateChar = 'P';
508 break;
509 case FLUSHED:
510 stateChar = 'F';
511 break;
512 default:
513 stateChar = '?';
514 break;
515 }
Eric Laurent81784c32012-11-19 14:55:58 -0800516 }
517 char nowInUnderrun;
518 switch (mObservedUnderruns.mBitFields.mMostRecent) {
519 case UNDERRUN_FULL:
520 nowInUnderrun = ' ';
521 break;
522 case UNDERRUN_PARTIAL:
523 nowInUnderrun = '<';
524 break;
525 case UNDERRUN_EMPTY:
526 nowInUnderrun = '*';
527 break;
528 default:
529 nowInUnderrun = '?';
530 break;
531 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000532 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 +0000533 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800534 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800535 (mClient == 0) ? getpid_cached : mClient->pid(),
536 mStreamType,
537 mFormat,
538 mChannelMask,
539 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800540 mFrameCount,
541 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800542 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800543 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700544 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
545 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700546 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000547 mMainBuffer,
548 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700549 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700550 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800551 nowInUnderrun);
552}
553
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800554uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
555 return mAudioTrackServerProxy->getSampleRate();
556}
557
Eric Laurent81784c32012-11-19 14:55:58 -0800558// AudioBufferProvider interface
559status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -0800560 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -0800561{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800562 ServerProxy::Buffer buf;
563 size_t desiredFrames = buffer->frameCount;
564 buf.mFrameCount = desiredFrames;
565 status_t status = mServerProxy->obtainBuffer(&buf);
566 buffer->frameCount = buf.mFrameCount;
567 buffer->raw = buf.mRaw;
568 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700569 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -0800570 } else {
571 mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -0800572 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800573
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800574 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800575}
576
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700577// releaseBuffer() is not overridden
578
579// ExtendedAudioBufferProvider interface
580
Andy Hung27876c02014-09-09 18:07:55 -0700581// framesReady() may return an approximation of the number of frames if called
582// from a different thread than the one calling Proxy->obtainBuffer() and
583// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
584// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800585size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700586 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
587 // Static tracks return zero frames immediately upon stopping (for FastTracks).
588 // The remainder of the buffer is not drained.
589 return 0;
590 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800591 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800592}
593
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700594size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
595{
596 return mAudioTrackServerProxy->framesReleased();
597}
598
Andy Hungb3a486f2015-08-04 15:17:58 -0700599void AudioFlinger::PlaybackThread::Track::onTimestamp(const AudioTimestamp &timestamp)
600{
601 mAudioTrackServerProxy->setTimestamp(timestamp);
602}
603
Eric Laurent81784c32012-11-19 14:55:58 -0800604// Don't call for fast tracks; the framesReady() could result in priority inversion
605bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800606 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
607 return true;
608 }
609
Eric Laurent16498512014-03-17 17:22:08 -0700610 if (isStopping()) {
611 if (framesReady() > 0) {
612 mFillingUpStatus = FS_FILLED;
613 }
Eric Laurent81784c32012-11-19 14:55:58 -0800614 return true;
615 }
616
617 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700618 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800619 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700620 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800621 return true;
622 }
623 return false;
624}
625
Glenn Kasten0f11b512014-01-31 16:18:54 -0800626status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
627 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800628{
629 status_t status = NO_ERROR;
630 ALOGV("start(%d), calling pid %d session %d",
631 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
632
633 sp<ThreadBase> thread = mThread.promote();
634 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700635 if (isOffloaded()) {
636 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
637 Mutex::Autolock _lth(thread->mLock);
638 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700639 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
640 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700641 invalidate();
642 return PERMISSION_DENIED;
643 }
644 }
645 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800646 track_state state = mState;
647 // here the track could be either new, or restarted
648 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800649
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800650 // initial state-stopping. next state-pausing.
651 // What if resume is called ?
652
653 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800654 if (mResumeToStopping) {
655 // happened we need to resume to STOPPING_1
656 mState = TrackBase::STOPPING_1;
657 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
658 } else {
659 mState = TrackBase::RESUMING;
660 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
661 }
Eric Laurent81784c32012-11-19 14:55:58 -0800662 } else {
663 mState = TrackBase::ACTIVE;
664 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
665 }
666
Andy Hunge10393e2015-06-12 13:59:33 -0700667 // states to reset position info for non-offloaded/direct tracks
668 if (!isOffloaded() && !isDirect()
669 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
670 mFrameMap.reset();
671 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800672 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700673 if (isFastTrack()) {
674 // refresh fast track underruns on start because that field is never cleared
675 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
676 // after stop.
677 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
678 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800679 status = playbackThread->addTrack_l(this);
680 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800681 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800682 // restore previous state if start was rejected by policy manager
683 if (status == PERMISSION_DENIED) {
684 mState = state;
685 }
686 }
687 // track was already in the active list, not a problem
688 if (status == ALREADY_EXISTS) {
689 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700690 } else {
691 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
692 // It is usually unsafe to access the server proxy from a binder thread.
693 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
694 // isn't looking at this track yet: we still hold the normal mixer thread lock,
695 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Andy Hunge6fb82a2015-09-09 14:39:02 -0700696 // For static tracks, this is used to acknowledge change in position or loop.
Eric Laurent564d1442015-09-09 12:26:52 -0700697 ServerProxy::Buffer buffer;
698 buffer.mFrameCount = 1;
699 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800700 }
701 } else {
702 status = BAD_VALUE;
703 }
704 return status;
705}
706
707void AudioFlinger::PlaybackThread::Track::stop()
708{
709 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
710 sp<ThreadBase> thread = mThread.promote();
711 if (thread != 0) {
712 Mutex::Autolock _l(thread->mLock);
713 track_state state = mState;
714 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
715 // If the track is not active (PAUSED and buffers full), flush buffers
716 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
717 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
718 reset();
719 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700720 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800721 mState = STOPPED;
722 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800723 // For fast tracks prepareTracks_l() will set state to STOPPING_2
724 // presentation is complete
725 // For an offloaded track this starts a drain and state will
726 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800727 mState = STOPPING_1;
728 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700729 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800730 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
731 playbackThread);
732 }
Eric Laurent81784c32012-11-19 14:55:58 -0800733 }
734}
735
736void AudioFlinger::PlaybackThread::Track::pause()
737{
738 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
739 sp<ThreadBase> thread = mThread.promote();
740 if (thread != 0) {
741 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800742 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
743 switch (mState) {
744 case STOPPING_1:
745 case STOPPING_2:
746 if (!isOffloaded()) {
747 /* nothing to do if track is not offloaded */
748 break;
749 }
750
751 // Offloaded track was draining, we need to carry on draining when resumed
752 mResumeToStopping = true;
753 // fall through...
754 case ACTIVE:
755 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800756 mState = PAUSING;
757 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700758 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800759 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800760
Eric Laurentbfb1b832013-01-07 09:53:42 -0800761 default:
762 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800763 }
764 }
765}
766
767void AudioFlinger::PlaybackThread::Track::flush()
768{
769 ALOGV("flush(%d)", mName);
770 sp<ThreadBase> thread = mThread.promote();
771 if (thread != 0) {
772 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800773 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800774
775 if (isOffloaded()) {
776 // If offloaded we allow flush during any state except terminated
777 // and keep the track active to avoid problems if user is seeking
778 // rapidly and underlying hardware has a significant delay handling
779 // a pause
780 if (isTerminated()) {
781 return;
782 }
783
784 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800785 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800786
787 if (mState == STOPPING_1 || mState == STOPPING_2) {
788 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
789 mState = ACTIVE;
790 }
791
792 if (mState == ACTIVE) {
793 ALOGV("flush called in active state, resetting buffer time out retry count");
794 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
795 }
796
Haynes Mathew George7844f672014-01-15 12:32:55 -0800797 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800798 mResumeToStopping = false;
799 } else {
800 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
801 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
802 return;
803 }
804 // No point remaining in PAUSED state after a flush => go to
805 // FLUSHED state
806 mState = FLUSHED;
807 // do not reset the track if it is still in the process of being stopped or paused.
808 // this will be done by prepareTracks_l() when the track is stopped.
809 // prepareTracks_l() will see mState == FLUSHED, then
810 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800811 if (isDirect()) {
812 mFlushHwPending = true;
813 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800814 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
815 reset();
816 }
Eric Laurent81784c32012-11-19 14:55:58 -0800817 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800818 // Prevent flush being lost if the track is flushed and then resumed
819 // before mixer thread can run. This is important when offloading
820 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700821 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800822 }
823}
824
Haynes Mathew George7844f672014-01-15 12:32:55 -0800825// must be called with thread lock held
826void AudioFlinger::PlaybackThread::Track::flushAck()
827{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800828 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800829 return;
830
831 mFlushHwPending = false;
832}
833
Eric Laurent81784c32012-11-19 14:55:58 -0800834void AudioFlinger::PlaybackThread::Track::reset()
835{
836 // Do not reset twice to avoid discarding data written just after a flush and before
837 // the audioflinger thread detects the track is stopped.
838 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800839 // Force underrun condition to avoid false underrun callback until first data is
840 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700841 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800842 mFillingUpStatus = FS_FILLING;
843 mResetDone = true;
844 if (mState == FLUSHED) {
845 mState = IDLE;
846 }
847 }
848}
849
Eric Laurentbfb1b832013-01-07 09:53:42 -0800850status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
851{
852 sp<ThreadBase> thread = mThread.promote();
853 if (thread == 0) {
854 ALOGE("thread is dead");
855 return FAILED_TRANSACTION;
856 } else if ((thread->type() == ThreadBase::DIRECT) ||
857 (thread->type() == ThreadBase::OFFLOAD)) {
858 return thread->setParameters(keyValuePairs);
859 } else {
860 return PERMISSION_DENIED;
861 }
862}
863
Glenn Kasten573d80a2013-08-26 09:36:23 -0700864status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
865{
Andy Hungb3a486f2015-08-04 15:17:58 -0700866 // FastTrack timestamps are read through SSQ
Glenn Kastenfe346c72013-08-30 13:28:22 -0700867 if (isFastTrack()) {
868 return INVALID_OPERATION;
869 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700870 sp<ThreadBase> thread = mThread.promote();
871 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700872 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700873 }
Phil Burk6140c792015-03-19 14:30:21 -0700874
Glenn Kasten573d80a2013-08-26 09:36:23 -0700875 Mutex::Autolock _l(thread->mLock);
876 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Phil Burk6140c792015-03-19 14:30:21 -0700877
Andy Hunge10393e2015-06-12 13:59:33 -0700878 if (isOffloaded() || isDirect()) {
879 return playbackThread->getTimestamp_l(timestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700880 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700881
Andy Hunge10393e2015-06-12 13:59:33 -0700882 if (!mFrameMap.hasData()) {
883 // WOULD_BLOCK is consistent with AudioTrack::getTimestamp() in the
884 // FLUSHED and STOPPED state. We should only return INVALID_OPERATION
885 // when this method is not permitted due to configuration or device.
886 return WOULD_BLOCK;
887 }
888 status_t result = OK;
889 if (!mSinkTimestampValid) { // if no sink position, try to fetch again
890 result = playbackThread->getTimestamp_l(mSinkTimestamp);
891 }
892
893 if (result == OK) {
894 // Lookup the track frame corresponding to the sink frame position.
895 timestamp.mPosition = mFrameMap.findX(mSinkTimestamp.mPosition);
896 timestamp.mTime = mSinkTimestamp.mTime;
897 // ALOGD("track (server-side) timestamp: mPosition(%u) mTime(%llu)",
898 // timestamp.mPosition, TIME_TO_NANOS(timestamp.mTime));
899 }
900 // (Possible) FIXME: mSinkTimestamp is updated only when the track is on
901 // the Thread active list. If the track is no longer on the thread active
902 // list should we use current time?
Phil Burk6140c792015-03-19 14:30:21 -0700903 return result;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700904}
905
Eric Laurent81784c32012-11-19 14:55:58 -0800906status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
907{
908 status_t status = DEAD_OBJECT;
909 sp<ThreadBase> thread = mThread.promote();
910 if (thread != 0) {
911 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
912 sp<AudioFlinger> af = mClient->audioFlinger();
913
914 Mutex::Autolock _l(af->mLock);
915
916 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
917
918 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
919 Mutex::Autolock _dl(playbackThread->mLock);
920 Mutex::Autolock _sl(srcThread->mLock);
921 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
922 if (chain == 0) {
923 return INVALID_OPERATION;
924 }
925
926 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
927 if (effect == 0) {
928 return INVALID_OPERATION;
929 }
930 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700931 status = playbackThread->addEffect_l(effect);
932 if (status != NO_ERROR) {
933 srcThread->addEffect_l(effect);
934 return INVALID_OPERATION;
935 }
Eric Laurent81784c32012-11-19 14:55:58 -0800936 // removeEffect_l() has stopped the effect if it was active so it must be restarted
937 if (effect->state() == EffectModule::ACTIVE ||
938 effect->state() == EffectModule::STOPPING) {
939 effect->start();
940 }
941
942 sp<EffectChain> dstChain = effect->chain().promote();
943 if (dstChain == 0) {
944 srcThread->addEffect_l(effect);
945 return INVALID_OPERATION;
946 }
947 AudioSystem::unregisterEffect(effect->id());
948 AudioSystem::registerEffect(&effect->desc(),
949 srcThread->id(),
950 dstChain->strategy(),
951 AUDIO_SESSION_OUTPUT_MIX,
952 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700953 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800954 }
955 status = playbackThread->attachAuxEffect(this, EffectId);
956 }
957 return status;
958}
959
960void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
961{
962 mAuxEffectId = EffectId;
963 mAuxBuffer = buffer;
964}
965
966bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
967 size_t audioHalFrames)
968{
969 // a track is considered presented when the total number of frames written to audio HAL
970 // corresponds to the number of frames written when presentationComplete() is called for the
971 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800972 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
973 // to detect when all frames have been played. In this case framesWritten isn't
974 // useful because it doesn't always reflect whether there is data in the h/w
975 // buffers, particularly if a track has been paused and resumed during draining
976 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
977 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800978 if (mPresentationCompleteFrames == 0) {
979 mPresentationCompleteFrames = framesWritten + audioHalFrames;
980 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
981 mPresentationCompleteFrames, audioHalFrames);
982 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800983
984 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800985 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800986 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800987 return true;
988 }
989 return false;
990}
991
992void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
993{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700994 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -0800995 if (mSyncEvents[i]->type() == type) {
996 mSyncEvents[i]->trigger();
997 mSyncEvents.removeAt(i);
998 i--;
999 }
1000 }
1001}
1002
1003// implement VolumeBufferProvider interface
1004
Glenn Kastenc56f3422014-03-21 17:53:17 -07001005gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001006{
1007 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1008 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001009 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1010 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1011 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001012 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001013 if (vl > GAIN_FLOAT_UNITY) {
1014 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001015 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001016 if (vr > GAIN_FLOAT_UNITY) {
1017 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001018 }
1019 // now apply the cached master volume and stream type volume;
1020 // this is trusted but lacks any synchronization or barrier so may be stale
1021 float v = mCachedVolume;
1022 vl *= v;
1023 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001024 // re-combine into packed minifloat
1025 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001026 // FIXME look at mute, pause, and stop flags
1027 return vlr;
1028}
1029
1030status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1031{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001032 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001033 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1034 (mState == STOPPED)))) {
1035 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1036 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1037 event->cancel();
1038 return INVALID_OPERATION;
1039 }
1040 (void) TrackBase::setSyncEvent(event);
1041 return NO_ERROR;
1042}
1043
Glenn Kasten5736c352012-12-04 12:12:34 -08001044void AudioFlinger::PlaybackThread::Track::invalidate()
1045{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001046 // FIXME should use proxy, and needs work
1047 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001048 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001049 android_atomic_release_store(0x40000000, &cblk->mFutex);
1050 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001051 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001052 mIsInvalid = true;
1053}
1054
Eric Laurent59fe0102013-09-27 18:48:26 -07001055void AudioFlinger::PlaybackThread::Track::signal()
1056{
1057 sp<ThreadBase> thread = mThread.promote();
1058 if (thread != 0) {
1059 PlaybackThread *t = (PlaybackThread *)thread.get();
1060 Mutex::Autolock _l(t->mLock);
1061 t->broadcast_l();
1062 }
1063}
1064
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001065//To be called with thread lock held
1066bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1067
1068 if (mState == RESUMING)
1069 return true;
1070 /* Resume is pending if track was stopping before pause was called */
1071 if (mState == STOPPING_1 &&
1072 mResumeToStopping)
1073 return true;
1074
1075 return false;
1076}
1077
1078//To be called with thread lock held
1079void AudioFlinger::PlaybackThread::Track::resumeAck() {
1080
1081
1082 if (mState == RESUMING)
1083 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001084
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001085 // Other possibility of pending resume is stopping_1 state
1086 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001087 // drain being called.
1088 if (mState == STOPPING_1) {
1089 mResumeToStopping = false;
1090 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001091}
Andy Hunge10393e2015-06-12 13:59:33 -07001092
1093//To be called with thread lock held
1094void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
1095 uint32_t trackFramesReleased, uint32_t sinkFramesWritten, AudioTimestamp *timeStamp) {
1096 mFrameMap.push(trackFramesReleased, sinkFramesWritten);
1097 if (timeStamp == NULL) {
1098 mSinkTimestampValid = false;
1099 } else {
1100 mSinkTimestampValid = true;
1101 mSinkTimestamp = *timeStamp;
1102 }
1103}
1104
Eric Laurent81784c32012-11-19 14:55:58 -08001105// ----------------------------------------------------------------------------
1106
Eric Laurent81784c32012-11-19 14:55:58 -08001107AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1108 PlaybackThread *playbackThread,
1109 DuplicatingThread *sourceThread,
1110 uint32_t sampleRate,
1111 audio_format_t format,
1112 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001113 size_t frameCount,
1114 int uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001115 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1116 sampleRate, format, channelMask, frameCount,
1117 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001118 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001119{
1120
1121 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001122 mOutBuffer.frameCount = 0;
1123 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001124 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001125 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001126 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001127 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001128 // since client and server are in the same process,
1129 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001130 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1131 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001132 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001133 mClientProxy->setSendLevel(0.0);
1134 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001135 } else {
1136 ALOGW("Error creating output track on thread %p", playbackThread);
1137 }
1138}
1139
1140AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1141{
1142 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001143 delete mClientProxy;
1144 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001145}
1146
1147status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1148 int triggerSession)
1149{
1150 status_t status = Track::start(event, triggerSession);
1151 if (status != NO_ERROR) {
1152 return status;
1153 }
1154
1155 mActive = true;
1156 mRetryCount = 127;
1157 return status;
1158}
1159
1160void AudioFlinger::PlaybackThread::OutputTrack::stop()
1161{
1162 Track::stop();
1163 clearBufferQueue();
1164 mOutBuffer.frameCount = 0;
1165 mActive = false;
1166}
1167
Andy Hungc25b84a2015-01-14 19:04:10 -08001168bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001169{
1170 Buffer *pInBuffer;
1171 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001172 bool outputBufferFull = false;
1173 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001174 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001175
1176 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1177
1178 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001179 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001180 }
1181
1182 while (waitTimeLeftMs) {
1183 // First write pending buffers, then new data
1184 if (mBufferQueue.size()) {
1185 pInBuffer = mBufferQueue.itemAt(0);
1186 } else {
1187 pInBuffer = &inBuffer;
1188 }
1189
1190 if (pInBuffer->frameCount == 0) {
1191 break;
1192 }
1193
1194 if (mOutBuffer.frameCount == 0) {
1195 mOutBuffer.frameCount = pInBuffer->frameCount;
1196 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001197 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1198 if (status != NO_ERROR) {
1199 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1200 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001201 outputBufferFull = true;
1202 break;
1203 }
1204 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1205 if (waitTimeLeftMs >= waitTimeMs) {
1206 waitTimeLeftMs -= waitTimeMs;
1207 } else {
1208 waitTimeLeftMs = 0;
1209 }
1210 }
1211
1212 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1213 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001214 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001215 Proxy::Buffer buf;
1216 buf.mFrameCount = outFrames;
1217 buf.mRaw = NULL;
1218 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001219 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001220 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001221 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001222 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001223
1224 if (pInBuffer->frameCount == 0) {
1225 if (mBufferQueue.size()) {
1226 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001227 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001228 delete pInBuffer;
1229 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1230 mThread.unsafe_get(), mBufferQueue.size());
1231 } else {
1232 break;
1233 }
1234 }
1235 }
1236
1237 // If we could not write all frames, allocate a buffer and queue it for next time.
1238 if (inBuffer.frameCount) {
1239 sp<ThreadBase> thread = mThread.promote();
1240 if (thread != 0 && !thread->standby()) {
1241 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1242 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001243 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001244 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001245 pInBuffer->raw = pInBuffer->mBuffer;
1246 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001247 mBufferQueue.add(pInBuffer);
1248 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1249 mThread.unsafe_get(), mBufferQueue.size());
1250 } else {
1251 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1252 mThread.unsafe_get(), this);
1253 }
1254 }
1255 }
1256
Andy Hungc25b84a2015-01-14 19:04:10 -08001257 // Calling write() with a 0 length buffer means that no more data will be written:
1258 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1259 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1260 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001261 }
1262
1263 return outputBufferFull;
1264}
1265
1266status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1267 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1268{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001269 ClientProxy::Buffer buf;
1270 buf.mFrameCount = buffer->frameCount;
1271 struct timespec timeout;
1272 timeout.tv_sec = waitTimeMs / 1000;
1273 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1274 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1275 buffer->frameCount = buf.mFrameCount;
1276 buffer->raw = buf.mRaw;
1277 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001278}
1279
Eric Laurent81784c32012-11-19 14:55:58 -08001280void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1281{
1282 size_t size = mBufferQueue.size();
1283
1284 for (size_t i = 0; i < size; i++) {
1285 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001286 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001287 delete pBuffer;
1288 }
1289 mBufferQueue.clear();
1290}
1291
1292
Eric Laurent83b88082014-06-20 18:31:16 -07001293AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001294 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001295 uint32_t sampleRate,
1296 audio_channel_mask_t channelMask,
1297 audio_format_t format,
1298 size_t frameCount,
1299 void *buffer,
1300 IAudioFlinger::track_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001301 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001302 sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001303 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1304 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1305{
1306 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1307 playbackThread->sampleRate();
1308 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1309 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1310
1311 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1312 this, sampleRate,
1313 (int)mPeerTimeout.tv_sec,
1314 (int)(mPeerTimeout.tv_nsec / 1000000));
1315}
1316
1317AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1318{
1319}
1320
1321// AudioBufferProvider interface
1322status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001323 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001324{
1325 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1326 Proxy::Buffer buf;
1327 buf.mFrameCount = buffer->frameCount;
1328 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1329 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001330 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001331 if (buf.mFrameCount == 0) {
1332 return WOULD_BLOCK;
1333 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001334 status = Track::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001335 return status;
1336}
1337
1338void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1339{
1340 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1341 Proxy::Buffer buf;
1342 buf.mFrameCount = buffer->frameCount;
1343 buf.mRaw = buffer->raw;
1344 mPeerProxy->releaseBuffer(&buf);
1345 TrackBase::releaseBuffer(buffer);
1346}
1347
1348status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1349 const struct timespec *timeOut)
1350{
1351 return mProxy->obtainBuffer(buffer, timeOut);
1352}
1353
1354void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1355{
1356 mProxy->releaseBuffer(buffer);
1357 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1358 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1359 start();
1360 }
1361 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1362}
1363
Eric Laurent81784c32012-11-19 14:55:58 -08001364// ----------------------------------------------------------------------------
1365// Record
1366// ----------------------------------------------------------------------------
1367
1368AudioFlinger::RecordHandle::RecordHandle(
1369 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1370 : BnAudioRecord(),
1371 mRecordTrack(recordTrack)
1372{
1373}
1374
1375AudioFlinger::RecordHandle::~RecordHandle() {
1376 stop_nonvirtual();
1377 mRecordTrack->destroy();
1378}
1379
Eric Laurent81784c32012-11-19 14:55:58 -08001380status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1381 int triggerSession) {
1382 ALOGV("RecordHandle::start()");
1383 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1384}
1385
1386void AudioFlinger::RecordHandle::stop() {
1387 stop_nonvirtual();
1388}
1389
1390void AudioFlinger::RecordHandle::stop_nonvirtual() {
1391 ALOGV("RecordHandle::stop()");
1392 mRecordTrack->stop();
1393}
1394
1395status_t AudioFlinger::RecordHandle::onTransact(
1396 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1397{
1398 return BnAudioRecord::onTransact(code, data, reply, flags);
1399}
1400
1401// ----------------------------------------------------------------------------
1402
Glenn Kasten05997e22014-03-13 15:08:33 -07001403// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001404AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1405 RecordThread *thread,
1406 const sp<Client>& client,
1407 uint32_t sampleRate,
1408 audio_format_t format,
1409 audio_channel_mask_t channelMask,
1410 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001411 void *buffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001412 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001413 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -07001414 IAudioFlinger::track_flags_t flags,
1415 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001416 : TrackBase(thread, client, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001417 channelMask, frameCount, buffer, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001418 flags, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001419 (type == TYPE_DEFAULT) ?
1420 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1421 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1422 type),
Andy Hung97a893e2015-03-29 01:03:07 -07001423 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001424 mFramesToDrop(0),
1425 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
1426 mRecordBufferConverter(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001427{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001428 if (mCblk == NULL) {
1429 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001430 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001431
Andy Hung97a893e2015-03-29 01:03:07 -07001432 mRecordBufferConverter = new RecordBufferConverter(
1433 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1434 channelMask, format, sampleRate);
1435 // Check if the RecordBufferConverter construction was successful.
1436 // If not, don't continue with construction.
1437 //
1438 // NOTE: It would be extremely rare that the record track cannot be created
1439 // for the current device, but a pending or future device change would make
1440 // the record track configuration valid.
1441 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1442 ALOGE("RecordTrack unable to create record buffer converter");
1443 return;
1444 }
1445
Andy Hung3f0c9022016-01-15 17:49:46 -08001446 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1447 mFrameSize, !isExternalTrack());
1448 mServerProxy = mAudioRecordServerProxy;
1449
Andy Hung97a893e2015-03-29 01:03:07 -07001450 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001451
1452 if (flags & IAudioFlinger::TRACK_FAST) {
1453 ALOG_ASSERT(thread->mFastTrackAvail);
1454 thread->mFastTrackAvail = false;
1455 }
Eric Laurent81784c32012-11-19 14:55:58 -08001456}
1457
1458AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1459{
1460 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001461 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001462 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001463}
1464
Andy Hung97a893e2015-03-29 01:03:07 -07001465status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1466{
1467 status_t status = TrackBase::initCheck();
1468 if (status == NO_ERROR && mServerProxy == 0) {
1469 status = BAD_VALUE;
1470 }
1471 return status;
1472}
1473
Eric Laurent81784c32012-11-19 14:55:58 -08001474// AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001475status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08001476{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001477 ServerProxy::Buffer buf;
1478 buf.mFrameCount = buffer->frameCount;
1479 status_t status = mServerProxy->obtainBuffer(&buf);
1480 buffer->frameCount = buf.mFrameCount;
1481 buffer->raw = buf.mRaw;
1482 if (buf.mFrameCount == 0) {
1483 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001484 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001485 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001486 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001487}
1488
1489status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1490 int triggerSession)
1491{
1492 sp<ThreadBase> thread = mThread.promote();
1493 if (thread != 0) {
1494 RecordThread *recordThread = (RecordThread *)thread.get();
1495 return recordThread->start(this, event, triggerSession);
1496 } else {
1497 return BAD_VALUE;
1498 }
1499}
1500
1501void AudioFlinger::RecordThread::RecordTrack::stop()
1502{
1503 sp<ThreadBase> thread = mThread.promote();
1504 if (thread != 0) {
1505 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07001506 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07001507 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001508 }
1509 }
1510}
1511
1512void AudioFlinger::RecordThread::RecordTrack::destroy()
1513{
1514 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1515 sp<RecordTrack> keep(this);
1516 {
Eric Laurentaaa44472014-09-12 17:41:50 -07001517 if (isExternalTrack()) {
1518 if (mState == ACTIVE || mState == RESUMING) {
1519 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
1520 }
1521 AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
1522 }
Eric Laurent81784c32012-11-19 14:55:58 -08001523 sp<ThreadBase> thread = mThread.promote();
1524 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001525 Mutex::Autolock _l(thread->mLock);
1526 RecordThread *recordThread = (RecordThread *) thread.get();
1527 recordThread->destroyTrack_l(this);
1528 }
1529 }
1530}
1531
Eric Laurent9a54bc22013-09-09 09:08:44 -07001532void AudioFlinger::RecordThread::RecordTrack::invalidate()
1533{
1534 // FIXME should use proxy, and needs work
1535 audio_track_cblk_t* cblk = mCblk;
1536 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1537 android_atomic_release_store(0x40000000, &cblk->mFutex);
1538 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001539 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001540}
1541
Eric Laurent81784c32012-11-19 14:55:58 -08001542
1543/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1544{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001545 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001546}
1547
Marco Nelissenb2208842014-02-07 14:00:50 -08001548void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001549{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001550 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001551 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001552 (mClient == 0) ? getpid_cached : mClient->pid(),
1553 mFormat,
1554 mChannelMask,
1555 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001556 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001557 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001558 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07001559 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001560
Eric Laurent81784c32012-11-19 14:55:58 -08001561}
1562
Glenn Kasten25f4aa82014-02-07 10:50:43 -08001563void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1564{
1565 if (event == mSyncStartEvent) {
1566 ssize_t framesToDrop = 0;
1567 sp<ThreadBase> threadBase = mThread.promote();
1568 if (threadBase != 0) {
1569 // TODO: use actual buffer filling status instead of 2 buffers when info is available
1570 // from audio HAL
1571 framesToDrop = threadBase->mFrameCount * 2;
1572 }
1573 mFramesToDrop = framesToDrop;
1574 }
1575}
1576
1577void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1578{
1579 if (mSyncStartEvent != 0) {
1580 mSyncStartEvent->cancel();
1581 mSyncStartEvent.clear();
1582 }
1583 mFramesToDrop = 0;
1584}
1585
Andy Hung3f0c9022016-01-15 17:49:46 -08001586void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1587 int64_t trackFramesReleased, int64_t sourceFramesRead,
1588 uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1589{
1590 ExtendedTimestamp local = timestamp;
1591
1592 // Convert HAL frames to server-side track frames at track sample rate.
1593 // We use trackFramesReleased and sourceFramesRead as an anchor point.
1594 for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1595 if (local.mTimeNs[i] != 0) {
1596 const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1597 const int64_t relativeTrackFrames = relativeServerFrames
1598 * mSampleRate / halSampleRate; // TODO: potential computation overflow
1599 local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1600 }
1601 }
1602 mAudioRecordServerProxy->setExtendedTimestamp(local);
1603}
Eric Laurent83b88082014-06-20 18:31:16 -07001604
1605AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1606 uint32_t sampleRate,
1607 audio_channel_mask_t channelMask,
1608 audio_format_t format,
1609 size_t frameCount,
1610 void *buffer,
1611 IAudioFlinger::track_flags_t flags)
1612 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
1613 buffer, 0, getuid(), flags, TYPE_PATCH),
1614 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1615{
1616 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1617 recordThread->sampleRate();
1618 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1619 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1620
1621 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1622 this, sampleRate,
1623 (int)mPeerTimeout.tv_sec,
1624 (int)(mPeerTimeout.tv_nsec / 1000000));
1625}
1626
1627AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1628{
1629}
1630
1631// AudioBufferProvider interface
1632status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08001633 AudioBufferProvider::Buffer* buffer)
Eric Laurent83b88082014-06-20 18:31:16 -07001634{
1635 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1636 Proxy::Buffer buf;
1637 buf.mFrameCount = buffer->frameCount;
1638 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1639 ALOGV_IF(status != NO_ERROR,
1640 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001641 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001642 if (buf.mFrameCount == 0) {
1643 return WOULD_BLOCK;
1644 }
Glenn Kastend79072e2016-01-06 08:41:20 -08001645 status = RecordTrack::getNextBuffer(buffer);
Eric Laurent83b88082014-06-20 18:31:16 -07001646 return status;
1647}
1648
1649void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1650{
1651 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1652 Proxy::Buffer buf;
1653 buf.mFrameCount = buffer->frameCount;
1654 buf.mRaw = buffer->raw;
1655 mPeerProxy->releaseBuffer(&buf);
1656 TrackBase::releaseBuffer(buffer);
1657}
1658
1659status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1660 const struct timespec *timeOut)
1661{
1662 return mProxy->obtainBuffer(buffer, timeOut);
1663}
1664
1665void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1666{
1667 mProxy->releaseBuffer(buffer);
1668}
1669
Glenn Kasten63238ef2015-03-02 15:50:29 -08001670} // namespace android