blob: 1e906adbdb0e199f577586f5c13e0a43499111d8 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080023#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070024#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080025#include <utils/Log.h>
26
27#include <private/media/AudioTrackShared.h>
28
29#include <common_time/cc_helper.h>
30#include <common_time/local_clock.h>
31
32#include "AudioMixer.h"
33#include "AudioFlinger.h"
34#include "ServiceUtilities.h"
35
Glenn Kastenda6ef132013-01-10 12:31:01 -080036#include <media/nbaio/Pipe.h>
37#include <media/nbaio/PipeReader.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070038#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080039
Eric Laurent81784c32012-11-19 14:55:58 -080040// ----------------------------------------------------------------------------
41
42// Note: the following macro is used for extremely verbose logging message. In
43// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
44// 0; but one side effect of this is to turn all LOGV's as well. Some messages
45// are so verbose that we want to suppress them even when we have ALOG_ASSERT
46// turned on. Do not uncomment the #def below unless you really know what you
47// are doing and want to see all of the extremely verbose messages.
48//#define VERY_VERY_VERBOSE_LOGGING
49#ifdef VERY_VERY_VERBOSE_LOGGING
50#define ALOGVV ALOGV
51#else
52#define ALOGVV(a...) do { } while(0)
53#endif
54
55namespace android {
56
57// ----------------------------------------------------------------------------
58// TrackBase
59// ----------------------------------------------------------------------------
60
Glenn Kastenda6ef132013-01-10 12:31:01 -080061static volatile int32_t nextTrackId = 55;
62
Eric Laurent81784c32012-11-19 14:55:58 -080063// TrackBase constructor must be called with AudioFlinger::mLock held
64AudioFlinger::ThreadBase::TrackBase::TrackBase(
65 ThreadBase *thread,
66 const sp<Client>& client,
67 uint32_t sampleRate,
68 audio_format_t format,
69 audio_channel_mask_t channelMask,
70 size_t frameCount,
71 const sp<IMemory>& sharedBuffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080072 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080073 int clientUid,
Glenn Kasten755b0a62014-05-13 11:30:28 -070074 IAudioFlinger::track_flags_t flags,
Glenn Kastend776ac62014-05-07 09:16:09 -070075 bool isOut,
Glenn Kastenc263ca02014-06-04 20:31:46 -070076 alloc_type alloc)
Eric Laurent81784c32012-11-19 14:55:58 -080077 : RefBase(),
78 mThread(thread),
79 mClient(client),
80 mCblk(NULL),
81 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080082 mState(IDLE),
83 mSampleRate(sampleRate),
84 mFormat(format),
85 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070086 mChannelCount(isOut ?
87 audio_channel_count_from_out_mask(channelMask) :
88 audio_channel_count_from_in_mask(channelMask)),
Eric Laurent81784c32012-11-19 14:55:58 -080089 mFrameSize(audio_is_linear_pcm(format) ?
90 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
91 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080092 mSessionId(sessionId),
Glenn Kasten755b0a62014-05-13 11:30:28 -070093 mFlags(flags),
Glenn Kastene3aa6592012-12-04 12:22:46 -080094 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080095 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080096 mId(android_atomic_inc(&nextTrackId)),
97 mTerminated(false)
Eric Laurent81784c32012-11-19 14:55:58 -080098{
Marco Nelissen462fd2f2013-01-14 14:12:05 -080099 // if the caller is us, trust the specified uid
100 if (IPCThreadState::self()->getCallingPid() != getpid_cached || clientUid == -1) {
101 int newclientUid = IPCThreadState::self()->getCallingUid();
102 if (clientUid != -1 && clientUid != newclientUid) {
103 ALOGW("uid %d tried to pass itself off as %d", newclientUid, clientUid);
104 }
105 clientUid = newclientUid;
106 }
107 // clientUid contains the uid of the app that is responsible for this track, so we can blame
108 // battery usage on it.
109 mUid = clientUid;
110
Eric Laurent81784c32012-11-19 14:55:58 -0800111 // client == 0 implies sharedBuffer == 0
112 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
113
114 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
115 sharedBuffer->size());
116
117 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
118 size_t size = sizeof(audio_track_cblk_t);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800119 size_t bufferSize = (sharedBuffer == 0 ? roundup(frameCount) : frameCount) * mFrameSize;
Glenn Kastenc263ca02014-06-04 20:31:46 -0700120 if (sharedBuffer == 0 && alloc == ALLOC_CBLK) {
Eric Laurent81784c32012-11-19 14:55:58 -0800121 size += bufferSize;
122 }
123
124 if (client != 0) {
125 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700126 if (mCblkMemory == 0 ||
127 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800128 ALOGE("not enough memory for AudioTrack size=%u", size);
129 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700130 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800131 return;
132 }
133 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800134 // this syntax avoids calling the audio_track_cblk_t constructor twice
135 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800136 // assume mCblk != NULL
137 }
138
139 // construct the shared structure in-place.
140 if (mCblk != NULL) {
141 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700142 switch (alloc) {
143 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700144 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
145 if (roHeap == 0 ||
146 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
147 (mBuffer = mBufferMemory->pointer()) == NULL) {
148 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
149 if (roHeap != 0) {
150 roHeap->dump("buffer");
151 }
152 mCblkMemory.clear();
153 mBufferMemory.clear();
154 return;
155 }
Eric Laurent81784c32012-11-19 14:55:58 -0800156 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700157 } break;
158 case ALLOC_PIPE:
159 mBufferMemory = thread->pipeMemory();
160 // mBuffer is the virtual address as seen from current process (mediaserver),
161 // and should normally be coming from mBufferMemory->pointer().
162 // However in this case the TrackBase does not reference the buffer directly.
163 // It should references the buffer via the pipe.
164 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
165 mBuffer = NULL;
166 break;
167 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700168 // clear all buffers
169 if (sharedBuffer == 0) {
170 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
171 memset(mBuffer, 0, bufferSize);
172 } else {
173 mBuffer = sharedBuffer->pointer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800174#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700175 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800176#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700177 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700178 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800179 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800180
Glenn Kasten46909e72013-02-26 09:20:22 -0800181#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800182 if (mTeeSinkTrackEnabled) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800183 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800184 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800185 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
186 size_t numCounterOffers = 0;
187 const NBAIO_Format offers[1] = {pipeFormat};
188 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
189 ALOG_ASSERT(index == 0);
190 PipeReader *pipeReader = new PipeReader(*pipe);
191 numCounterOffers = 0;
192 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
193 ALOG_ASSERT(index == 0);
194 mTeeSink = pipe;
195 mTeeSource = pipeReader;
196 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800197 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800198#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800199
Eric Laurent81784c32012-11-19 14:55:58 -0800200 }
201}
202
203AudioFlinger::ThreadBase::TrackBase::~TrackBase()
204{
Glenn Kasten46909e72013-02-26 09:20:22 -0800205#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800206 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800207#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800208 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
209 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800210 if (mCblk != NULL) {
211 if (mClient == 0) {
212 delete mCblk;
213 } else {
214 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
215 }
216 }
217 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
218 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700219 // Client destructor must run with AudioFlinger client mutex locked
220 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800221 // If the client's reference count drops to zero, the associated destructor
222 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
223 // relying on the automatic clear() at end of scope.
224 mClient.clear();
225 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700226 // flush the binder command buffer
227 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800228}
229
230// AudioBufferProvider interface
231// getNextBuffer() = 0;
232// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
233void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
234{
Glenn Kasten46909e72013-02-26 09:20:22 -0800235#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800236 if (mTeeSink != 0) {
237 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
238 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800239#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800240
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800241 ServerProxy::Buffer buf;
242 buf.mFrameCount = buffer->frameCount;
243 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800244 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800245 buffer->raw = NULL;
246 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800247}
248
Eric Laurent81784c32012-11-19 14:55:58 -0800249status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
250{
251 mSyncEvents.add(event);
252 return NO_ERROR;
253}
254
255// ----------------------------------------------------------------------------
256// Playback
257// ----------------------------------------------------------------------------
258
259AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
260 : BnAudioTrack(),
261 mTrack(track)
262{
263}
264
265AudioFlinger::TrackHandle::~TrackHandle() {
266 // just stop the track on deletion, associated resources
267 // will be freed from the main thread once all pending buffers have
268 // been played. Unless it's not in the active track list, in which
269 // case we free everything now...
270 mTrack->destroy();
271}
272
273sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
274 return mTrack->getCblk();
275}
276
277status_t AudioFlinger::TrackHandle::start() {
278 return mTrack->start();
279}
280
281void AudioFlinger::TrackHandle::stop() {
282 mTrack->stop();
283}
284
285void AudioFlinger::TrackHandle::flush() {
286 mTrack->flush();
287}
288
Eric Laurent81784c32012-11-19 14:55:58 -0800289void AudioFlinger::TrackHandle::pause() {
290 mTrack->pause();
291}
292
293status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
294{
295 return mTrack->attachAuxEffect(EffectId);
296}
297
298status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
299 sp<IMemory>* buffer) {
300 if (!mTrack->isTimedTrack())
301 return INVALID_OPERATION;
302
303 PlaybackThread::TimedTrack* tt =
304 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
305 return tt->allocateTimedBuffer(size, buffer);
306}
307
308status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
309 int64_t pts) {
310 if (!mTrack->isTimedTrack())
311 return INVALID_OPERATION;
312
Glenn Kasten663c2242013-09-24 11:52:37 -0700313 if (buffer == 0 || buffer->pointer() == NULL) {
314 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
315 return BAD_VALUE;
316 }
317
Eric Laurent81784c32012-11-19 14:55:58 -0800318 PlaybackThread::TimedTrack* tt =
319 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
320 return tt->queueTimedBuffer(buffer, pts);
321}
322
323status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
324 const LinearTransform& xform, int target) {
325
326 if (!mTrack->isTimedTrack())
327 return INVALID_OPERATION;
328
329 PlaybackThread::TimedTrack* tt =
330 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
331 return tt->setMediaTimeTransform(
332 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
333}
334
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700335status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
336 return mTrack->setParameters(keyValuePairs);
337}
338
Glenn Kasten53cec222013-08-29 09:01:02 -0700339status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
340{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700341 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700342}
343
Eric Laurent59fe0102013-09-27 18:48:26 -0700344
345void AudioFlinger::TrackHandle::signal()
346{
347 return mTrack->signal();
348}
349
Eric Laurent81784c32012-11-19 14:55:58 -0800350status_t AudioFlinger::TrackHandle::onTransact(
351 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
352{
353 return BnAudioTrack::onTransact(code, data, reply, flags);
354}
355
356// ----------------------------------------------------------------------------
357
358// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
359AudioFlinger::PlaybackThread::Track::Track(
360 PlaybackThread *thread,
361 const sp<Client>& client,
362 audio_stream_type_t streamType,
363 uint32_t sampleRate,
364 audio_format_t format,
365 audio_channel_mask_t channelMask,
366 size_t frameCount,
367 const sp<IMemory>& sharedBuffer,
368 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800369 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -0800370 IAudioFlinger::track_flags_t flags)
371 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
Glenn Kasten755b0a62014-05-13 11:30:28 -0700372 sessionId, uid, flags, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800373 mFillingUpStatus(FS_INVALID),
374 // mRetryCount initialized later when needed
375 mSharedBuffer(sharedBuffer),
376 mStreamType(streamType),
377 mName(-1), // see note below
378 mMainBuffer(thread->mixBuffer()),
379 mAuxBuffer(NULL),
380 mAuxEffectId(0), mHasVolumeController(false),
381 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800382 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800383 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800384 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800385 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800386 mResumeToStopping(false),
Glenn Kastenced6e742014-06-09 17:12:32 -0700387 mFlushHwPending(false),
388 mPreviousValid(false),
389 mPreviousFramesWritten(0)
390 // mPreviousTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800391{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700392 if (mCblk == NULL) {
393 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800394 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700395
396 if (sharedBuffer == 0) {
397 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
398 mFrameSize);
399 } else {
400 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
401 mFrameSize);
402 }
403 mServerProxy = mAudioTrackServerProxy;
404
Glenn Kastenc263ca02014-06-04 20:31:46 -0700405 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700406 if (mName < 0) {
407 ALOGE("no more track names available");
408 return;
409 }
410 // only allocate a fast track index if we were able to allocate a normal track name
411 if (flags & IAudioFlinger::TRACK_FAST) {
412 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
413 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
414 int i = __builtin_ctz(thread->mFastTrackAvailMask);
415 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
416 // FIXME This is too eager. We allocate a fast track index before the
417 // fast track becomes active. Since fast tracks are a scarce resource,
418 // this means we are potentially denying other more important fast tracks from
419 // being created. It would be better to allocate the index dynamically.
420 mFastIndex = i;
421 // Read the initial underruns because this field is never cleared by the fast mixer
422 mObservedUnderruns = thread->getFastTrackUnderruns(i);
423 thread->mFastTrackAvailMask &= ~(1 << i);
424 }
Eric Laurent81784c32012-11-19 14:55:58 -0800425}
426
427AudioFlinger::PlaybackThread::Track::~Track()
428{
429 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700430
431 // The destructor would clear mSharedBuffer,
432 // but it will not push the decremented reference count,
433 // leaving the client's IMemory dangling indefinitely.
434 // This prevents that leak.
435 if (mSharedBuffer != 0) {
436 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700437 }
Eric Laurent81784c32012-11-19 14:55:58 -0800438}
439
Glenn Kasten03003332013-08-06 15:40:54 -0700440status_t AudioFlinger::PlaybackThread::Track::initCheck() const
441{
442 status_t status = TrackBase::initCheck();
443 if (status == NO_ERROR && mName < 0) {
444 status = NO_MEMORY;
445 }
446 return status;
447}
448
Eric Laurent81784c32012-11-19 14:55:58 -0800449void AudioFlinger::PlaybackThread::Track::destroy()
450{
451 // NOTE: destroyTrack_l() can remove a strong reference to this Track
452 // by removing it from mTracks vector, so there is a risk that this Tracks's
453 // destructor is called. As the destructor needs to lock mLock,
454 // we must acquire a strong reference on this Track before locking mLock
455 // here so that the destructor is called only when exiting this function.
456 // On the other hand, as long as Track::destroy() is only called by
457 // TrackHandle destructor, the TrackHandle still holds a strong ref on
458 // this Track with its member mTrack.
459 sp<Track> keep(this);
460 { // scope for mLock
461 sp<ThreadBase> thread = mThread.promote();
462 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800463 Mutex::Autolock _l(thread->mLock);
464 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800465 bool wasActive = playbackThread->destroyTrack_l(this);
466 if (!isOutputTrack() && !wasActive) {
467 AudioSystem::releaseOutput(thread->id());
468 }
Eric Laurent81784c32012-11-19 14:55:58 -0800469 }
470 }
471}
472
473/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
474{
Marco Nelissenb2208842014-02-07 14:00:50 -0800475 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700476 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800477}
478
Marco Nelissenb2208842014-02-07 14:00:50 -0800479void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800480{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700481 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800482 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800483 sprintf(buffer, " F %2d", mFastIndex);
484 } else if (mName >= AudioMixer::TRACK0) {
485 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800486 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800487 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800488 }
489 track_state state = mState;
490 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800491 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800492 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800493 } else {
494 switch (state) {
495 case IDLE:
496 stateChar = 'I';
497 break;
498 case STOPPING_1:
499 stateChar = 's';
500 break;
501 case STOPPING_2:
502 stateChar = '5';
503 break;
504 case STOPPED:
505 stateChar = 'S';
506 break;
507 case RESUMING:
508 stateChar = 'R';
509 break;
510 case ACTIVE:
511 stateChar = 'A';
512 break;
513 case PAUSING:
514 stateChar = 'p';
515 break;
516 case PAUSED:
517 stateChar = 'P';
518 break;
519 case FLUSHED:
520 stateChar = 'F';
521 break;
522 default:
523 stateChar = '?';
524 break;
525 }
Eric Laurent81784c32012-11-19 14:55:58 -0800526 }
527 char nowInUnderrun;
528 switch (mObservedUnderruns.mBitFields.mMostRecent) {
529 case UNDERRUN_FULL:
530 nowInUnderrun = ' ';
531 break;
532 case UNDERRUN_PARTIAL:
533 nowInUnderrun = '<';
534 break;
535 case UNDERRUN_EMPTY:
536 nowInUnderrun = '*';
537 break;
538 default:
539 nowInUnderrun = '?';
540 break;
541 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000542 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 +0000543 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800544 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800545 (mClient == 0) ? getpid_cached : mClient->pid(),
546 mStreamType,
547 mFormat,
548 mChannelMask,
549 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800550 mFrameCount,
551 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800552 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800553 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700554 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
555 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700556 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000557 mMainBuffer,
558 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700559 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700560 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800561 nowInUnderrun);
562}
563
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800564uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
565 return mAudioTrackServerProxy->getSampleRate();
566}
567
Eric Laurent81784c32012-11-19 14:55:58 -0800568// AudioBufferProvider interface
569status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800570 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800571{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800572 ServerProxy::Buffer buf;
573 size_t desiredFrames = buffer->frameCount;
574 buf.mFrameCount = desiredFrames;
575 status_t status = mServerProxy->obtainBuffer(&buf);
576 buffer->frameCount = buf.mFrameCount;
577 buffer->raw = buf.mRaw;
578 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700579 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800580 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800581 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800582}
583
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700584// releaseBuffer() is not overridden
585
586// ExtendedAudioBufferProvider interface
587
Eric Laurent81784c32012-11-19 14:55:58 -0800588// Note that framesReady() takes a mutex on the control block using tryLock().
589// This could result in priority inversion if framesReady() is called by the normal mixer,
590// as the normal mixer thread runs at lower
591// priority than the client's callback thread: there is a short window within framesReady()
592// during which the normal mixer could be preempted, and the client callback would block.
593// Another problem can occur if framesReady() is called by the fast mixer:
594// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
595// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
596size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800597 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800598}
599
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700600size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
601{
602 return mAudioTrackServerProxy->framesReleased();
603}
604
Eric Laurent81784c32012-11-19 14:55:58 -0800605// Don't call for fast tracks; the framesReady() could result in priority inversion
606bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800607 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
608 return true;
609 }
610
Eric Laurent16498512014-03-17 17:22:08 -0700611 if (isStopping()) {
612 if (framesReady() > 0) {
613 mFillingUpStatus = FS_FILLED;
614 }
Eric Laurent81784c32012-11-19 14:55:58 -0800615 return true;
616 }
617
618 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700619 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800620 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700621 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800622 return true;
623 }
624 return false;
625}
626
Glenn Kasten0f11b512014-01-31 16:18:54 -0800627status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
628 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800629{
630 status_t status = NO_ERROR;
631 ALOGV("start(%d), calling pid %d session %d",
632 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
633
634 sp<ThreadBase> thread = mThread.promote();
635 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700636 if (isOffloaded()) {
637 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
638 Mutex::Autolock _lth(thread->mLock);
639 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700640 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
641 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700642 invalidate();
643 return PERMISSION_DENIED;
644 }
645 }
646 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800647 track_state state = mState;
648 // here the track could be either new, or restarted
649 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800650
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800651 // initial state-stopping. next state-pausing.
652 // What if resume is called ?
653
654 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800655 if (mResumeToStopping) {
656 // happened we need to resume to STOPPING_1
657 mState = TrackBase::STOPPING_1;
658 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
659 } else {
660 mState = TrackBase::RESUMING;
661 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
662 }
Eric Laurent81784c32012-11-19 14:55:58 -0800663 } else {
664 mState = TrackBase::ACTIVE;
665 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
666 }
667
Eric Laurentbfb1b832013-01-07 09:53:42 -0800668 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
669 status = playbackThread->addTrack_l(this);
670 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800671 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800672 // restore previous state if start was rejected by policy manager
673 if (status == PERMISSION_DENIED) {
674 mState = state;
675 }
676 }
677 // track was already in the active list, not a problem
678 if (status == ALREADY_EXISTS) {
679 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700680 } else {
681 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
682 // It is usually unsafe to access the server proxy from a binder thread.
683 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
684 // isn't looking at this track yet: we still hold the normal mixer thread lock,
685 // and for fast tracks the track is not yet in the fast mixer thread's active set.
686 ServerProxy::Buffer buffer;
687 buffer.mFrameCount = 1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700688 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800689 }
690 } else {
691 status = BAD_VALUE;
692 }
693 return status;
694}
695
696void AudioFlinger::PlaybackThread::Track::stop()
697{
698 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
699 sp<ThreadBase> thread = mThread.promote();
700 if (thread != 0) {
701 Mutex::Autolock _l(thread->mLock);
702 track_state state = mState;
703 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
704 // If the track is not active (PAUSED and buffers full), flush buffers
705 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
706 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
707 reset();
708 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800709 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800710 mState = STOPPED;
711 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800712 // For fast tracks prepareTracks_l() will set state to STOPPING_2
713 // presentation is complete
714 // For an offloaded track this starts a drain and state will
715 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800716 mState = STOPPING_1;
717 }
718 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
719 playbackThread);
720 }
Eric Laurent81784c32012-11-19 14:55:58 -0800721 }
722}
723
724void AudioFlinger::PlaybackThread::Track::pause()
725{
726 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
727 sp<ThreadBase> thread = mThread.promote();
728 if (thread != 0) {
729 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800730 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
731 switch (mState) {
732 case STOPPING_1:
733 case STOPPING_2:
734 if (!isOffloaded()) {
735 /* nothing to do if track is not offloaded */
736 break;
737 }
738
739 // Offloaded track was draining, we need to carry on draining when resumed
740 mResumeToStopping = true;
741 // fall through...
742 case ACTIVE:
743 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800744 mState = PAUSING;
745 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700746 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800747 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800748
Eric Laurentbfb1b832013-01-07 09:53:42 -0800749 default:
750 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800751 }
752 }
753}
754
755void AudioFlinger::PlaybackThread::Track::flush()
756{
757 ALOGV("flush(%d)", mName);
758 sp<ThreadBase> thread = mThread.promote();
759 if (thread != 0) {
760 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800761 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800762
763 if (isOffloaded()) {
764 // If offloaded we allow flush during any state except terminated
765 // and keep the track active to avoid problems if user is seeking
766 // rapidly and underlying hardware has a significant delay handling
767 // a pause
768 if (isTerminated()) {
769 return;
770 }
771
772 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800773 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800774
775 if (mState == STOPPING_1 || mState == STOPPING_2) {
776 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
777 mState = ACTIVE;
778 }
779
780 if (mState == ACTIVE) {
781 ALOGV("flush called in active state, resetting buffer time out retry count");
782 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
783 }
784
Haynes Mathew George7844f672014-01-15 12:32:55 -0800785 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800786 mResumeToStopping = false;
787 } else {
788 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
789 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
790 return;
791 }
792 // No point remaining in PAUSED state after a flush => go to
793 // FLUSHED state
794 mState = FLUSHED;
795 // do not reset the track if it is still in the process of being stopped or paused.
796 // this will be done by prepareTracks_l() when the track is stopped.
797 // prepareTracks_l() will see mState == FLUSHED, then
798 // remove from active track list, reset(), and trigger presentation complete
799 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
800 reset();
801 }
Eric Laurent81784c32012-11-19 14:55:58 -0800802 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800803 // Prevent flush being lost if the track is flushed and then resumed
804 // before mixer thread can run. This is important when offloading
805 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700806 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800807 }
808}
809
Haynes Mathew George7844f672014-01-15 12:32:55 -0800810// must be called with thread lock held
811void AudioFlinger::PlaybackThread::Track::flushAck()
812{
813 if (!isOffloaded())
814 return;
815
816 mFlushHwPending = false;
817}
818
Eric Laurent81784c32012-11-19 14:55:58 -0800819void AudioFlinger::PlaybackThread::Track::reset()
820{
821 // Do not reset twice to avoid discarding data written just after a flush and before
822 // the audioflinger thread detects the track is stopped.
823 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800824 // Force underrun condition to avoid false underrun callback until first data is
825 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700826 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800827 mFillingUpStatus = FS_FILLING;
828 mResetDone = true;
829 if (mState == FLUSHED) {
830 mState = IDLE;
831 }
832 }
833}
834
Eric Laurentbfb1b832013-01-07 09:53:42 -0800835status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
836{
837 sp<ThreadBase> thread = mThread.promote();
838 if (thread == 0) {
839 ALOGE("thread is dead");
840 return FAILED_TRANSACTION;
841 } else if ((thread->type() == ThreadBase::DIRECT) ||
842 (thread->type() == ThreadBase::OFFLOAD)) {
843 return thread->setParameters(keyValuePairs);
844 } else {
845 return PERMISSION_DENIED;
846 }
847}
848
Glenn Kasten573d80a2013-08-26 09:36:23 -0700849status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
850{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700851 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
852 if (isFastTrack()) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700853 // FIXME no lock held to set mPreviousValid = false
Glenn Kastenfe346c72013-08-30 13:28:22 -0700854 return INVALID_OPERATION;
855 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700856 sp<ThreadBase> thread = mThread.promote();
857 if (thread == 0) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700858 // FIXME no lock held to set mPreviousValid = false
Glenn Kastenfe346c72013-08-30 13:28:22 -0700859 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700860 }
861 Mutex::Autolock _l(thread->mLock);
862 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaccc1472013-09-20 09:36:34 -0700863 if (!isOffloaded()) {
864 if (!playbackThread->mLatchQValid) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700865 mPreviousValid = false;
Eric Laurentaccc1472013-09-20 09:36:34 -0700866 return INVALID_OPERATION;
867 }
868 uint32_t unpresentedFrames =
869 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
870 playbackThread->mSampleRate;
871 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
Glenn Kastenced6e742014-06-09 17:12:32 -0700872 bool checkPreviousTimestamp = mPreviousValid && framesWritten >= mPreviousFramesWritten;
Eric Laurentaccc1472013-09-20 09:36:34 -0700873 if (framesWritten < unpresentedFrames) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700874 mPreviousValid = false;
Eric Laurentaccc1472013-09-20 09:36:34 -0700875 return INVALID_OPERATION;
876 }
Glenn Kastenced6e742014-06-09 17:12:32 -0700877 mPreviousFramesWritten = framesWritten;
878 uint32_t position = framesWritten - unpresentedFrames;
879 struct timespec time = playbackThread->mLatchQ.mTimestamp.mTime;
880 if (checkPreviousTimestamp) {
881 if (time.tv_sec < mPreviousTimestamp.mTime.tv_sec ||
882 (time.tv_sec == mPreviousTimestamp.mTime.tv_sec &&
883 time.tv_nsec < mPreviousTimestamp.mTime.tv_nsec)) {
884 ALOGW("Time is going backwards");
885 }
886 // position can bobble slightly as an artifact; this hides the bobble
887 static const uint32_t MINIMUM_POSITION_DELTA = 8u;
888 if ((position <= mPreviousTimestamp.mPosition) ||
889 (position - mPreviousTimestamp.mPosition) < MINIMUM_POSITION_DELTA) {
890 position = mPreviousTimestamp.mPosition;
891 time = mPreviousTimestamp.mTime;
892 }
893 }
894 timestamp.mPosition = position;
895 timestamp.mTime = time;
896 mPreviousTimestamp = timestamp;
897 mPreviousValid = true;
Eric Laurentaccc1472013-09-20 09:36:34 -0700898 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700899 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700900
901 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700902}
903
Eric Laurent81784c32012-11-19 14:55:58 -0800904status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
905{
906 status_t status = DEAD_OBJECT;
907 sp<ThreadBase> thread = mThread.promote();
908 if (thread != 0) {
909 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
910 sp<AudioFlinger> af = mClient->audioFlinger();
911
912 Mutex::Autolock _l(af->mLock);
913
914 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
915
916 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
917 Mutex::Autolock _dl(playbackThread->mLock);
918 Mutex::Autolock _sl(srcThread->mLock);
919 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
920 if (chain == 0) {
921 return INVALID_OPERATION;
922 }
923
924 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
925 if (effect == 0) {
926 return INVALID_OPERATION;
927 }
928 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700929 status = playbackThread->addEffect_l(effect);
930 if (status != NO_ERROR) {
931 srcThread->addEffect_l(effect);
932 return INVALID_OPERATION;
933 }
Eric Laurent81784c32012-11-19 14:55:58 -0800934 // removeEffect_l() has stopped the effect if it was active so it must be restarted
935 if (effect->state() == EffectModule::ACTIVE ||
936 effect->state() == EffectModule::STOPPING) {
937 effect->start();
938 }
939
940 sp<EffectChain> dstChain = effect->chain().promote();
941 if (dstChain == 0) {
942 srcThread->addEffect_l(effect);
943 return INVALID_OPERATION;
944 }
945 AudioSystem::unregisterEffect(effect->id());
946 AudioSystem::registerEffect(&effect->desc(),
947 srcThread->id(),
948 dstChain->strategy(),
949 AUDIO_SESSION_OUTPUT_MIX,
950 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700951 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800952 }
953 status = playbackThread->attachAuxEffect(this, EffectId);
954 }
955 return status;
956}
957
958void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
959{
960 mAuxEffectId = EffectId;
961 mAuxBuffer = buffer;
962}
963
964bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
965 size_t audioHalFrames)
966{
967 // a track is considered presented when the total number of frames written to audio HAL
968 // corresponds to the number of frames written when presentationComplete() is called for the
969 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800970 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
971 // to detect when all frames have been played. In this case framesWritten isn't
972 // useful because it doesn't always reflect whether there is data in the h/w
973 // buffers, particularly if a track has been paused and resumed during draining
974 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
975 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800976 if (mPresentationCompleteFrames == 0) {
977 mPresentationCompleteFrames = framesWritten + audioHalFrames;
978 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
979 mPresentationCompleteFrames, audioHalFrames);
980 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800981
982 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800983 ALOGV("presentationComplete() session %d complete: framesWritten %d",
984 mSessionId, framesWritten);
985 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800986 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800987 return true;
988 }
989 return false;
990}
991
992void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
993{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700994 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -0800995 if (mSyncEvents[i]->type() == type) {
996 mSyncEvents[i]->trigger();
997 mSyncEvents.removeAt(i);
998 i--;
999 }
1000 }
1001}
1002
1003// implement VolumeBufferProvider interface
1004
Glenn Kastenc56f3422014-03-21 17:53:17 -07001005gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001006{
1007 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1008 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001009 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1010 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1011 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001012 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001013 if (vl > GAIN_FLOAT_UNITY) {
1014 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001015 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001016 if (vr > GAIN_FLOAT_UNITY) {
1017 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001018 }
1019 // now apply the cached master volume and stream type volume;
1020 // this is trusted but lacks any synchronization or barrier so may be stale
1021 float v = mCachedVolume;
1022 vl *= v;
1023 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001024 // re-combine into packed minifloat
1025 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001026 // FIXME look at mute, pause, and stop flags
1027 return vlr;
1028}
1029
1030status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1031{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001032 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001033 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1034 (mState == STOPPED)))) {
1035 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1036 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1037 event->cancel();
1038 return INVALID_OPERATION;
1039 }
1040 (void) TrackBase::setSyncEvent(event);
1041 return NO_ERROR;
1042}
1043
Glenn Kasten5736c352012-12-04 12:12:34 -08001044void AudioFlinger::PlaybackThread::Track::invalidate()
1045{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001046 // FIXME should use proxy, and needs work
1047 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001048 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001049 android_atomic_release_store(0x40000000, &cblk->mFutex);
1050 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001051 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001052 mIsInvalid = true;
1053}
1054
Eric Laurent59fe0102013-09-27 18:48:26 -07001055void AudioFlinger::PlaybackThread::Track::signal()
1056{
1057 sp<ThreadBase> thread = mThread.promote();
1058 if (thread != 0) {
1059 PlaybackThread *t = (PlaybackThread *)thread.get();
1060 Mutex::Autolock _l(t->mLock);
1061 t->broadcast_l();
1062 }
1063}
1064
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001065//To be called with thread lock held
1066bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1067
1068 if (mState == RESUMING)
1069 return true;
1070 /* Resume is pending if track was stopping before pause was called */
1071 if (mState == STOPPING_1 &&
1072 mResumeToStopping)
1073 return true;
1074
1075 return false;
1076}
1077
1078//To be called with thread lock held
1079void AudioFlinger::PlaybackThread::Track::resumeAck() {
1080
1081
1082 if (mState == RESUMING)
1083 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001084
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001085 // Other possibility of pending resume is stopping_1 state
1086 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001087 // drain being called.
1088 if (mState == STOPPING_1) {
1089 mResumeToStopping = false;
1090 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001091}
Eric Laurent81784c32012-11-19 14:55:58 -08001092// ----------------------------------------------------------------------------
1093
1094sp<AudioFlinger::PlaybackThread::TimedTrack>
1095AudioFlinger::PlaybackThread::TimedTrack::create(
1096 PlaybackThread *thread,
1097 const sp<Client>& client,
1098 audio_stream_type_t streamType,
1099 uint32_t sampleRate,
1100 audio_format_t format,
1101 audio_channel_mask_t channelMask,
1102 size_t frameCount,
1103 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001104 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001105 int uid)
1106{
Eric Laurent81784c32012-11-19 14:55:58 -08001107 if (!client->reserveTimedTrack())
1108 return 0;
1109
1110 return new TimedTrack(
1111 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001112 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001113}
1114
1115AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1116 PlaybackThread *thread,
1117 const sp<Client>& client,
1118 audio_stream_type_t streamType,
1119 uint32_t sampleRate,
1120 audio_format_t format,
1121 audio_channel_mask_t channelMask,
1122 size_t frameCount,
1123 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001124 int sessionId,
1125 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001126 : Track(thread, client, streamType, sampleRate, format, channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001127 frameCount, sharedBuffer, sessionId, uid, IAudioFlinger::TRACK_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001128 mQueueHeadInFlight(false),
1129 mTrimQueueHeadOnRelease(false),
1130 mFramesPendingInQueue(0),
1131 mTimedSilenceBuffer(NULL),
1132 mTimedSilenceBufferSize(0),
1133 mTimedAudioOutputOnTime(false),
1134 mMediaTimeTransformValid(false)
1135{
1136 LocalClock lc;
1137 mLocalTimeFreq = lc.getLocalFreq();
1138
1139 mLocalTimeToSampleTransform.a_zero = 0;
1140 mLocalTimeToSampleTransform.b_zero = 0;
1141 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1142 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1143 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1144 &mLocalTimeToSampleTransform.a_to_b_denom);
1145
1146 mMediaTimeToSampleTransform.a_zero = 0;
1147 mMediaTimeToSampleTransform.b_zero = 0;
1148 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1149 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1150 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1151 &mMediaTimeToSampleTransform.a_to_b_denom);
1152}
1153
1154AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1155 mClient->releaseTimedTrack();
1156 delete [] mTimedSilenceBuffer;
1157}
1158
1159status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1160 size_t size, sp<IMemory>* buffer) {
1161
1162 Mutex::Autolock _l(mTimedBufferQueueLock);
1163
1164 trimTimedBufferQueue_l();
1165
1166 // lazily initialize the shared memory heap for timed buffers
1167 if (mTimedMemoryDealer == NULL) {
1168 const int kTimedBufferHeapSize = 512 << 10;
1169
1170 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1171 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001172 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001173 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001174 }
Eric Laurent81784c32012-11-19 14:55:58 -08001175 }
1176
1177 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001178 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001179 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001180 }
1181
1182 *buffer = newBuffer;
1183 return NO_ERROR;
1184}
1185
1186// caller must hold mTimedBufferQueueLock
1187void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1188 int64_t mediaTimeNow;
1189 {
1190 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1191 if (!mMediaTimeTransformValid)
1192 return;
1193
1194 int64_t targetTimeNow;
1195 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1196 ? mCCHelper.getCommonTime(&targetTimeNow)
1197 : mCCHelper.getLocalTime(&targetTimeNow);
1198
1199 if (OK != res)
1200 return;
1201
1202 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1203 &mediaTimeNow)) {
1204 return;
1205 }
1206 }
1207
1208 size_t trimEnd;
1209 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1210 int64_t bufEnd;
1211
1212 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1213 // We have a next buffer. Just use its PTS as the PTS of the frame
1214 // following the last frame in this buffer. If the stream is sparse
1215 // (ie, there are deliberate gaps left in the stream which should be
1216 // filled with silence by the TimedAudioTrack), then this can result
1217 // in one extra buffer being left un-trimmed when it could have
1218 // been. In general, this is not typical, and we would rather
1219 // optimized away the TS calculation below for the more common case
1220 // where PTSes are contiguous.
1221 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1222 } else {
1223 // We have no next buffer. Compute the PTS of the frame following
1224 // the last frame in this buffer by computing the duration of of
1225 // this frame in media time units and adding it to the PTS of the
1226 // buffer.
1227 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1228 / mFrameSize;
1229
1230 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1231 &bufEnd)) {
1232 ALOGE("Failed to convert frame count of %lld to media time"
1233 " duration" " (scale factor %d/%u) in %s",
1234 frameCount,
1235 mMediaTimeToSampleTransform.a_to_b_numer,
1236 mMediaTimeToSampleTransform.a_to_b_denom,
1237 __PRETTY_FUNCTION__);
1238 break;
1239 }
1240 bufEnd += mTimedBufferQueue[trimEnd].pts();
1241 }
1242
1243 if (bufEnd > mediaTimeNow)
1244 break;
1245
1246 // Is the buffer we want to use in the middle of a mix operation right
1247 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1248 // from the mixer which should be coming back shortly.
1249 if (!trimEnd && mQueueHeadInFlight) {
1250 mTrimQueueHeadOnRelease = true;
1251 }
1252 }
1253
1254 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1255 if (trimStart < trimEnd) {
1256 // Update the bookkeeping for framesReady()
1257 for (size_t i = trimStart; i < trimEnd; ++i) {
1258 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1259 }
1260
1261 // Now actually remove the buffers from the queue.
1262 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1263 }
1264}
1265
1266void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1267 const char* logTag) {
1268 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1269 "%s called (reason \"%s\"), but timed buffer queue has no"
1270 " elements to trim.", __FUNCTION__, logTag);
1271
1272 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1273 mTimedBufferQueue.removeAt(0);
1274}
1275
1276void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1277 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001278 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001279 uint32_t bufBytes = buf.buffer()->size();
1280 uint32_t consumedAlready = buf.position();
1281
1282 ALOG_ASSERT(consumedAlready <= bufBytes,
1283 "Bad bookkeeping while updating frames pending. Timed buffer is"
1284 " only %u bytes long, but claims to have consumed %u"
1285 " bytes. (update reason: \"%s\")",
1286 bufBytes, consumedAlready, logTag);
1287
1288 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1289 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1290 "Bad bookkeeping while updating frames pending. Should have at"
1291 " least %u queued frames, but we think we have only %u. (update"
1292 " reason: \"%s\")",
1293 bufFrames, mFramesPendingInQueue, logTag);
1294
1295 mFramesPendingInQueue -= bufFrames;
1296}
1297
1298status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1299 const sp<IMemory>& buffer, int64_t pts) {
1300
1301 {
1302 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1303 if (!mMediaTimeTransformValid)
1304 return INVALID_OPERATION;
1305 }
1306
1307 Mutex::Autolock _l(mTimedBufferQueueLock);
1308
1309 uint32_t bufFrames = buffer->size() / mFrameSize;
1310 mFramesPendingInQueue += bufFrames;
1311 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1312
1313 return NO_ERROR;
1314}
1315
1316status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1317 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1318
1319 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1320 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1321 target);
1322
1323 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1324 target == TimedAudioTrack::COMMON_TIME)) {
1325 return BAD_VALUE;
1326 }
1327
1328 Mutex::Autolock lock(mMediaTimeTransformLock);
1329 mMediaTimeTransform = xform;
1330 mMediaTimeTransformTarget = target;
1331 mMediaTimeTransformValid = true;
1332
1333 return NO_ERROR;
1334}
1335
1336#define min(a, b) ((a) < (b) ? (a) : (b))
1337
1338// implementation of getNextBuffer for tracks whose buffers have timestamps
1339status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1340 AudioBufferProvider::Buffer* buffer, int64_t pts)
1341{
1342 if (pts == AudioBufferProvider::kInvalidPTS) {
1343 buffer->raw = NULL;
1344 buffer->frameCount = 0;
1345 mTimedAudioOutputOnTime = false;
1346 return INVALID_OPERATION;
1347 }
1348
1349 Mutex::Autolock _l(mTimedBufferQueueLock);
1350
1351 ALOG_ASSERT(!mQueueHeadInFlight,
1352 "getNextBuffer called without releaseBuffer!");
1353
1354 while (true) {
1355
1356 // if we have no timed buffers, then fail
1357 if (mTimedBufferQueue.isEmpty()) {
1358 buffer->raw = NULL;
1359 buffer->frameCount = 0;
1360 return NOT_ENOUGH_DATA;
1361 }
1362
1363 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1364
1365 // calculate the PTS of the head of the timed buffer queue expressed in
1366 // local time
1367 int64_t headLocalPTS;
1368 {
1369 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1370
1371 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1372
1373 if (mMediaTimeTransform.a_to_b_denom == 0) {
1374 // the transform represents a pause, so yield silence
1375 timedYieldSilence_l(buffer->frameCount, buffer);
1376 return NO_ERROR;
1377 }
1378
1379 int64_t transformedPTS;
1380 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1381 &transformedPTS)) {
1382 // the transform failed. this shouldn't happen, but if it does
1383 // then just drop this buffer
1384 ALOGW("timedGetNextBuffer transform failed");
1385 buffer->raw = NULL;
1386 buffer->frameCount = 0;
1387 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1388 return NO_ERROR;
1389 }
1390
1391 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1392 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1393 &headLocalPTS)) {
1394 buffer->raw = NULL;
1395 buffer->frameCount = 0;
1396 return INVALID_OPERATION;
1397 }
1398 } else {
1399 headLocalPTS = transformedPTS;
1400 }
1401 }
1402
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001403 uint32_t sr = sampleRate();
1404
Eric Laurent81784c32012-11-19 14:55:58 -08001405 // adjust the head buffer's PTS to reflect the portion of the head buffer
1406 // that has already been consumed
1407 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001408 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001409
1410 // Calculate the delta in samples between the head of the input buffer
1411 // queue and the start of the next output buffer that will be written.
1412 // If the transformation fails because of over or underflow, it means
1413 // that the sample's position in the output stream is so far out of
1414 // whack that it should just be dropped.
1415 int64_t sampleDelta;
1416 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1417 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1418 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1419 " mix");
1420 continue;
1421 }
1422 if (!mLocalTimeToSampleTransform.doForwardTransform(
1423 (effectivePTS - pts) << 32, &sampleDelta)) {
1424 ALOGV("*** too late during sample rate transform: dropped buffer");
1425 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1426 continue;
1427 }
1428
1429 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1430 " sampleDelta=[%d.%08x]",
1431 head.pts(), head.position(), pts,
1432 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1433 + (sampleDelta >> 32)),
1434 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1435
1436 // if the delta between the ideal placement for the next input sample and
1437 // the current output position is within this threshold, then we will
1438 // concatenate the next input samples to the previous output
1439 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001440 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001441
1442 // if this is the first buffer of audio that we're emitting from this track
1443 // then it should be almost exactly on time.
1444 const int64_t kSampleStartupThreshold = 1LL << 32;
1445
1446 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1447 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1448 // the next input is close enough to being on time, so concatenate it
1449 // with the last output
1450 timedYieldSamples_l(buffer);
1451
1452 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1453 head.position(), buffer->frameCount);
1454 return NO_ERROR;
1455 }
1456
1457 // Looks like our output is not on time. Reset our on timed status.
1458 // Next time we mix samples from our input queue, then should be within
1459 // the StartupThreshold.
1460 mTimedAudioOutputOnTime = false;
1461 if (sampleDelta > 0) {
1462 // the gap between the current output position and the proper start of
1463 // the next input sample is too big, so fill it with silence
1464 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1465
1466 timedYieldSilence_l(framesUntilNextInput, buffer);
1467 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1468 return NO_ERROR;
1469 } else {
1470 // the next input sample is late
1471 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1472 size_t onTimeSamplePosition =
1473 head.position() + lateFrames * mFrameSize;
1474
1475 if (onTimeSamplePosition > head.buffer()->size()) {
1476 // all the remaining samples in the head are too late, so
1477 // drop it and move on
1478 ALOGV("*** too late: dropped buffer");
1479 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1480 continue;
1481 } else {
1482 // skip over the late samples
1483 head.setPosition(onTimeSamplePosition);
1484
1485 // yield the available samples
1486 timedYieldSamples_l(buffer);
1487
1488 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1489 return NO_ERROR;
1490 }
1491 }
1492 }
1493}
1494
1495// Yield samples from the timed buffer queue head up to the given output
1496// buffer's capacity.
1497//
1498// Caller must hold mTimedBufferQueueLock
1499void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1500 AudioBufferProvider::Buffer* buffer) {
1501
1502 const TimedBuffer& head = mTimedBufferQueue[0];
1503
1504 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1505 head.position());
1506
1507 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1508 mFrameSize);
1509 size_t framesRequested = buffer->frameCount;
1510 buffer->frameCount = min(framesLeftInHead, framesRequested);
1511
1512 mQueueHeadInFlight = true;
1513 mTimedAudioOutputOnTime = true;
1514}
1515
1516// Yield samples of silence up to the given output buffer's capacity
1517//
1518// Caller must hold mTimedBufferQueueLock
1519void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1520 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1521
1522 // lazily allocate a buffer filled with silence
1523 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1524 delete [] mTimedSilenceBuffer;
1525 mTimedSilenceBufferSize = numFrames * mFrameSize;
1526 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1527 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1528 }
1529
1530 buffer->raw = mTimedSilenceBuffer;
1531 size_t framesRequested = buffer->frameCount;
1532 buffer->frameCount = min(numFrames, framesRequested);
1533
1534 mTimedAudioOutputOnTime = false;
1535}
1536
1537// AudioBufferProvider interface
1538void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1539 AudioBufferProvider::Buffer* buffer) {
1540
1541 Mutex::Autolock _l(mTimedBufferQueueLock);
1542
1543 // If the buffer which was just released is part of the buffer at the head
1544 // of the queue, be sure to update the amt of the buffer which has been
1545 // consumed. If the buffer being returned is not part of the head of the
1546 // queue, its either because the buffer is part of the silence buffer, or
1547 // because the head of the timed queue was trimmed after the mixer called
1548 // getNextBuffer but before the mixer called releaseBuffer.
1549 if (buffer->raw == mTimedSilenceBuffer) {
1550 ALOG_ASSERT(!mQueueHeadInFlight,
1551 "Queue head in flight during release of silence buffer!");
1552 goto done;
1553 }
1554
1555 ALOG_ASSERT(mQueueHeadInFlight,
1556 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1557 " head in flight.");
1558
1559 if (mTimedBufferQueue.size()) {
1560 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1561
1562 void* start = head.buffer()->pointer();
1563 void* end = reinterpret_cast<void*>(
1564 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1565 + head.buffer()->size());
1566
1567 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1568 "released buffer not within the head of the timed buffer"
1569 " queue; qHead = [%p, %p], released buffer = %p",
1570 start, end, buffer->raw);
1571
1572 head.setPosition(head.position() +
1573 (buffer->frameCount * mFrameSize));
1574 mQueueHeadInFlight = false;
1575
1576 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1577 "Bad bookkeeping during releaseBuffer! Should have at"
1578 " least %u queued frames, but we think we have only %u",
1579 buffer->frameCount, mFramesPendingInQueue);
1580
1581 mFramesPendingInQueue -= buffer->frameCount;
1582
1583 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1584 || mTrimQueueHeadOnRelease) {
1585 trimTimedBufferQueueHead_l("releaseBuffer");
1586 mTrimQueueHeadOnRelease = false;
1587 }
1588 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001589 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001590 " buffers in the timed buffer queue");
1591 }
1592
1593done:
1594 buffer->raw = 0;
1595 buffer->frameCount = 0;
1596}
1597
1598size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1599 Mutex::Autolock _l(mTimedBufferQueueLock);
1600 return mFramesPendingInQueue;
1601}
1602
1603AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1604 : mPTS(0), mPosition(0) {}
1605
1606AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1607 const sp<IMemory>& buffer, int64_t pts)
1608 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1609
1610
1611// ----------------------------------------------------------------------------
1612
1613AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1614 PlaybackThread *playbackThread,
1615 DuplicatingThread *sourceThread,
1616 uint32_t sampleRate,
1617 audio_format_t format,
1618 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001619 size_t frameCount,
1620 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001621 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001622 NULL, 0, uid, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001623 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001624{
1625
1626 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001627 mOutBuffer.frameCount = 0;
1628 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001629 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001630 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001631 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001632 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001633 // since client and server are in the same process,
1634 // the buffer has the same virtual address on both sides
1635 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001636 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001637 mClientProxy->setSendLevel(0.0);
1638 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001639 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1640 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001641 } else {
1642 ALOGW("Error creating output track on thread %p", playbackThread);
1643 }
1644}
1645
1646AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1647{
1648 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001649 delete mClientProxy;
1650 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001651}
1652
1653status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1654 int triggerSession)
1655{
1656 status_t status = Track::start(event, triggerSession);
1657 if (status != NO_ERROR) {
1658 return status;
1659 }
1660
1661 mActive = true;
1662 mRetryCount = 127;
1663 return status;
1664}
1665
1666void AudioFlinger::PlaybackThread::OutputTrack::stop()
1667{
1668 Track::stop();
1669 clearBufferQueue();
1670 mOutBuffer.frameCount = 0;
1671 mActive = false;
1672}
1673
1674bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1675{
1676 Buffer *pInBuffer;
1677 Buffer inBuffer;
1678 uint32_t channelCount = mChannelCount;
1679 bool outputBufferFull = false;
1680 inBuffer.frameCount = frames;
1681 inBuffer.i16 = data;
1682
1683 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1684
1685 if (!mActive && frames != 0) {
1686 start();
1687 sp<ThreadBase> thread = mThread.promote();
1688 if (thread != 0) {
1689 MixerThread *mixerThread = (MixerThread *)thread.get();
1690 if (mFrameCount > frames) {
1691 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1692 uint32_t startFrames = (mFrameCount - frames);
1693 pInBuffer = new Buffer;
1694 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1695 pInBuffer->frameCount = startFrames;
1696 pInBuffer->i16 = pInBuffer->mBuffer;
1697 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1698 mBufferQueue.add(pInBuffer);
1699 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001700 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001701 }
1702 }
1703 }
1704 }
1705
1706 while (waitTimeLeftMs) {
1707 // First write pending buffers, then new data
1708 if (mBufferQueue.size()) {
1709 pInBuffer = mBufferQueue.itemAt(0);
1710 } else {
1711 pInBuffer = &inBuffer;
1712 }
1713
1714 if (pInBuffer->frameCount == 0) {
1715 break;
1716 }
1717
1718 if (mOutBuffer.frameCount == 0) {
1719 mOutBuffer.frameCount = pInBuffer->frameCount;
1720 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001721 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1722 if (status != NO_ERROR) {
1723 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1724 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001725 outputBufferFull = true;
1726 break;
1727 }
1728 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1729 if (waitTimeLeftMs >= waitTimeMs) {
1730 waitTimeLeftMs -= waitTimeMs;
1731 } else {
1732 waitTimeLeftMs = 0;
1733 }
1734 }
1735
1736 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1737 pInBuffer->frameCount;
1738 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001739 Proxy::Buffer buf;
1740 buf.mFrameCount = outFrames;
1741 buf.mRaw = NULL;
1742 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001743 pInBuffer->frameCount -= outFrames;
1744 pInBuffer->i16 += outFrames * channelCount;
1745 mOutBuffer.frameCount -= outFrames;
1746 mOutBuffer.i16 += outFrames * channelCount;
1747
1748 if (pInBuffer->frameCount == 0) {
1749 if (mBufferQueue.size()) {
1750 mBufferQueue.removeAt(0);
1751 delete [] pInBuffer->mBuffer;
1752 delete pInBuffer;
1753 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1754 mThread.unsafe_get(), mBufferQueue.size());
1755 } else {
1756 break;
1757 }
1758 }
1759 }
1760
1761 // If we could not write all frames, allocate a buffer and queue it for next time.
1762 if (inBuffer.frameCount) {
1763 sp<ThreadBase> thread = mThread.promote();
1764 if (thread != 0 && !thread->standby()) {
1765 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1766 pInBuffer = new Buffer;
1767 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1768 pInBuffer->frameCount = inBuffer.frameCount;
1769 pInBuffer->i16 = pInBuffer->mBuffer;
1770 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1771 sizeof(int16_t));
1772 mBufferQueue.add(pInBuffer);
1773 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1774 mThread.unsafe_get(), mBufferQueue.size());
1775 } else {
1776 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1777 mThread.unsafe_get(), this);
1778 }
1779 }
1780 }
1781
1782 // Calling write() with a 0 length buffer, means that no more data will be written:
1783 // If no more buffers are pending, fill output track buffer to make sure it is started
1784 // by output mixer.
1785 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001786 // FIXME borken, replace by getting framesReady() from proxy
1787 size_t user = 0; // was mCblk->user
1788 if (user < mFrameCount) {
1789 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001790 pInBuffer = new Buffer;
1791 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1792 pInBuffer->frameCount = frames;
1793 pInBuffer->i16 = pInBuffer->mBuffer;
1794 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1795 mBufferQueue.add(pInBuffer);
1796 } else if (mActive) {
1797 stop();
1798 }
1799 }
1800
1801 return outputBufferFull;
1802}
1803
1804status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1805 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1806{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001807 ClientProxy::Buffer buf;
1808 buf.mFrameCount = buffer->frameCount;
1809 struct timespec timeout;
1810 timeout.tv_sec = waitTimeMs / 1000;
1811 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1812 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1813 buffer->frameCount = buf.mFrameCount;
1814 buffer->raw = buf.mRaw;
1815 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001816}
1817
Eric Laurent81784c32012-11-19 14:55:58 -08001818void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1819{
1820 size_t size = mBufferQueue.size();
1821
1822 for (size_t i = 0; i < size; i++) {
1823 Buffer *pBuffer = mBufferQueue.itemAt(i);
1824 delete [] pBuffer->mBuffer;
1825 delete pBuffer;
1826 }
1827 mBufferQueue.clear();
1828}
1829
1830
1831// ----------------------------------------------------------------------------
1832// Record
1833// ----------------------------------------------------------------------------
1834
1835AudioFlinger::RecordHandle::RecordHandle(
1836 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1837 : BnAudioRecord(),
1838 mRecordTrack(recordTrack)
1839{
1840}
1841
1842AudioFlinger::RecordHandle::~RecordHandle() {
1843 stop_nonvirtual();
1844 mRecordTrack->destroy();
1845}
1846
Eric Laurent81784c32012-11-19 14:55:58 -08001847status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1848 int triggerSession) {
1849 ALOGV("RecordHandle::start()");
1850 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1851}
1852
1853void AudioFlinger::RecordHandle::stop() {
1854 stop_nonvirtual();
1855}
1856
1857void AudioFlinger::RecordHandle::stop_nonvirtual() {
1858 ALOGV("RecordHandle::stop()");
1859 mRecordTrack->stop();
1860}
1861
1862status_t AudioFlinger::RecordHandle::onTransact(
1863 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1864{
1865 return BnAudioRecord::onTransact(code, data, reply, flags);
1866}
1867
1868// ----------------------------------------------------------------------------
1869
Glenn Kasten05997e22014-03-13 15:08:33 -07001870// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001871AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1872 RecordThread *thread,
1873 const sp<Client>& client,
1874 uint32_t sampleRate,
1875 audio_format_t format,
1876 audio_channel_mask_t channelMask,
1877 size_t frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001878 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001879 int uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001880 IAudioFlinger::track_flags_t flags)
Eric Laurent81784c32012-11-19 14:55:58 -08001881 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001882 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, uid,
1883 flags, false /*isOut*/,
Glenn Kastenc263ca02014-06-04 20:31:46 -07001884 flags & IAudioFlinger::TRACK_FAST ? ALLOC_PIPE : ALLOC_CBLK),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001885 mOverflow(false), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0),
1886 // See real initialization of mRsmpInFront at RecordThread::start()
1887 mRsmpInUnrel(0), mRsmpInFront(0), mFramesToDrop(0), mResamplerBufferProvider(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001888{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001889 if (mCblk == NULL) {
1890 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001891 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001892
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001893 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount, mFrameSize);
1894
Andy Hunge5412692014-05-16 11:25:07 -07001895 uint32_t channelCount = audio_channel_count_from_in_mask(channelMask);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001896 // FIXME I don't understand either of the channel count checks
1897 if (thread->mSampleRate != sampleRate && thread->mChannelCount <= FCC_2 &&
1898 channelCount <= FCC_2) {
1899 // sink SR
1900 mResampler = AudioResampler::create(16, thread->mChannelCount, sampleRate);
1901 // source SR
1902 mResampler->setSampleRate(thread->mSampleRate);
Glenn Kastenc263ca02014-06-04 20:31:46 -07001903 mResampler->setVolume(AudioMixer::UNITY_GAIN_INT, AudioMixer::UNITY_GAIN_INT);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001904 mResamplerBufferProvider = new ResamplerBufferProvider(this);
1905 }
Glenn Kastenc263ca02014-06-04 20:31:46 -07001906
1907 if (flags & IAudioFlinger::TRACK_FAST) {
1908 ALOG_ASSERT(thread->mFastTrackAvail);
1909 thread->mFastTrackAvail = false;
1910 }
Eric Laurent81784c32012-11-19 14:55:58 -08001911}
1912
1913AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1914{
1915 ALOGV("%s", __func__);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001916 delete mResampler;
1917 delete[] mRsmpOutBuffer;
1918 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001919}
1920
1921// AudioBufferProvider interface
1922status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001923 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001924{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001925 ServerProxy::Buffer buf;
1926 buf.mFrameCount = buffer->frameCount;
1927 status_t status = mServerProxy->obtainBuffer(&buf);
1928 buffer->frameCount = buf.mFrameCount;
1929 buffer->raw = buf.mRaw;
1930 if (buf.mFrameCount == 0) {
1931 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001932 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001933 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001934 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001935}
1936
1937status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1938 int triggerSession)
1939{
1940 sp<ThreadBase> thread = mThread.promote();
1941 if (thread != 0) {
1942 RecordThread *recordThread = (RecordThread *)thread.get();
1943 return recordThread->start(this, event, triggerSession);
1944 } else {
1945 return BAD_VALUE;
1946 }
1947}
1948
1949void AudioFlinger::RecordThread::RecordTrack::stop()
1950{
1951 sp<ThreadBase> thread = mThread.promote();
1952 if (thread != 0) {
1953 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001954 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001955 AudioSystem::stopInput(recordThread->id());
1956 }
1957 }
1958}
1959
1960void AudioFlinger::RecordThread::RecordTrack::destroy()
1961{
1962 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1963 sp<RecordTrack> keep(this);
1964 {
1965 sp<ThreadBase> thread = mThread.promote();
1966 if (thread != 0) {
1967 if (mState == ACTIVE || mState == RESUMING) {
1968 AudioSystem::stopInput(thread->id());
1969 }
1970 AudioSystem::releaseInput(thread->id());
1971 Mutex::Autolock _l(thread->mLock);
1972 RecordThread *recordThread = (RecordThread *) thread.get();
1973 recordThread->destroyTrack_l(this);
1974 }
1975 }
1976}
1977
Eric Laurent9a54bc22013-09-09 09:08:44 -07001978void AudioFlinger::RecordThread::RecordTrack::invalidate()
1979{
1980 // FIXME should use proxy, and needs work
1981 audio_track_cblk_t* cblk = mCblk;
1982 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1983 android_atomic_release_store(0x40000000, &cblk->mFutex);
1984 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001985 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07001986}
1987
Eric Laurent81784c32012-11-19 14:55:58 -08001988
1989/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1990{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001991 result.append(" Active Client Fmt Chn mask Session S Server fCount Resampling\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001992}
1993
Marco Nelissenb2208842014-02-07 14:00:50 -08001994void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08001995{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001996 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %10d\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08001997 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08001998 (mClient == 0) ? getpid_cached : mClient->pid(),
1999 mFormat,
2000 mChannelMask,
2001 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08002002 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002003 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002004 mFrameCount,
2005 mResampler != NULL);
2006
Eric Laurent81784c32012-11-19 14:55:58 -08002007}
2008
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002009void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2010{
2011 if (event == mSyncStartEvent) {
2012 ssize_t framesToDrop = 0;
2013 sp<ThreadBase> threadBase = mThread.promote();
2014 if (threadBase != 0) {
2015 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2016 // from audio HAL
2017 framesToDrop = threadBase->mFrameCount * 2;
2018 }
2019 mFramesToDrop = framesToDrop;
2020 }
2021}
2022
2023void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2024{
2025 if (mSyncStartEvent != 0) {
2026 mSyncStartEvent->cancel();
2027 mSyncStartEvent.clear();
2028 }
2029 mFramesToDrop = 0;
2030}
2031
Eric Laurent81784c32012-11-19 14:55:58 -08002032}; // namespace android