blob: b3fac0bd1d2d8be0ce4dc5027c1b6d1d52ff61b7 [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
30#include <common_time/cc_helper.h>
31#include <common_time/local_clock.h>
32
33#include "AudioMixer.h"
34#include "AudioFlinger.h"
35#include "ServiceUtilities.h"
36
Glenn Kastenda6ef132013-01-10 12:31:01 -080037#include <media/nbaio/Pipe.h>
38#include <media/nbaio/PipeReader.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070039#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080040
Eric Laurent81784c32012-11-19 14:55:58 -080041// ----------------------------------------------------------------------------
42
43// Note: the following macro is used for extremely verbose logging message. In
44// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
45// 0; but one side effect of this is to turn all LOGV's as well. Some messages
46// are so verbose that we want to suppress them even when we have ALOG_ASSERT
47// turned on. Do not uncomment the #def below unless you really know what you
48// are doing and want to see all of the extremely verbose messages.
49//#define VERY_VERY_VERBOSE_LOGGING
50#ifdef VERY_VERY_VERBOSE_LOGGING
51#define ALOGVV ALOGV
52#else
53#define ALOGVV(a...) do { } while(0)
54#endif
55
56namespace android {
57
58// ----------------------------------------------------------------------------
59// TrackBase
60// ----------------------------------------------------------------------------
61
Glenn Kastenda6ef132013-01-10 12:31:01 -080062static volatile int32_t nextTrackId = 55;
63
Eric Laurent81784c32012-11-19 14:55:58 -080064// TrackBase constructor must be called with AudioFlinger::mLock held
65AudioFlinger::ThreadBase::TrackBase::TrackBase(
66 ThreadBase *thread,
67 const sp<Client>& client,
68 uint32_t sampleRate,
69 audio_format_t format,
70 audio_channel_mask_t channelMask,
71 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070072 void *buffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080073 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080074 int clientUid,
Glenn Kasten755b0a62014-05-13 11:30:28 -070075 IAudioFlinger::track_flags_t flags,
Glenn Kastend776ac62014-05-07 09:16:09 -070076 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070077 alloc_type alloc,
78 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -080079 : RefBase(),
80 mThread(thread),
81 mClient(client),
82 mCblk(NULL),
83 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080084 mState(IDLE),
85 mSampleRate(sampleRate),
86 mFormat(format),
87 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070088 mChannelCount(isOut ?
89 audio_channel_count_from_out_mask(channelMask) :
90 audio_channel_count_from_in_mask(channelMask)),
Eric Laurent81784c32012-11-19 14:55:58 -080091 mFrameSize(audio_is_linear_pcm(format) ?
92 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
93 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080094 mSessionId(sessionId),
Glenn Kasten755b0a62014-05-13 11:30:28 -070095 mFlags(flags),
Glenn Kastene3aa6592012-12-04 12:22:46 -080096 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080097 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080098 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070099 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -0700100 mType(type),
101 mThreadIoHandle(thread->id())
Eric Laurent81784c32012-11-19 14:55:58 -0800102{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800103 // if the caller is us, trust the specified uid
104 if (IPCThreadState::self()->getCallingPid() != getpid_cached || clientUid == -1) {
105 int newclientUid = IPCThreadState::self()->getCallingUid();
106 if (clientUid != -1 && clientUid != newclientUid) {
107 ALOGW("uid %d tried to pass itself off as %d", newclientUid, clientUid);
108 }
109 clientUid = newclientUid;
110 }
111 // clientUid contains the uid of the app that is responsible for this track, so we can blame
112 // battery usage on it.
113 mUid = clientUid;
114
Eric Laurent81784c32012-11-19 14:55:58 -0800115 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
116 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700117 size_t bufferSize = (buffer == NULL ? roundup(frameCount) : frameCount) * mFrameSize;
118 if (buffer == NULL && alloc == ALLOC_CBLK) {
Eric Laurent81784c32012-11-19 14:55:58 -0800119 size += bufferSize;
120 }
121
122 if (client != 0) {
123 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700124 if (mCblkMemory == 0 ||
125 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800126 ALOGE("not enough memory for AudioTrack size=%u", size);
127 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700128 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800129 return;
130 }
131 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800132 // this syntax avoids calling the audio_track_cblk_t constructor twice
133 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800134 // assume mCblk != NULL
135 }
136
137 // construct the shared structure in-place.
138 if (mCblk != NULL) {
139 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700140 switch (alloc) {
141 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700142 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
143 if (roHeap == 0 ||
144 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
145 (mBuffer = mBufferMemory->pointer()) == NULL) {
146 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
147 if (roHeap != 0) {
148 roHeap->dump("buffer");
149 }
150 mCblkMemory.clear();
151 mBufferMemory.clear();
152 return;
153 }
Eric Laurent81784c32012-11-19 14:55:58 -0800154 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700155 } break;
156 case ALLOC_PIPE:
157 mBufferMemory = thread->pipeMemory();
158 // mBuffer is the virtual address as seen from current process (mediaserver),
159 // and should normally be coming from mBufferMemory->pointer().
160 // However in this case the TrackBase does not reference the buffer directly.
161 // It should references the buffer via the pipe.
162 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
163 mBuffer = NULL;
164 break;
165 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700166 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700167 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700168 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
169 memset(mBuffer, 0, bufferSize);
170 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700171 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800172#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700173 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800174#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700175 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700176 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700177 case ALLOC_LOCAL:
178 mBuffer = calloc(1, bufferSize);
179 break;
180 case ALLOC_NONE:
181 mBuffer = buffer;
182 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800183 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800184
Glenn Kasten46909e72013-02-26 09:20:22 -0800185#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800186 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700187 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800188 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800189 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
190 size_t numCounterOffers = 0;
191 const NBAIO_Format offers[1] = {pipeFormat};
192 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
193 ALOG_ASSERT(index == 0);
194 PipeReader *pipeReader = new PipeReader(*pipe);
195 numCounterOffers = 0;
196 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
197 ALOG_ASSERT(index == 0);
198 mTeeSink = pipe;
199 mTeeSource = pipeReader;
200 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800201 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800202#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800203
Eric Laurent81784c32012-11-19 14:55:58 -0800204 }
205}
206
Eric Laurent83b88082014-06-20 18:31:16 -0700207status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
208{
209 status_t status;
210 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
211 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
212 } else {
213 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
214 }
215 return status;
216}
217
Eric Laurent81784c32012-11-19 14:55:58 -0800218AudioFlinger::ThreadBase::TrackBase::~TrackBase()
219{
Glenn Kasten46909e72013-02-26 09:20:22 -0800220#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800221 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800222#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800223 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
224 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800225 if (mCblk != NULL) {
226 if (mClient == 0) {
227 delete mCblk;
228 } else {
229 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
230 }
231 }
232 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
233 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700234 // Client destructor must run with AudioFlinger client mutex locked
235 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800236 // If the client's reference count drops to zero, the associated destructor
237 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
238 // relying on the automatic clear() at end of scope.
239 mClient.clear();
240 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700241 // flush the binder command buffer
242 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800243}
244
245// AudioBufferProvider interface
246// getNextBuffer() = 0;
247// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
248void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
249{
Glenn Kasten46909e72013-02-26 09:20:22 -0800250#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800251 if (mTeeSink != 0) {
252 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
253 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800254#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800255
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800256 ServerProxy::Buffer buf;
257 buf.mFrameCount = buffer->frameCount;
258 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800259 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800260 buffer->raw = NULL;
261 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800262}
263
Eric Laurent81784c32012-11-19 14:55:58 -0800264status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
265{
266 mSyncEvents.add(event);
267 return NO_ERROR;
268}
269
270// ----------------------------------------------------------------------------
271// Playback
272// ----------------------------------------------------------------------------
273
274AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
275 : BnAudioTrack(),
276 mTrack(track)
277{
278}
279
280AudioFlinger::TrackHandle::~TrackHandle() {
281 // just stop the track on deletion, associated resources
282 // will be freed from the main thread once all pending buffers have
283 // been played. Unless it's not in the active track list, in which
284 // case we free everything now...
285 mTrack->destroy();
286}
287
288sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
289 return mTrack->getCblk();
290}
291
292status_t AudioFlinger::TrackHandle::start() {
293 return mTrack->start();
294}
295
296void AudioFlinger::TrackHandle::stop() {
297 mTrack->stop();
298}
299
300void AudioFlinger::TrackHandle::flush() {
301 mTrack->flush();
302}
303
Eric Laurent81784c32012-11-19 14:55:58 -0800304void AudioFlinger::TrackHandle::pause() {
305 mTrack->pause();
306}
307
308status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
309{
310 return mTrack->attachAuxEffect(EffectId);
311}
312
313status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
314 sp<IMemory>* buffer) {
315 if (!mTrack->isTimedTrack())
316 return INVALID_OPERATION;
317
318 PlaybackThread::TimedTrack* tt =
319 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
320 return tt->allocateTimedBuffer(size, buffer);
321}
322
323status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
324 int64_t pts) {
325 if (!mTrack->isTimedTrack())
326 return INVALID_OPERATION;
327
Glenn Kasten663c2242013-09-24 11:52:37 -0700328 if (buffer == 0 || buffer->pointer() == NULL) {
329 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
330 return BAD_VALUE;
331 }
332
Eric Laurent81784c32012-11-19 14:55:58 -0800333 PlaybackThread::TimedTrack* tt =
334 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
335 return tt->queueTimedBuffer(buffer, pts);
336}
337
338status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
339 const LinearTransform& xform, int target) {
340
341 if (!mTrack->isTimedTrack())
342 return INVALID_OPERATION;
343
344 PlaybackThread::TimedTrack* tt =
345 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
346 return tt->setMediaTimeTransform(
347 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
348}
349
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700350status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
351 return mTrack->setParameters(keyValuePairs);
352}
353
Glenn Kasten53cec222013-08-29 09:01:02 -0700354status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
355{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700356 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700357}
358
Eric Laurent59fe0102013-09-27 18:48:26 -0700359
360void AudioFlinger::TrackHandle::signal()
361{
362 return mTrack->signal();
363}
364
Eric Laurent81784c32012-11-19 14:55:58 -0800365status_t AudioFlinger::TrackHandle::onTransact(
366 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
367{
368 return BnAudioTrack::onTransact(code, data, reply, flags);
369}
370
371// ----------------------------------------------------------------------------
372
373// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
374AudioFlinger::PlaybackThread::Track::Track(
375 PlaybackThread *thread,
376 const sp<Client>& client,
377 audio_stream_type_t streamType,
378 uint32_t sampleRate,
379 audio_format_t format,
380 audio_channel_mask_t channelMask,
381 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700382 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800383 const sp<IMemory>& sharedBuffer,
384 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800385 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -0700386 IAudioFlinger::track_flags_t flags,
387 track_type type)
388 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
389 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
390 sessionId, uid, flags, true /*isOut*/,
391 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
392 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800393 mFillingUpStatus(FS_INVALID),
394 // mRetryCount initialized later when needed
395 mSharedBuffer(sharedBuffer),
396 mStreamType(streamType),
397 mName(-1), // see note below
398 mMainBuffer(thread->mixBuffer()),
399 mAuxBuffer(NULL),
400 mAuxEffectId(0), mHasVolumeController(false),
401 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800402 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800403 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800404 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800405 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800406 mResumeToStopping(false),
Phil Burk1b420972015-04-22 10:52:21 -0700407 mFlushHwPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800408{
Eric Laurent83b88082014-06-20 18:31:16 -0700409 // client == 0 implies sharedBuffer == 0
410 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
411
412 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
413 sharedBuffer->size());
414
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700415 if (mCblk == NULL) {
416 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800417 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700418
419 if (sharedBuffer == 0) {
420 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700421 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700422 } else {
423 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
424 mFrameSize);
425 }
426 mServerProxy = mAudioTrackServerProxy;
427
Glenn Kastenc263ca02014-06-04 20:31:46 -0700428 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700429 if (mName < 0) {
430 ALOGE("no more track names available");
431 return;
432 }
433 // only allocate a fast track index if we were able to allocate a normal track name
434 if (flags & IAudioFlinger::TRACK_FAST) {
Andy Hunga5427822015-09-11 16:15:35 -0700435 // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
436 // race with setSyncEvent(). However, if we call it, we cannot properly start
437 // static fast tracks (SoundPool) immediately after stopping.
438 //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700439 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
440 int i = __builtin_ctz(thread->mFastTrackAvailMask);
441 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
442 // FIXME This is too eager. We allocate a fast track index before the
443 // fast track becomes active. Since fast tracks are a scarce resource,
444 // this means we are potentially denying other more important fast tracks from
445 // being created. It would be better to allocate the index dynamically.
446 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700447 thread->mFastTrackAvailMask &= ~(1 << i);
448 }
Eric Laurent81784c32012-11-19 14:55:58 -0800449}
450
451AudioFlinger::PlaybackThread::Track::~Track()
452{
453 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700454
455 // The destructor would clear mSharedBuffer,
456 // but it will not push the decremented reference count,
457 // leaving the client's IMemory dangling indefinitely.
458 // This prevents that leak.
459 if (mSharedBuffer != 0) {
460 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700461 }
Eric Laurent81784c32012-11-19 14:55:58 -0800462}
463
Glenn Kasten03003332013-08-06 15:40:54 -0700464status_t AudioFlinger::PlaybackThread::Track::initCheck() const
465{
466 status_t status = TrackBase::initCheck();
467 if (status == NO_ERROR && mName < 0) {
468 status = NO_MEMORY;
469 }
470 return status;
471}
472
Eric Laurent81784c32012-11-19 14:55:58 -0800473void AudioFlinger::PlaybackThread::Track::destroy()
474{
475 // NOTE: destroyTrack_l() can remove a strong reference to this Track
476 // by removing it from mTracks vector, so there is a risk that this Tracks's
477 // destructor is called. As the destructor needs to lock mLock,
478 // we must acquire a strong reference on this Track before locking mLock
479 // here so that the destructor is called only when exiting this function.
480 // On the other hand, as long as Track::destroy() is only called by
481 // TrackHandle destructor, the TrackHandle still holds a strong ref on
482 // this Track with its member mTrack.
483 sp<Track> keep(this);
484 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700485 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800486 sp<ThreadBase> thread = mThread.promote();
487 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800488 Mutex::Autolock _l(thread->mLock);
489 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700490 wasActive = playbackThread->destroyTrack_l(this);
491 }
492 if (isExternalTrack() && !wasActive) {
Eric Laurente83b55d2014-11-14 10:06:21 -0800493 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800494 }
495 }
496}
497
498/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
499{
Marco Nelissenb2208842014-02-07 14:00:50 -0800500 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700501 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800502}
503
Marco Nelissenb2208842014-02-07 14:00:50 -0800504void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800505{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700506 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800507 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800508 sprintf(buffer, " F %2d", mFastIndex);
509 } else if (mName >= AudioMixer::TRACK0) {
510 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800511 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800512 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800513 }
514 track_state state = mState;
515 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800516 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800517 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800518 } else {
519 switch (state) {
520 case IDLE:
521 stateChar = 'I';
522 break;
523 case STOPPING_1:
524 stateChar = 's';
525 break;
526 case STOPPING_2:
527 stateChar = '5';
528 break;
529 case STOPPED:
530 stateChar = 'S';
531 break;
532 case RESUMING:
533 stateChar = 'R';
534 break;
535 case ACTIVE:
536 stateChar = 'A';
537 break;
538 case PAUSING:
539 stateChar = 'p';
540 break;
541 case PAUSED:
542 stateChar = 'P';
543 break;
544 case FLUSHED:
545 stateChar = 'F';
546 break;
547 default:
548 stateChar = '?';
549 break;
550 }
Eric Laurent81784c32012-11-19 14:55:58 -0800551 }
552 char nowInUnderrun;
553 switch (mObservedUnderruns.mBitFields.mMostRecent) {
554 case UNDERRUN_FULL:
555 nowInUnderrun = ' ';
556 break;
557 case UNDERRUN_PARTIAL:
558 nowInUnderrun = '<';
559 break;
560 case UNDERRUN_EMPTY:
561 nowInUnderrun = '*';
562 break;
563 default:
564 nowInUnderrun = '?';
565 break;
566 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000567 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 +0000568 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800569 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800570 (mClient == 0) ? getpid_cached : mClient->pid(),
571 mStreamType,
572 mFormat,
573 mChannelMask,
574 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800575 mFrameCount,
576 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800577 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800578 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700579 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
580 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700581 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000582 mMainBuffer,
583 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700584 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700585 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800586 nowInUnderrun);
587}
588
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800589uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
590 return mAudioTrackServerProxy->getSampleRate();
591}
592
Eric Laurent81784c32012-11-19 14:55:58 -0800593// AudioBufferProvider interface
594status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800595 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800596{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800597 ServerProxy::Buffer buf;
598 size_t desiredFrames = buffer->frameCount;
599 buf.mFrameCount = desiredFrames;
600 status_t status = mServerProxy->obtainBuffer(&buf);
601 buffer->frameCount = buf.mFrameCount;
602 buffer->raw = buf.mRaw;
603 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700604 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800605 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800606 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800607}
608
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700609// releaseBuffer() is not overridden
610
611// ExtendedAudioBufferProvider interface
612
Andy Hung27876c02014-09-09 18:07:55 -0700613// framesReady() may return an approximation of the number of frames if called
614// from a different thread than the one calling Proxy->obtainBuffer() and
615// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
616// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800617size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700618 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
619 // Static tracks return zero frames immediately upon stopping (for FastTracks).
620 // The remainder of the buffer is not drained.
621 return 0;
622 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800623 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800624}
625
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700626size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
627{
628 return mAudioTrackServerProxy->framesReleased();
629}
630
Eric Laurent81784c32012-11-19 14:55:58 -0800631// Don't call for fast tracks; the framesReady() could result in priority inversion
632bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800633 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
634 return true;
635 }
636
Eric Laurent16498512014-03-17 17:22:08 -0700637 if (isStopping()) {
638 if (framesReady() > 0) {
639 mFillingUpStatus = FS_FILLED;
640 }
Eric Laurent81784c32012-11-19 14:55:58 -0800641 return true;
642 }
643
644 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700645 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800646 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700647 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800648 return true;
649 }
650 return false;
651}
652
Glenn Kasten0f11b512014-01-31 16:18:54 -0800653status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
654 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800655{
656 status_t status = NO_ERROR;
657 ALOGV("start(%d), calling pid %d session %d",
658 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
659
660 sp<ThreadBase> thread = mThread.promote();
661 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700662 if (isOffloaded()) {
663 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
664 Mutex::Autolock _lth(thread->mLock);
665 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700666 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
667 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700668 invalidate();
669 return PERMISSION_DENIED;
670 }
671 }
672 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800673 track_state state = mState;
674 // here the track could be either new, or restarted
675 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800676
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800677 // initial state-stopping. next state-pausing.
678 // What if resume is called ?
679
680 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800681 if (mResumeToStopping) {
682 // happened we need to resume to STOPPING_1
683 mState = TrackBase::STOPPING_1;
684 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
685 } else {
686 mState = TrackBase::RESUMING;
687 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
688 }
Eric Laurent81784c32012-11-19 14:55:58 -0800689 } else {
690 mState = TrackBase::ACTIVE;
691 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
692 }
693
Eric Laurentbfb1b832013-01-07 09:53:42 -0800694 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700695 if (isFastTrack()) {
696 // refresh fast track underruns on start because that field is never cleared
697 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
698 // after stop.
699 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
700 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800701 status = playbackThread->addTrack_l(this);
702 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800703 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800704 // restore previous state if start was rejected by policy manager
705 if (status == PERMISSION_DENIED) {
706 mState = state;
707 }
708 }
709 // track was already in the active list, not a problem
710 if (status == ALREADY_EXISTS) {
711 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700712 } else {
713 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
714 // It is usually unsafe to access the server proxy from a binder thread.
715 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
716 // isn't looking at this track yet: we still hold the normal mixer thread lock,
717 // and for fast tracks the track is not yet in the fast mixer thread's active set.
Eric Laurent564d1442015-09-09 12:26:52 -0700718 ServerProxy::Buffer buffer;
719 buffer.mFrameCount = 1;
720 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800721 }
722 } else {
723 status = BAD_VALUE;
724 }
725 return status;
726}
727
728void AudioFlinger::PlaybackThread::Track::stop()
729{
730 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
731 sp<ThreadBase> thread = mThread.promote();
732 if (thread != 0) {
733 Mutex::Autolock _l(thread->mLock);
734 track_state state = mState;
735 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
736 // If the track is not active (PAUSED and buffers full), flush buffers
737 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
738 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
739 reset();
740 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700741 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800742 mState = STOPPED;
743 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800744 // For fast tracks prepareTracks_l() will set state to STOPPING_2
745 // presentation is complete
746 // For an offloaded track this starts a drain and state will
747 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800748 mState = STOPPING_1;
749 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700750 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800751 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
752 playbackThread);
753 }
Eric Laurent81784c32012-11-19 14:55:58 -0800754 }
755}
756
757void AudioFlinger::PlaybackThread::Track::pause()
758{
759 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
760 sp<ThreadBase> thread = mThread.promote();
761 if (thread != 0) {
762 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800763 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
764 switch (mState) {
765 case STOPPING_1:
766 case STOPPING_2:
767 if (!isOffloaded()) {
768 /* nothing to do if track is not offloaded */
769 break;
770 }
771
772 // Offloaded track was draining, we need to carry on draining when resumed
773 mResumeToStopping = true;
774 // fall through...
775 case ACTIVE:
776 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800777 mState = PAUSING;
778 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700779 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800780 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800781
Eric Laurentbfb1b832013-01-07 09:53:42 -0800782 default:
783 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800784 }
785 }
786}
787
788void AudioFlinger::PlaybackThread::Track::flush()
789{
790 ALOGV("flush(%d)", mName);
791 sp<ThreadBase> thread = mThread.promote();
792 if (thread != 0) {
793 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800794 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800795
796 if (isOffloaded()) {
797 // If offloaded we allow flush during any state except terminated
798 // and keep the track active to avoid problems if user is seeking
799 // rapidly and underlying hardware has a significant delay handling
800 // a pause
801 if (isTerminated()) {
802 return;
803 }
804
805 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800806 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800807
808 if (mState == STOPPING_1 || mState == STOPPING_2) {
809 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
810 mState = ACTIVE;
811 }
812
813 if (mState == ACTIVE) {
814 ALOGV("flush called in active state, resetting buffer time out retry count");
815 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
816 }
817
Haynes Mathew George7844f672014-01-15 12:32:55 -0800818 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800819 mResumeToStopping = false;
820 } else {
821 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
822 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
823 return;
824 }
825 // No point remaining in PAUSED state after a flush => go to
826 // FLUSHED state
827 mState = FLUSHED;
828 // do not reset the track if it is still in the process of being stopped or paused.
829 // this will be done by prepareTracks_l() when the track is stopped.
830 // prepareTracks_l() will see mState == FLUSHED, then
831 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800832 if (isDirect()) {
833 mFlushHwPending = true;
834 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800835 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
836 reset();
837 }
Eric Laurent81784c32012-11-19 14:55:58 -0800838 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800839 // Prevent flush being lost if the track is flushed and then resumed
840 // before mixer thread can run. This is important when offloading
841 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700842 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800843 }
844}
845
Haynes Mathew George7844f672014-01-15 12:32:55 -0800846// must be called with thread lock held
847void AudioFlinger::PlaybackThread::Track::flushAck()
848{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800849 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800850 return;
851
852 mFlushHwPending = false;
853}
854
Eric Laurent81784c32012-11-19 14:55:58 -0800855void AudioFlinger::PlaybackThread::Track::reset()
856{
857 // Do not reset twice to avoid discarding data written just after a flush and before
858 // the audioflinger thread detects the track is stopped.
859 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800860 // Force underrun condition to avoid false underrun callback until first data is
861 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700862 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800863 mFillingUpStatus = FS_FILLING;
864 mResetDone = true;
865 if (mState == FLUSHED) {
866 mState = IDLE;
867 }
868 }
869}
870
Eric Laurentbfb1b832013-01-07 09:53:42 -0800871status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
872{
873 sp<ThreadBase> thread = mThread.promote();
874 if (thread == 0) {
875 ALOGE("thread is dead");
876 return FAILED_TRANSACTION;
877 } else if ((thread->type() == ThreadBase::DIRECT) ||
878 (thread->type() == ThreadBase::OFFLOAD)) {
879 return thread->setParameters(keyValuePairs);
880 } else {
881 return PERMISSION_DENIED;
882 }
883}
884
Glenn Kasten573d80a2013-08-26 09:36:23 -0700885status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
886{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700887 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
888 if (isFastTrack()) {
889 return INVALID_OPERATION;
890 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700891 sp<ThreadBase> thread = mThread.promote();
892 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700893 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700894 }
Phil Burk6140c792015-03-19 14:30:21 -0700895
Glenn Kasten573d80a2013-08-26 09:36:23 -0700896 Mutex::Autolock _l(thread->mLock);
897 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Phil Burk6140c792015-03-19 14:30:21 -0700898
899 status_t result = INVALID_OPERATION;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700900 if (!isOffloaded() && !isDirect()) {
Eric Laurentaccc1472013-09-20 09:36:34 -0700901 if (!playbackThread->mLatchQValid) {
902 return INVALID_OPERATION;
903 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700904 // FIXME Not accurate under dynamic changes of sample rate and speed.
905 // Do not use track's mSampleRate as it is not current for mixer tracks.
906 uint32_t sampleRate = mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700907 AudioPlaybackRate playbackRate = mAudioTrackServerProxy->getPlaybackRate();
908 uint32_t unpresentedFrames = ((double) playbackThread->mLatchQ.mUnpresentedFrames *
909 sampleRate * playbackRate.mSpeed)/ playbackThread->mSampleRate;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700910 // FIXME Since we're using a raw pointer as the key, it is theoretically possible
911 // for a brand new track to share the same address as a recently destroyed
912 // track, and thus for us to get the frames released of the wrong track.
913 // It is unlikely that we would be able to call getTimestamp() so quickly
914 // right after creating a new track. Nevertheless, the index here should
915 // be changed to something that is unique. Or use a completely different strategy.
916 ssize_t i = playbackThread->mLatchQ.mFramesReleased.indexOfKey(this);
917 uint32_t framesWritten = i >= 0 ?
918 playbackThread->mLatchQ.mFramesReleased[i] :
919 mAudioTrackServerProxy->framesReleased();
Phil Burk1b420972015-04-22 10:52:21 -0700920 if (framesWritten >= unpresentedFrames) {
Phil Burk6140c792015-03-19 14:30:21 -0700921 timestamp.mPosition = framesWritten - unpresentedFrames;
922 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
923 result = NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -0700924 }
Phil Burk6140c792015-03-19 14:30:21 -0700925 } else { // offloaded or direct
926 result = playbackThread->getTimestamp_l(timestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700927 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700928
Phil Burk6140c792015-03-19 14:30:21 -0700929 return result;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700930}
931
Eric Laurent81784c32012-11-19 14:55:58 -0800932status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
933{
934 status_t status = DEAD_OBJECT;
935 sp<ThreadBase> thread = mThread.promote();
936 if (thread != 0) {
937 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
938 sp<AudioFlinger> af = mClient->audioFlinger();
939
940 Mutex::Autolock _l(af->mLock);
941
942 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
943
944 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
945 Mutex::Autolock _dl(playbackThread->mLock);
946 Mutex::Autolock _sl(srcThread->mLock);
947 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
948 if (chain == 0) {
949 return INVALID_OPERATION;
950 }
951
952 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
953 if (effect == 0) {
954 return INVALID_OPERATION;
955 }
956 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700957 status = playbackThread->addEffect_l(effect);
958 if (status != NO_ERROR) {
959 srcThread->addEffect_l(effect);
960 return INVALID_OPERATION;
961 }
Eric Laurent81784c32012-11-19 14:55:58 -0800962 // removeEffect_l() has stopped the effect if it was active so it must be restarted
963 if (effect->state() == EffectModule::ACTIVE ||
964 effect->state() == EffectModule::STOPPING) {
965 effect->start();
966 }
967
968 sp<EffectChain> dstChain = effect->chain().promote();
969 if (dstChain == 0) {
970 srcThread->addEffect_l(effect);
971 return INVALID_OPERATION;
972 }
973 AudioSystem::unregisterEffect(effect->id());
974 AudioSystem::registerEffect(&effect->desc(),
975 srcThread->id(),
976 dstChain->strategy(),
977 AUDIO_SESSION_OUTPUT_MIX,
978 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700979 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800980 }
981 status = playbackThread->attachAuxEffect(this, EffectId);
982 }
983 return status;
984}
985
986void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
987{
988 mAuxEffectId = EffectId;
989 mAuxBuffer = buffer;
990}
991
992bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
993 size_t audioHalFrames)
994{
995 // a track is considered presented when the total number of frames written to audio HAL
996 // corresponds to the number of frames written when presentationComplete() is called for the
997 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800998 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
999 // to detect when all frames have been played. In this case framesWritten isn't
1000 // useful because it doesn't always reflect whether there is data in the h/w
1001 // buffers, particularly if a track has been paused and resumed during draining
1002 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
1003 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001004 if (mPresentationCompleteFrames == 0) {
1005 mPresentationCompleteFrames = framesWritten + audioHalFrames;
1006 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
1007 mPresentationCompleteFrames, audioHalFrames);
1008 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001009
1010 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001011 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001012 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001013 return true;
1014 }
1015 return false;
1016}
1017
1018void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1019{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001020 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001021 if (mSyncEvents[i]->type() == type) {
1022 mSyncEvents[i]->trigger();
1023 mSyncEvents.removeAt(i);
1024 i--;
1025 }
1026 }
1027}
1028
1029// implement VolumeBufferProvider interface
1030
Glenn Kastenc56f3422014-03-21 17:53:17 -07001031gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001032{
1033 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1034 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001035 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1036 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1037 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001038 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001039 if (vl > GAIN_FLOAT_UNITY) {
1040 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001041 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001042 if (vr > GAIN_FLOAT_UNITY) {
1043 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001044 }
1045 // now apply the cached master volume and stream type volume;
1046 // this is trusted but lacks any synchronization or barrier so may be stale
1047 float v = mCachedVolume;
1048 vl *= v;
1049 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001050 // re-combine into packed minifloat
1051 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001052 // FIXME look at mute, pause, and stop flags
1053 return vlr;
1054}
1055
1056status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1057{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001058 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001059 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1060 (mState == STOPPED)))) {
1061 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1062 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1063 event->cancel();
1064 return INVALID_OPERATION;
1065 }
1066 (void) TrackBase::setSyncEvent(event);
1067 return NO_ERROR;
1068}
1069
Glenn Kasten5736c352012-12-04 12:12:34 -08001070void AudioFlinger::PlaybackThread::Track::invalidate()
1071{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001072 // FIXME should use proxy, and needs work
1073 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001074 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001075 android_atomic_release_store(0x40000000, &cblk->mFutex);
1076 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001077 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001078 mIsInvalid = true;
1079}
1080
Eric Laurent59fe0102013-09-27 18:48:26 -07001081void AudioFlinger::PlaybackThread::Track::signal()
1082{
1083 sp<ThreadBase> thread = mThread.promote();
1084 if (thread != 0) {
1085 PlaybackThread *t = (PlaybackThread *)thread.get();
1086 Mutex::Autolock _l(t->mLock);
1087 t->broadcast_l();
1088 }
1089}
1090
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001091//To be called with thread lock held
1092bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1093
1094 if (mState == RESUMING)
1095 return true;
1096 /* Resume is pending if track was stopping before pause was called */
1097 if (mState == STOPPING_1 &&
1098 mResumeToStopping)
1099 return true;
1100
1101 return false;
1102}
1103
1104//To be called with thread lock held
1105void AudioFlinger::PlaybackThread::Track::resumeAck() {
1106
1107
1108 if (mState == RESUMING)
1109 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001110
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001111 // Other possibility of pending resume is stopping_1 state
1112 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001113 // drain being called.
1114 if (mState == STOPPING_1) {
1115 mResumeToStopping = false;
1116 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001117}
Eric Laurent81784c32012-11-19 14:55:58 -08001118// ----------------------------------------------------------------------------
1119
1120sp<AudioFlinger::PlaybackThread::TimedTrack>
1121AudioFlinger::PlaybackThread::TimedTrack::create(
1122 PlaybackThread *thread,
1123 const sp<Client>& client,
1124 audio_stream_type_t streamType,
1125 uint32_t sampleRate,
1126 audio_format_t format,
1127 audio_channel_mask_t channelMask,
1128 size_t frameCount,
1129 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001130 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001131 int uid)
1132{
Eric Laurent81784c32012-11-19 14:55:58 -08001133 if (!client->reserveTimedTrack())
1134 return 0;
1135
1136 return new TimedTrack(
1137 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001138 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001139}
1140
1141AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1142 PlaybackThread *thread,
1143 const sp<Client>& client,
1144 audio_stream_type_t streamType,
1145 uint32_t sampleRate,
1146 audio_format_t format,
1147 audio_channel_mask_t channelMask,
1148 size_t frameCount,
1149 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001150 int sessionId,
1151 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001152 : Track(thread, client, streamType, sampleRate, format, channelMask,
Eric Laurent83b88082014-06-20 18:31:16 -07001153 frameCount, (sharedBuffer != 0) ? sharedBuffer->pointer() : NULL, sharedBuffer,
1154 sessionId, uid, IAudioFlinger::TRACK_TIMED, TYPE_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001155 mQueueHeadInFlight(false),
1156 mTrimQueueHeadOnRelease(false),
1157 mFramesPendingInQueue(0),
1158 mTimedSilenceBuffer(NULL),
1159 mTimedSilenceBufferSize(0),
1160 mTimedAudioOutputOnTime(false),
1161 mMediaTimeTransformValid(false)
1162{
1163 LocalClock lc;
1164 mLocalTimeFreq = lc.getLocalFreq();
1165
1166 mLocalTimeToSampleTransform.a_zero = 0;
1167 mLocalTimeToSampleTransform.b_zero = 0;
1168 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1169 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1170 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1171 &mLocalTimeToSampleTransform.a_to_b_denom);
1172
1173 mMediaTimeToSampleTransform.a_zero = 0;
1174 mMediaTimeToSampleTransform.b_zero = 0;
1175 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1176 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1177 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1178 &mMediaTimeToSampleTransform.a_to_b_denom);
1179}
1180
1181AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1182 mClient->releaseTimedTrack();
1183 delete [] mTimedSilenceBuffer;
1184}
1185
1186status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1187 size_t size, sp<IMemory>* buffer) {
1188
1189 Mutex::Autolock _l(mTimedBufferQueueLock);
1190
1191 trimTimedBufferQueue_l();
1192
1193 // lazily initialize the shared memory heap for timed buffers
1194 if (mTimedMemoryDealer == NULL) {
1195 const int kTimedBufferHeapSize = 512 << 10;
1196
1197 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1198 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001199 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001200 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001201 }
Eric Laurent81784c32012-11-19 14:55:58 -08001202 }
1203
1204 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001205 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001206 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001207 }
1208
1209 *buffer = newBuffer;
1210 return NO_ERROR;
1211}
1212
1213// caller must hold mTimedBufferQueueLock
1214void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1215 int64_t mediaTimeNow;
1216 {
1217 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1218 if (!mMediaTimeTransformValid)
1219 return;
1220
1221 int64_t targetTimeNow;
1222 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1223 ? mCCHelper.getCommonTime(&targetTimeNow)
1224 : mCCHelper.getLocalTime(&targetTimeNow);
1225
1226 if (OK != res)
1227 return;
1228
1229 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1230 &mediaTimeNow)) {
1231 return;
1232 }
1233 }
1234
1235 size_t trimEnd;
1236 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1237 int64_t bufEnd;
1238
1239 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1240 // We have a next buffer. Just use its PTS as the PTS of the frame
1241 // following the last frame in this buffer. If the stream is sparse
1242 // (ie, there are deliberate gaps left in the stream which should be
1243 // filled with silence by the TimedAudioTrack), then this can result
1244 // in one extra buffer being left un-trimmed when it could have
1245 // been. In general, this is not typical, and we would rather
1246 // optimized away the TS calculation below for the more common case
1247 // where PTSes are contiguous.
1248 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1249 } else {
1250 // We have no next buffer. Compute the PTS of the frame following
1251 // the last frame in this buffer by computing the duration of of
1252 // this frame in media time units and adding it to the PTS of the
1253 // buffer.
1254 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1255 / mFrameSize;
1256
1257 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1258 &bufEnd)) {
1259 ALOGE("Failed to convert frame count of %lld to media time"
1260 " duration" " (scale factor %d/%u) in %s",
1261 frameCount,
1262 mMediaTimeToSampleTransform.a_to_b_numer,
1263 mMediaTimeToSampleTransform.a_to_b_denom,
1264 __PRETTY_FUNCTION__);
1265 break;
1266 }
1267 bufEnd += mTimedBufferQueue[trimEnd].pts();
1268 }
1269
1270 if (bufEnd > mediaTimeNow)
1271 break;
1272
1273 // Is the buffer we want to use in the middle of a mix operation right
1274 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1275 // from the mixer which should be coming back shortly.
1276 if (!trimEnd && mQueueHeadInFlight) {
1277 mTrimQueueHeadOnRelease = true;
1278 }
1279 }
1280
1281 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1282 if (trimStart < trimEnd) {
1283 // Update the bookkeeping for framesReady()
1284 for (size_t i = trimStart; i < trimEnd; ++i) {
1285 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1286 }
1287
1288 // Now actually remove the buffers from the queue.
1289 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1290 }
1291}
1292
1293void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1294 const char* logTag) {
1295 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1296 "%s called (reason \"%s\"), but timed buffer queue has no"
1297 " elements to trim.", __FUNCTION__, logTag);
1298
1299 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1300 mTimedBufferQueue.removeAt(0);
1301}
1302
1303void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1304 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001305 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001306 uint32_t bufBytes = buf.buffer()->size();
1307 uint32_t consumedAlready = buf.position();
1308
1309 ALOG_ASSERT(consumedAlready <= bufBytes,
1310 "Bad bookkeeping while updating frames pending. Timed buffer is"
1311 " only %u bytes long, but claims to have consumed %u"
1312 " bytes. (update reason: \"%s\")",
1313 bufBytes, consumedAlready, logTag);
1314
1315 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1316 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1317 "Bad bookkeeping while updating frames pending. Should have at"
1318 " least %u queued frames, but we think we have only %u. (update"
1319 " reason: \"%s\")",
1320 bufFrames, mFramesPendingInQueue, logTag);
1321
1322 mFramesPendingInQueue -= bufFrames;
1323}
1324
1325status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1326 const sp<IMemory>& buffer, int64_t pts) {
1327
1328 {
1329 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1330 if (!mMediaTimeTransformValid)
1331 return INVALID_OPERATION;
1332 }
1333
1334 Mutex::Autolock _l(mTimedBufferQueueLock);
1335
1336 uint32_t bufFrames = buffer->size() / mFrameSize;
1337 mFramesPendingInQueue += bufFrames;
1338 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1339
1340 return NO_ERROR;
1341}
1342
1343status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1344 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1345
1346 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1347 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1348 target);
1349
1350 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1351 target == TimedAudioTrack::COMMON_TIME)) {
1352 return BAD_VALUE;
1353 }
1354
1355 Mutex::Autolock lock(mMediaTimeTransformLock);
1356 mMediaTimeTransform = xform;
1357 mMediaTimeTransformTarget = target;
1358 mMediaTimeTransformValid = true;
1359
1360 return NO_ERROR;
1361}
1362
1363#define min(a, b) ((a) < (b) ? (a) : (b))
1364
1365// implementation of getNextBuffer for tracks whose buffers have timestamps
1366status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1367 AudioBufferProvider::Buffer* buffer, int64_t pts)
1368{
1369 if (pts == AudioBufferProvider::kInvalidPTS) {
1370 buffer->raw = NULL;
1371 buffer->frameCount = 0;
1372 mTimedAudioOutputOnTime = false;
1373 return INVALID_OPERATION;
1374 }
1375
1376 Mutex::Autolock _l(mTimedBufferQueueLock);
1377
1378 ALOG_ASSERT(!mQueueHeadInFlight,
1379 "getNextBuffer called without releaseBuffer!");
1380
1381 while (true) {
1382
1383 // if we have no timed buffers, then fail
1384 if (mTimedBufferQueue.isEmpty()) {
1385 buffer->raw = NULL;
1386 buffer->frameCount = 0;
1387 return NOT_ENOUGH_DATA;
1388 }
1389
1390 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1391
1392 // calculate the PTS of the head of the timed buffer queue expressed in
1393 // local time
1394 int64_t headLocalPTS;
1395 {
1396 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1397
1398 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1399
1400 if (mMediaTimeTransform.a_to_b_denom == 0) {
1401 // the transform represents a pause, so yield silence
1402 timedYieldSilence_l(buffer->frameCount, buffer);
1403 return NO_ERROR;
1404 }
1405
1406 int64_t transformedPTS;
1407 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1408 &transformedPTS)) {
1409 // the transform failed. this shouldn't happen, but if it does
1410 // then just drop this buffer
1411 ALOGW("timedGetNextBuffer transform failed");
1412 buffer->raw = NULL;
1413 buffer->frameCount = 0;
1414 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1415 return NO_ERROR;
1416 }
1417
1418 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1419 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1420 &headLocalPTS)) {
1421 buffer->raw = NULL;
1422 buffer->frameCount = 0;
1423 return INVALID_OPERATION;
1424 }
1425 } else {
1426 headLocalPTS = transformedPTS;
1427 }
1428 }
1429
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001430 uint32_t sr = sampleRate();
1431
Eric Laurent81784c32012-11-19 14:55:58 -08001432 // adjust the head buffer's PTS to reflect the portion of the head buffer
1433 // that has already been consumed
1434 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001435 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001436
1437 // Calculate the delta in samples between the head of the input buffer
1438 // queue and the start of the next output buffer that will be written.
1439 // If the transformation fails because of over or underflow, it means
1440 // that the sample's position in the output stream is so far out of
1441 // whack that it should just be dropped.
1442 int64_t sampleDelta;
1443 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1444 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1445 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1446 " mix");
1447 continue;
1448 }
1449 if (!mLocalTimeToSampleTransform.doForwardTransform(
1450 (effectivePTS - pts) << 32, &sampleDelta)) {
1451 ALOGV("*** too late during sample rate transform: dropped buffer");
1452 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1453 continue;
1454 }
1455
1456 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1457 " sampleDelta=[%d.%08x]",
1458 head.pts(), head.position(), pts,
1459 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1460 + (sampleDelta >> 32)),
1461 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1462
1463 // if the delta between the ideal placement for the next input sample and
1464 // the current output position is within this threshold, then we will
1465 // concatenate the next input samples to the previous output
1466 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001467 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001468
1469 // if this is the first buffer of audio that we're emitting from this track
1470 // then it should be almost exactly on time.
1471 const int64_t kSampleStartupThreshold = 1LL << 32;
1472
1473 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1474 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1475 // the next input is close enough to being on time, so concatenate it
1476 // with the last output
1477 timedYieldSamples_l(buffer);
1478
1479 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1480 head.position(), buffer->frameCount);
1481 return NO_ERROR;
1482 }
1483
1484 // Looks like our output is not on time. Reset our on timed status.
1485 // Next time we mix samples from our input queue, then should be within
1486 // the StartupThreshold.
1487 mTimedAudioOutputOnTime = false;
1488 if (sampleDelta > 0) {
1489 // the gap between the current output position and the proper start of
1490 // the next input sample is too big, so fill it with silence
1491 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1492
1493 timedYieldSilence_l(framesUntilNextInput, buffer);
1494 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1495 return NO_ERROR;
1496 } else {
1497 // the next input sample is late
1498 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1499 size_t onTimeSamplePosition =
1500 head.position() + lateFrames * mFrameSize;
1501
1502 if (onTimeSamplePosition > head.buffer()->size()) {
1503 // all the remaining samples in the head are too late, so
1504 // drop it and move on
1505 ALOGV("*** too late: dropped buffer");
1506 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1507 continue;
1508 } else {
1509 // skip over the late samples
1510 head.setPosition(onTimeSamplePosition);
1511
1512 // yield the available samples
1513 timedYieldSamples_l(buffer);
1514
1515 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1516 return NO_ERROR;
1517 }
1518 }
1519 }
1520}
1521
1522// Yield samples from the timed buffer queue head up to the given output
1523// buffer's capacity.
1524//
1525// Caller must hold mTimedBufferQueueLock
1526void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1527 AudioBufferProvider::Buffer* buffer) {
1528
1529 const TimedBuffer& head = mTimedBufferQueue[0];
1530
1531 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1532 head.position());
1533
1534 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1535 mFrameSize);
1536 size_t framesRequested = buffer->frameCount;
1537 buffer->frameCount = min(framesLeftInHead, framesRequested);
1538
1539 mQueueHeadInFlight = true;
1540 mTimedAudioOutputOnTime = true;
1541}
1542
1543// Yield samples of silence up to the given output buffer's capacity
1544//
1545// Caller must hold mTimedBufferQueueLock
1546void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1547 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1548
1549 // lazily allocate a buffer filled with silence
1550 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1551 delete [] mTimedSilenceBuffer;
1552 mTimedSilenceBufferSize = numFrames * mFrameSize;
1553 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1554 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1555 }
1556
1557 buffer->raw = mTimedSilenceBuffer;
1558 size_t framesRequested = buffer->frameCount;
1559 buffer->frameCount = min(numFrames, framesRequested);
1560
1561 mTimedAudioOutputOnTime = false;
1562}
1563
1564// AudioBufferProvider interface
1565void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1566 AudioBufferProvider::Buffer* buffer) {
1567
1568 Mutex::Autolock _l(mTimedBufferQueueLock);
1569
1570 // If the buffer which was just released is part of the buffer at the head
1571 // of the queue, be sure to update the amt of the buffer which has been
1572 // consumed. If the buffer being returned is not part of the head of the
1573 // queue, its either because the buffer is part of the silence buffer, or
1574 // because the head of the timed queue was trimmed after the mixer called
1575 // getNextBuffer but before the mixer called releaseBuffer.
1576 if (buffer->raw == mTimedSilenceBuffer) {
1577 ALOG_ASSERT(!mQueueHeadInFlight,
1578 "Queue head in flight during release of silence buffer!");
1579 goto done;
1580 }
1581
1582 ALOG_ASSERT(mQueueHeadInFlight,
1583 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1584 " head in flight.");
1585
1586 if (mTimedBufferQueue.size()) {
1587 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1588
1589 void* start = head.buffer()->pointer();
1590 void* end = reinterpret_cast<void*>(
1591 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1592 + head.buffer()->size());
1593
1594 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1595 "released buffer not within the head of the timed buffer"
1596 " queue; qHead = [%p, %p], released buffer = %p",
1597 start, end, buffer->raw);
1598
1599 head.setPosition(head.position() +
1600 (buffer->frameCount * mFrameSize));
1601 mQueueHeadInFlight = false;
1602
1603 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1604 "Bad bookkeeping during releaseBuffer! Should have at"
1605 " least %u queued frames, but we think we have only %u",
1606 buffer->frameCount, mFramesPendingInQueue);
1607
1608 mFramesPendingInQueue -= buffer->frameCount;
1609
1610 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1611 || mTrimQueueHeadOnRelease) {
1612 trimTimedBufferQueueHead_l("releaseBuffer");
1613 mTrimQueueHeadOnRelease = false;
1614 }
1615 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001616 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001617 " buffers in the timed buffer queue");
1618 }
1619
1620done:
1621 buffer->raw = 0;
1622 buffer->frameCount = 0;
1623}
1624
1625size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1626 Mutex::Autolock _l(mTimedBufferQueueLock);
1627 return mFramesPendingInQueue;
1628}
1629
1630AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1631 : mPTS(0), mPosition(0) {}
1632
1633AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1634 const sp<IMemory>& buffer, int64_t pts)
1635 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1636
1637
1638// ----------------------------------------------------------------------------
1639
1640AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1641 PlaybackThread *playbackThread,
1642 DuplicatingThread *sourceThread,
1643 uint32_t sampleRate,
1644 audio_format_t format,
1645 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001646 size_t frameCount,
1647 int uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001648 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1649 sampleRate, format, channelMask, frameCount,
1650 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001651 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001652{
1653
1654 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001655 mOutBuffer.frameCount = 0;
1656 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001657 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001658 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001659 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001660 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001661 // since client and server are in the same process,
1662 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001663 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1664 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001665 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001666 mClientProxy->setSendLevel(0.0);
1667 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001668 } else {
1669 ALOGW("Error creating output track on thread %p", playbackThread);
1670 }
1671}
1672
1673AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1674{
1675 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001676 delete mClientProxy;
1677 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001678}
1679
1680status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1681 int triggerSession)
1682{
1683 status_t status = Track::start(event, triggerSession);
1684 if (status != NO_ERROR) {
1685 return status;
1686 }
1687
1688 mActive = true;
1689 mRetryCount = 127;
1690 return status;
1691}
1692
1693void AudioFlinger::PlaybackThread::OutputTrack::stop()
1694{
1695 Track::stop();
1696 clearBufferQueue();
1697 mOutBuffer.frameCount = 0;
1698 mActive = false;
1699}
1700
Andy Hungc25b84a2015-01-14 19:04:10 -08001701bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001702{
1703 Buffer *pInBuffer;
1704 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001705 bool outputBufferFull = false;
1706 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001707 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001708
1709 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1710
1711 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001712 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001713 }
1714
1715 while (waitTimeLeftMs) {
1716 // First write pending buffers, then new data
1717 if (mBufferQueue.size()) {
1718 pInBuffer = mBufferQueue.itemAt(0);
1719 } else {
1720 pInBuffer = &inBuffer;
1721 }
1722
1723 if (pInBuffer->frameCount == 0) {
1724 break;
1725 }
1726
1727 if (mOutBuffer.frameCount == 0) {
1728 mOutBuffer.frameCount = pInBuffer->frameCount;
1729 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001730 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1731 if (status != NO_ERROR) {
1732 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1733 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001734 outputBufferFull = true;
1735 break;
1736 }
1737 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1738 if (waitTimeLeftMs >= waitTimeMs) {
1739 waitTimeLeftMs -= waitTimeMs;
1740 } else {
1741 waitTimeLeftMs = 0;
1742 }
1743 }
1744
1745 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1746 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001747 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001748 Proxy::Buffer buf;
1749 buf.mFrameCount = outFrames;
1750 buf.mRaw = NULL;
1751 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001752 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001753 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001754 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001755 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001756
1757 if (pInBuffer->frameCount == 0) {
1758 if (mBufferQueue.size()) {
1759 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001760 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001761 delete pInBuffer;
1762 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1763 mThread.unsafe_get(), mBufferQueue.size());
1764 } else {
1765 break;
1766 }
1767 }
1768 }
1769
1770 // If we could not write all frames, allocate a buffer and queue it for next time.
1771 if (inBuffer.frameCount) {
1772 sp<ThreadBase> thread = mThread.promote();
1773 if (thread != 0 && !thread->standby()) {
1774 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1775 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001776 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001777 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001778 pInBuffer->raw = pInBuffer->mBuffer;
1779 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001780 mBufferQueue.add(pInBuffer);
1781 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1782 mThread.unsafe_get(), mBufferQueue.size());
1783 } else {
1784 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1785 mThread.unsafe_get(), this);
1786 }
1787 }
1788 }
1789
Andy Hungc25b84a2015-01-14 19:04:10 -08001790 // Calling write() with a 0 length buffer means that no more data will be written:
1791 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1792 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1793 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001794 }
1795
1796 return outputBufferFull;
1797}
1798
1799status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1800 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1801{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001802 ClientProxy::Buffer buf;
1803 buf.mFrameCount = buffer->frameCount;
1804 struct timespec timeout;
1805 timeout.tv_sec = waitTimeMs / 1000;
1806 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1807 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1808 buffer->frameCount = buf.mFrameCount;
1809 buffer->raw = buf.mRaw;
1810 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001811}
1812
Eric Laurent81784c32012-11-19 14:55:58 -08001813void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1814{
1815 size_t size = mBufferQueue.size();
1816
1817 for (size_t i = 0; i < size; i++) {
1818 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001819 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001820 delete pBuffer;
1821 }
1822 mBufferQueue.clear();
1823}
1824
1825
Eric Laurent83b88082014-06-20 18:31:16 -07001826AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001827 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001828 uint32_t sampleRate,
1829 audio_channel_mask_t channelMask,
1830 audio_format_t format,
1831 size_t frameCount,
1832 void *buffer,
1833 IAudioFlinger::track_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001834 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001835 sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001836 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1837 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1838{
1839 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1840 playbackThread->sampleRate();
1841 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1842 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1843
1844 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1845 this, sampleRate,
1846 (int)mPeerTimeout.tv_sec,
1847 (int)(mPeerTimeout.tv_nsec / 1000000));
1848}
1849
1850AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1851{
1852}
1853
1854// AudioBufferProvider interface
1855status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
1856 AudioBufferProvider::Buffer* buffer, int64_t pts)
1857{
1858 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1859 Proxy::Buffer buf;
1860 buf.mFrameCount = buffer->frameCount;
1861 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1862 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001863 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001864 if (buf.mFrameCount == 0) {
1865 return WOULD_BLOCK;
1866 }
Eric Laurent83b88082014-06-20 18:31:16 -07001867 status = Track::getNextBuffer(buffer, pts);
1868 return status;
1869}
1870
1871void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1872{
1873 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1874 Proxy::Buffer buf;
1875 buf.mFrameCount = buffer->frameCount;
1876 buf.mRaw = buffer->raw;
1877 mPeerProxy->releaseBuffer(&buf);
1878 TrackBase::releaseBuffer(buffer);
1879}
1880
1881status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1882 const struct timespec *timeOut)
1883{
1884 return mProxy->obtainBuffer(buffer, timeOut);
1885}
1886
1887void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1888{
1889 mProxy->releaseBuffer(buffer);
1890 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1891 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1892 start();
1893 }
1894 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1895}
1896
Eric Laurent81784c32012-11-19 14:55:58 -08001897// ----------------------------------------------------------------------------
1898// Record
1899// ----------------------------------------------------------------------------
1900
1901AudioFlinger::RecordHandle::RecordHandle(
1902 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1903 : BnAudioRecord(),
1904 mRecordTrack(recordTrack)
1905{
1906}
1907
1908AudioFlinger::RecordHandle::~RecordHandle() {
1909 stop_nonvirtual();
1910 mRecordTrack->destroy();
1911}
1912
Eric Laurent81784c32012-11-19 14:55:58 -08001913status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1914 int triggerSession) {
1915 ALOGV("RecordHandle::start()");
1916 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1917}
1918
1919void AudioFlinger::RecordHandle::stop() {
1920 stop_nonvirtual();
1921}
1922
1923void AudioFlinger::RecordHandle::stop_nonvirtual() {
1924 ALOGV("RecordHandle::stop()");
1925 mRecordTrack->stop();
1926}
1927
1928status_t AudioFlinger::RecordHandle::onTransact(
1929 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1930{
1931 return BnAudioRecord::onTransact(code, data, reply, flags);
1932}
1933
1934// ----------------------------------------------------------------------------
1935
Glenn Kasten05997e22014-03-13 15:08:33 -07001936// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001937AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1938 RecordThread *thread,
1939 const sp<Client>& client,
1940 uint32_t sampleRate,
1941 audio_format_t format,
1942 audio_channel_mask_t channelMask,
1943 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001944 void *buffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001945 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001946 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -07001947 IAudioFlinger::track_flags_t flags,
1948 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001949 : TrackBase(thread, client, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001950 channelMask, frameCount, buffer, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001951 flags, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001952 (type == TYPE_DEFAULT) ?
1953 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1954 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1955 type),
Andy Hung97a893e2015-03-29 01:03:07 -07001956 mOverflow(false),
Andy Hung4c6afaf2015-06-12 18:23:35 -07001957 mFramesToDrop(0),
1958 mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
1959 mRecordBufferConverter(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001960{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001961 if (mCblk == NULL) {
1962 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001963 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001964
Andy Hung97a893e2015-03-29 01:03:07 -07001965 mRecordBufferConverter = new RecordBufferConverter(
1966 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1967 channelMask, format, sampleRate);
1968 // Check if the RecordBufferConverter construction was successful.
1969 // If not, don't continue with construction.
1970 //
1971 // NOTE: It would be extremely rare that the record track cannot be created
1972 // for the current device, but a pending or future device change would make
1973 // the record track configuration valid.
1974 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1975 ALOGE("RecordTrack unable to create record buffer converter");
1976 return;
1977 }
1978
Eric Laurent83b88082014-06-20 18:31:16 -07001979 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1980 mFrameSize, !isExternalTrack());
Andy Hung97a893e2015-03-29 01:03:07 -07001981 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001982
1983 if (flags & IAudioFlinger::TRACK_FAST) {
1984 ALOG_ASSERT(thread->mFastTrackAvail);
1985 thread->mFastTrackAvail = false;
1986 }
Eric Laurent81784c32012-11-19 14:55:58 -08001987}
1988
1989AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1990{
1991 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07001992 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001993 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001994}
1995
Andy Hung97a893e2015-03-29 01:03:07 -07001996status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1997{
1998 status_t status = TrackBase::initCheck();
1999 if (status == NO_ERROR && mServerProxy == 0) {
2000 status = BAD_VALUE;
2001 }
2002 return status;
2003}
2004
Eric Laurent81784c32012-11-19 14:55:58 -08002005// AudioBufferProvider interface
2006status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002007 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002008{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002009 ServerProxy::Buffer buf;
2010 buf.mFrameCount = buffer->frameCount;
2011 status_t status = mServerProxy->obtainBuffer(&buf);
2012 buffer->frameCount = buf.mFrameCount;
2013 buffer->raw = buf.mRaw;
2014 if (buf.mFrameCount == 0) {
2015 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07002016 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002017 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002018 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002019}
2020
2021status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
2022 int triggerSession)
2023{
2024 sp<ThreadBase> thread = mThread.promote();
2025 if (thread != 0) {
2026 RecordThread *recordThread = (RecordThread *)thread.get();
2027 return recordThread->start(this, event, triggerSession);
2028 } else {
2029 return BAD_VALUE;
2030 }
2031}
2032
2033void AudioFlinger::RecordThread::RecordTrack::stop()
2034{
2035 sp<ThreadBase> thread = mThread.promote();
2036 if (thread != 0) {
2037 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07002038 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07002039 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002040 }
2041 }
2042}
2043
2044void AudioFlinger::RecordThread::RecordTrack::destroy()
2045{
2046 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
2047 sp<RecordTrack> keep(this);
2048 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002049 if (isExternalTrack()) {
2050 if (mState == ACTIVE || mState == RESUMING) {
2051 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
2052 }
2053 AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
2054 }
Eric Laurent81784c32012-11-19 14:55:58 -08002055 sp<ThreadBase> thread = mThread.promote();
2056 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002057 Mutex::Autolock _l(thread->mLock);
2058 RecordThread *recordThread = (RecordThread *) thread.get();
2059 recordThread->destroyTrack_l(this);
2060 }
2061 }
2062}
2063
Eric Laurent9a54bc22013-09-09 09:08:44 -07002064void AudioFlinger::RecordThread::RecordTrack::invalidate()
2065{
2066 // FIXME should use proxy, and needs work
2067 audio_track_cblk_t* cblk = mCblk;
2068 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2069 android_atomic_release_store(0x40000000, &cblk->mFutex);
2070 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07002071 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07002072}
2073
Eric Laurent81784c32012-11-19 14:55:58 -08002074
2075/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
2076{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002077 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08002078}
2079
Marco Nelissenb2208842014-02-07 14:00:50 -08002080void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08002081{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002082 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08002083 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08002084 (mClient == 0) ? getpid_cached : mClient->pid(),
2085 mFormat,
2086 mChannelMask,
2087 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08002088 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002089 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002090 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002091 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002092
Eric Laurent81784c32012-11-19 14:55:58 -08002093}
2094
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002095void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2096{
2097 if (event == mSyncStartEvent) {
2098 ssize_t framesToDrop = 0;
2099 sp<ThreadBase> threadBase = mThread.promote();
2100 if (threadBase != 0) {
2101 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2102 // from audio HAL
2103 framesToDrop = threadBase->mFrameCount * 2;
2104 }
2105 mFramesToDrop = framesToDrop;
2106 }
2107}
2108
2109void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2110{
2111 if (mSyncStartEvent != 0) {
2112 mSyncStartEvent->cancel();
2113 mSyncStartEvent.clear();
2114 }
2115 mFramesToDrop = 0;
2116}
2117
Eric Laurent83b88082014-06-20 18:31:16 -07002118
2119AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
2120 uint32_t sampleRate,
2121 audio_channel_mask_t channelMask,
2122 audio_format_t format,
2123 size_t frameCount,
2124 void *buffer,
2125 IAudioFlinger::track_flags_t flags)
2126 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
2127 buffer, 0, getuid(), flags, TYPE_PATCH),
2128 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
2129{
2130 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
2131 recordThread->sampleRate();
2132 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
2133 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
2134
2135 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
2136 this, sampleRate,
2137 (int)mPeerTimeout.tv_sec,
2138 (int)(mPeerTimeout.tv_nsec / 1000000));
2139}
2140
2141AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
2142{
2143}
2144
2145// AudioBufferProvider interface
2146status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
2147 AudioBufferProvider::Buffer* buffer, int64_t pts)
2148{
2149 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
2150 Proxy::Buffer buf;
2151 buf.mFrameCount = buffer->frameCount;
2152 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
2153 ALOGV_IF(status != NO_ERROR,
2154 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07002155 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07002156 if (buf.mFrameCount == 0) {
2157 return WOULD_BLOCK;
2158 }
Eric Laurent83b88082014-06-20 18:31:16 -07002159 status = RecordTrack::getNextBuffer(buffer, pts);
2160 return status;
2161}
2162
2163void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2164{
2165 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
2166 Proxy::Buffer buf;
2167 buf.mFrameCount = buffer->frameCount;
2168 buf.mRaw = buffer->raw;
2169 mPeerProxy->releaseBuffer(&buf);
2170 TrackBase::releaseBuffer(buffer);
2171}
2172
2173status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
2174 const struct timespec *timeOut)
2175{
2176 return mProxy->obtainBuffer(buffer, timeOut);
2177}
2178
2179void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2180{
2181 mProxy->releaseBuffer(buffer);
2182}
2183
Glenn Kasten63238ef2015-03-02 15:50:29 -08002184} // namespace android