blob: a0be96c3057b289b888863db8c7983af644521bd [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),
Eric Laurentaaa44472014-09-12 17:41:50 -070099 mType(type),
100 mThreadIoHandle(thread->id())
Eric Laurent81784c32012-11-19 14:55:58 -0800101{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800102 // if the caller is us, trust the specified uid
103 if (IPCThreadState::self()->getCallingPid() != getpid_cached || clientUid == -1) {
104 int newclientUid = IPCThreadState::self()->getCallingUid();
105 if (clientUid != -1 && clientUid != newclientUid) {
106 ALOGW("uid %d tried to pass itself off as %d", newclientUid, clientUid);
107 }
108 clientUid = newclientUid;
109 }
110 // clientUid contains the uid of the app that is responsible for this track, so we can blame
111 // battery usage on it.
112 mUid = clientUid;
113
Eric Laurent81784c32012-11-19 14:55:58 -0800114 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Andy Hungeaa39692017-02-13 18:48:39 -0800115
116 size_t bufferSize = buffer == NULL ? roundup(frameCount) : frameCount;
117 // check overflow when computing bufferSize due to multiplication by mFrameSize.
118 if (bufferSize < frameCount // roundup rounds down for values above UINT_MAX / 2
119 || mFrameSize == 0 // format needs to be correct
120 || bufferSize > SIZE_MAX / mFrameSize) {
121 android_errorWriteLog(0x534e4554, "34749571");
122 return;
123 }
124 bufferSize *= mFrameSize;
125
Eric Laurent81784c32012-11-19 14:55:58 -0800126 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700127 if (buffer == NULL && alloc == ALLOC_CBLK) {
Andy Hungeaa39692017-02-13 18:48:39 -0800128 // check overflow when computing allocation size for streaming tracks.
129 if (size > SIZE_MAX - bufferSize) {
130 android_errorWriteLog(0x534e4554, "34749571");
131 return;
132 }
Eric Laurent81784c32012-11-19 14:55:58 -0800133 size += bufferSize;
134 }
135
136 if (client != 0) {
137 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700138 if (mCblkMemory == 0 ||
139 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800140 ALOGE("not enough memory for AudioTrack size=%u", size);
141 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700142 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800143 return;
144 }
145 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800146 // this syntax avoids calling the audio_track_cblk_t constructor twice
147 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800148 // assume mCblk != NULL
149 }
150
151 // construct the shared structure in-place.
152 if (mCblk != NULL) {
153 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700154 switch (alloc) {
155 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700156 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
157 if (roHeap == 0 ||
158 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
159 (mBuffer = mBufferMemory->pointer()) == NULL) {
160 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
161 if (roHeap != 0) {
162 roHeap->dump("buffer");
163 }
164 mCblkMemory.clear();
165 mBufferMemory.clear();
166 return;
167 }
Eric Laurent81784c32012-11-19 14:55:58 -0800168 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700169 } break;
170 case ALLOC_PIPE:
171 mBufferMemory = thread->pipeMemory();
172 // mBuffer is the virtual address as seen from current process (mediaserver),
173 // and should normally be coming from mBufferMemory->pointer().
174 // However in this case the TrackBase does not reference the buffer directly.
175 // It should references the buffer via the pipe.
176 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
177 mBuffer = NULL;
178 break;
179 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700180 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700181 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700182 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
183 memset(mBuffer, 0, bufferSize);
184 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700185 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800186#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700187 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800188#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700189 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700190 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700191 case ALLOC_LOCAL:
192 mBuffer = calloc(1, bufferSize);
193 break;
194 case ALLOC_NONE:
195 mBuffer = buffer;
196 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800197 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800198
Glenn Kasten46909e72013-02-26 09:20:22 -0800199#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800200 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700201 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800202 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800203 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
204 size_t numCounterOffers = 0;
205 const NBAIO_Format offers[1] = {pipeFormat};
206 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
207 ALOG_ASSERT(index == 0);
208 PipeReader *pipeReader = new PipeReader(*pipe);
209 numCounterOffers = 0;
210 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
211 ALOG_ASSERT(index == 0);
212 mTeeSink = pipe;
213 mTeeSource = pipeReader;
214 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800215 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800216#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800217
Eric Laurent81784c32012-11-19 14:55:58 -0800218 }
219}
220
Eric Laurent83b88082014-06-20 18:31:16 -0700221status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
222{
223 status_t status;
224 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
225 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
226 } else {
227 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
228 }
229 return status;
230}
231
Eric Laurent81784c32012-11-19 14:55:58 -0800232AudioFlinger::ThreadBase::TrackBase::~TrackBase()
233{
Glenn Kasten46909e72013-02-26 09:20:22 -0800234#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800235 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800236#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800237 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
238 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800239 if (mCblk != NULL) {
240 if (mClient == 0) {
241 delete mCblk;
242 } else {
243 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
244 }
245 }
246 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
247 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700248 // Client destructor must run with AudioFlinger client mutex locked
249 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800250 // If the client's reference count drops to zero, the associated destructor
251 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
252 // relying on the automatic clear() at end of scope.
253 mClient.clear();
254 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700255 // flush the binder command buffer
256 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800257}
258
259// AudioBufferProvider interface
260// getNextBuffer() = 0;
261// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
262void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
263{
Glenn Kasten46909e72013-02-26 09:20:22 -0800264#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800265 if (mTeeSink != 0) {
266 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
267 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800268#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800269
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800270 ServerProxy::Buffer buf;
271 buf.mFrameCount = buffer->frameCount;
272 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800273 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800274 buffer->raw = NULL;
275 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800276}
277
Eric Laurent81784c32012-11-19 14:55:58 -0800278status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
279{
280 mSyncEvents.add(event);
281 return NO_ERROR;
282}
283
284// ----------------------------------------------------------------------------
285// Playback
286// ----------------------------------------------------------------------------
287
288AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
289 : BnAudioTrack(),
290 mTrack(track)
291{
292}
293
294AudioFlinger::TrackHandle::~TrackHandle() {
295 // just stop the track on deletion, associated resources
296 // will be freed from the main thread once all pending buffers have
297 // been played. Unless it's not in the active track list, in which
298 // case we free everything now...
299 mTrack->destroy();
300}
301
302sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
303 return mTrack->getCblk();
304}
305
306status_t AudioFlinger::TrackHandle::start() {
307 return mTrack->start();
308}
309
310void AudioFlinger::TrackHandle::stop() {
311 mTrack->stop();
312}
313
314void AudioFlinger::TrackHandle::flush() {
315 mTrack->flush();
316}
317
Eric Laurent81784c32012-11-19 14:55:58 -0800318void AudioFlinger::TrackHandle::pause() {
319 mTrack->pause();
320}
321
322status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
323{
324 return mTrack->attachAuxEffect(EffectId);
325}
326
327status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
328 sp<IMemory>* buffer) {
329 if (!mTrack->isTimedTrack())
330 return INVALID_OPERATION;
331
332 PlaybackThread::TimedTrack* tt =
333 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
334 return tt->allocateTimedBuffer(size, buffer);
335}
336
337status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
338 int64_t pts) {
339 if (!mTrack->isTimedTrack())
340 return INVALID_OPERATION;
341
Glenn Kasten663c2242013-09-24 11:52:37 -0700342 if (buffer == 0 || buffer->pointer() == NULL) {
343 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
344 return BAD_VALUE;
345 }
346
Eric Laurent81784c32012-11-19 14:55:58 -0800347 PlaybackThread::TimedTrack* tt =
348 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
349 return tt->queueTimedBuffer(buffer, pts);
350}
351
352status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
353 const LinearTransform& xform, int target) {
354
355 if (!mTrack->isTimedTrack())
356 return INVALID_OPERATION;
357
358 PlaybackThread::TimedTrack* tt =
359 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
360 return tt->setMediaTimeTransform(
361 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
362}
363
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700364status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
365 return mTrack->setParameters(keyValuePairs);
366}
367
Glenn Kasten53cec222013-08-29 09:01:02 -0700368status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
369{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700370 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700371}
372
Eric Laurent59fe0102013-09-27 18:48:26 -0700373
374void AudioFlinger::TrackHandle::signal()
375{
376 return mTrack->signal();
377}
378
Eric Laurent81784c32012-11-19 14:55:58 -0800379status_t AudioFlinger::TrackHandle::onTransact(
380 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
381{
382 return BnAudioTrack::onTransact(code, data, reply, flags);
383}
384
385// ----------------------------------------------------------------------------
386
387// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
388AudioFlinger::PlaybackThread::Track::Track(
389 PlaybackThread *thread,
390 const sp<Client>& client,
391 audio_stream_type_t streamType,
392 uint32_t sampleRate,
393 audio_format_t format,
394 audio_channel_mask_t channelMask,
395 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700396 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800397 const sp<IMemory>& sharedBuffer,
398 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800399 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -0700400 IAudioFlinger::track_flags_t flags,
401 track_type type)
402 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
403 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
404 sessionId, uid, flags, true /*isOut*/,
405 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
406 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800407 mFillingUpStatus(FS_INVALID),
408 // mRetryCount initialized later when needed
409 mSharedBuffer(sharedBuffer),
410 mStreamType(streamType),
411 mName(-1), // see note below
412 mMainBuffer(thread->mixBuffer()),
413 mAuxBuffer(NULL),
414 mAuxEffectId(0), mHasVolumeController(false),
415 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800416 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800417 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800418 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800419 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800420 mResumeToStopping(false),
Glenn Kastenced6e742014-06-09 17:12:32 -0700421 mFlushHwPending(false),
422 mPreviousValid(false),
423 mPreviousFramesWritten(0)
424 // mPreviousTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800425{
Eric Laurent83b88082014-06-20 18:31:16 -0700426 // client == 0 implies sharedBuffer == 0
427 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
428
429 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
430 sharedBuffer->size());
431
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700432 if (mCblk == NULL) {
433 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800434 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700435
436 if (sharedBuffer == 0) {
437 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700438 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700439 } else {
Andy Hungf4aeab22017-06-12 17:22:46 -0700440 // Is the shared buffer of sufficient size?
441 // (frameCount * mFrameSize) is <= SIZE_MAX, checked in TrackBase.
442 if (sharedBuffer->size() < frameCount * mFrameSize) {
443 // Workaround: clear out mCblk to indicate track hasn't been properly created.
444 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
445 if (mClient == 0) {
446 free(mCblk);
447 }
448 mCblk = NULL;
449
450 mSharedBuffer.clear(); // release shared buffer early
451 android_errorWriteLog(0x534e4554, "38340117");
452 return;
453 }
454
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700455 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
456 mFrameSize);
457 }
458 mServerProxy = mAudioTrackServerProxy;
459
Glenn Kastenc263ca02014-06-04 20:31:46 -0700460 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700461 if (mName < 0) {
462 ALOGE("no more track names available");
463 return;
464 }
465 // only allocate a fast track index if we were able to allocate a normal track name
466 if (flags & IAudioFlinger::TRACK_FAST) {
467 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
468 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
469 int i = __builtin_ctz(thread->mFastTrackAvailMask);
470 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
471 // FIXME This is too eager. We allocate a fast track index before the
472 // fast track becomes active. Since fast tracks are a scarce resource,
473 // this means we are potentially denying other more important fast tracks from
474 // being created. It would be better to allocate the index dynamically.
475 mFastIndex = i;
476 // Read the initial underruns because this field is never cleared by the fast mixer
477 mObservedUnderruns = thread->getFastTrackUnderruns(i);
478 thread->mFastTrackAvailMask &= ~(1 << i);
479 }
Eric Laurent81784c32012-11-19 14:55:58 -0800480}
481
482AudioFlinger::PlaybackThread::Track::~Track()
483{
484 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700485
486 // The destructor would clear mSharedBuffer,
487 // but it will not push the decremented reference count,
488 // leaving the client's IMemory dangling indefinitely.
489 // This prevents that leak.
490 if (mSharedBuffer != 0) {
491 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700492 }
Eric Laurent81784c32012-11-19 14:55:58 -0800493}
494
Glenn Kasten03003332013-08-06 15:40:54 -0700495status_t AudioFlinger::PlaybackThread::Track::initCheck() const
496{
497 status_t status = TrackBase::initCheck();
498 if (status == NO_ERROR && mName < 0) {
499 status = NO_MEMORY;
500 }
501 return status;
502}
503
Eric Laurent81784c32012-11-19 14:55:58 -0800504void AudioFlinger::PlaybackThread::Track::destroy()
505{
506 // NOTE: destroyTrack_l() can remove a strong reference to this Track
507 // by removing it from mTracks vector, so there is a risk that this Tracks's
508 // destructor is called. As the destructor needs to lock mLock,
509 // we must acquire a strong reference on this Track before locking mLock
510 // here so that the destructor is called only when exiting this function.
511 // On the other hand, as long as Track::destroy() is only called by
512 // TrackHandle destructor, the TrackHandle still holds a strong ref on
513 // this Track with its member mTrack.
514 sp<Track> keep(this);
515 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700516 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800517 sp<ThreadBase> thread = mThread.promote();
518 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800519 Mutex::Autolock _l(thread->mLock);
520 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700521 wasActive = playbackThread->destroyTrack_l(this);
522 }
523 if (isExternalTrack() && !wasActive) {
524 AudioSystem::releaseOutput(mThreadIoHandle);
Eric Laurent81784c32012-11-19 14:55:58 -0800525 }
526 }
527}
528
529/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
530{
Marco Nelissenb2208842014-02-07 14:00:50 -0800531 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700532 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800533}
534
Marco Nelissenb2208842014-02-07 14:00:50 -0800535void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800536{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700537 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800538 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800539 sprintf(buffer, " F %2d", mFastIndex);
540 } else if (mName >= AudioMixer::TRACK0) {
541 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800542 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800543 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800544 }
545 track_state state = mState;
546 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800547 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800548 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800549 } else {
550 switch (state) {
551 case IDLE:
552 stateChar = 'I';
553 break;
554 case STOPPING_1:
555 stateChar = 's';
556 break;
557 case STOPPING_2:
558 stateChar = '5';
559 break;
560 case STOPPED:
561 stateChar = 'S';
562 break;
563 case RESUMING:
564 stateChar = 'R';
565 break;
566 case ACTIVE:
567 stateChar = 'A';
568 break;
569 case PAUSING:
570 stateChar = 'p';
571 break;
572 case PAUSED:
573 stateChar = 'P';
574 break;
575 case FLUSHED:
576 stateChar = 'F';
577 break;
578 default:
579 stateChar = '?';
580 break;
581 }
Eric Laurent81784c32012-11-19 14:55:58 -0800582 }
583 char nowInUnderrun;
584 switch (mObservedUnderruns.mBitFields.mMostRecent) {
585 case UNDERRUN_FULL:
586 nowInUnderrun = ' ';
587 break;
588 case UNDERRUN_PARTIAL:
589 nowInUnderrun = '<';
590 break;
591 case UNDERRUN_EMPTY:
592 nowInUnderrun = '*';
593 break;
594 default:
595 nowInUnderrun = '?';
596 break;
597 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000598 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 +0000599 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800600 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800601 (mClient == 0) ? getpid_cached : mClient->pid(),
602 mStreamType,
603 mFormat,
604 mChannelMask,
605 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800606 mFrameCount,
607 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800608 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800609 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700610 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
611 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700612 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000613 mMainBuffer,
614 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700615 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700616 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800617 nowInUnderrun);
618}
619
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800620uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
621 return mAudioTrackServerProxy->getSampleRate();
622}
623
Eric Laurent81784c32012-11-19 14:55:58 -0800624// AudioBufferProvider interface
625status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800626 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800627{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800628 ServerProxy::Buffer buf;
629 size_t desiredFrames = buffer->frameCount;
630 buf.mFrameCount = desiredFrames;
631 status_t status = mServerProxy->obtainBuffer(&buf);
632 buffer->frameCount = buf.mFrameCount;
633 buffer->raw = buf.mRaw;
634 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700635 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800636 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800637 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800638}
639
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700640// releaseBuffer() is not overridden
641
642// ExtendedAudioBufferProvider interface
643
Eric Laurent81784c32012-11-19 14:55:58 -0800644// Note that framesReady() takes a mutex on the control block using tryLock().
645// This could result in priority inversion if framesReady() is called by the normal mixer,
646// as the normal mixer thread runs at lower
647// priority than the client's callback thread: there is a short window within framesReady()
648// during which the normal mixer could be preempted, and the client callback would block.
649// Another problem can occur if framesReady() is called by the fast mixer:
650// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
651// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
652size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800653 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800654}
655
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700656size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
657{
658 return mAudioTrackServerProxy->framesReleased();
659}
660
Eric Laurent81784c32012-11-19 14:55:58 -0800661// Don't call for fast tracks; the framesReady() could result in priority inversion
662bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800663 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
664 return true;
665 }
666
Eric Laurent16498512014-03-17 17:22:08 -0700667 if (isStopping()) {
668 if (framesReady() > 0) {
669 mFillingUpStatus = FS_FILLED;
670 }
Eric Laurent81784c32012-11-19 14:55:58 -0800671 return true;
672 }
673
674 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700675 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800676 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700677 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800678 return true;
679 }
680 return false;
681}
682
Glenn Kasten0f11b512014-01-31 16:18:54 -0800683status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
684 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800685{
686 status_t status = NO_ERROR;
687 ALOGV("start(%d), calling pid %d session %d",
688 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
689
690 sp<ThreadBase> thread = mThread.promote();
691 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700692 if (isOffloaded()) {
693 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
694 Mutex::Autolock _lth(thread->mLock);
695 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700696 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
697 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700698 invalidate();
699 return PERMISSION_DENIED;
700 }
701 }
702 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800703 track_state state = mState;
704 // here the track could be either new, or restarted
705 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800706
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800707 // initial state-stopping. next state-pausing.
708 // What if resume is called ?
709
710 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800711 if (mResumeToStopping) {
712 // happened we need to resume to STOPPING_1
713 mState = TrackBase::STOPPING_1;
714 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
715 } else {
716 mState = TrackBase::RESUMING;
717 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
718 }
Eric Laurent81784c32012-11-19 14:55:58 -0800719 } else {
720 mState = TrackBase::ACTIVE;
721 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
722 }
723
Eric Laurentbfb1b832013-01-07 09:53:42 -0800724 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
725 status = playbackThread->addTrack_l(this);
726 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800727 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800728 // restore previous state if start was rejected by policy manager
729 if (status == PERMISSION_DENIED) {
730 mState = state;
731 }
732 }
733 // track was already in the active list, not a problem
734 if (status == ALREADY_EXISTS) {
735 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700736 } else {
737 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
738 // It is usually unsafe to access the server proxy from a binder thread.
739 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
740 // isn't looking at this track yet: we still hold the normal mixer thread lock,
741 // and for fast tracks the track is not yet in the fast mixer thread's active set.
742 ServerProxy::Buffer buffer;
743 buffer.mFrameCount = 1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700744 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800745 }
746 } else {
747 status = BAD_VALUE;
748 }
749 return status;
750}
751
752void AudioFlinger::PlaybackThread::Track::stop()
753{
754 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
755 sp<ThreadBase> thread = mThread.promote();
756 if (thread != 0) {
757 Mutex::Autolock _l(thread->mLock);
758 track_state state = mState;
759 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
760 // If the track is not active (PAUSED and buffers full), flush buffers
761 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
762 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
763 reset();
764 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700765 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800766 mState = STOPPED;
767 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800768 // For fast tracks prepareTracks_l() will set state to STOPPING_2
769 // presentation is complete
770 // For an offloaded track this starts a drain and state will
771 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800772 mState = STOPPING_1;
773 }
774 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
775 playbackThread);
776 }
Eric Laurent81784c32012-11-19 14:55:58 -0800777 }
778}
779
780void AudioFlinger::PlaybackThread::Track::pause()
781{
782 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
783 sp<ThreadBase> thread = mThread.promote();
784 if (thread != 0) {
785 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800786 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
787 switch (mState) {
788 case STOPPING_1:
789 case STOPPING_2:
790 if (!isOffloaded()) {
791 /* nothing to do if track is not offloaded */
792 break;
793 }
794
795 // Offloaded track was draining, we need to carry on draining when resumed
796 mResumeToStopping = true;
797 // fall through...
798 case ACTIVE:
799 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800800 mState = PAUSING;
801 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700802 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800803 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800804
Eric Laurentbfb1b832013-01-07 09:53:42 -0800805 default:
806 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800807 }
808 }
809}
810
811void AudioFlinger::PlaybackThread::Track::flush()
812{
813 ALOGV("flush(%d)", mName);
814 sp<ThreadBase> thread = mThread.promote();
815 if (thread != 0) {
816 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800817 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800818
819 if (isOffloaded()) {
820 // If offloaded we allow flush during any state except terminated
821 // and keep the track active to avoid problems if user is seeking
822 // rapidly and underlying hardware has a significant delay handling
823 // a pause
824 if (isTerminated()) {
825 return;
826 }
827
828 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800829 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800830
831 if (mState == STOPPING_1 || mState == STOPPING_2) {
832 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
833 mState = ACTIVE;
834 }
835
836 if (mState == ACTIVE) {
837 ALOGV("flush called in active state, resetting buffer time out retry count");
838 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
839 }
840
Haynes Mathew George7844f672014-01-15 12:32:55 -0800841 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800842 mResumeToStopping = false;
843 } else {
844 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
845 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
846 return;
847 }
848 // No point remaining in PAUSED state after a flush => go to
849 // FLUSHED state
850 mState = FLUSHED;
851 // do not reset the track if it is still in the process of being stopped or paused.
852 // this will be done by prepareTracks_l() when the track is stopped.
853 // prepareTracks_l() will see mState == FLUSHED, then
854 // remove from active track list, reset(), and trigger presentation complete
855 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
856 reset();
Eric Laurente659ef42014-09-29 13:06:46 -0700857 if (thread->type() == ThreadBase::DIRECT) {
858 DirectOutputThread *t = (DirectOutputThread *)playbackThread;
859 t->flushHw_l();
860 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800861 }
Eric Laurent81784c32012-11-19 14:55:58 -0800862 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800863 // Prevent flush being lost if the track is flushed and then resumed
864 // before mixer thread can run. This is important when offloading
865 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700866 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800867 }
868}
869
Haynes Mathew George7844f672014-01-15 12:32:55 -0800870// must be called with thread lock held
871void AudioFlinger::PlaybackThread::Track::flushAck()
872{
873 if (!isOffloaded())
874 return;
875
876 mFlushHwPending = false;
877}
878
Eric Laurent81784c32012-11-19 14:55:58 -0800879void AudioFlinger::PlaybackThread::Track::reset()
880{
881 // Do not reset twice to avoid discarding data written just after a flush and before
882 // the audioflinger thread detects the track is stopped.
883 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800884 // Force underrun condition to avoid false underrun callback until first data is
885 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700886 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800887 mFillingUpStatus = FS_FILLING;
888 mResetDone = true;
889 if (mState == FLUSHED) {
890 mState = IDLE;
891 }
892 }
893}
894
Eric Laurentbfb1b832013-01-07 09:53:42 -0800895status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
896{
897 sp<ThreadBase> thread = mThread.promote();
898 if (thread == 0) {
899 ALOGE("thread is dead");
900 return FAILED_TRANSACTION;
901 } else if ((thread->type() == ThreadBase::DIRECT) ||
902 (thread->type() == ThreadBase::OFFLOAD)) {
903 return thread->setParameters(keyValuePairs);
904 } else {
905 return PERMISSION_DENIED;
906 }
907}
908
Glenn Kasten573d80a2013-08-26 09:36:23 -0700909status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
910{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700911 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
912 if (isFastTrack()) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700913 // FIXME no lock held to set mPreviousValid = false
Glenn Kastenfe346c72013-08-30 13:28:22 -0700914 return INVALID_OPERATION;
915 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700916 sp<ThreadBase> thread = mThread.promote();
917 if (thread == 0) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700918 // FIXME no lock held to set mPreviousValid = false
Glenn Kastenfe346c72013-08-30 13:28:22 -0700919 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700920 }
921 Mutex::Autolock _l(thread->mLock);
922 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentab5cdba2014-06-09 17:22:27 -0700923 if (!isOffloaded() && !isDirect()) {
Eric Laurentaccc1472013-09-20 09:36:34 -0700924 if (!playbackThread->mLatchQValid) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700925 mPreviousValid = false;
Eric Laurentaccc1472013-09-20 09:36:34 -0700926 return INVALID_OPERATION;
927 }
928 uint32_t unpresentedFrames =
929 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
930 playbackThread->mSampleRate;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700931 // FIXME Since we're using a raw pointer as the key, it is theoretically possible
932 // for a brand new track to share the same address as a recently destroyed
933 // track, and thus for us to get the frames released of the wrong track.
934 // It is unlikely that we would be able to call getTimestamp() so quickly
935 // right after creating a new track. Nevertheless, the index here should
936 // be changed to something that is unique. Or use a completely different strategy.
937 ssize_t i = playbackThread->mLatchQ.mFramesReleased.indexOfKey(this);
938 uint32_t framesWritten = i >= 0 ?
939 playbackThread->mLatchQ.mFramesReleased[i] :
940 mAudioTrackServerProxy->framesReleased();
Glenn Kastenced6e742014-06-09 17:12:32 -0700941 bool checkPreviousTimestamp = mPreviousValid && framesWritten >= mPreviousFramesWritten;
Eric Laurentaccc1472013-09-20 09:36:34 -0700942 if (framesWritten < unpresentedFrames) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700943 mPreviousValid = false;
Eric Laurentaccc1472013-09-20 09:36:34 -0700944 return INVALID_OPERATION;
945 }
Glenn Kastenced6e742014-06-09 17:12:32 -0700946 mPreviousFramesWritten = framesWritten;
947 uint32_t position = framesWritten - unpresentedFrames;
948 struct timespec time = playbackThread->mLatchQ.mTimestamp.mTime;
949 if (checkPreviousTimestamp) {
950 if (time.tv_sec < mPreviousTimestamp.mTime.tv_sec ||
951 (time.tv_sec == mPreviousTimestamp.mTime.tv_sec &&
952 time.tv_nsec < mPreviousTimestamp.mTime.tv_nsec)) {
953 ALOGW("Time is going backwards");
954 }
955 // position can bobble slightly as an artifact; this hides the bobble
956 static const uint32_t MINIMUM_POSITION_DELTA = 8u;
957 if ((position <= mPreviousTimestamp.mPosition) ||
958 (position - mPreviousTimestamp.mPosition) < MINIMUM_POSITION_DELTA) {
959 position = mPreviousTimestamp.mPosition;
960 time = mPreviousTimestamp.mTime;
961 }
962 }
963 timestamp.mPosition = position;
964 timestamp.mTime = time;
965 mPreviousTimestamp = timestamp;
966 mPreviousValid = true;
Eric Laurentaccc1472013-09-20 09:36:34 -0700967 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700968 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700969
970 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700971}
972
Eric Laurent81784c32012-11-19 14:55:58 -0800973status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
974{
975 status_t status = DEAD_OBJECT;
976 sp<ThreadBase> thread = mThread.promote();
977 if (thread != 0) {
978 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
979 sp<AudioFlinger> af = mClient->audioFlinger();
980
981 Mutex::Autolock _l(af->mLock);
982
983 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
984
985 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
986 Mutex::Autolock _dl(playbackThread->mLock);
987 Mutex::Autolock _sl(srcThread->mLock);
988 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
989 if (chain == 0) {
990 return INVALID_OPERATION;
991 }
992
993 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
994 if (effect == 0) {
995 return INVALID_OPERATION;
996 }
997 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700998 status = playbackThread->addEffect_l(effect);
999 if (status != NO_ERROR) {
1000 srcThread->addEffect_l(effect);
1001 return INVALID_OPERATION;
1002 }
Eric Laurent81784c32012-11-19 14:55:58 -08001003 // removeEffect_l() has stopped the effect if it was active so it must be restarted
1004 if (effect->state() == EffectModule::ACTIVE ||
1005 effect->state() == EffectModule::STOPPING) {
1006 effect->start();
1007 }
1008
1009 sp<EffectChain> dstChain = effect->chain().promote();
1010 if (dstChain == 0) {
1011 srcThread->addEffect_l(effect);
1012 return INVALID_OPERATION;
1013 }
1014 AudioSystem::unregisterEffect(effect->id());
1015 AudioSystem::registerEffect(&effect->desc(),
1016 srcThread->id(),
1017 dstChain->strategy(),
1018 AUDIO_SESSION_OUTPUT_MIX,
1019 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07001020 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -08001021 }
1022 status = playbackThread->attachAuxEffect(this, EffectId);
1023 }
1024 return status;
1025}
1026
1027void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
1028{
1029 mAuxEffectId = EffectId;
1030 mAuxBuffer = buffer;
1031}
1032
1033bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
1034 size_t audioHalFrames)
1035{
1036 // a track is considered presented when the total number of frames written to audio HAL
1037 // corresponds to the number of frames written when presentationComplete() is called for the
1038 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001039 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1040 // to detect when all frames have been played. In this case framesWritten isn't
1041 // useful because it doesn't always reflect whether there is data in the h/w
1042 // buffers, particularly if a track has been paused and resumed during draining
1043 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
1044 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001045 if (mPresentationCompleteFrames == 0) {
1046 mPresentationCompleteFrames = framesWritten + audioHalFrames;
1047 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
1048 mPresentationCompleteFrames, audioHalFrames);
1049 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001050
1051 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001052 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001053 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001054 return true;
1055 }
1056 return false;
1057}
1058
1059void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1060{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001061 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001062 if (mSyncEvents[i]->type() == type) {
1063 mSyncEvents[i]->trigger();
1064 mSyncEvents.removeAt(i);
1065 i--;
1066 }
1067 }
1068}
1069
1070// implement VolumeBufferProvider interface
1071
Glenn Kastenc56f3422014-03-21 17:53:17 -07001072gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001073{
1074 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1075 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001076 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1077 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1078 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001079 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001080 if (vl > GAIN_FLOAT_UNITY) {
1081 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001082 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001083 if (vr > GAIN_FLOAT_UNITY) {
1084 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001085 }
1086 // now apply the cached master volume and stream type volume;
1087 // this is trusted but lacks any synchronization or barrier so may be stale
1088 float v = mCachedVolume;
1089 vl *= v;
1090 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001091 // re-combine into packed minifloat
1092 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001093 // FIXME look at mute, pause, and stop flags
1094 return vlr;
1095}
1096
1097status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1098{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001099 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001100 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1101 (mState == STOPPED)))) {
1102 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1103 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1104 event->cancel();
1105 return INVALID_OPERATION;
1106 }
1107 (void) TrackBase::setSyncEvent(event);
1108 return NO_ERROR;
1109}
1110
Glenn Kasten5736c352012-12-04 12:12:34 -08001111void AudioFlinger::PlaybackThread::Track::invalidate()
1112{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001113 // FIXME should use proxy, and needs work
1114 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001115 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001116 android_atomic_release_store(0x40000000, &cblk->mFutex);
1117 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001118 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001119 mIsInvalid = true;
1120}
1121
Eric Laurent59fe0102013-09-27 18:48:26 -07001122void AudioFlinger::PlaybackThread::Track::signal()
1123{
1124 sp<ThreadBase> thread = mThread.promote();
1125 if (thread != 0) {
1126 PlaybackThread *t = (PlaybackThread *)thread.get();
1127 Mutex::Autolock _l(t->mLock);
1128 t->broadcast_l();
1129 }
1130}
1131
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001132//To be called with thread lock held
1133bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1134
1135 if (mState == RESUMING)
1136 return true;
1137 /* Resume is pending if track was stopping before pause was called */
1138 if (mState == STOPPING_1 &&
1139 mResumeToStopping)
1140 return true;
1141
1142 return false;
1143}
1144
1145//To be called with thread lock held
1146void AudioFlinger::PlaybackThread::Track::resumeAck() {
1147
1148
1149 if (mState == RESUMING)
1150 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001151
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001152 // Other possibility of pending resume is stopping_1 state
1153 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001154 // drain being called.
1155 if (mState == STOPPING_1) {
1156 mResumeToStopping = false;
1157 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001158}
Eric Laurent81784c32012-11-19 14:55:58 -08001159// ----------------------------------------------------------------------------
1160
1161sp<AudioFlinger::PlaybackThread::TimedTrack>
1162AudioFlinger::PlaybackThread::TimedTrack::create(
1163 PlaybackThread *thread,
1164 const sp<Client>& client,
1165 audio_stream_type_t streamType,
1166 uint32_t sampleRate,
1167 audio_format_t format,
1168 audio_channel_mask_t channelMask,
1169 size_t frameCount,
1170 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001171 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001172 int uid)
1173{
Eric Laurent81784c32012-11-19 14:55:58 -08001174 if (!client->reserveTimedTrack())
1175 return 0;
1176
1177 return new TimedTrack(
1178 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001179 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001180}
1181
1182AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1183 PlaybackThread *thread,
1184 const sp<Client>& client,
1185 audio_stream_type_t streamType,
1186 uint32_t sampleRate,
1187 audio_format_t format,
1188 audio_channel_mask_t channelMask,
1189 size_t frameCount,
1190 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001191 int sessionId,
1192 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001193 : Track(thread, client, streamType, sampleRate, format, channelMask,
Eric Laurent83b88082014-06-20 18:31:16 -07001194 frameCount, (sharedBuffer != 0) ? sharedBuffer->pointer() : NULL, sharedBuffer,
1195 sessionId, uid, IAudioFlinger::TRACK_TIMED, TYPE_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001196 mQueueHeadInFlight(false),
1197 mTrimQueueHeadOnRelease(false),
1198 mFramesPendingInQueue(0),
1199 mTimedSilenceBuffer(NULL),
1200 mTimedSilenceBufferSize(0),
1201 mTimedAudioOutputOnTime(false),
1202 mMediaTimeTransformValid(false)
1203{
1204 LocalClock lc;
1205 mLocalTimeFreq = lc.getLocalFreq();
1206
1207 mLocalTimeToSampleTransform.a_zero = 0;
1208 mLocalTimeToSampleTransform.b_zero = 0;
1209 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1210 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1211 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1212 &mLocalTimeToSampleTransform.a_to_b_denom);
1213
1214 mMediaTimeToSampleTransform.a_zero = 0;
1215 mMediaTimeToSampleTransform.b_zero = 0;
1216 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1217 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1218 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1219 &mMediaTimeToSampleTransform.a_to_b_denom);
1220}
1221
1222AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1223 mClient->releaseTimedTrack();
1224 delete [] mTimedSilenceBuffer;
1225}
1226
1227status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1228 size_t size, sp<IMemory>* buffer) {
1229
1230 Mutex::Autolock _l(mTimedBufferQueueLock);
1231
1232 trimTimedBufferQueue_l();
1233
1234 // lazily initialize the shared memory heap for timed buffers
1235 if (mTimedMemoryDealer == NULL) {
1236 const int kTimedBufferHeapSize = 512 << 10;
1237
1238 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1239 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001240 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001241 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001242 }
Eric Laurent81784c32012-11-19 14:55:58 -08001243 }
1244
1245 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001246 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001247 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001248 }
1249
1250 *buffer = newBuffer;
1251 return NO_ERROR;
1252}
1253
1254// caller must hold mTimedBufferQueueLock
1255void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1256 int64_t mediaTimeNow;
1257 {
1258 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1259 if (!mMediaTimeTransformValid)
1260 return;
1261
1262 int64_t targetTimeNow;
1263 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1264 ? mCCHelper.getCommonTime(&targetTimeNow)
1265 : mCCHelper.getLocalTime(&targetTimeNow);
1266
1267 if (OK != res)
1268 return;
1269
1270 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1271 &mediaTimeNow)) {
1272 return;
1273 }
1274 }
1275
1276 size_t trimEnd;
1277 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1278 int64_t bufEnd;
1279
1280 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1281 // We have a next buffer. Just use its PTS as the PTS of the frame
1282 // following the last frame in this buffer. If the stream is sparse
1283 // (ie, there are deliberate gaps left in the stream which should be
1284 // filled with silence by the TimedAudioTrack), then this can result
1285 // in one extra buffer being left un-trimmed when it could have
1286 // been. In general, this is not typical, and we would rather
1287 // optimized away the TS calculation below for the more common case
1288 // where PTSes are contiguous.
1289 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1290 } else {
1291 // We have no next buffer. Compute the PTS of the frame following
1292 // the last frame in this buffer by computing the duration of of
1293 // this frame in media time units and adding it to the PTS of the
1294 // buffer.
1295 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1296 / mFrameSize;
1297
1298 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1299 &bufEnd)) {
1300 ALOGE("Failed to convert frame count of %lld to media time"
1301 " duration" " (scale factor %d/%u) in %s",
1302 frameCount,
1303 mMediaTimeToSampleTransform.a_to_b_numer,
1304 mMediaTimeToSampleTransform.a_to_b_denom,
1305 __PRETTY_FUNCTION__);
1306 break;
1307 }
1308 bufEnd += mTimedBufferQueue[trimEnd].pts();
1309 }
1310
1311 if (bufEnd > mediaTimeNow)
1312 break;
1313
1314 // Is the buffer we want to use in the middle of a mix operation right
1315 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1316 // from the mixer which should be coming back shortly.
1317 if (!trimEnd && mQueueHeadInFlight) {
1318 mTrimQueueHeadOnRelease = true;
1319 }
1320 }
1321
1322 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1323 if (trimStart < trimEnd) {
1324 // Update the bookkeeping for framesReady()
1325 for (size_t i = trimStart; i < trimEnd; ++i) {
1326 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1327 }
1328
1329 // Now actually remove the buffers from the queue.
1330 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1331 }
1332}
1333
1334void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1335 const char* logTag) {
1336 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1337 "%s called (reason \"%s\"), but timed buffer queue has no"
1338 " elements to trim.", __FUNCTION__, logTag);
1339
1340 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1341 mTimedBufferQueue.removeAt(0);
1342}
1343
1344void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1345 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001346 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001347 uint32_t bufBytes = buf.buffer()->size();
1348 uint32_t consumedAlready = buf.position();
1349
1350 ALOG_ASSERT(consumedAlready <= bufBytes,
1351 "Bad bookkeeping while updating frames pending. Timed buffer is"
1352 " only %u bytes long, but claims to have consumed %u"
1353 " bytes. (update reason: \"%s\")",
1354 bufBytes, consumedAlready, logTag);
1355
1356 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1357 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1358 "Bad bookkeeping while updating frames pending. Should have at"
1359 " least %u queued frames, but we think we have only %u. (update"
1360 " reason: \"%s\")",
1361 bufFrames, mFramesPendingInQueue, logTag);
1362
1363 mFramesPendingInQueue -= bufFrames;
1364}
1365
1366status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1367 const sp<IMemory>& buffer, int64_t pts) {
1368
1369 {
1370 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1371 if (!mMediaTimeTransformValid)
1372 return INVALID_OPERATION;
1373 }
1374
1375 Mutex::Autolock _l(mTimedBufferQueueLock);
1376
1377 uint32_t bufFrames = buffer->size() / mFrameSize;
1378 mFramesPendingInQueue += bufFrames;
1379 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1380
1381 return NO_ERROR;
1382}
1383
1384status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1385 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1386
1387 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1388 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1389 target);
1390
1391 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1392 target == TimedAudioTrack::COMMON_TIME)) {
1393 return BAD_VALUE;
1394 }
1395
1396 Mutex::Autolock lock(mMediaTimeTransformLock);
1397 mMediaTimeTransform = xform;
1398 mMediaTimeTransformTarget = target;
1399 mMediaTimeTransformValid = true;
1400
1401 return NO_ERROR;
1402}
1403
1404#define min(a, b) ((a) < (b) ? (a) : (b))
1405
1406// implementation of getNextBuffer for tracks whose buffers have timestamps
1407status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1408 AudioBufferProvider::Buffer* buffer, int64_t pts)
1409{
1410 if (pts == AudioBufferProvider::kInvalidPTS) {
1411 buffer->raw = NULL;
1412 buffer->frameCount = 0;
1413 mTimedAudioOutputOnTime = false;
1414 return INVALID_OPERATION;
1415 }
1416
1417 Mutex::Autolock _l(mTimedBufferQueueLock);
1418
1419 ALOG_ASSERT(!mQueueHeadInFlight,
1420 "getNextBuffer called without releaseBuffer!");
1421
1422 while (true) {
1423
1424 // if we have no timed buffers, then fail
1425 if (mTimedBufferQueue.isEmpty()) {
1426 buffer->raw = NULL;
1427 buffer->frameCount = 0;
1428 return NOT_ENOUGH_DATA;
1429 }
1430
1431 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1432
1433 // calculate the PTS of the head of the timed buffer queue expressed in
1434 // local time
1435 int64_t headLocalPTS;
1436 {
1437 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1438
1439 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1440
1441 if (mMediaTimeTransform.a_to_b_denom == 0) {
1442 // the transform represents a pause, so yield silence
1443 timedYieldSilence_l(buffer->frameCount, buffer);
1444 return NO_ERROR;
1445 }
1446
1447 int64_t transformedPTS;
1448 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1449 &transformedPTS)) {
1450 // the transform failed. this shouldn't happen, but if it does
1451 // then just drop this buffer
1452 ALOGW("timedGetNextBuffer transform failed");
1453 buffer->raw = NULL;
1454 buffer->frameCount = 0;
1455 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1456 return NO_ERROR;
1457 }
1458
1459 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1460 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1461 &headLocalPTS)) {
1462 buffer->raw = NULL;
1463 buffer->frameCount = 0;
1464 return INVALID_OPERATION;
1465 }
1466 } else {
1467 headLocalPTS = transformedPTS;
1468 }
1469 }
1470
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001471 uint32_t sr = sampleRate();
1472
Eric Laurent81784c32012-11-19 14:55:58 -08001473 // adjust the head buffer's PTS to reflect the portion of the head buffer
1474 // that has already been consumed
1475 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001476 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001477
1478 // Calculate the delta in samples between the head of the input buffer
1479 // queue and the start of the next output buffer that will be written.
1480 // If the transformation fails because of over or underflow, it means
1481 // that the sample's position in the output stream is so far out of
1482 // whack that it should just be dropped.
1483 int64_t sampleDelta;
1484 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1485 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1486 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1487 " mix");
1488 continue;
1489 }
1490 if (!mLocalTimeToSampleTransform.doForwardTransform(
1491 (effectivePTS - pts) << 32, &sampleDelta)) {
1492 ALOGV("*** too late during sample rate transform: dropped buffer");
1493 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1494 continue;
1495 }
1496
1497 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1498 " sampleDelta=[%d.%08x]",
1499 head.pts(), head.position(), pts,
1500 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1501 + (sampleDelta >> 32)),
1502 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1503
1504 // if the delta between the ideal placement for the next input sample and
1505 // the current output position is within this threshold, then we will
1506 // concatenate the next input samples to the previous output
1507 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001508 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001509
1510 // if this is the first buffer of audio that we're emitting from this track
1511 // then it should be almost exactly on time.
1512 const int64_t kSampleStartupThreshold = 1LL << 32;
1513
1514 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1515 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1516 // the next input is close enough to being on time, so concatenate it
1517 // with the last output
1518 timedYieldSamples_l(buffer);
1519
1520 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1521 head.position(), buffer->frameCount);
1522 return NO_ERROR;
1523 }
1524
1525 // Looks like our output is not on time. Reset our on timed status.
1526 // Next time we mix samples from our input queue, then should be within
1527 // the StartupThreshold.
1528 mTimedAudioOutputOnTime = false;
1529 if (sampleDelta > 0) {
1530 // the gap between the current output position and the proper start of
1531 // the next input sample is too big, so fill it with silence
1532 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1533
1534 timedYieldSilence_l(framesUntilNextInput, buffer);
1535 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1536 return NO_ERROR;
1537 } else {
1538 // the next input sample is late
1539 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1540 size_t onTimeSamplePosition =
1541 head.position() + lateFrames * mFrameSize;
1542
1543 if (onTimeSamplePosition > head.buffer()->size()) {
1544 // all the remaining samples in the head are too late, so
1545 // drop it and move on
1546 ALOGV("*** too late: dropped buffer");
1547 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1548 continue;
1549 } else {
1550 // skip over the late samples
1551 head.setPosition(onTimeSamplePosition);
1552
1553 // yield the available samples
1554 timedYieldSamples_l(buffer);
1555
1556 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1557 return NO_ERROR;
1558 }
1559 }
1560 }
1561}
1562
1563// Yield samples from the timed buffer queue head up to the given output
1564// buffer's capacity.
1565//
1566// Caller must hold mTimedBufferQueueLock
1567void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1568 AudioBufferProvider::Buffer* buffer) {
1569
1570 const TimedBuffer& head = mTimedBufferQueue[0];
1571
1572 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1573 head.position());
1574
1575 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1576 mFrameSize);
1577 size_t framesRequested = buffer->frameCount;
1578 buffer->frameCount = min(framesLeftInHead, framesRequested);
1579
1580 mQueueHeadInFlight = true;
1581 mTimedAudioOutputOnTime = true;
1582}
1583
1584// Yield samples of silence up to the given output buffer's capacity
1585//
1586// Caller must hold mTimedBufferQueueLock
1587void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1588 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1589
1590 // lazily allocate a buffer filled with silence
1591 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1592 delete [] mTimedSilenceBuffer;
1593 mTimedSilenceBufferSize = numFrames * mFrameSize;
1594 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1595 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1596 }
1597
1598 buffer->raw = mTimedSilenceBuffer;
1599 size_t framesRequested = buffer->frameCount;
1600 buffer->frameCount = min(numFrames, framesRequested);
1601
1602 mTimedAudioOutputOnTime = false;
1603}
1604
1605// AudioBufferProvider interface
1606void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1607 AudioBufferProvider::Buffer* buffer) {
1608
1609 Mutex::Autolock _l(mTimedBufferQueueLock);
1610
1611 // If the buffer which was just released is part of the buffer at the head
1612 // of the queue, be sure to update the amt of the buffer which has been
1613 // consumed. If the buffer being returned is not part of the head of the
1614 // queue, its either because the buffer is part of the silence buffer, or
1615 // because the head of the timed queue was trimmed after the mixer called
1616 // getNextBuffer but before the mixer called releaseBuffer.
1617 if (buffer->raw == mTimedSilenceBuffer) {
1618 ALOG_ASSERT(!mQueueHeadInFlight,
1619 "Queue head in flight during release of silence buffer!");
1620 goto done;
1621 }
1622
1623 ALOG_ASSERT(mQueueHeadInFlight,
1624 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1625 " head in flight.");
1626
1627 if (mTimedBufferQueue.size()) {
1628 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1629
1630 void* start = head.buffer()->pointer();
1631 void* end = reinterpret_cast<void*>(
1632 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1633 + head.buffer()->size());
1634
1635 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1636 "released buffer not within the head of the timed buffer"
1637 " queue; qHead = [%p, %p], released buffer = %p",
1638 start, end, buffer->raw);
1639
1640 head.setPosition(head.position() +
1641 (buffer->frameCount * mFrameSize));
1642 mQueueHeadInFlight = false;
1643
1644 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1645 "Bad bookkeeping during releaseBuffer! Should have at"
1646 " least %u queued frames, but we think we have only %u",
1647 buffer->frameCount, mFramesPendingInQueue);
1648
1649 mFramesPendingInQueue -= buffer->frameCount;
1650
1651 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1652 || mTrimQueueHeadOnRelease) {
1653 trimTimedBufferQueueHead_l("releaseBuffer");
1654 mTrimQueueHeadOnRelease = false;
1655 }
1656 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001657 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001658 " buffers in the timed buffer queue");
1659 }
1660
1661done:
1662 buffer->raw = 0;
1663 buffer->frameCount = 0;
1664}
1665
1666size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1667 Mutex::Autolock _l(mTimedBufferQueueLock);
1668 return mFramesPendingInQueue;
1669}
1670
1671AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1672 : mPTS(0), mPosition(0) {}
1673
1674AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1675 const sp<IMemory>& buffer, int64_t pts)
1676 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1677
1678
1679// ----------------------------------------------------------------------------
1680
1681AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1682 PlaybackThread *playbackThread,
1683 DuplicatingThread *sourceThread,
1684 uint32_t sampleRate,
1685 audio_format_t format,
1686 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001687 size_t frameCount,
1688 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001689 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001690 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001691 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001692{
1693
1694 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001695 mOutBuffer.frameCount = 0;
1696 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001697 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001698 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001699 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001700 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001701 // since client and server are in the same process,
1702 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001703 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1704 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001705 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001706 mClientProxy->setSendLevel(0.0);
1707 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001708 } else {
1709 ALOGW("Error creating output track on thread %p", playbackThread);
1710 }
1711}
1712
1713AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1714{
1715 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001716 delete mClientProxy;
1717 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001718}
1719
1720status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1721 int triggerSession)
1722{
1723 status_t status = Track::start(event, triggerSession);
1724 if (status != NO_ERROR) {
1725 return status;
1726 }
1727
1728 mActive = true;
1729 mRetryCount = 127;
1730 return status;
1731}
1732
1733void AudioFlinger::PlaybackThread::OutputTrack::stop()
1734{
1735 Track::stop();
1736 clearBufferQueue();
1737 mOutBuffer.frameCount = 0;
1738 mActive = false;
1739}
1740
1741bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1742{
1743 Buffer *pInBuffer;
1744 Buffer inBuffer;
1745 uint32_t channelCount = mChannelCount;
1746 bool outputBufferFull = false;
1747 inBuffer.frameCount = frames;
1748 inBuffer.i16 = data;
1749
1750 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1751
1752 if (!mActive && frames != 0) {
1753 start();
1754 sp<ThreadBase> thread = mThread.promote();
1755 if (thread != 0) {
1756 MixerThread *mixerThread = (MixerThread *)thread.get();
1757 if (mFrameCount > frames) {
1758 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1759 uint32_t startFrames = (mFrameCount - frames);
1760 pInBuffer = new Buffer;
1761 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1762 pInBuffer->frameCount = startFrames;
1763 pInBuffer->i16 = pInBuffer->mBuffer;
1764 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1765 mBufferQueue.add(pInBuffer);
1766 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001767 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001768 }
1769 }
1770 }
1771 }
1772
1773 while (waitTimeLeftMs) {
1774 // First write pending buffers, then new data
1775 if (mBufferQueue.size()) {
1776 pInBuffer = mBufferQueue.itemAt(0);
1777 } else {
1778 pInBuffer = &inBuffer;
1779 }
1780
1781 if (pInBuffer->frameCount == 0) {
1782 break;
1783 }
1784
1785 if (mOutBuffer.frameCount == 0) {
1786 mOutBuffer.frameCount = pInBuffer->frameCount;
1787 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001788 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1789 if (status != NO_ERROR) {
1790 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1791 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001792 outputBufferFull = true;
1793 break;
1794 }
1795 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1796 if (waitTimeLeftMs >= waitTimeMs) {
1797 waitTimeLeftMs -= waitTimeMs;
1798 } else {
1799 waitTimeLeftMs = 0;
1800 }
1801 }
1802
1803 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1804 pInBuffer->frameCount;
1805 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001806 Proxy::Buffer buf;
1807 buf.mFrameCount = outFrames;
1808 buf.mRaw = NULL;
1809 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001810 pInBuffer->frameCount -= outFrames;
1811 pInBuffer->i16 += outFrames * channelCount;
1812 mOutBuffer.frameCount -= outFrames;
1813 mOutBuffer.i16 += outFrames * channelCount;
1814
1815 if (pInBuffer->frameCount == 0) {
1816 if (mBufferQueue.size()) {
1817 mBufferQueue.removeAt(0);
1818 delete [] pInBuffer->mBuffer;
1819 delete pInBuffer;
1820 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1821 mThread.unsafe_get(), mBufferQueue.size());
1822 } else {
1823 break;
1824 }
1825 }
1826 }
1827
1828 // If we could not write all frames, allocate a buffer and queue it for next time.
1829 if (inBuffer.frameCount) {
1830 sp<ThreadBase> thread = mThread.promote();
1831 if (thread != 0 && !thread->standby()) {
1832 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1833 pInBuffer = new Buffer;
1834 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1835 pInBuffer->frameCount = inBuffer.frameCount;
1836 pInBuffer->i16 = pInBuffer->mBuffer;
1837 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1838 sizeof(int16_t));
1839 mBufferQueue.add(pInBuffer);
1840 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1841 mThread.unsafe_get(), mBufferQueue.size());
1842 } else {
1843 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1844 mThread.unsafe_get(), this);
1845 }
1846 }
1847 }
1848
1849 // Calling write() with a 0 length buffer, means that no more data will be written:
1850 // If no more buffers are pending, fill output track buffer to make sure it is started
1851 // by output mixer.
1852 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001853 // FIXME borken, replace by getting framesReady() from proxy
1854 size_t user = 0; // was mCblk->user
1855 if (user < mFrameCount) {
1856 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001857 pInBuffer = new Buffer;
1858 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1859 pInBuffer->frameCount = frames;
1860 pInBuffer->i16 = pInBuffer->mBuffer;
1861 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1862 mBufferQueue.add(pInBuffer);
1863 } else if (mActive) {
1864 stop();
1865 }
1866 }
1867
1868 return outputBufferFull;
1869}
1870
1871status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1872 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1873{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001874 ClientProxy::Buffer buf;
1875 buf.mFrameCount = buffer->frameCount;
1876 struct timespec timeout;
1877 timeout.tv_sec = waitTimeMs / 1000;
1878 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1879 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1880 buffer->frameCount = buf.mFrameCount;
1881 buffer->raw = buf.mRaw;
1882 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001883}
1884
Eric Laurent81784c32012-11-19 14:55:58 -08001885void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1886{
1887 size_t size = mBufferQueue.size();
1888
1889 for (size_t i = 0; i < size; i++) {
1890 Buffer *pBuffer = mBufferQueue.itemAt(i);
1891 delete [] pBuffer->mBuffer;
1892 delete pBuffer;
1893 }
1894 mBufferQueue.clear();
1895}
1896
1897
Eric Laurent83b88082014-06-20 18:31:16 -07001898AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
1899 uint32_t sampleRate,
1900 audio_channel_mask_t channelMask,
1901 audio_format_t format,
1902 size_t frameCount,
1903 void *buffer,
1904 IAudioFlinger::track_flags_t flags)
1905 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1906 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1907 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1908{
1909 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1910 playbackThread->sampleRate();
1911 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1912 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1913
1914 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1915 this, sampleRate,
1916 (int)mPeerTimeout.tv_sec,
1917 (int)(mPeerTimeout.tv_nsec / 1000000));
1918}
1919
1920AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1921{
1922}
1923
1924// AudioBufferProvider interface
1925status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
1926 AudioBufferProvider::Buffer* buffer, int64_t pts)
1927{
1928 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1929 Proxy::Buffer buf;
1930 buf.mFrameCount = buffer->frameCount;
1931 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1932 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001933 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001934 if (buf.mFrameCount == 0) {
1935 return WOULD_BLOCK;
1936 }
Eric Laurent83b88082014-06-20 18:31:16 -07001937 status = Track::getNextBuffer(buffer, pts);
1938 return status;
1939}
1940
1941void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1942{
1943 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1944 Proxy::Buffer buf;
1945 buf.mFrameCount = buffer->frameCount;
1946 buf.mRaw = buffer->raw;
1947 mPeerProxy->releaseBuffer(&buf);
1948 TrackBase::releaseBuffer(buffer);
1949}
1950
1951status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1952 const struct timespec *timeOut)
1953{
1954 return mProxy->obtainBuffer(buffer, timeOut);
1955}
1956
1957void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1958{
1959 mProxy->releaseBuffer(buffer);
1960 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1961 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1962 start();
1963 }
1964 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1965}
1966
Eric Laurent81784c32012-11-19 14:55:58 -08001967// ----------------------------------------------------------------------------
1968// Record
1969// ----------------------------------------------------------------------------
1970
1971AudioFlinger::RecordHandle::RecordHandle(
1972 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1973 : BnAudioRecord(),
1974 mRecordTrack(recordTrack)
1975{
1976}
1977
1978AudioFlinger::RecordHandle::~RecordHandle() {
1979 stop_nonvirtual();
1980 mRecordTrack->destroy();
1981}
1982
Eric Laurent81784c32012-11-19 14:55:58 -08001983status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1984 int triggerSession) {
1985 ALOGV("RecordHandle::start()");
1986 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1987}
1988
1989void AudioFlinger::RecordHandle::stop() {
1990 stop_nonvirtual();
1991}
1992
1993void AudioFlinger::RecordHandle::stop_nonvirtual() {
1994 ALOGV("RecordHandle::stop()");
1995 mRecordTrack->stop();
1996}
1997
1998status_t AudioFlinger::RecordHandle::onTransact(
1999 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2000{
2001 return BnAudioRecord::onTransact(code, data, reply, flags);
2002}
2003
2004// ----------------------------------------------------------------------------
2005
Glenn Kasten05997e22014-03-13 15:08:33 -07002006// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08002007AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2008 RecordThread *thread,
2009 const sp<Client>& client,
2010 uint32_t sampleRate,
2011 audio_format_t format,
2012 audio_channel_mask_t channelMask,
2013 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07002014 void *buffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002015 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07002016 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -07002017 IAudioFlinger::track_flags_t flags,
2018 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08002019 : TrackBase(thread, client, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07002020 channelMask, frameCount, buffer, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07002021 flags, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07002022 (type == TYPE_DEFAULT) ?
2023 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
2024 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
2025 type),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002026 mOverflow(false), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0),
2027 // See real initialization of mRsmpInFront at RecordThread::start()
2028 mRsmpInUnrel(0), mRsmpInFront(0), mFramesToDrop(0), mResamplerBufferProvider(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08002029{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07002030 if (mCblk == NULL) {
2031 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002032 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002033
Eric Laurent83b88082014-06-20 18:31:16 -07002034 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
2035 mFrameSize, !isExternalTrack());
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07002036
Andy Hunge5412692014-05-16 11:25:07 -07002037 uint32_t channelCount = audio_channel_count_from_in_mask(channelMask);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002038 // FIXME I don't understand either of the channel count checks
2039 if (thread->mSampleRate != sampleRate && thread->mChannelCount <= FCC_2 &&
2040 channelCount <= FCC_2) {
2041 // sink SR
Andy Hung3348e362014-07-07 10:21:44 -07002042 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_16_BIT,
2043 thread->mChannelCount, sampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002044 // source SR
2045 mResampler->setSampleRate(thread->mSampleRate);
Andy Hung5e58b0a2014-06-23 19:07:29 -07002046 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002047 mResamplerBufferProvider = new ResamplerBufferProvider(this);
2048 }
Glenn Kastenc263ca02014-06-04 20:31:46 -07002049
2050 if (flags & IAudioFlinger::TRACK_FAST) {
2051 ALOG_ASSERT(thread->mFastTrackAvail);
2052 thread->mFastTrackAvail = false;
2053 }
Eric Laurent81784c32012-11-19 14:55:58 -08002054}
2055
2056AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
2057{
2058 ALOGV("%s", __func__);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002059 delete mResampler;
2060 delete[] mRsmpOutBuffer;
2061 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08002062}
2063
2064// AudioBufferProvider interface
2065status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002066 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002067{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002068 ServerProxy::Buffer buf;
2069 buf.mFrameCount = buffer->frameCount;
2070 status_t status = mServerProxy->obtainBuffer(&buf);
2071 buffer->frameCount = buf.mFrameCount;
2072 buffer->raw = buf.mRaw;
2073 if (buf.mFrameCount == 0) {
2074 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07002075 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002076 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002077 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002078}
2079
2080status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
2081 int triggerSession)
2082{
2083 sp<ThreadBase> thread = mThread.promote();
2084 if (thread != 0) {
2085 RecordThread *recordThread = (RecordThread *)thread.get();
2086 return recordThread->start(this, event, triggerSession);
2087 } else {
2088 return BAD_VALUE;
2089 }
2090}
2091
2092void AudioFlinger::RecordThread::RecordTrack::stop()
2093{
2094 sp<ThreadBase> thread = mThread.promote();
2095 if (thread != 0) {
2096 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07002097 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07002098 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002099 }
2100 }
2101}
2102
2103void AudioFlinger::RecordThread::RecordTrack::destroy()
2104{
2105 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
2106 sp<RecordTrack> keep(this);
2107 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002108 if (isExternalTrack()) {
2109 if (mState == ACTIVE || mState == RESUMING) {
2110 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
2111 }
2112 AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
2113 }
Eric Laurent81784c32012-11-19 14:55:58 -08002114 sp<ThreadBase> thread = mThread.promote();
2115 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002116 Mutex::Autolock _l(thread->mLock);
2117 RecordThread *recordThread = (RecordThread *) thread.get();
2118 recordThread->destroyTrack_l(this);
2119 }
2120 }
2121}
2122
Eric Laurent9a54bc22013-09-09 09:08:44 -07002123void AudioFlinger::RecordThread::RecordTrack::invalidate()
2124{
2125 // FIXME should use proxy, and needs work
2126 audio_track_cblk_t* cblk = mCblk;
2127 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2128 android_atomic_release_store(0x40000000, &cblk->mFutex);
2129 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07002130 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07002131}
2132
Eric Laurent81784c32012-11-19 14:55:58 -08002133
2134/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
2135{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002136 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08002137}
2138
Marco Nelissenb2208842014-02-07 14:00:50 -08002139void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08002140{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002141 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08002142 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08002143 (mClient == 0) ? getpid_cached : mClient->pid(),
2144 mFormat,
2145 mChannelMask,
2146 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08002147 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002148 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002149 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002150 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002151
Eric Laurent81784c32012-11-19 14:55:58 -08002152}
2153
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002154void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2155{
2156 if (event == mSyncStartEvent) {
2157 ssize_t framesToDrop = 0;
2158 sp<ThreadBase> threadBase = mThread.promote();
2159 if (threadBase != 0) {
2160 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2161 // from audio HAL
2162 framesToDrop = threadBase->mFrameCount * 2;
2163 }
2164 mFramesToDrop = framesToDrop;
2165 }
2166}
2167
2168void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2169{
2170 if (mSyncStartEvent != 0) {
2171 mSyncStartEvent->cancel();
2172 mSyncStartEvent.clear();
2173 }
2174 mFramesToDrop = 0;
2175}
2176
Eric Laurent83b88082014-06-20 18:31:16 -07002177
2178AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
2179 uint32_t sampleRate,
2180 audio_channel_mask_t channelMask,
2181 audio_format_t format,
2182 size_t frameCount,
2183 void *buffer,
2184 IAudioFlinger::track_flags_t flags)
2185 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
2186 buffer, 0, getuid(), flags, TYPE_PATCH),
2187 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
2188{
2189 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
2190 recordThread->sampleRate();
2191 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
2192 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
2193
2194 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
2195 this, sampleRate,
2196 (int)mPeerTimeout.tv_sec,
2197 (int)(mPeerTimeout.tv_nsec / 1000000));
2198}
2199
2200AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
2201{
2202}
2203
2204// AudioBufferProvider interface
2205status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
2206 AudioBufferProvider::Buffer* buffer, int64_t pts)
2207{
2208 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
2209 Proxy::Buffer buf;
2210 buf.mFrameCount = buffer->frameCount;
2211 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
2212 ALOGV_IF(status != NO_ERROR,
2213 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07002214 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07002215 if (buf.mFrameCount == 0) {
2216 return WOULD_BLOCK;
2217 }
Eric Laurent83b88082014-06-20 18:31:16 -07002218 status = RecordTrack::getNextBuffer(buffer, pts);
2219 return status;
2220}
2221
2222void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2223{
2224 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
2225 Proxy::Buffer buf;
2226 buf.mFrameCount = buffer->frameCount;
2227 buf.mRaw = buffer->raw;
2228 mPeerProxy->releaseBuffer(&buf);
2229 TrackBase::releaseBuffer(buffer);
2230}
2231
2232status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
2233 const struct timespec *timeOut)
2234{
2235 return mProxy->obtainBuffer(buffer, timeOut);
2236}
2237
2238void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2239{
2240 mProxy->releaseBuffer(buffer);
2241}
2242
Eric Laurent81784c32012-11-19 14:55:58 -08002243}; // namespace android