blob: 6482f686336b745a8c04673fab2e7edc9a8d5cfa [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080023#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070024#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080025#include <utils/Log.h>
26
27#include <private/media/AudioTrackShared.h>
28
29#include <common_time/cc_helper.h>
30#include <common_time/local_clock.h>
31
32#include "AudioMixer.h"
33#include "AudioFlinger.h"
34#include "ServiceUtilities.h"
35
Glenn Kastenda6ef132013-01-10 12:31:01 -080036#include <media/nbaio/Pipe.h>
37#include <media/nbaio/PipeReader.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070038#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080039
Eric Laurent81784c32012-11-19 14:55:58 -080040// ----------------------------------------------------------------------------
41
42// Note: the following macro is used for extremely verbose logging message. In
43// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
44// 0; but one side effect of this is to turn all LOGV's as well. Some messages
45// are so verbose that we want to suppress them even when we have ALOG_ASSERT
46// turned on. Do not uncomment the #def below unless you really know what you
47// are doing and want to see all of the extremely verbose messages.
48//#define VERY_VERY_VERBOSE_LOGGING
49#ifdef VERY_VERY_VERBOSE_LOGGING
50#define ALOGVV ALOGV
51#else
52#define ALOGVV(a...) do { } while(0)
53#endif
54
55namespace android {
56
57// ----------------------------------------------------------------------------
58// TrackBase
59// ----------------------------------------------------------------------------
60
Glenn Kastenda6ef132013-01-10 12:31:01 -080061static volatile int32_t nextTrackId = 55;
62
Eric Laurent81784c32012-11-19 14:55:58 -080063// TrackBase constructor must be called with AudioFlinger::mLock held
64AudioFlinger::ThreadBase::TrackBase::TrackBase(
65 ThreadBase *thread,
66 const sp<Client>& client,
67 uint32_t sampleRate,
68 audio_format_t format,
69 audio_channel_mask_t channelMask,
70 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070071 void *buffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080072 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080073 int clientUid,
Glenn Kasten755b0a62014-05-13 11:30:28 -070074 IAudioFlinger::track_flags_t flags,
Glenn Kastend776ac62014-05-07 09:16:09 -070075 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070076 alloc_type alloc,
77 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -080078 : RefBase(),
79 mThread(thread),
80 mClient(client),
81 mCblk(NULL),
82 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080083 mState(IDLE),
84 mSampleRate(sampleRate),
85 mFormat(format),
86 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070087 mChannelCount(isOut ?
88 audio_channel_count_from_out_mask(channelMask) :
89 audio_channel_count_from_in_mask(channelMask)),
Eric Laurent81784c32012-11-19 14:55:58 -080090 mFrameSize(audio_is_linear_pcm(format) ?
91 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
92 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080093 mSessionId(sessionId),
Glenn Kasten755b0a62014-05-13 11:30:28 -070094 mFlags(flags),
Glenn Kastene3aa6592012-12-04 12:22:46 -080095 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080096 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080097 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070098 mTerminated(false),
99 mType(type)
Eric Laurent81784c32012-11-19 14:55:58 -0800100{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800101 // if the caller is us, trust the specified uid
102 if (IPCThreadState::self()->getCallingPid() != getpid_cached || clientUid == -1) {
103 int newclientUid = IPCThreadState::self()->getCallingUid();
104 if (clientUid != -1 && clientUid != newclientUid) {
105 ALOGW("uid %d tried to pass itself off as %d", newclientUid, clientUid);
106 }
107 clientUid = newclientUid;
108 }
109 // clientUid contains the uid of the app that is responsible for this track, so we can blame
110 // battery usage on it.
111 mUid = clientUid;
112
Eric Laurent81784c32012-11-19 14:55:58 -0800113 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
114 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700115 size_t bufferSize = (buffer == NULL ? roundup(frameCount) : frameCount) * mFrameSize;
116 if (buffer == NULL && alloc == ALLOC_CBLK) {
Eric Laurent81784c32012-11-19 14:55:58 -0800117 size += bufferSize;
118 }
119
120 if (client != 0) {
121 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700122 if (mCblkMemory == 0 ||
123 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800124 ALOGE("not enough memory for AudioTrack size=%u", size);
125 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700126 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800127 return;
128 }
129 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800130 // this syntax avoids calling the audio_track_cblk_t constructor twice
131 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800132 // assume mCblk != NULL
133 }
134
135 // construct the shared structure in-place.
136 if (mCblk != NULL) {
137 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700138 switch (alloc) {
139 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700140 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
141 if (roHeap == 0 ||
142 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
143 (mBuffer = mBufferMemory->pointer()) == NULL) {
144 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
145 if (roHeap != 0) {
146 roHeap->dump("buffer");
147 }
148 mCblkMemory.clear();
149 mBufferMemory.clear();
150 return;
151 }
Eric Laurent81784c32012-11-19 14:55:58 -0800152 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700153 } break;
154 case ALLOC_PIPE:
155 mBufferMemory = thread->pipeMemory();
156 // mBuffer is the virtual address as seen from current process (mediaserver),
157 // and should normally be coming from mBufferMemory->pointer().
158 // However in this case the TrackBase does not reference the buffer directly.
159 // It should references the buffer via the pipe.
160 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
161 mBuffer = NULL;
162 break;
163 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700164 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700165 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700166 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
167 memset(mBuffer, 0, bufferSize);
168 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700169 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800170#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700171 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800172#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700173 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700174 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700175 case ALLOC_LOCAL:
176 mBuffer = calloc(1, bufferSize);
177 break;
178 case ALLOC_NONE:
179 mBuffer = buffer;
180 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800181 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800182
Glenn Kasten46909e72013-02-26 09:20:22 -0800183#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800184 if (mTeeSinkTrackEnabled) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800185 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800186 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800187 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
188 size_t numCounterOffers = 0;
189 const NBAIO_Format offers[1] = {pipeFormat};
190 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
191 ALOG_ASSERT(index == 0);
192 PipeReader *pipeReader = new PipeReader(*pipe);
193 numCounterOffers = 0;
194 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
195 ALOG_ASSERT(index == 0);
196 mTeeSink = pipe;
197 mTeeSource = pipeReader;
198 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800199 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800200#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800201
Eric Laurent81784c32012-11-19 14:55:58 -0800202 }
203}
204
Eric Laurent83b88082014-06-20 18:31:16 -0700205status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
206{
207 status_t status;
208 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
209 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
210 } else {
211 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
212 }
213 return status;
214}
215
Eric Laurent81784c32012-11-19 14:55:58 -0800216AudioFlinger::ThreadBase::TrackBase::~TrackBase()
217{
Glenn Kasten46909e72013-02-26 09:20:22 -0800218#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800219 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800220#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800221 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
222 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800223 if (mCblk != NULL) {
224 if (mClient == 0) {
225 delete mCblk;
226 } else {
227 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
228 }
229 }
230 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
231 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700232 // Client destructor must run with AudioFlinger client mutex locked
233 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800234 // If the client's reference count drops to zero, the associated destructor
235 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
236 // relying on the automatic clear() at end of scope.
237 mClient.clear();
238 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700239 // flush the binder command buffer
240 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800241}
242
243// AudioBufferProvider interface
244// getNextBuffer() = 0;
245// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
246void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
247{
Glenn Kasten46909e72013-02-26 09:20:22 -0800248#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800249 if (mTeeSink != 0) {
250 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
251 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800252#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800253
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800254 ServerProxy::Buffer buf;
255 buf.mFrameCount = buffer->frameCount;
256 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800257 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800258 buffer->raw = NULL;
259 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800260}
261
Eric Laurent81784c32012-11-19 14:55:58 -0800262status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
263{
264 mSyncEvents.add(event);
265 return NO_ERROR;
266}
267
268// ----------------------------------------------------------------------------
269// Playback
270// ----------------------------------------------------------------------------
271
272AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
273 : BnAudioTrack(),
274 mTrack(track)
275{
276}
277
278AudioFlinger::TrackHandle::~TrackHandle() {
279 // just stop the track on deletion, associated resources
280 // will be freed from the main thread once all pending buffers have
281 // been played. Unless it's not in the active track list, in which
282 // case we free everything now...
283 mTrack->destroy();
284}
285
286sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
287 return mTrack->getCblk();
288}
289
290status_t AudioFlinger::TrackHandle::start() {
291 return mTrack->start();
292}
293
294void AudioFlinger::TrackHandle::stop() {
295 mTrack->stop();
296}
297
298void AudioFlinger::TrackHandle::flush() {
299 mTrack->flush();
300}
301
Eric Laurent81784c32012-11-19 14:55:58 -0800302void AudioFlinger::TrackHandle::pause() {
303 mTrack->pause();
304}
305
306status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
307{
308 return mTrack->attachAuxEffect(EffectId);
309}
310
311status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
312 sp<IMemory>* buffer) {
313 if (!mTrack->isTimedTrack())
314 return INVALID_OPERATION;
315
316 PlaybackThread::TimedTrack* tt =
317 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
318 return tt->allocateTimedBuffer(size, buffer);
319}
320
321status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
322 int64_t pts) {
323 if (!mTrack->isTimedTrack())
324 return INVALID_OPERATION;
325
Glenn Kasten663c2242013-09-24 11:52:37 -0700326 if (buffer == 0 || buffer->pointer() == NULL) {
327 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
328 return BAD_VALUE;
329 }
330
Eric Laurent81784c32012-11-19 14:55:58 -0800331 PlaybackThread::TimedTrack* tt =
332 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
333 return tt->queueTimedBuffer(buffer, pts);
334}
335
336status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
337 const LinearTransform& xform, int target) {
338
339 if (!mTrack->isTimedTrack())
340 return INVALID_OPERATION;
341
342 PlaybackThread::TimedTrack* tt =
343 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
344 return tt->setMediaTimeTransform(
345 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
346}
347
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700348status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
349 return mTrack->setParameters(keyValuePairs);
350}
351
Glenn Kasten53cec222013-08-29 09:01:02 -0700352status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
353{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700354 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700355}
356
Eric Laurent59fe0102013-09-27 18:48:26 -0700357
358void AudioFlinger::TrackHandle::signal()
359{
360 return mTrack->signal();
361}
362
Eric Laurent81784c32012-11-19 14:55:58 -0800363status_t AudioFlinger::TrackHandle::onTransact(
364 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
365{
366 return BnAudioTrack::onTransact(code, data, reply, flags);
367}
368
369// ----------------------------------------------------------------------------
370
371// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
372AudioFlinger::PlaybackThread::Track::Track(
373 PlaybackThread *thread,
374 const sp<Client>& client,
375 audio_stream_type_t streamType,
376 uint32_t sampleRate,
377 audio_format_t format,
378 audio_channel_mask_t channelMask,
379 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700380 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800381 const sp<IMemory>& sharedBuffer,
382 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800383 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -0700384 IAudioFlinger::track_flags_t flags,
385 track_type type)
386 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
387 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
388 sessionId, uid, flags, true /*isOut*/,
389 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
390 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800391 mFillingUpStatus(FS_INVALID),
392 // mRetryCount initialized later when needed
393 mSharedBuffer(sharedBuffer),
394 mStreamType(streamType),
395 mName(-1), // see note below
396 mMainBuffer(thread->mixBuffer()),
397 mAuxBuffer(NULL),
398 mAuxEffectId(0), mHasVolumeController(false),
399 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800400 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800401 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800402 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800403 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800404 mResumeToStopping(false),
Glenn Kastenced6e742014-06-09 17:12:32 -0700405 mFlushHwPending(false),
406 mPreviousValid(false),
407 mPreviousFramesWritten(0)
408 // mPreviousTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800409{
Eric Laurent83b88082014-06-20 18:31:16 -0700410 // client == 0 implies sharedBuffer == 0
411 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
412
413 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
414 sharedBuffer->size());
415
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700416 if (mCblk == NULL) {
417 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800418 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700419
420 if (sharedBuffer == 0) {
421 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700422 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700423 } else {
424 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
425 mFrameSize);
426 }
427 mServerProxy = mAudioTrackServerProxy;
428
Glenn Kastenc263ca02014-06-04 20:31:46 -0700429 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700430 if (mName < 0) {
431 ALOGE("no more track names available");
432 return;
433 }
434 // only allocate a fast track index if we were able to allocate a normal track name
435 if (flags & IAudioFlinger::TRACK_FAST) {
436 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
437 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
438 int i = __builtin_ctz(thread->mFastTrackAvailMask);
439 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
440 // FIXME This is too eager. We allocate a fast track index before the
441 // fast track becomes active. Since fast tracks are a scarce resource,
442 // this means we are potentially denying other more important fast tracks from
443 // being created. It would be better to allocate the index dynamically.
444 mFastIndex = i;
445 // Read the initial underruns because this field is never cleared by the fast mixer
446 mObservedUnderruns = thread->getFastTrackUnderruns(i);
447 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
485 sp<ThreadBase> thread = mThread.promote();
486 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800487 Mutex::Autolock _l(thread->mLock);
488 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800489 bool wasActive = playbackThread->destroyTrack_l(this);
Eric Laurent83b88082014-06-20 18:31:16 -0700490 if (isExternalTrack() && !wasActive) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800491 AudioSystem::releaseOutput(thread->id());
492 }
Eric Laurent81784c32012-11-19 14:55:58 -0800493 }
494 }
495}
496
497/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
498{
Marco Nelissenb2208842014-02-07 14:00:50 -0800499 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700500 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800501}
502
Marco Nelissenb2208842014-02-07 14:00:50 -0800503void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800504{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700505 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800506 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800507 sprintf(buffer, " F %2d", mFastIndex);
508 } else if (mName >= AudioMixer::TRACK0) {
509 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800510 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800511 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800512 }
513 track_state state = mState;
514 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800515 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800516 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800517 } else {
518 switch (state) {
519 case IDLE:
520 stateChar = 'I';
521 break;
522 case STOPPING_1:
523 stateChar = 's';
524 break;
525 case STOPPING_2:
526 stateChar = '5';
527 break;
528 case STOPPED:
529 stateChar = 'S';
530 break;
531 case RESUMING:
532 stateChar = 'R';
533 break;
534 case ACTIVE:
535 stateChar = 'A';
536 break;
537 case PAUSING:
538 stateChar = 'p';
539 break;
540 case PAUSED:
541 stateChar = 'P';
542 break;
543 case FLUSHED:
544 stateChar = 'F';
545 break;
546 default:
547 stateChar = '?';
548 break;
549 }
Eric Laurent81784c32012-11-19 14:55:58 -0800550 }
551 char nowInUnderrun;
552 switch (mObservedUnderruns.mBitFields.mMostRecent) {
553 case UNDERRUN_FULL:
554 nowInUnderrun = ' ';
555 break;
556 case UNDERRUN_PARTIAL:
557 nowInUnderrun = '<';
558 break;
559 case UNDERRUN_EMPTY:
560 nowInUnderrun = '*';
561 break;
562 default:
563 nowInUnderrun = '?';
564 break;
565 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000566 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 +0000567 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800568 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800569 (mClient == 0) ? getpid_cached : mClient->pid(),
570 mStreamType,
571 mFormat,
572 mChannelMask,
573 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800574 mFrameCount,
575 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800576 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800577 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700578 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
579 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700580 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000581 mMainBuffer,
582 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700583 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700584 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800585 nowInUnderrun);
586}
587
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800588uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
589 return mAudioTrackServerProxy->getSampleRate();
590}
591
Eric Laurent81784c32012-11-19 14:55:58 -0800592// AudioBufferProvider interface
593status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800594 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800595{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800596 ServerProxy::Buffer buf;
597 size_t desiredFrames = buffer->frameCount;
598 buf.mFrameCount = desiredFrames;
599 status_t status = mServerProxy->obtainBuffer(&buf);
600 buffer->frameCount = buf.mFrameCount;
601 buffer->raw = buf.mRaw;
602 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700603 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800604 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800605 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700608// releaseBuffer() is not overridden
609
610// ExtendedAudioBufferProvider interface
611
Eric Laurent81784c32012-11-19 14:55:58 -0800612// Note that framesReady() takes a mutex on the control block using tryLock().
613// This could result in priority inversion if framesReady() is called by the normal mixer,
614// as the normal mixer thread runs at lower
615// priority than the client's callback thread: there is a short window within framesReady()
616// during which the normal mixer could be preempted, and the client callback would block.
617// Another problem can occur if framesReady() is called by the fast mixer:
618// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
619// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
620size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800621 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800622}
623
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700624size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
625{
626 return mAudioTrackServerProxy->framesReleased();
627}
628
Eric Laurent81784c32012-11-19 14:55:58 -0800629// Don't call for fast tracks; the framesReady() could result in priority inversion
630bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800631 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
632 return true;
633 }
634
Eric Laurent16498512014-03-17 17:22:08 -0700635 if (isStopping()) {
636 if (framesReady() > 0) {
637 mFillingUpStatus = FS_FILLED;
638 }
Eric Laurent81784c32012-11-19 14:55:58 -0800639 return true;
640 }
641
642 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700643 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800644 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700645 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800646 return true;
647 }
648 return false;
649}
650
Glenn Kasten0f11b512014-01-31 16:18:54 -0800651status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
652 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800653{
654 status_t status = NO_ERROR;
655 ALOGV("start(%d), calling pid %d session %d",
656 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
657
658 sp<ThreadBase> thread = mThread.promote();
659 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700660 if (isOffloaded()) {
661 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
662 Mutex::Autolock _lth(thread->mLock);
663 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700664 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
665 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700666 invalidate();
667 return PERMISSION_DENIED;
668 }
669 }
670 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800671 track_state state = mState;
672 // here the track could be either new, or restarted
673 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800674
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800675 // initial state-stopping. next state-pausing.
676 // What if resume is called ?
677
678 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800679 if (mResumeToStopping) {
680 // happened we need to resume to STOPPING_1
681 mState = TrackBase::STOPPING_1;
682 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
683 } else {
684 mState = TrackBase::RESUMING;
685 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
686 }
Eric Laurent81784c32012-11-19 14:55:58 -0800687 } else {
688 mState = TrackBase::ACTIVE;
689 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
690 }
691
Eric Laurentbfb1b832013-01-07 09:53:42 -0800692 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
693 status = playbackThread->addTrack_l(this);
694 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800695 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800696 // restore previous state if start was rejected by policy manager
697 if (status == PERMISSION_DENIED) {
698 mState = state;
699 }
700 }
701 // track was already in the active list, not a problem
702 if (status == ALREADY_EXISTS) {
703 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700704 } else {
705 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
706 // It is usually unsafe to access the server proxy from a binder thread.
707 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
708 // isn't looking at this track yet: we still hold the normal mixer thread lock,
709 // and for fast tracks the track is not yet in the fast mixer thread's active set.
710 ServerProxy::Buffer buffer;
711 buffer.mFrameCount = 1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700712 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800713 }
714 } else {
715 status = BAD_VALUE;
716 }
717 return status;
718}
719
720void AudioFlinger::PlaybackThread::Track::stop()
721{
722 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
723 sp<ThreadBase> thread = mThread.promote();
724 if (thread != 0) {
725 Mutex::Autolock _l(thread->mLock);
726 track_state state = mState;
727 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
728 // If the track is not active (PAUSED and buffers full), flush buffers
729 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
730 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
731 reset();
732 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700733 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800734 mState = STOPPED;
735 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800736 // For fast tracks prepareTracks_l() will set state to STOPPING_2
737 // presentation is complete
738 // For an offloaded track this starts a drain and state will
739 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800740 mState = STOPPING_1;
741 }
742 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
743 playbackThread);
744 }
Eric Laurent81784c32012-11-19 14:55:58 -0800745 }
746}
747
748void AudioFlinger::PlaybackThread::Track::pause()
749{
750 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
751 sp<ThreadBase> thread = mThread.promote();
752 if (thread != 0) {
753 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800754 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
755 switch (mState) {
756 case STOPPING_1:
757 case STOPPING_2:
758 if (!isOffloaded()) {
759 /* nothing to do if track is not offloaded */
760 break;
761 }
762
763 // Offloaded track was draining, we need to carry on draining when resumed
764 mResumeToStopping = true;
765 // fall through...
766 case ACTIVE:
767 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800768 mState = PAUSING;
769 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700770 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800771 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800772
Eric Laurentbfb1b832013-01-07 09:53:42 -0800773 default:
774 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800775 }
776 }
777}
778
779void AudioFlinger::PlaybackThread::Track::flush()
780{
781 ALOGV("flush(%d)", mName);
782 sp<ThreadBase> thread = mThread.promote();
783 if (thread != 0) {
784 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800785 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800786
787 if (isOffloaded()) {
788 // If offloaded we allow flush during any state except terminated
789 // and keep the track active to avoid problems if user is seeking
790 // rapidly and underlying hardware has a significant delay handling
791 // a pause
792 if (isTerminated()) {
793 return;
794 }
795
796 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800797 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800798
799 if (mState == STOPPING_1 || mState == STOPPING_2) {
800 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
801 mState = ACTIVE;
802 }
803
804 if (mState == ACTIVE) {
805 ALOGV("flush called in active state, resetting buffer time out retry count");
806 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
807 }
808
Haynes Mathew George7844f672014-01-15 12:32:55 -0800809 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800810 mResumeToStopping = false;
811 } else {
812 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
813 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
814 return;
815 }
816 // No point remaining in PAUSED state after a flush => go to
817 // FLUSHED state
818 mState = FLUSHED;
819 // do not reset the track if it is still in the process of being stopped or paused.
820 // this will be done by prepareTracks_l() when the track is stopped.
821 // prepareTracks_l() will see mState == FLUSHED, then
822 // remove from active track list, reset(), and trigger presentation complete
823 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
824 reset();
825 }
Eric Laurent81784c32012-11-19 14:55:58 -0800826 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800827 // Prevent flush being lost if the track is flushed and then resumed
828 // before mixer thread can run. This is important when offloading
829 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700830 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800831 }
832}
833
Haynes Mathew George7844f672014-01-15 12:32:55 -0800834// must be called with thread lock held
835void AudioFlinger::PlaybackThread::Track::flushAck()
836{
837 if (!isOffloaded())
838 return;
839
840 mFlushHwPending = false;
841}
842
Eric Laurent81784c32012-11-19 14:55:58 -0800843void AudioFlinger::PlaybackThread::Track::reset()
844{
845 // Do not reset twice to avoid discarding data written just after a flush and before
846 // the audioflinger thread detects the track is stopped.
847 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800848 // Force underrun condition to avoid false underrun callback until first data is
849 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700850 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800851 mFillingUpStatus = FS_FILLING;
852 mResetDone = true;
853 if (mState == FLUSHED) {
854 mState = IDLE;
855 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -0700856 mPreviousValid = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800857 }
858}
859
Eric Laurentbfb1b832013-01-07 09:53:42 -0800860status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
861{
862 sp<ThreadBase> thread = mThread.promote();
863 if (thread == 0) {
864 ALOGE("thread is dead");
865 return FAILED_TRANSACTION;
866 } else if ((thread->type() == ThreadBase::DIRECT) ||
867 (thread->type() == ThreadBase::OFFLOAD)) {
868 return thread->setParameters(keyValuePairs);
869 } else {
870 return PERMISSION_DENIED;
871 }
872}
873
Glenn Kasten573d80a2013-08-26 09:36:23 -0700874status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
875{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700876 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
877 if (isFastTrack()) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700878 // FIXME no lock held to set mPreviousValid = false
Glenn Kastenfe346c72013-08-30 13:28:22 -0700879 return INVALID_OPERATION;
880 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700881 sp<ThreadBase> thread = mThread.promote();
882 if (thread == 0) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700883 // FIXME no lock held to set mPreviousValid = false
Glenn Kastenfe346c72013-08-30 13:28:22 -0700884 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700885 }
886 Mutex::Autolock _l(thread->mLock);
887 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentab5cdba2014-06-09 17:22:27 -0700888 if (!isOffloaded() && !isDirect()) {
Eric Laurentaccc1472013-09-20 09:36:34 -0700889 if (!playbackThread->mLatchQValid) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700890 mPreviousValid = false;
Eric Laurentaccc1472013-09-20 09:36:34 -0700891 return INVALID_OPERATION;
892 }
893 uint32_t unpresentedFrames =
894 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
895 playbackThread->mSampleRate;
896 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
Glenn Kastenced6e742014-06-09 17:12:32 -0700897 bool checkPreviousTimestamp = mPreviousValid && framesWritten >= mPreviousFramesWritten;
Eric Laurentaccc1472013-09-20 09:36:34 -0700898 if (framesWritten < unpresentedFrames) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700899 mPreviousValid = false;
Eric Laurentaccc1472013-09-20 09:36:34 -0700900 return INVALID_OPERATION;
901 }
Glenn Kastenced6e742014-06-09 17:12:32 -0700902 mPreviousFramesWritten = framesWritten;
903 uint32_t position = framesWritten - unpresentedFrames;
904 struct timespec time = playbackThread->mLatchQ.mTimestamp.mTime;
905 if (checkPreviousTimestamp) {
906 if (time.tv_sec < mPreviousTimestamp.mTime.tv_sec ||
907 (time.tv_sec == mPreviousTimestamp.mTime.tv_sec &&
908 time.tv_nsec < mPreviousTimestamp.mTime.tv_nsec)) {
909 ALOGW("Time is going backwards");
910 }
911 // position can bobble slightly as an artifact; this hides the bobble
912 static const uint32_t MINIMUM_POSITION_DELTA = 8u;
913 if ((position <= mPreviousTimestamp.mPosition) ||
914 (position - mPreviousTimestamp.mPosition) < MINIMUM_POSITION_DELTA) {
915 position = mPreviousTimestamp.mPosition;
916 time = mPreviousTimestamp.mTime;
917 }
918 }
919 timestamp.mPosition = position;
920 timestamp.mTime = time;
921 mPreviousTimestamp = timestamp;
922 mPreviousValid = true;
Eric Laurentaccc1472013-09-20 09:36:34 -0700923 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700924 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700925
926 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700927}
928
Eric Laurent81784c32012-11-19 14:55:58 -0800929status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
930{
931 status_t status = DEAD_OBJECT;
932 sp<ThreadBase> thread = mThread.promote();
933 if (thread != 0) {
934 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
935 sp<AudioFlinger> af = mClient->audioFlinger();
936
937 Mutex::Autolock _l(af->mLock);
938
939 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
940
941 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
942 Mutex::Autolock _dl(playbackThread->mLock);
943 Mutex::Autolock _sl(srcThread->mLock);
944 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
945 if (chain == 0) {
946 return INVALID_OPERATION;
947 }
948
949 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
950 if (effect == 0) {
951 return INVALID_OPERATION;
952 }
953 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700954 status = playbackThread->addEffect_l(effect);
955 if (status != NO_ERROR) {
956 srcThread->addEffect_l(effect);
957 return INVALID_OPERATION;
958 }
Eric Laurent81784c32012-11-19 14:55:58 -0800959 // removeEffect_l() has stopped the effect if it was active so it must be restarted
960 if (effect->state() == EffectModule::ACTIVE ||
961 effect->state() == EffectModule::STOPPING) {
962 effect->start();
963 }
964
965 sp<EffectChain> dstChain = effect->chain().promote();
966 if (dstChain == 0) {
967 srcThread->addEffect_l(effect);
968 return INVALID_OPERATION;
969 }
970 AudioSystem::unregisterEffect(effect->id());
971 AudioSystem::registerEffect(&effect->desc(),
972 srcThread->id(),
973 dstChain->strategy(),
974 AUDIO_SESSION_OUTPUT_MIX,
975 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700976 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800977 }
978 status = playbackThread->attachAuxEffect(this, EffectId);
979 }
980 return status;
981}
982
983void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
984{
985 mAuxEffectId = EffectId;
986 mAuxBuffer = buffer;
987}
988
989bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
990 size_t audioHalFrames)
991{
992 // a track is considered presented when the total number of frames written to audio HAL
993 // corresponds to the number of frames written when presentationComplete() is called for the
994 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800995 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
996 // to detect when all frames have been played. In this case framesWritten isn't
997 // useful because it doesn't always reflect whether there is data in the h/w
998 // buffers, particularly if a track has been paused and resumed during draining
999 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
1000 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001001 if (mPresentationCompleteFrames == 0) {
1002 mPresentationCompleteFrames = framesWritten + audioHalFrames;
1003 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
1004 mPresentationCompleteFrames, audioHalFrames);
1005 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001006
1007 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001008 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001009 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001010 return true;
1011 }
1012 return false;
1013}
1014
1015void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1016{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001017 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001018 if (mSyncEvents[i]->type() == type) {
1019 mSyncEvents[i]->trigger();
1020 mSyncEvents.removeAt(i);
1021 i--;
1022 }
1023 }
1024}
1025
1026// implement VolumeBufferProvider interface
1027
Glenn Kastenc56f3422014-03-21 17:53:17 -07001028gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001029{
1030 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1031 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001032 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1033 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1034 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001035 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001036 if (vl > GAIN_FLOAT_UNITY) {
1037 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001038 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001039 if (vr > GAIN_FLOAT_UNITY) {
1040 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001041 }
1042 // now apply the cached master volume and stream type volume;
1043 // this is trusted but lacks any synchronization or barrier so may be stale
1044 float v = mCachedVolume;
1045 vl *= v;
1046 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001047 // re-combine into packed minifloat
1048 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001049 // FIXME look at mute, pause, and stop flags
1050 return vlr;
1051}
1052
1053status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1054{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001055 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001056 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1057 (mState == STOPPED)))) {
1058 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1059 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1060 event->cancel();
1061 return INVALID_OPERATION;
1062 }
1063 (void) TrackBase::setSyncEvent(event);
1064 return NO_ERROR;
1065}
1066
Glenn Kasten5736c352012-12-04 12:12:34 -08001067void AudioFlinger::PlaybackThread::Track::invalidate()
1068{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001069 // FIXME should use proxy, and needs work
1070 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001071 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001072 android_atomic_release_store(0x40000000, &cblk->mFutex);
1073 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001074 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001075 mIsInvalid = true;
1076}
1077
Eric Laurent59fe0102013-09-27 18:48:26 -07001078void AudioFlinger::PlaybackThread::Track::signal()
1079{
1080 sp<ThreadBase> thread = mThread.promote();
1081 if (thread != 0) {
1082 PlaybackThread *t = (PlaybackThread *)thread.get();
1083 Mutex::Autolock _l(t->mLock);
1084 t->broadcast_l();
1085 }
1086}
1087
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001088//To be called with thread lock held
1089bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1090
1091 if (mState == RESUMING)
1092 return true;
1093 /* Resume is pending if track was stopping before pause was called */
1094 if (mState == STOPPING_1 &&
1095 mResumeToStopping)
1096 return true;
1097
1098 return false;
1099}
1100
1101//To be called with thread lock held
1102void AudioFlinger::PlaybackThread::Track::resumeAck() {
1103
1104
1105 if (mState == RESUMING)
1106 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001107
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001108 // Other possibility of pending resume is stopping_1 state
1109 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001110 // drain being called.
1111 if (mState == STOPPING_1) {
1112 mResumeToStopping = false;
1113 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001114}
Eric Laurent81784c32012-11-19 14:55:58 -08001115// ----------------------------------------------------------------------------
1116
1117sp<AudioFlinger::PlaybackThread::TimedTrack>
1118AudioFlinger::PlaybackThread::TimedTrack::create(
1119 PlaybackThread *thread,
1120 const sp<Client>& client,
1121 audio_stream_type_t streamType,
1122 uint32_t sampleRate,
1123 audio_format_t format,
1124 audio_channel_mask_t channelMask,
1125 size_t frameCount,
1126 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001127 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001128 int uid)
1129{
Eric Laurent81784c32012-11-19 14:55:58 -08001130 if (!client->reserveTimedTrack())
1131 return 0;
1132
1133 return new TimedTrack(
1134 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001135 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001136}
1137
1138AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1139 PlaybackThread *thread,
1140 const sp<Client>& client,
1141 audio_stream_type_t streamType,
1142 uint32_t sampleRate,
1143 audio_format_t format,
1144 audio_channel_mask_t channelMask,
1145 size_t frameCount,
1146 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001147 int sessionId,
1148 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001149 : Track(thread, client, streamType, sampleRate, format, channelMask,
Eric Laurent83b88082014-06-20 18:31:16 -07001150 frameCount, (sharedBuffer != 0) ? sharedBuffer->pointer() : NULL, sharedBuffer,
1151 sessionId, uid, IAudioFlinger::TRACK_TIMED, TYPE_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001152 mQueueHeadInFlight(false),
1153 mTrimQueueHeadOnRelease(false),
1154 mFramesPendingInQueue(0),
1155 mTimedSilenceBuffer(NULL),
1156 mTimedSilenceBufferSize(0),
1157 mTimedAudioOutputOnTime(false),
1158 mMediaTimeTransformValid(false)
1159{
1160 LocalClock lc;
1161 mLocalTimeFreq = lc.getLocalFreq();
1162
1163 mLocalTimeToSampleTransform.a_zero = 0;
1164 mLocalTimeToSampleTransform.b_zero = 0;
1165 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1166 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1167 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1168 &mLocalTimeToSampleTransform.a_to_b_denom);
1169
1170 mMediaTimeToSampleTransform.a_zero = 0;
1171 mMediaTimeToSampleTransform.b_zero = 0;
1172 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1173 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1174 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1175 &mMediaTimeToSampleTransform.a_to_b_denom);
1176}
1177
1178AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1179 mClient->releaseTimedTrack();
1180 delete [] mTimedSilenceBuffer;
1181}
1182
1183status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1184 size_t size, sp<IMemory>* buffer) {
1185
1186 Mutex::Autolock _l(mTimedBufferQueueLock);
1187
1188 trimTimedBufferQueue_l();
1189
1190 // lazily initialize the shared memory heap for timed buffers
1191 if (mTimedMemoryDealer == NULL) {
1192 const int kTimedBufferHeapSize = 512 << 10;
1193
1194 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1195 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001196 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001197 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001198 }
Eric Laurent81784c32012-11-19 14:55:58 -08001199 }
1200
1201 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001202 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001203 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001204 }
1205
1206 *buffer = newBuffer;
1207 return NO_ERROR;
1208}
1209
1210// caller must hold mTimedBufferQueueLock
1211void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1212 int64_t mediaTimeNow;
1213 {
1214 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1215 if (!mMediaTimeTransformValid)
1216 return;
1217
1218 int64_t targetTimeNow;
1219 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1220 ? mCCHelper.getCommonTime(&targetTimeNow)
1221 : mCCHelper.getLocalTime(&targetTimeNow);
1222
1223 if (OK != res)
1224 return;
1225
1226 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1227 &mediaTimeNow)) {
1228 return;
1229 }
1230 }
1231
1232 size_t trimEnd;
1233 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1234 int64_t bufEnd;
1235
1236 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1237 // We have a next buffer. Just use its PTS as the PTS of the frame
1238 // following the last frame in this buffer. If the stream is sparse
1239 // (ie, there are deliberate gaps left in the stream which should be
1240 // filled with silence by the TimedAudioTrack), then this can result
1241 // in one extra buffer being left un-trimmed when it could have
1242 // been. In general, this is not typical, and we would rather
1243 // optimized away the TS calculation below for the more common case
1244 // where PTSes are contiguous.
1245 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1246 } else {
1247 // We have no next buffer. Compute the PTS of the frame following
1248 // the last frame in this buffer by computing the duration of of
1249 // this frame in media time units and adding it to the PTS of the
1250 // buffer.
1251 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1252 / mFrameSize;
1253
1254 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1255 &bufEnd)) {
1256 ALOGE("Failed to convert frame count of %lld to media time"
1257 " duration" " (scale factor %d/%u) in %s",
1258 frameCount,
1259 mMediaTimeToSampleTransform.a_to_b_numer,
1260 mMediaTimeToSampleTransform.a_to_b_denom,
1261 __PRETTY_FUNCTION__);
1262 break;
1263 }
1264 bufEnd += mTimedBufferQueue[trimEnd].pts();
1265 }
1266
1267 if (bufEnd > mediaTimeNow)
1268 break;
1269
1270 // Is the buffer we want to use in the middle of a mix operation right
1271 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1272 // from the mixer which should be coming back shortly.
1273 if (!trimEnd && mQueueHeadInFlight) {
1274 mTrimQueueHeadOnRelease = true;
1275 }
1276 }
1277
1278 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1279 if (trimStart < trimEnd) {
1280 // Update the bookkeeping for framesReady()
1281 for (size_t i = trimStart; i < trimEnd; ++i) {
1282 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1283 }
1284
1285 // Now actually remove the buffers from the queue.
1286 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1287 }
1288}
1289
1290void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1291 const char* logTag) {
1292 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1293 "%s called (reason \"%s\"), but timed buffer queue has no"
1294 " elements to trim.", __FUNCTION__, logTag);
1295
1296 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1297 mTimedBufferQueue.removeAt(0);
1298}
1299
1300void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1301 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001302 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001303 uint32_t bufBytes = buf.buffer()->size();
1304 uint32_t consumedAlready = buf.position();
1305
1306 ALOG_ASSERT(consumedAlready <= bufBytes,
1307 "Bad bookkeeping while updating frames pending. Timed buffer is"
1308 " only %u bytes long, but claims to have consumed %u"
1309 " bytes. (update reason: \"%s\")",
1310 bufBytes, consumedAlready, logTag);
1311
1312 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1313 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1314 "Bad bookkeeping while updating frames pending. Should have at"
1315 " least %u queued frames, but we think we have only %u. (update"
1316 " reason: \"%s\")",
1317 bufFrames, mFramesPendingInQueue, logTag);
1318
1319 mFramesPendingInQueue -= bufFrames;
1320}
1321
1322status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1323 const sp<IMemory>& buffer, int64_t pts) {
1324
1325 {
1326 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1327 if (!mMediaTimeTransformValid)
1328 return INVALID_OPERATION;
1329 }
1330
1331 Mutex::Autolock _l(mTimedBufferQueueLock);
1332
1333 uint32_t bufFrames = buffer->size() / mFrameSize;
1334 mFramesPendingInQueue += bufFrames;
1335 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1336
1337 return NO_ERROR;
1338}
1339
1340status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1341 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1342
1343 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1344 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1345 target);
1346
1347 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1348 target == TimedAudioTrack::COMMON_TIME)) {
1349 return BAD_VALUE;
1350 }
1351
1352 Mutex::Autolock lock(mMediaTimeTransformLock);
1353 mMediaTimeTransform = xform;
1354 mMediaTimeTransformTarget = target;
1355 mMediaTimeTransformValid = true;
1356
1357 return NO_ERROR;
1358}
1359
1360#define min(a, b) ((a) < (b) ? (a) : (b))
1361
1362// implementation of getNextBuffer for tracks whose buffers have timestamps
1363status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1364 AudioBufferProvider::Buffer* buffer, int64_t pts)
1365{
1366 if (pts == AudioBufferProvider::kInvalidPTS) {
1367 buffer->raw = NULL;
1368 buffer->frameCount = 0;
1369 mTimedAudioOutputOnTime = false;
1370 return INVALID_OPERATION;
1371 }
1372
1373 Mutex::Autolock _l(mTimedBufferQueueLock);
1374
1375 ALOG_ASSERT(!mQueueHeadInFlight,
1376 "getNextBuffer called without releaseBuffer!");
1377
1378 while (true) {
1379
1380 // if we have no timed buffers, then fail
1381 if (mTimedBufferQueue.isEmpty()) {
1382 buffer->raw = NULL;
1383 buffer->frameCount = 0;
1384 return NOT_ENOUGH_DATA;
1385 }
1386
1387 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1388
1389 // calculate the PTS of the head of the timed buffer queue expressed in
1390 // local time
1391 int64_t headLocalPTS;
1392 {
1393 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1394
1395 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1396
1397 if (mMediaTimeTransform.a_to_b_denom == 0) {
1398 // the transform represents a pause, so yield silence
1399 timedYieldSilence_l(buffer->frameCount, buffer);
1400 return NO_ERROR;
1401 }
1402
1403 int64_t transformedPTS;
1404 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1405 &transformedPTS)) {
1406 // the transform failed. this shouldn't happen, but if it does
1407 // then just drop this buffer
1408 ALOGW("timedGetNextBuffer transform failed");
1409 buffer->raw = NULL;
1410 buffer->frameCount = 0;
1411 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1412 return NO_ERROR;
1413 }
1414
1415 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1416 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1417 &headLocalPTS)) {
1418 buffer->raw = NULL;
1419 buffer->frameCount = 0;
1420 return INVALID_OPERATION;
1421 }
1422 } else {
1423 headLocalPTS = transformedPTS;
1424 }
1425 }
1426
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001427 uint32_t sr = sampleRate();
1428
Eric Laurent81784c32012-11-19 14:55:58 -08001429 // adjust the head buffer's PTS to reflect the portion of the head buffer
1430 // that has already been consumed
1431 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001432 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001433
1434 // Calculate the delta in samples between the head of the input buffer
1435 // queue and the start of the next output buffer that will be written.
1436 // If the transformation fails because of over or underflow, it means
1437 // that the sample's position in the output stream is so far out of
1438 // whack that it should just be dropped.
1439 int64_t sampleDelta;
1440 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1441 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1442 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1443 " mix");
1444 continue;
1445 }
1446 if (!mLocalTimeToSampleTransform.doForwardTransform(
1447 (effectivePTS - pts) << 32, &sampleDelta)) {
1448 ALOGV("*** too late during sample rate transform: dropped buffer");
1449 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1450 continue;
1451 }
1452
1453 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1454 " sampleDelta=[%d.%08x]",
1455 head.pts(), head.position(), pts,
1456 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1457 + (sampleDelta >> 32)),
1458 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1459
1460 // if the delta between the ideal placement for the next input sample and
1461 // the current output position is within this threshold, then we will
1462 // concatenate the next input samples to the previous output
1463 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001464 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001465
1466 // if this is the first buffer of audio that we're emitting from this track
1467 // then it should be almost exactly on time.
1468 const int64_t kSampleStartupThreshold = 1LL << 32;
1469
1470 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1471 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1472 // the next input is close enough to being on time, so concatenate it
1473 // with the last output
1474 timedYieldSamples_l(buffer);
1475
1476 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1477 head.position(), buffer->frameCount);
1478 return NO_ERROR;
1479 }
1480
1481 // Looks like our output is not on time. Reset our on timed status.
1482 // Next time we mix samples from our input queue, then should be within
1483 // the StartupThreshold.
1484 mTimedAudioOutputOnTime = false;
1485 if (sampleDelta > 0) {
1486 // the gap between the current output position and the proper start of
1487 // the next input sample is too big, so fill it with silence
1488 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1489
1490 timedYieldSilence_l(framesUntilNextInput, buffer);
1491 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1492 return NO_ERROR;
1493 } else {
1494 // the next input sample is late
1495 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1496 size_t onTimeSamplePosition =
1497 head.position() + lateFrames * mFrameSize;
1498
1499 if (onTimeSamplePosition > head.buffer()->size()) {
1500 // all the remaining samples in the head are too late, so
1501 // drop it and move on
1502 ALOGV("*** too late: dropped buffer");
1503 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1504 continue;
1505 } else {
1506 // skip over the late samples
1507 head.setPosition(onTimeSamplePosition);
1508
1509 // yield the available samples
1510 timedYieldSamples_l(buffer);
1511
1512 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1513 return NO_ERROR;
1514 }
1515 }
1516 }
1517}
1518
1519// Yield samples from the timed buffer queue head up to the given output
1520// buffer's capacity.
1521//
1522// Caller must hold mTimedBufferQueueLock
1523void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1524 AudioBufferProvider::Buffer* buffer) {
1525
1526 const TimedBuffer& head = mTimedBufferQueue[0];
1527
1528 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1529 head.position());
1530
1531 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1532 mFrameSize);
1533 size_t framesRequested = buffer->frameCount;
1534 buffer->frameCount = min(framesLeftInHead, framesRequested);
1535
1536 mQueueHeadInFlight = true;
1537 mTimedAudioOutputOnTime = true;
1538}
1539
1540// Yield samples of silence up to the given output buffer's capacity
1541//
1542// Caller must hold mTimedBufferQueueLock
1543void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1544 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1545
1546 // lazily allocate a buffer filled with silence
1547 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1548 delete [] mTimedSilenceBuffer;
1549 mTimedSilenceBufferSize = numFrames * mFrameSize;
1550 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1551 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1552 }
1553
1554 buffer->raw = mTimedSilenceBuffer;
1555 size_t framesRequested = buffer->frameCount;
1556 buffer->frameCount = min(numFrames, framesRequested);
1557
1558 mTimedAudioOutputOnTime = false;
1559}
1560
1561// AudioBufferProvider interface
1562void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1563 AudioBufferProvider::Buffer* buffer) {
1564
1565 Mutex::Autolock _l(mTimedBufferQueueLock);
1566
1567 // If the buffer which was just released is part of the buffer at the head
1568 // of the queue, be sure to update the amt of the buffer which has been
1569 // consumed. If the buffer being returned is not part of the head of the
1570 // queue, its either because the buffer is part of the silence buffer, or
1571 // because the head of the timed queue was trimmed after the mixer called
1572 // getNextBuffer but before the mixer called releaseBuffer.
1573 if (buffer->raw == mTimedSilenceBuffer) {
1574 ALOG_ASSERT(!mQueueHeadInFlight,
1575 "Queue head in flight during release of silence buffer!");
1576 goto done;
1577 }
1578
1579 ALOG_ASSERT(mQueueHeadInFlight,
1580 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1581 " head in flight.");
1582
1583 if (mTimedBufferQueue.size()) {
1584 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1585
1586 void* start = head.buffer()->pointer();
1587 void* end = reinterpret_cast<void*>(
1588 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1589 + head.buffer()->size());
1590
1591 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1592 "released buffer not within the head of the timed buffer"
1593 " queue; qHead = [%p, %p], released buffer = %p",
1594 start, end, buffer->raw);
1595
1596 head.setPosition(head.position() +
1597 (buffer->frameCount * mFrameSize));
1598 mQueueHeadInFlight = false;
1599
1600 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1601 "Bad bookkeeping during releaseBuffer! Should have at"
1602 " least %u queued frames, but we think we have only %u",
1603 buffer->frameCount, mFramesPendingInQueue);
1604
1605 mFramesPendingInQueue -= buffer->frameCount;
1606
1607 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1608 || mTrimQueueHeadOnRelease) {
1609 trimTimedBufferQueueHead_l("releaseBuffer");
1610 mTrimQueueHeadOnRelease = false;
1611 }
1612 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001613 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001614 " buffers in the timed buffer queue");
1615 }
1616
1617done:
1618 buffer->raw = 0;
1619 buffer->frameCount = 0;
1620}
1621
1622size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1623 Mutex::Autolock _l(mTimedBufferQueueLock);
1624 return mFramesPendingInQueue;
1625}
1626
1627AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1628 : mPTS(0), mPosition(0) {}
1629
1630AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1631 const sp<IMemory>& buffer, int64_t pts)
1632 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1633
1634
1635// ----------------------------------------------------------------------------
1636
1637AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1638 PlaybackThread *playbackThread,
1639 DuplicatingThread *sourceThread,
1640 uint32_t sampleRate,
1641 audio_format_t format,
1642 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001643 size_t frameCount,
1644 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001645 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001646 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001647 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001648{
1649
1650 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001651 mOutBuffer.frameCount = 0;
1652 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001653 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001654 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001655 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001656 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001657 // since client and server are in the same process,
1658 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001659 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1660 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001661 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001662 mClientProxy->setSendLevel(0.0);
1663 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001664 } else {
1665 ALOGW("Error creating output track on thread %p", playbackThread);
1666 }
1667}
1668
1669AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1670{
1671 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001672 delete mClientProxy;
1673 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001674}
1675
1676status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1677 int triggerSession)
1678{
1679 status_t status = Track::start(event, triggerSession);
1680 if (status != NO_ERROR) {
1681 return status;
1682 }
1683
1684 mActive = true;
1685 mRetryCount = 127;
1686 return status;
1687}
1688
1689void AudioFlinger::PlaybackThread::OutputTrack::stop()
1690{
1691 Track::stop();
1692 clearBufferQueue();
1693 mOutBuffer.frameCount = 0;
1694 mActive = false;
1695}
1696
1697bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1698{
1699 Buffer *pInBuffer;
1700 Buffer inBuffer;
1701 uint32_t channelCount = mChannelCount;
1702 bool outputBufferFull = false;
1703 inBuffer.frameCount = frames;
1704 inBuffer.i16 = data;
1705
1706 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1707
1708 if (!mActive && frames != 0) {
1709 start();
1710 sp<ThreadBase> thread = mThread.promote();
1711 if (thread != 0) {
1712 MixerThread *mixerThread = (MixerThread *)thread.get();
1713 if (mFrameCount > frames) {
1714 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1715 uint32_t startFrames = (mFrameCount - frames);
1716 pInBuffer = new Buffer;
1717 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1718 pInBuffer->frameCount = startFrames;
1719 pInBuffer->i16 = pInBuffer->mBuffer;
1720 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1721 mBufferQueue.add(pInBuffer);
1722 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001723 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001724 }
1725 }
1726 }
1727 }
1728
1729 while (waitTimeLeftMs) {
1730 // First write pending buffers, then new data
1731 if (mBufferQueue.size()) {
1732 pInBuffer = mBufferQueue.itemAt(0);
1733 } else {
1734 pInBuffer = &inBuffer;
1735 }
1736
1737 if (pInBuffer->frameCount == 0) {
1738 break;
1739 }
1740
1741 if (mOutBuffer.frameCount == 0) {
1742 mOutBuffer.frameCount = pInBuffer->frameCount;
1743 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001744 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1745 if (status != NO_ERROR) {
1746 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1747 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001748 outputBufferFull = true;
1749 break;
1750 }
1751 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1752 if (waitTimeLeftMs >= waitTimeMs) {
1753 waitTimeLeftMs -= waitTimeMs;
1754 } else {
1755 waitTimeLeftMs = 0;
1756 }
1757 }
1758
1759 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1760 pInBuffer->frameCount;
1761 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001762 Proxy::Buffer buf;
1763 buf.mFrameCount = outFrames;
1764 buf.mRaw = NULL;
1765 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001766 pInBuffer->frameCount -= outFrames;
1767 pInBuffer->i16 += outFrames * channelCount;
1768 mOutBuffer.frameCount -= outFrames;
1769 mOutBuffer.i16 += outFrames * channelCount;
1770
1771 if (pInBuffer->frameCount == 0) {
1772 if (mBufferQueue.size()) {
1773 mBufferQueue.removeAt(0);
1774 delete [] pInBuffer->mBuffer;
1775 delete pInBuffer;
1776 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1777 mThread.unsafe_get(), mBufferQueue.size());
1778 } else {
1779 break;
1780 }
1781 }
1782 }
1783
1784 // If we could not write all frames, allocate a buffer and queue it for next time.
1785 if (inBuffer.frameCount) {
1786 sp<ThreadBase> thread = mThread.promote();
1787 if (thread != 0 && !thread->standby()) {
1788 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1789 pInBuffer = new Buffer;
1790 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1791 pInBuffer->frameCount = inBuffer.frameCount;
1792 pInBuffer->i16 = pInBuffer->mBuffer;
1793 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1794 sizeof(int16_t));
1795 mBufferQueue.add(pInBuffer);
1796 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1797 mThread.unsafe_get(), mBufferQueue.size());
1798 } else {
1799 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1800 mThread.unsafe_get(), this);
1801 }
1802 }
1803 }
1804
1805 // Calling write() with a 0 length buffer, means that no more data will be written:
1806 // If no more buffers are pending, fill output track buffer to make sure it is started
1807 // by output mixer.
1808 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001809 // FIXME borken, replace by getting framesReady() from proxy
1810 size_t user = 0; // was mCblk->user
1811 if (user < mFrameCount) {
1812 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001813 pInBuffer = new Buffer;
1814 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1815 pInBuffer->frameCount = frames;
1816 pInBuffer->i16 = pInBuffer->mBuffer;
1817 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1818 mBufferQueue.add(pInBuffer);
1819 } else if (mActive) {
1820 stop();
1821 }
1822 }
1823
1824 return outputBufferFull;
1825}
1826
1827status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1828 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1829{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001830 ClientProxy::Buffer buf;
1831 buf.mFrameCount = buffer->frameCount;
1832 struct timespec timeout;
1833 timeout.tv_sec = waitTimeMs / 1000;
1834 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1835 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1836 buffer->frameCount = buf.mFrameCount;
1837 buffer->raw = buf.mRaw;
1838 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001839}
1840
Eric Laurent81784c32012-11-19 14:55:58 -08001841void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1842{
1843 size_t size = mBufferQueue.size();
1844
1845 for (size_t i = 0; i < size; i++) {
1846 Buffer *pBuffer = mBufferQueue.itemAt(i);
1847 delete [] pBuffer->mBuffer;
1848 delete pBuffer;
1849 }
1850 mBufferQueue.clear();
1851}
1852
1853
Eric Laurent83b88082014-06-20 18:31:16 -07001854AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
1855 uint32_t sampleRate,
1856 audio_channel_mask_t channelMask,
1857 audio_format_t format,
1858 size_t frameCount,
1859 void *buffer,
1860 IAudioFlinger::track_flags_t flags)
1861 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1862 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1863 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1864{
1865 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1866 playbackThread->sampleRate();
1867 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1868 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1869
1870 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1871 this, sampleRate,
1872 (int)mPeerTimeout.tv_sec,
1873 (int)(mPeerTimeout.tv_nsec / 1000000));
1874}
1875
1876AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1877{
1878}
1879
1880// AudioBufferProvider interface
1881status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
1882 AudioBufferProvider::Buffer* buffer, int64_t pts)
1883{
1884 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1885 Proxy::Buffer buf;
1886 buf.mFrameCount = buffer->frameCount;
1887 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1888 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001889 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001890 if (buf.mFrameCount == 0) {
1891 return WOULD_BLOCK;
1892 }
Eric Laurent83b88082014-06-20 18:31:16 -07001893 status = Track::getNextBuffer(buffer, pts);
1894 return status;
1895}
1896
1897void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1898{
1899 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1900 Proxy::Buffer buf;
1901 buf.mFrameCount = buffer->frameCount;
1902 buf.mRaw = buffer->raw;
1903 mPeerProxy->releaseBuffer(&buf);
1904 TrackBase::releaseBuffer(buffer);
1905}
1906
1907status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1908 const struct timespec *timeOut)
1909{
1910 return mProxy->obtainBuffer(buffer, timeOut);
1911}
1912
1913void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1914{
1915 mProxy->releaseBuffer(buffer);
1916 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1917 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1918 start();
1919 }
1920 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1921}
1922
Eric Laurent81784c32012-11-19 14:55:58 -08001923// ----------------------------------------------------------------------------
1924// Record
1925// ----------------------------------------------------------------------------
1926
1927AudioFlinger::RecordHandle::RecordHandle(
1928 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1929 : BnAudioRecord(),
1930 mRecordTrack(recordTrack)
1931{
1932}
1933
1934AudioFlinger::RecordHandle::~RecordHandle() {
1935 stop_nonvirtual();
1936 mRecordTrack->destroy();
1937}
1938
Eric Laurent81784c32012-11-19 14:55:58 -08001939status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1940 int triggerSession) {
1941 ALOGV("RecordHandle::start()");
1942 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1943}
1944
1945void AudioFlinger::RecordHandle::stop() {
1946 stop_nonvirtual();
1947}
1948
1949void AudioFlinger::RecordHandle::stop_nonvirtual() {
1950 ALOGV("RecordHandle::stop()");
1951 mRecordTrack->stop();
1952}
1953
1954status_t AudioFlinger::RecordHandle::onTransact(
1955 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1956{
1957 return BnAudioRecord::onTransact(code, data, reply, flags);
1958}
1959
1960// ----------------------------------------------------------------------------
1961
Glenn Kasten05997e22014-03-13 15:08:33 -07001962// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001963AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1964 RecordThread *thread,
1965 const sp<Client>& client,
1966 uint32_t sampleRate,
1967 audio_format_t format,
1968 audio_channel_mask_t channelMask,
1969 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001970 void *buffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001971 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001972 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -07001973 IAudioFlinger::track_flags_t flags,
1974 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001975 : TrackBase(thread, client, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001976 channelMask, frameCount, buffer, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001977 flags, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001978 (type == TYPE_DEFAULT) ?
1979 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1980 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1981 type),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001982 mOverflow(false), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0),
1983 // See real initialization of mRsmpInFront at RecordThread::start()
1984 mRsmpInUnrel(0), mRsmpInFront(0), mFramesToDrop(0), mResamplerBufferProvider(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001985{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001986 if (mCblk == NULL) {
1987 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001988 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001989
Eric Laurent83b88082014-06-20 18:31:16 -07001990 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1991 mFrameSize, !isExternalTrack());
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001992
Andy Hunge5412692014-05-16 11:25:07 -07001993 uint32_t channelCount = audio_channel_count_from_in_mask(channelMask);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001994 // FIXME I don't understand either of the channel count checks
1995 if (thread->mSampleRate != sampleRate && thread->mChannelCount <= FCC_2 &&
1996 channelCount <= FCC_2) {
1997 // sink SR
Andy Hung3348e362014-07-07 10:21:44 -07001998 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_16_BIT,
1999 thread->mChannelCount, sampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002000 // source SR
2001 mResampler->setSampleRate(thread->mSampleRate);
Andy Hung5e58b0a2014-06-23 19:07:29 -07002002 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002003 mResamplerBufferProvider = new ResamplerBufferProvider(this);
2004 }
Glenn Kastenc263ca02014-06-04 20:31:46 -07002005
2006 if (flags & IAudioFlinger::TRACK_FAST) {
2007 ALOG_ASSERT(thread->mFastTrackAvail);
2008 thread->mFastTrackAvail = false;
2009 }
Eric Laurent81784c32012-11-19 14:55:58 -08002010}
2011
2012AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
2013{
2014 ALOGV("%s", __func__);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002015 delete mResampler;
2016 delete[] mRsmpOutBuffer;
2017 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08002018}
2019
2020// AudioBufferProvider interface
2021status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002022 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002023{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002024 ServerProxy::Buffer buf;
2025 buf.mFrameCount = buffer->frameCount;
2026 status_t status = mServerProxy->obtainBuffer(&buf);
2027 buffer->frameCount = buf.mFrameCount;
2028 buffer->raw = buf.mRaw;
2029 if (buf.mFrameCount == 0) {
2030 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07002031 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002032 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002033 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002034}
2035
2036status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
2037 int triggerSession)
2038{
2039 sp<ThreadBase> thread = mThread.promote();
2040 if (thread != 0) {
2041 RecordThread *recordThread = (RecordThread *)thread.get();
2042 return recordThread->start(this, event, triggerSession);
2043 } else {
2044 return BAD_VALUE;
2045 }
2046}
2047
2048void AudioFlinger::RecordThread::RecordTrack::stop()
2049{
2050 sp<ThreadBase> thread = mThread.promote();
2051 if (thread != 0) {
2052 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07002053 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002054 AudioSystem::stopInput(recordThread->id(), (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002055 }
2056 }
2057}
2058
2059void AudioFlinger::RecordThread::RecordTrack::destroy()
2060{
2061 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
2062 sp<RecordTrack> keep(this);
2063 {
2064 sp<ThreadBase> thread = mThread.promote();
2065 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002066 if (isExternalTrack()) {
2067 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002068 AudioSystem::stopInput(thread->id(), (audio_session_t)mSessionId);
Eric Laurent83b88082014-06-20 18:31:16 -07002069 }
Eric Laurent4dc68062014-07-28 17:26:49 -07002070 AudioSystem::releaseInput(thread->id(), (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002071 }
Eric Laurent81784c32012-11-19 14:55:58 -08002072 Mutex::Autolock _l(thread->mLock);
2073 RecordThread *recordThread = (RecordThread *) thread.get();
2074 recordThread->destroyTrack_l(this);
2075 }
2076 }
2077}
2078
Eric Laurent9a54bc22013-09-09 09:08:44 -07002079void AudioFlinger::RecordThread::RecordTrack::invalidate()
2080{
2081 // FIXME should use proxy, and needs work
2082 audio_track_cblk_t* cblk = mCblk;
2083 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2084 android_atomic_release_store(0x40000000, &cblk->mFutex);
2085 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07002086 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07002087}
2088
Eric Laurent81784c32012-11-19 14:55:58 -08002089
2090/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
2091{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002092 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08002093}
2094
Marco Nelissenb2208842014-02-07 14:00:50 -08002095void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08002096{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002097 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08002098 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08002099 (mClient == 0) ? getpid_cached : mClient->pid(),
2100 mFormat,
2101 mChannelMask,
2102 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08002103 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002104 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002105 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002106 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002107
Eric Laurent81784c32012-11-19 14:55:58 -08002108}
2109
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002110void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2111{
2112 if (event == mSyncStartEvent) {
2113 ssize_t framesToDrop = 0;
2114 sp<ThreadBase> threadBase = mThread.promote();
2115 if (threadBase != 0) {
2116 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2117 // from audio HAL
2118 framesToDrop = threadBase->mFrameCount * 2;
2119 }
2120 mFramesToDrop = framesToDrop;
2121 }
2122}
2123
2124void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2125{
2126 if (mSyncStartEvent != 0) {
2127 mSyncStartEvent->cancel();
2128 mSyncStartEvent.clear();
2129 }
2130 mFramesToDrop = 0;
2131}
2132
Eric Laurent83b88082014-06-20 18:31:16 -07002133
2134AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
2135 uint32_t sampleRate,
2136 audio_channel_mask_t channelMask,
2137 audio_format_t format,
2138 size_t frameCount,
2139 void *buffer,
2140 IAudioFlinger::track_flags_t flags)
2141 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
2142 buffer, 0, getuid(), flags, TYPE_PATCH),
2143 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
2144{
2145 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
2146 recordThread->sampleRate();
2147 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
2148 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
2149
2150 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
2151 this, sampleRate,
2152 (int)mPeerTimeout.tv_sec,
2153 (int)(mPeerTimeout.tv_nsec / 1000000));
2154}
2155
2156AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
2157{
2158}
2159
2160// AudioBufferProvider interface
2161status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
2162 AudioBufferProvider::Buffer* buffer, int64_t pts)
2163{
2164 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
2165 Proxy::Buffer buf;
2166 buf.mFrameCount = buffer->frameCount;
2167 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
2168 ALOGV_IF(status != NO_ERROR,
2169 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07002170 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07002171 if (buf.mFrameCount == 0) {
2172 return WOULD_BLOCK;
2173 }
Eric Laurent83b88082014-06-20 18:31:16 -07002174 status = RecordTrack::getNextBuffer(buffer, pts);
2175 return status;
2176}
2177
2178void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2179{
2180 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
2181 Proxy::Buffer buf;
2182 buf.mFrameCount = buffer->frameCount;
2183 buf.mRaw = buffer->raw;
2184 mPeerProxy->releaseBuffer(&buf);
2185 TrackBase::releaseBuffer(buffer);
2186}
2187
2188status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
2189 const struct timespec *timeOut)
2190{
2191 return mProxy->obtainBuffer(buffer, timeOut);
2192}
2193
2194void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2195{
2196 mProxy->releaseBuffer(buffer);
2197}
2198
Eric Laurent81784c32012-11-19 14:55:58 -08002199}; // namespace android