blob: da2d634ecd44ff7589128e6985510ae41b8fb866 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenad8510a2015-02-17 16:24:07 -080023#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070025#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080026#include <utils/Log.h>
27
28#include <private/media/AudioTrackShared.h>
29
30#include <common_time/cc_helper.h>
31#include <common_time/local_clock.h>
32
33#include "AudioMixer.h"
34#include "AudioFlinger.h"
35#include "ServiceUtilities.h"
36
Glenn Kastenda6ef132013-01-10 12:31:01 -080037#include <media/nbaio/Pipe.h>
38#include <media/nbaio/PipeReader.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070039#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080040
Eric Laurent81784c32012-11-19 14:55:58 -080041// ----------------------------------------------------------------------------
42
43// Note: the following macro is used for extremely verbose logging message. In
44// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
45// 0; but one side effect of this is to turn all LOGV's as well. Some messages
46// are so verbose that we want to suppress them even when we have ALOG_ASSERT
47// turned on. Do not uncomment the #def below unless you really know what you
48// are doing and want to see all of the extremely verbose messages.
49//#define VERY_VERY_VERBOSE_LOGGING
50#ifdef VERY_VERY_VERBOSE_LOGGING
51#define ALOGVV ALOGV
52#else
53#define ALOGVV(a...) do { } while(0)
54#endif
55
56namespace android {
57
58// ----------------------------------------------------------------------------
59// TrackBase
60// ----------------------------------------------------------------------------
61
Glenn Kastenda6ef132013-01-10 12:31:01 -080062static volatile int32_t nextTrackId = 55;
63
Eric Laurent81784c32012-11-19 14:55:58 -080064// TrackBase constructor must be called with AudioFlinger::mLock held
65AudioFlinger::ThreadBase::TrackBase::TrackBase(
66 ThreadBase *thread,
67 const sp<Client>& client,
68 uint32_t sampleRate,
69 audio_format_t format,
70 audio_channel_mask_t channelMask,
71 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070072 void *buffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080073 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080074 int clientUid,
Glenn Kasten755b0a62014-05-13 11:30:28 -070075 IAudioFlinger::track_flags_t flags,
Glenn Kastend776ac62014-05-07 09:16:09 -070076 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070077 alloc_type alloc,
78 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -080079 : RefBase(),
80 mThread(thread),
81 mClient(client),
82 mCblk(NULL),
83 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080084 mState(IDLE),
85 mSampleRate(sampleRate),
86 mFormat(format),
87 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070088 mChannelCount(isOut ?
89 audio_channel_count_from_out_mask(channelMask) :
90 audio_channel_count_from_in_mask(channelMask)),
Eric Laurent81784c32012-11-19 14:55:58 -080091 mFrameSize(audio_is_linear_pcm(format) ?
92 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
93 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080094 mSessionId(sessionId),
Glenn Kasten755b0a62014-05-13 11:30:28 -070095 mFlags(flags),
Glenn Kastene3aa6592012-12-04 12:22:46 -080096 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080097 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080098 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070099 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -0700100 mType(type),
101 mThreadIoHandle(thread->id())
Eric Laurent81784c32012-11-19 14:55:58 -0800102{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800103 // if the caller is us, trust the specified uid
104 if (IPCThreadState::self()->getCallingPid() != getpid_cached || clientUid == -1) {
105 int newclientUid = IPCThreadState::self()->getCallingUid();
106 if (clientUid != -1 && clientUid != newclientUid) {
107 ALOGW("uid %d tried to pass itself off as %d", newclientUid, clientUid);
108 }
109 clientUid = newclientUid;
110 }
111 // clientUid contains the uid of the app that is responsible for this track, so we can blame
112 // battery usage on it.
113 mUid = clientUid;
114
Eric Laurent81784c32012-11-19 14:55:58 -0800115 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
116 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700117 size_t bufferSize = (buffer == NULL ? roundup(frameCount) : frameCount) * mFrameSize;
118 if (buffer == NULL && alloc == ALLOC_CBLK) {
Eric Laurent81784c32012-11-19 14:55:58 -0800119 size += bufferSize;
120 }
121
122 if (client != 0) {
123 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700124 if (mCblkMemory == 0 ||
125 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800126 ALOGE("not enough memory for AudioTrack size=%u", size);
127 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700128 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800129 return;
130 }
131 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800132 // this syntax avoids calling the audio_track_cblk_t constructor twice
133 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800134 // assume mCblk != NULL
135 }
136
137 // construct the shared structure in-place.
138 if (mCblk != NULL) {
139 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700140 switch (alloc) {
141 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700142 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
143 if (roHeap == 0 ||
144 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
145 (mBuffer = mBufferMemory->pointer()) == NULL) {
146 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
147 if (roHeap != 0) {
148 roHeap->dump("buffer");
149 }
150 mCblkMemory.clear();
151 mBufferMemory.clear();
152 return;
153 }
Eric Laurent81784c32012-11-19 14:55:58 -0800154 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700155 } break;
156 case ALLOC_PIPE:
157 mBufferMemory = thread->pipeMemory();
158 // mBuffer is the virtual address as seen from current process (mediaserver),
159 // and should normally be coming from mBufferMemory->pointer().
160 // However in this case the TrackBase does not reference the buffer directly.
161 // It should references the buffer via the pipe.
162 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
163 mBuffer = NULL;
164 break;
165 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700166 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700167 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700168 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
169 memset(mBuffer, 0, bufferSize);
170 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700171 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800172#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700173 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800174#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700175 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700176 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700177 case ALLOC_LOCAL:
178 mBuffer = calloc(1, bufferSize);
179 break;
180 case ALLOC_NONE:
181 mBuffer = buffer;
182 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800183 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800184
Glenn Kasten46909e72013-02-26 09:20:22 -0800185#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800186 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700187 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800188 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800189 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
190 size_t numCounterOffers = 0;
191 const NBAIO_Format offers[1] = {pipeFormat};
192 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
193 ALOG_ASSERT(index == 0);
194 PipeReader *pipeReader = new PipeReader(*pipe);
195 numCounterOffers = 0;
196 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
197 ALOG_ASSERT(index == 0);
198 mTeeSink = pipe;
199 mTeeSource = pipeReader;
200 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800201 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800202#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800203
Eric Laurent81784c32012-11-19 14:55:58 -0800204 }
205}
206
Eric Laurent83b88082014-06-20 18:31:16 -0700207status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
208{
209 status_t status;
210 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
211 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
212 } else {
213 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
214 }
215 return status;
216}
217
Eric Laurent81784c32012-11-19 14:55:58 -0800218AudioFlinger::ThreadBase::TrackBase::~TrackBase()
219{
Glenn Kasten46909e72013-02-26 09:20:22 -0800220#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800221 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800222#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800223 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
224 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800225 if (mCblk != NULL) {
226 if (mClient == 0) {
227 delete mCblk;
228 } else {
229 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
230 }
231 }
232 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
233 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700234 // Client destructor must run with AudioFlinger client mutex locked
235 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800236 // If the client's reference count drops to zero, the associated destructor
237 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
238 // relying on the automatic clear() at end of scope.
239 mClient.clear();
240 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700241 // flush the binder command buffer
242 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800243}
244
245// AudioBufferProvider interface
246// getNextBuffer() = 0;
247// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
248void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
249{
Glenn Kasten46909e72013-02-26 09:20:22 -0800250#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800251 if (mTeeSink != 0) {
252 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
253 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800254#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800255
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800256 ServerProxy::Buffer buf;
257 buf.mFrameCount = buffer->frameCount;
258 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800259 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800260 buffer->raw = NULL;
261 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800262}
263
Eric Laurent81784c32012-11-19 14:55:58 -0800264status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
265{
266 mSyncEvents.add(event);
267 return NO_ERROR;
268}
269
270// ----------------------------------------------------------------------------
271// Playback
272// ----------------------------------------------------------------------------
273
274AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
275 : BnAudioTrack(),
276 mTrack(track)
277{
278}
279
280AudioFlinger::TrackHandle::~TrackHandle() {
281 // just stop the track on deletion, associated resources
282 // will be freed from the main thread once all pending buffers have
283 // been played. Unless it's not in the active track list, in which
284 // case we free everything now...
285 mTrack->destroy();
286}
287
288sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
289 return mTrack->getCblk();
290}
291
292status_t AudioFlinger::TrackHandle::start() {
293 return mTrack->start();
294}
295
296void AudioFlinger::TrackHandle::stop() {
297 mTrack->stop();
298}
299
300void AudioFlinger::TrackHandle::flush() {
301 mTrack->flush();
302}
303
Eric Laurent81784c32012-11-19 14:55:58 -0800304void AudioFlinger::TrackHandle::pause() {
305 mTrack->pause();
306}
307
308status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
309{
310 return mTrack->attachAuxEffect(EffectId);
311}
312
313status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
314 sp<IMemory>* buffer) {
315 if (!mTrack->isTimedTrack())
316 return INVALID_OPERATION;
317
318 PlaybackThread::TimedTrack* tt =
319 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
320 return tt->allocateTimedBuffer(size, buffer);
321}
322
323status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
324 int64_t pts) {
325 if (!mTrack->isTimedTrack())
326 return INVALID_OPERATION;
327
Glenn Kasten663c2242013-09-24 11:52:37 -0700328 if (buffer == 0 || buffer->pointer() == NULL) {
329 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
330 return BAD_VALUE;
331 }
332
Eric Laurent81784c32012-11-19 14:55:58 -0800333 PlaybackThread::TimedTrack* tt =
334 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
335 return tt->queueTimedBuffer(buffer, pts);
336}
337
338status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
339 const LinearTransform& xform, int target) {
340
341 if (!mTrack->isTimedTrack())
342 return INVALID_OPERATION;
343
344 PlaybackThread::TimedTrack* tt =
345 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
346 return tt->setMediaTimeTransform(
347 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
348}
349
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700350status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
351 return mTrack->setParameters(keyValuePairs);
352}
353
Glenn Kasten53cec222013-08-29 09:01:02 -0700354status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
355{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700356 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700357}
358
Eric Laurent59fe0102013-09-27 18:48:26 -0700359
360void AudioFlinger::TrackHandle::signal()
361{
362 return mTrack->signal();
363}
364
Eric Laurent81784c32012-11-19 14:55:58 -0800365status_t AudioFlinger::TrackHandle::onTransact(
366 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
367{
368 return BnAudioTrack::onTransact(code, data, reply, flags);
369}
370
371// ----------------------------------------------------------------------------
372
373// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
374AudioFlinger::PlaybackThread::Track::Track(
375 PlaybackThread *thread,
376 const sp<Client>& client,
377 audio_stream_type_t streamType,
378 uint32_t sampleRate,
379 audio_format_t format,
380 audio_channel_mask_t channelMask,
381 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700382 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800383 const sp<IMemory>& sharedBuffer,
384 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800385 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -0700386 IAudioFlinger::track_flags_t flags,
387 track_type type)
388 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
389 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
390 sessionId, uid, flags, true /*isOut*/,
391 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
392 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800393 mFillingUpStatus(FS_INVALID),
394 // mRetryCount initialized later when needed
395 mSharedBuffer(sharedBuffer),
396 mStreamType(streamType),
397 mName(-1), // see note below
398 mMainBuffer(thread->mixBuffer()),
399 mAuxBuffer(NULL),
400 mAuxEffectId(0), mHasVolumeController(false),
401 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800402 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800403 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800404 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800405 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800406 mResumeToStopping(false),
Glenn Kastenced6e742014-06-09 17:12:32 -0700407 mFlushHwPending(false),
Phil Burk6140c792015-03-19 14:30:21 -0700408 mPreviousTimestampValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800409{
Eric Laurent83b88082014-06-20 18:31:16 -0700410 // client == 0 implies sharedBuffer == 0
411 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
412
413 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
414 sharedBuffer->size());
415
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700416 if (mCblk == NULL) {
417 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800418 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700419
420 if (sharedBuffer == 0) {
421 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700422 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700423 } else {
424 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
425 mFrameSize);
426 }
427 mServerProxy = mAudioTrackServerProxy;
428
Glenn Kastenc263ca02014-06-04 20:31:46 -0700429 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700430 if (mName < 0) {
431 ALOGE("no more track names available");
432 return;
433 }
434 // only allocate a fast track index if we were able to allocate a normal track name
435 if (flags & IAudioFlinger::TRACK_FAST) {
436 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
437 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
438 int i = __builtin_ctz(thread->mFastTrackAvailMask);
439 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
440 // FIXME This is too eager. We allocate a fast track index before the
441 // fast track becomes active. Since fast tracks are a scarce resource,
442 // this means we are potentially denying other more important fast tracks from
443 // being created. It would be better to allocate the index dynamically.
444 mFastIndex = i;
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700445 thread->mFastTrackAvailMask &= ~(1 << i);
446 }
Eric Laurent81784c32012-11-19 14:55:58 -0800447}
448
449AudioFlinger::PlaybackThread::Track::~Track()
450{
451 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700452
453 // The destructor would clear mSharedBuffer,
454 // but it will not push the decremented reference count,
455 // leaving the client's IMemory dangling indefinitely.
456 // This prevents that leak.
457 if (mSharedBuffer != 0) {
458 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700459 }
Eric Laurent81784c32012-11-19 14:55:58 -0800460}
461
Glenn Kasten03003332013-08-06 15:40:54 -0700462status_t AudioFlinger::PlaybackThread::Track::initCheck() const
463{
464 status_t status = TrackBase::initCheck();
465 if (status == NO_ERROR && mName < 0) {
466 status = NO_MEMORY;
467 }
468 return status;
469}
470
Eric Laurent81784c32012-11-19 14:55:58 -0800471void AudioFlinger::PlaybackThread::Track::destroy()
472{
473 // NOTE: destroyTrack_l() can remove a strong reference to this Track
474 // by removing it from mTracks vector, so there is a risk that this Tracks's
475 // destructor is called. As the destructor needs to lock mLock,
476 // we must acquire a strong reference on this Track before locking mLock
477 // here so that the destructor is called only when exiting this function.
478 // On the other hand, as long as Track::destroy() is only called by
479 // TrackHandle destructor, the TrackHandle still holds a strong ref on
480 // this Track with its member mTrack.
481 sp<Track> keep(this);
482 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700483 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800484 sp<ThreadBase> thread = mThread.promote();
485 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800486 Mutex::Autolock _l(thread->mLock);
487 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700488 wasActive = playbackThread->destroyTrack_l(this);
489 }
490 if (isExternalTrack() && !wasActive) {
Eric Laurente83b55d2014-11-14 10:06:21 -0800491 AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800492 }
493 }
494}
495
496/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
497{
Marco Nelissenb2208842014-02-07 14:00:50 -0800498 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700499 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800500}
501
Marco Nelissenb2208842014-02-07 14:00:50 -0800502void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800503{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700504 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800505 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800506 sprintf(buffer, " F %2d", mFastIndex);
507 } else if (mName >= AudioMixer::TRACK0) {
508 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800509 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800510 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800511 }
512 track_state state = mState;
513 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800514 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800515 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800516 } else {
517 switch (state) {
518 case IDLE:
519 stateChar = 'I';
520 break;
521 case STOPPING_1:
522 stateChar = 's';
523 break;
524 case STOPPING_2:
525 stateChar = '5';
526 break;
527 case STOPPED:
528 stateChar = 'S';
529 break;
530 case RESUMING:
531 stateChar = 'R';
532 break;
533 case ACTIVE:
534 stateChar = 'A';
535 break;
536 case PAUSING:
537 stateChar = 'p';
538 break;
539 case PAUSED:
540 stateChar = 'P';
541 break;
542 case FLUSHED:
543 stateChar = 'F';
544 break;
545 default:
546 stateChar = '?';
547 break;
548 }
Eric Laurent81784c32012-11-19 14:55:58 -0800549 }
550 char nowInUnderrun;
551 switch (mObservedUnderruns.mBitFields.mMostRecent) {
552 case UNDERRUN_FULL:
553 nowInUnderrun = ' ';
554 break;
555 case UNDERRUN_PARTIAL:
556 nowInUnderrun = '<';
557 break;
558 case UNDERRUN_EMPTY:
559 nowInUnderrun = '*';
560 break;
561 default:
562 nowInUnderrun = '?';
563 break;
564 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000565 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 +0000566 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800567 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800568 (mClient == 0) ? getpid_cached : mClient->pid(),
569 mStreamType,
570 mFormat,
571 mChannelMask,
572 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800573 mFrameCount,
574 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800575 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800576 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700577 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
578 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700579 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000580 mMainBuffer,
581 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700582 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700583 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800584 nowInUnderrun);
585}
586
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800587uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
588 return mAudioTrackServerProxy->getSampleRate();
589}
590
Eric Laurent81784c32012-11-19 14:55:58 -0800591// AudioBufferProvider interface
592status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800593 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800594{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800595 ServerProxy::Buffer buf;
596 size_t desiredFrames = buffer->frameCount;
597 buf.mFrameCount = desiredFrames;
598 status_t status = mServerProxy->obtainBuffer(&buf);
599 buffer->frameCount = buf.mFrameCount;
600 buffer->raw = buf.mRaw;
601 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700602 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800603 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800605}
606
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700607// releaseBuffer() is not overridden
608
609// ExtendedAudioBufferProvider interface
610
Andy Hung27876c02014-09-09 18:07:55 -0700611// framesReady() may return an approximation of the number of frames if called
612// from a different thread than the one calling Proxy->obtainBuffer() and
613// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
614// AudioTrackServerProxy so be especially careful calling with FastTracks.
Eric Laurent81784c32012-11-19 14:55:58 -0800615size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Andy Hung27876c02014-09-09 18:07:55 -0700616 if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
617 // Static tracks return zero frames immediately upon stopping (for FastTracks).
618 // The remainder of the buffer is not drained.
619 return 0;
620 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800621 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800622}
623
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700624size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
625{
626 return mAudioTrackServerProxy->framesReleased();
627}
628
Eric Laurent81784c32012-11-19 14:55:58 -0800629// Don't call for fast tracks; the framesReady() could result in priority inversion
630bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800631 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
632 return true;
633 }
634
Eric Laurent16498512014-03-17 17:22:08 -0700635 if (isStopping()) {
636 if (framesReady() > 0) {
637 mFillingUpStatus = FS_FILLED;
638 }
Eric Laurent81784c32012-11-19 14:55:58 -0800639 return true;
640 }
641
642 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700643 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800644 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700645 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800646 return true;
647 }
648 return false;
649}
650
Glenn Kasten0f11b512014-01-31 16:18:54 -0800651status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
652 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800653{
654 status_t status = NO_ERROR;
655 ALOGV("start(%d), calling pid %d session %d",
656 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
657
658 sp<ThreadBase> thread = mThread.promote();
659 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700660 if (isOffloaded()) {
661 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
662 Mutex::Autolock _lth(thread->mLock);
663 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700664 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
665 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700666 invalidate();
667 return PERMISSION_DENIED;
668 }
669 }
670 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800671 track_state state = mState;
672 // here the track could be either new, or restarted
673 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800674
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800675 // initial state-stopping. next state-pausing.
676 // What if resume is called ?
677
678 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800679 if (mResumeToStopping) {
680 // happened we need to resume to STOPPING_1
681 mState = TrackBase::STOPPING_1;
682 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
683 } else {
684 mState = TrackBase::RESUMING;
685 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
686 }
Eric Laurent81784c32012-11-19 14:55:58 -0800687 } else {
688 mState = TrackBase::ACTIVE;
689 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
690 }
691
Eric Laurentbfb1b832013-01-07 09:53:42 -0800692 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Haynes Mathew George240934b2015-03-11 18:25:50 -0700693 if (isFastTrack()) {
694 // refresh fast track underruns on start because that field is never cleared
695 // by the fast mixer; furthermore, the same track can be recycled, i.e. start
696 // after stop.
697 mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
698 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800699 status = playbackThread->addTrack_l(this);
700 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800701 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800702 // restore previous state if start was rejected by policy manager
703 if (status == PERMISSION_DENIED) {
704 mState = state;
705 }
706 }
707 // track was already in the active list, not a problem
708 if (status == ALREADY_EXISTS) {
709 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700710 } else {
711 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
712 // It is usually unsafe to access the server proxy from a binder thread.
713 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
714 // isn't looking at this track yet: we still hold the normal mixer thread lock,
715 // and for fast tracks the track is not yet in the fast mixer thread's active set.
716 ServerProxy::Buffer buffer;
717 buffer.mFrameCount = 1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700718 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800719 }
720 } else {
721 status = BAD_VALUE;
722 }
723 return status;
724}
725
726void AudioFlinger::PlaybackThread::Track::stop()
727{
728 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
729 sp<ThreadBase> thread = mThread.promote();
730 if (thread != 0) {
731 Mutex::Autolock _l(thread->mLock);
732 track_state state = mState;
733 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
734 // If the track is not active (PAUSED and buffers full), flush buffers
735 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
736 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
737 reset();
738 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700739 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800740 mState = STOPPED;
741 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800742 // For fast tracks prepareTracks_l() will set state to STOPPING_2
743 // presentation is complete
744 // For an offloaded track this starts a drain and state will
745 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800746 mState = STOPPING_1;
747 }
Eric Laurentb369caf2015-03-30 20:51:47 -0700748 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800749 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
750 playbackThread);
751 }
Eric Laurent81784c32012-11-19 14:55:58 -0800752 }
753}
754
755void AudioFlinger::PlaybackThread::Track::pause()
756{
757 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
758 sp<ThreadBase> thread = mThread.promote();
759 if (thread != 0) {
760 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800761 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
762 switch (mState) {
763 case STOPPING_1:
764 case STOPPING_2:
765 if (!isOffloaded()) {
766 /* nothing to do if track is not offloaded */
767 break;
768 }
769
770 // Offloaded track was draining, we need to carry on draining when resumed
771 mResumeToStopping = true;
772 // fall through...
773 case ACTIVE:
774 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800775 mState = PAUSING;
776 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700777 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800778 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800779
Eric Laurentbfb1b832013-01-07 09:53:42 -0800780 default:
781 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800782 }
783 }
784}
785
786void AudioFlinger::PlaybackThread::Track::flush()
787{
788 ALOGV("flush(%d)", mName);
789 sp<ThreadBase> thread = mThread.promote();
790 if (thread != 0) {
791 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800792 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800793
794 if (isOffloaded()) {
795 // If offloaded we allow flush during any state except terminated
796 // and keep the track active to avoid problems if user is seeking
797 // rapidly and underlying hardware has a significant delay handling
798 // a pause
799 if (isTerminated()) {
800 return;
801 }
802
803 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800804 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800805
806 if (mState == STOPPING_1 || mState == STOPPING_2) {
807 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
808 mState = ACTIVE;
809 }
810
811 if (mState == ACTIVE) {
812 ALOGV("flush called in active state, resetting buffer time out retry count");
813 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
814 }
815
Haynes Mathew George7844f672014-01-15 12:32:55 -0800816 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800817 mResumeToStopping = false;
818 } else {
819 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
820 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
821 return;
822 }
823 // No point remaining in PAUSED state after a flush => go to
824 // FLUSHED state
825 mState = FLUSHED;
826 // do not reset the track if it is still in the process of being stopped or paused.
827 // this will be done by prepareTracks_l() when the track is stopped.
828 // prepareTracks_l() will see mState == FLUSHED, then
829 // remove from active track list, reset(), and trigger presentation complete
Eric Laurentd1f69b02014-12-15 14:33:13 -0800830 if (isDirect()) {
831 mFlushHwPending = true;
832 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800833 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
834 reset();
835 }
Eric Laurent81784c32012-11-19 14:55:58 -0800836 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800837 // Prevent flush being lost if the track is flushed and then resumed
838 // before mixer thread can run. This is important when offloading
839 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700840 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800841 }
842}
843
Haynes Mathew George7844f672014-01-15 12:32:55 -0800844// must be called with thread lock held
845void AudioFlinger::PlaybackThread::Track::flushAck()
846{
Eric Laurentd1f69b02014-12-15 14:33:13 -0800847 if (!isOffloaded() && !isDirect())
Haynes Mathew George7844f672014-01-15 12:32:55 -0800848 return;
849
850 mFlushHwPending = false;
851}
852
Eric Laurent81784c32012-11-19 14:55:58 -0800853void AudioFlinger::PlaybackThread::Track::reset()
854{
855 // Do not reset twice to avoid discarding data written just after a flush and before
856 // the audioflinger thread detects the track is stopped.
857 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800858 // Force underrun condition to avoid false underrun callback until first data is
859 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700860 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800861 mFillingUpStatus = FS_FILLING;
862 mResetDone = true;
863 if (mState == FLUSHED) {
864 mState = IDLE;
865 }
Phil Burk6140c792015-03-19 14:30:21 -0700866 mPreviousTimestampValid = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800867 }
868}
869
Eric Laurentbfb1b832013-01-07 09:53:42 -0800870status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
871{
872 sp<ThreadBase> thread = mThread.promote();
873 if (thread == 0) {
874 ALOGE("thread is dead");
875 return FAILED_TRANSACTION;
876 } else if ((thread->type() == ThreadBase::DIRECT) ||
877 (thread->type() == ThreadBase::OFFLOAD)) {
878 return thread->setParameters(keyValuePairs);
879 } else {
880 return PERMISSION_DENIED;
881 }
882}
883
Glenn Kasten573d80a2013-08-26 09:36:23 -0700884status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
885{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700886 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
887 if (isFastTrack()) {
Phil Burk6140c792015-03-19 14:30:21 -0700888 // FIXME no lock held to set mPreviousTimestampValid = false
Glenn Kastenfe346c72013-08-30 13:28:22 -0700889 return INVALID_OPERATION;
890 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700891 sp<ThreadBase> thread = mThread.promote();
892 if (thread == 0) {
Phil Burk6140c792015-03-19 14:30:21 -0700893 // FIXME no lock held to set mPreviousTimestampValid = false
Glenn Kastenfe346c72013-08-30 13:28:22 -0700894 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700895 }
Phil Burk6140c792015-03-19 14:30:21 -0700896
Glenn Kasten573d80a2013-08-26 09:36:23 -0700897 Mutex::Autolock _l(thread->mLock);
898 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Phil Burk6140c792015-03-19 14:30:21 -0700899
900 status_t result = INVALID_OPERATION;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700901 if (!isOffloaded() && !isDirect()) {
Eric Laurentaccc1472013-09-20 09:36:34 -0700902 if (!playbackThread->mLatchQValid) {
Phil Burk6140c792015-03-19 14:30:21 -0700903 mPreviousTimestampValid = false;
Eric Laurentaccc1472013-09-20 09:36:34 -0700904 return INVALID_OPERATION;
905 }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700906 // FIXME Not accurate under dynamic changes of sample rate and speed.
907 // Do not use track's mSampleRate as it is not current for mixer tracks.
908 uint32_t sampleRate = mAudioTrackServerProxy->getSampleRate();
909 float speed, pitch;
910 mAudioTrackServerProxy->getPlaybackRate(&speed, &pitch);
Eric Laurentaccc1472013-09-20 09:36:34 -0700911 uint32_t unpresentedFrames =
Andy Hung8edb8dc2015-03-26 19:13:55 -0700912 ((double) playbackThread->mLatchQ.mUnpresentedFrames * sampleRate * speed)
913 / playbackThread->mSampleRate;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700914 // FIXME Since we're using a raw pointer as the key, it is theoretically possible
915 // for a brand new track to share the same address as a recently destroyed
916 // track, and thus for us to get the frames released of the wrong track.
917 // It is unlikely that we would be able to call getTimestamp() so quickly
918 // right after creating a new track. Nevertheless, the index here should
919 // be changed to something that is unique. Or use a completely different strategy.
920 ssize_t i = playbackThread->mLatchQ.mFramesReleased.indexOfKey(this);
921 uint32_t framesWritten = i >= 0 ?
922 playbackThread->mLatchQ.mFramesReleased[i] :
923 mAudioTrackServerProxy->framesReleased();
Eric Laurentaccc1472013-09-20 09:36:34 -0700924 if (framesWritten < unpresentedFrames) {
Phil Burk6140c792015-03-19 14:30:21 -0700925 mPreviousTimestampValid = false;
926 // return invalid result
927 } else {
928 timestamp.mPosition = framesWritten - unpresentedFrames;
929 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
930 result = NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -0700931 }
Phil Burk6140c792015-03-19 14:30:21 -0700932 } else { // offloaded or direct
933 result = playbackThread->getTimestamp_l(timestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700934 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700935
Phil Burk6140c792015-03-19 14:30:21 -0700936 // Prevent retrograde motion in timestamp.
937 if (result == NO_ERROR) {
938 if (mPreviousTimestampValid) {
939 if (timestamp.mTime.tv_sec < mPreviousTimestamp.mTime.tv_sec ||
940 (timestamp.mTime.tv_sec == mPreviousTimestamp.mTime.tv_sec &&
941 timestamp.mTime.tv_nsec < mPreviousTimestamp.mTime.tv_nsec)) {
942 ALOGW("WARNING - retrograde timestamp time");
943 // FIXME Consider blocking this from propagating upwards.
944 }
945
946 // Looking at signed delta will work even when the timestamps
947 // are wrapping around.
948 int32_t deltaPosition = static_cast<int32_t>(timestamp.mPosition
949 - mPreviousTimestamp.mPosition);
950 // position can bobble slightly as an artifact; this hides the bobble
951 static const int32_t MINIMUM_POSITION_DELTA = 8;
952 if (deltaPosition < 0) {
953#define TIME_TO_NANOS(time) ((uint64_t)time.tv_sec * 1000000000 + time.tv_nsec)
954 ALOGW("WARNING - retrograde timestamp position corrected,"
955 " %d = %u - %u, (at %llu, %llu nanos)",
956 deltaPosition,
957 timestamp.mPosition,
958 mPreviousTimestamp.mPosition,
959 TIME_TO_NANOS(timestamp.mTime),
960 TIME_TO_NANOS(mPreviousTimestamp.mTime));
961#undef TIME_TO_NANOS
962 }
963 if (deltaPosition < MINIMUM_POSITION_DELTA) {
964 // Current timestamp is bad. Use last valid timestamp.
965 timestamp = mPreviousTimestamp;
966 }
967 }
968 mPreviousTimestamp = timestamp;
969 mPreviousTimestampValid = true;
970 }
971 return result;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700972}
973
Eric Laurent81784c32012-11-19 14:55:58 -0800974status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
975{
976 status_t status = DEAD_OBJECT;
977 sp<ThreadBase> thread = mThread.promote();
978 if (thread != 0) {
979 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
980 sp<AudioFlinger> af = mClient->audioFlinger();
981
982 Mutex::Autolock _l(af->mLock);
983
984 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
985
986 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
987 Mutex::Autolock _dl(playbackThread->mLock);
988 Mutex::Autolock _sl(srcThread->mLock);
989 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
990 if (chain == 0) {
991 return INVALID_OPERATION;
992 }
993
994 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
995 if (effect == 0) {
996 return INVALID_OPERATION;
997 }
998 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700999 status = playbackThread->addEffect_l(effect);
1000 if (status != NO_ERROR) {
1001 srcThread->addEffect_l(effect);
1002 return INVALID_OPERATION;
1003 }
Eric Laurent81784c32012-11-19 14:55:58 -08001004 // removeEffect_l() has stopped the effect if it was active so it must be restarted
1005 if (effect->state() == EffectModule::ACTIVE ||
1006 effect->state() == EffectModule::STOPPING) {
1007 effect->start();
1008 }
1009
1010 sp<EffectChain> dstChain = effect->chain().promote();
1011 if (dstChain == 0) {
1012 srcThread->addEffect_l(effect);
1013 return INVALID_OPERATION;
1014 }
1015 AudioSystem::unregisterEffect(effect->id());
1016 AudioSystem::registerEffect(&effect->desc(),
1017 srcThread->id(),
1018 dstChain->strategy(),
1019 AUDIO_SESSION_OUTPUT_MIX,
1020 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07001021 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -08001022 }
1023 status = playbackThread->attachAuxEffect(this, EffectId);
1024 }
1025 return status;
1026}
1027
1028void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
1029{
1030 mAuxEffectId = EffectId;
1031 mAuxBuffer = buffer;
1032}
1033
1034bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
1035 size_t audioHalFrames)
1036{
1037 // a track is considered presented when the total number of frames written to audio HAL
1038 // corresponds to the number of frames written when presentationComplete() is called for the
1039 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001040 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1041 // to detect when all frames have been played. In this case framesWritten isn't
1042 // useful because it doesn't always reflect whether there is data in the h/w
1043 // buffers, particularly if a track has been paused and resumed during draining
1044 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
1045 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001046 if (mPresentationCompleteFrames == 0) {
1047 mPresentationCompleteFrames = framesWritten + audioHalFrames;
1048 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
1049 mPresentationCompleteFrames, audioHalFrames);
1050 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001051
1052 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001053 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001054 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001055 return true;
1056 }
1057 return false;
1058}
1059
1060void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1061{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001062 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001063 if (mSyncEvents[i]->type() == type) {
1064 mSyncEvents[i]->trigger();
1065 mSyncEvents.removeAt(i);
1066 i--;
1067 }
1068 }
1069}
1070
1071// implement VolumeBufferProvider interface
1072
Glenn Kastenc56f3422014-03-21 17:53:17 -07001073gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001074{
1075 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1076 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001077 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1078 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1079 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001080 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001081 if (vl > GAIN_FLOAT_UNITY) {
1082 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001083 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001084 if (vr > GAIN_FLOAT_UNITY) {
1085 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001086 }
1087 // now apply the cached master volume and stream type volume;
1088 // this is trusted but lacks any synchronization or barrier so may be stale
1089 float v = mCachedVolume;
1090 vl *= v;
1091 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001092 // re-combine into packed minifloat
1093 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001094 // FIXME look at mute, pause, and stop flags
1095 return vlr;
1096}
1097
1098status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1099{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001100 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001101 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1102 (mState == STOPPED)))) {
1103 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1104 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1105 event->cancel();
1106 return INVALID_OPERATION;
1107 }
1108 (void) TrackBase::setSyncEvent(event);
1109 return NO_ERROR;
1110}
1111
Glenn Kasten5736c352012-12-04 12:12:34 -08001112void AudioFlinger::PlaybackThread::Track::invalidate()
1113{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001114 // FIXME should use proxy, and needs work
1115 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001116 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001117 android_atomic_release_store(0x40000000, &cblk->mFutex);
1118 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001119 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001120 mIsInvalid = true;
1121}
1122
Eric Laurent59fe0102013-09-27 18:48:26 -07001123void AudioFlinger::PlaybackThread::Track::signal()
1124{
1125 sp<ThreadBase> thread = mThread.promote();
1126 if (thread != 0) {
1127 PlaybackThread *t = (PlaybackThread *)thread.get();
1128 Mutex::Autolock _l(t->mLock);
1129 t->broadcast_l();
1130 }
1131}
1132
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001133//To be called with thread lock held
1134bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1135
1136 if (mState == RESUMING)
1137 return true;
1138 /* Resume is pending if track was stopping before pause was called */
1139 if (mState == STOPPING_1 &&
1140 mResumeToStopping)
1141 return true;
1142
1143 return false;
1144}
1145
1146//To be called with thread lock held
1147void AudioFlinger::PlaybackThread::Track::resumeAck() {
1148
1149
1150 if (mState == RESUMING)
1151 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001152
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001153 // Other possibility of pending resume is stopping_1 state
1154 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001155 // drain being called.
1156 if (mState == STOPPING_1) {
1157 mResumeToStopping = false;
1158 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001159}
Eric Laurent81784c32012-11-19 14:55:58 -08001160// ----------------------------------------------------------------------------
1161
1162sp<AudioFlinger::PlaybackThread::TimedTrack>
1163AudioFlinger::PlaybackThread::TimedTrack::create(
1164 PlaybackThread *thread,
1165 const sp<Client>& client,
1166 audio_stream_type_t streamType,
1167 uint32_t sampleRate,
1168 audio_format_t format,
1169 audio_channel_mask_t channelMask,
1170 size_t frameCount,
1171 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001172 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001173 int uid)
1174{
Eric Laurent81784c32012-11-19 14:55:58 -08001175 if (!client->reserveTimedTrack())
1176 return 0;
1177
1178 return new TimedTrack(
1179 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001180 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001181}
1182
1183AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1184 PlaybackThread *thread,
1185 const sp<Client>& client,
1186 audio_stream_type_t streamType,
1187 uint32_t sampleRate,
1188 audio_format_t format,
1189 audio_channel_mask_t channelMask,
1190 size_t frameCount,
1191 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001192 int sessionId,
1193 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001194 : Track(thread, client, streamType, sampleRate, format, channelMask,
Eric Laurent83b88082014-06-20 18:31:16 -07001195 frameCount, (sharedBuffer != 0) ? sharedBuffer->pointer() : NULL, sharedBuffer,
1196 sessionId, uid, IAudioFlinger::TRACK_TIMED, TYPE_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001197 mQueueHeadInFlight(false),
1198 mTrimQueueHeadOnRelease(false),
1199 mFramesPendingInQueue(0),
1200 mTimedSilenceBuffer(NULL),
1201 mTimedSilenceBufferSize(0),
1202 mTimedAudioOutputOnTime(false),
1203 mMediaTimeTransformValid(false)
1204{
1205 LocalClock lc;
1206 mLocalTimeFreq = lc.getLocalFreq();
1207
1208 mLocalTimeToSampleTransform.a_zero = 0;
1209 mLocalTimeToSampleTransform.b_zero = 0;
1210 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1211 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1212 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1213 &mLocalTimeToSampleTransform.a_to_b_denom);
1214
1215 mMediaTimeToSampleTransform.a_zero = 0;
1216 mMediaTimeToSampleTransform.b_zero = 0;
1217 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1218 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1219 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1220 &mMediaTimeToSampleTransform.a_to_b_denom);
1221}
1222
1223AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1224 mClient->releaseTimedTrack();
1225 delete [] mTimedSilenceBuffer;
1226}
1227
1228status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1229 size_t size, sp<IMemory>* buffer) {
1230
1231 Mutex::Autolock _l(mTimedBufferQueueLock);
1232
1233 trimTimedBufferQueue_l();
1234
1235 // lazily initialize the shared memory heap for timed buffers
1236 if (mTimedMemoryDealer == NULL) {
1237 const int kTimedBufferHeapSize = 512 << 10;
1238
1239 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1240 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001241 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001242 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001243 }
Eric Laurent81784c32012-11-19 14:55:58 -08001244 }
1245
1246 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001247 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001248 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001249 }
1250
1251 *buffer = newBuffer;
1252 return NO_ERROR;
1253}
1254
1255// caller must hold mTimedBufferQueueLock
1256void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1257 int64_t mediaTimeNow;
1258 {
1259 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1260 if (!mMediaTimeTransformValid)
1261 return;
1262
1263 int64_t targetTimeNow;
1264 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1265 ? mCCHelper.getCommonTime(&targetTimeNow)
1266 : mCCHelper.getLocalTime(&targetTimeNow);
1267
1268 if (OK != res)
1269 return;
1270
1271 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1272 &mediaTimeNow)) {
1273 return;
1274 }
1275 }
1276
1277 size_t trimEnd;
1278 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1279 int64_t bufEnd;
1280
1281 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1282 // We have a next buffer. Just use its PTS as the PTS of the frame
1283 // following the last frame in this buffer. If the stream is sparse
1284 // (ie, there are deliberate gaps left in the stream which should be
1285 // filled with silence by the TimedAudioTrack), then this can result
1286 // in one extra buffer being left un-trimmed when it could have
1287 // been. In general, this is not typical, and we would rather
1288 // optimized away the TS calculation below for the more common case
1289 // where PTSes are contiguous.
1290 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1291 } else {
1292 // We have no next buffer. Compute the PTS of the frame following
1293 // the last frame in this buffer by computing the duration of of
1294 // this frame in media time units and adding it to the PTS of the
1295 // buffer.
1296 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1297 / mFrameSize;
1298
1299 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1300 &bufEnd)) {
1301 ALOGE("Failed to convert frame count of %lld to media time"
1302 " duration" " (scale factor %d/%u) in %s",
1303 frameCount,
1304 mMediaTimeToSampleTransform.a_to_b_numer,
1305 mMediaTimeToSampleTransform.a_to_b_denom,
1306 __PRETTY_FUNCTION__);
1307 break;
1308 }
1309 bufEnd += mTimedBufferQueue[trimEnd].pts();
1310 }
1311
1312 if (bufEnd > mediaTimeNow)
1313 break;
1314
1315 // Is the buffer we want to use in the middle of a mix operation right
1316 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1317 // from the mixer which should be coming back shortly.
1318 if (!trimEnd && mQueueHeadInFlight) {
1319 mTrimQueueHeadOnRelease = true;
1320 }
1321 }
1322
1323 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1324 if (trimStart < trimEnd) {
1325 // Update the bookkeeping for framesReady()
1326 for (size_t i = trimStart; i < trimEnd; ++i) {
1327 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1328 }
1329
1330 // Now actually remove the buffers from the queue.
1331 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1332 }
1333}
1334
1335void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1336 const char* logTag) {
1337 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1338 "%s called (reason \"%s\"), but timed buffer queue has no"
1339 " elements to trim.", __FUNCTION__, logTag);
1340
1341 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1342 mTimedBufferQueue.removeAt(0);
1343}
1344
1345void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1346 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001347 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001348 uint32_t bufBytes = buf.buffer()->size();
1349 uint32_t consumedAlready = buf.position();
1350
1351 ALOG_ASSERT(consumedAlready <= bufBytes,
1352 "Bad bookkeeping while updating frames pending. Timed buffer is"
1353 " only %u bytes long, but claims to have consumed %u"
1354 " bytes. (update reason: \"%s\")",
1355 bufBytes, consumedAlready, logTag);
1356
1357 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1358 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1359 "Bad bookkeeping while updating frames pending. Should have at"
1360 " least %u queued frames, but we think we have only %u. (update"
1361 " reason: \"%s\")",
1362 bufFrames, mFramesPendingInQueue, logTag);
1363
1364 mFramesPendingInQueue -= bufFrames;
1365}
1366
1367status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1368 const sp<IMemory>& buffer, int64_t pts) {
1369
1370 {
1371 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1372 if (!mMediaTimeTransformValid)
1373 return INVALID_OPERATION;
1374 }
1375
1376 Mutex::Autolock _l(mTimedBufferQueueLock);
1377
1378 uint32_t bufFrames = buffer->size() / mFrameSize;
1379 mFramesPendingInQueue += bufFrames;
1380 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1381
1382 return NO_ERROR;
1383}
1384
1385status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1386 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1387
1388 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1389 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1390 target);
1391
1392 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1393 target == TimedAudioTrack::COMMON_TIME)) {
1394 return BAD_VALUE;
1395 }
1396
1397 Mutex::Autolock lock(mMediaTimeTransformLock);
1398 mMediaTimeTransform = xform;
1399 mMediaTimeTransformTarget = target;
1400 mMediaTimeTransformValid = true;
1401
1402 return NO_ERROR;
1403}
1404
1405#define min(a, b) ((a) < (b) ? (a) : (b))
1406
1407// implementation of getNextBuffer for tracks whose buffers have timestamps
1408status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1409 AudioBufferProvider::Buffer* buffer, int64_t pts)
1410{
1411 if (pts == AudioBufferProvider::kInvalidPTS) {
1412 buffer->raw = NULL;
1413 buffer->frameCount = 0;
1414 mTimedAudioOutputOnTime = false;
1415 return INVALID_OPERATION;
1416 }
1417
1418 Mutex::Autolock _l(mTimedBufferQueueLock);
1419
1420 ALOG_ASSERT(!mQueueHeadInFlight,
1421 "getNextBuffer called without releaseBuffer!");
1422
1423 while (true) {
1424
1425 // if we have no timed buffers, then fail
1426 if (mTimedBufferQueue.isEmpty()) {
1427 buffer->raw = NULL;
1428 buffer->frameCount = 0;
1429 return NOT_ENOUGH_DATA;
1430 }
1431
1432 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1433
1434 // calculate the PTS of the head of the timed buffer queue expressed in
1435 // local time
1436 int64_t headLocalPTS;
1437 {
1438 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1439
1440 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1441
1442 if (mMediaTimeTransform.a_to_b_denom == 0) {
1443 // the transform represents a pause, so yield silence
1444 timedYieldSilence_l(buffer->frameCount, buffer);
1445 return NO_ERROR;
1446 }
1447
1448 int64_t transformedPTS;
1449 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1450 &transformedPTS)) {
1451 // the transform failed. this shouldn't happen, but if it does
1452 // then just drop this buffer
1453 ALOGW("timedGetNextBuffer transform failed");
1454 buffer->raw = NULL;
1455 buffer->frameCount = 0;
1456 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1457 return NO_ERROR;
1458 }
1459
1460 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1461 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1462 &headLocalPTS)) {
1463 buffer->raw = NULL;
1464 buffer->frameCount = 0;
1465 return INVALID_OPERATION;
1466 }
1467 } else {
1468 headLocalPTS = transformedPTS;
1469 }
1470 }
1471
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001472 uint32_t sr = sampleRate();
1473
Eric Laurent81784c32012-11-19 14:55:58 -08001474 // adjust the head buffer's PTS to reflect the portion of the head buffer
1475 // that has already been consumed
1476 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001477 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001478
1479 // Calculate the delta in samples between the head of the input buffer
1480 // queue and the start of the next output buffer that will be written.
1481 // If the transformation fails because of over or underflow, it means
1482 // that the sample's position in the output stream is so far out of
1483 // whack that it should just be dropped.
1484 int64_t sampleDelta;
1485 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1486 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1487 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1488 " mix");
1489 continue;
1490 }
1491 if (!mLocalTimeToSampleTransform.doForwardTransform(
1492 (effectivePTS - pts) << 32, &sampleDelta)) {
1493 ALOGV("*** too late during sample rate transform: dropped buffer");
1494 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1495 continue;
1496 }
1497
1498 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1499 " sampleDelta=[%d.%08x]",
1500 head.pts(), head.position(), pts,
1501 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1502 + (sampleDelta >> 32)),
1503 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1504
1505 // if the delta between the ideal placement for the next input sample and
1506 // the current output position is within this threshold, then we will
1507 // concatenate the next input samples to the previous output
1508 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001509 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001510
1511 // if this is the first buffer of audio that we're emitting from this track
1512 // then it should be almost exactly on time.
1513 const int64_t kSampleStartupThreshold = 1LL << 32;
1514
1515 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1516 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1517 // the next input is close enough to being on time, so concatenate it
1518 // with the last output
1519 timedYieldSamples_l(buffer);
1520
1521 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1522 head.position(), buffer->frameCount);
1523 return NO_ERROR;
1524 }
1525
1526 // Looks like our output is not on time. Reset our on timed status.
1527 // Next time we mix samples from our input queue, then should be within
1528 // the StartupThreshold.
1529 mTimedAudioOutputOnTime = false;
1530 if (sampleDelta > 0) {
1531 // the gap between the current output position and the proper start of
1532 // the next input sample is too big, so fill it with silence
1533 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1534
1535 timedYieldSilence_l(framesUntilNextInput, buffer);
1536 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1537 return NO_ERROR;
1538 } else {
1539 // the next input sample is late
1540 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1541 size_t onTimeSamplePosition =
1542 head.position() + lateFrames * mFrameSize;
1543
1544 if (onTimeSamplePosition > head.buffer()->size()) {
1545 // all the remaining samples in the head are too late, so
1546 // drop it and move on
1547 ALOGV("*** too late: dropped buffer");
1548 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1549 continue;
1550 } else {
1551 // skip over the late samples
1552 head.setPosition(onTimeSamplePosition);
1553
1554 // yield the available samples
1555 timedYieldSamples_l(buffer);
1556
1557 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1558 return NO_ERROR;
1559 }
1560 }
1561 }
1562}
1563
1564// Yield samples from the timed buffer queue head up to the given output
1565// buffer's capacity.
1566//
1567// Caller must hold mTimedBufferQueueLock
1568void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1569 AudioBufferProvider::Buffer* buffer) {
1570
1571 const TimedBuffer& head = mTimedBufferQueue[0];
1572
1573 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1574 head.position());
1575
1576 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1577 mFrameSize);
1578 size_t framesRequested = buffer->frameCount;
1579 buffer->frameCount = min(framesLeftInHead, framesRequested);
1580
1581 mQueueHeadInFlight = true;
1582 mTimedAudioOutputOnTime = true;
1583}
1584
1585// Yield samples of silence up to the given output buffer's capacity
1586//
1587// Caller must hold mTimedBufferQueueLock
1588void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1589 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1590
1591 // lazily allocate a buffer filled with silence
1592 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1593 delete [] mTimedSilenceBuffer;
1594 mTimedSilenceBufferSize = numFrames * mFrameSize;
1595 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1596 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1597 }
1598
1599 buffer->raw = mTimedSilenceBuffer;
1600 size_t framesRequested = buffer->frameCount;
1601 buffer->frameCount = min(numFrames, framesRequested);
1602
1603 mTimedAudioOutputOnTime = false;
1604}
1605
1606// AudioBufferProvider interface
1607void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1608 AudioBufferProvider::Buffer* buffer) {
1609
1610 Mutex::Autolock _l(mTimedBufferQueueLock);
1611
1612 // If the buffer which was just released is part of the buffer at the head
1613 // of the queue, be sure to update the amt of the buffer which has been
1614 // consumed. If the buffer being returned is not part of the head of the
1615 // queue, its either because the buffer is part of the silence buffer, or
1616 // because the head of the timed queue was trimmed after the mixer called
1617 // getNextBuffer but before the mixer called releaseBuffer.
1618 if (buffer->raw == mTimedSilenceBuffer) {
1619 ALOG_ASSERT(!mQueueHeadInFlight,
1620 "Queue head in flight during release of silence buffer!");
1621 goto done;
1622 }
1623
1624 ALOG_ASSERT(mQueueHeadInFlight,
1625 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1626 " head in flight.");
1627
1628 if (mTimedBufferQueue.size()) {
1629 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1630
1631 void* start = head.buffer()->pointer();
1632 void* end = reinterpret_cast<void*>(
1633 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1634 + head.buffer()->size());
1635
1636 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1637 "released buffer not within the head of the timed buffer"
1638 " queue; qHead = [%p, %p], released buffer = %p",
1639 start, end, buffer->raw);
1640
1641 head.setPosition(head.position() +
1642 (buffer->frameCount * mFrameSize));
1643 mQueueHeadInFlight = false;
1644
1645 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1646 "Bad bookkeeping during releaseBuffer! Should have at"
1647 " least %u queued frames, but we think we have only %u",
1648 buffer->frameCount, mFramesPendingInQueue);
1649
1650 mFramesPendingInQueue -= buffer->frameCount;
1651
1652 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1653 || mTrimQueueHeadOnRelease) {
1654 trimTimedBufferQueueHead_l("releaseBuffer");
1655 mTrimQueueHeadOnRelease = false;
1656 }
1657 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001658 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001659 " buffers in the timed buffer queue");
1660 }
1661
1662done:
1663 buffer->raw = 0;
1664 buffer->frameCount = 0;
1665}
1666
1667size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1668 Mutex::Autolock _l(mTimedBufferQueueLock);
1669 return mFramesPendingInQueue;
1670}
1671
1672AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1673 : mPTS(0), mPosition(0) {}
1674
1675AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1676 const sp<IMemory>& buffer, int64_t pts)
1677 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1678
1679
1680// ----------------------------------------------------------------------------
1681
1682AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1683 PlaybackThread *playbackThread,
1684 DuplicatingThread *sourceThread,
1685 uint32_t sampleRate,
1686 audio_format_t format,
1687 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001688 size_t frameCount,
1689 int uid)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001690 : Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1691 sampleRate, format, channelMask, frameCount,
1692 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001693 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001694{
1695
1696 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001697 mOutBuffer.frameCount = 0;
1698 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001699 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001700 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001701 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001702 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001703 // since client and server are in the same process,
1704 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001705 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1706 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001707 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001708 mClientProxy->setSendLevel(0.0);
1709 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001710 } else {
1711 ALOGW("Error creating output track on thread %p", playbackThread);
1712 }
1713}
1714
1715AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1716{
1717 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001718 delete mClientProxy;
1719 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001720}
1721
1722status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1723 int triggerSession)
1724{
1725 status_t status = Track::start(event, triggerSession);
1726 if (status != NO_ERROR) {
1727 return status;
1728 }
1729
1730 mActive = true;
1731 mRetryCount = 127;
1732 return status;
1733}
1734
1735void AudioFlinger::PlaybackThread::OutputTrack::stop()
1736{
1737 Track::stop();
1738 clearBufferQueue();
1739 mOutBuffer.frameCount = 0;
1740 mActive = false;
1741}
1742
Andy Hungc25b84a2015-01-14 19:04:10 -08001743bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
Eric Laurent81784c32012-11-19 14:55:58 -08001744{
1745 Buffer *pInBuffer;
1746 Buffer inBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08001747 bool outputBufferFull = false;
1748 inBuffer.frameCount = frames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001749 inBuffer.raw = data;
Eric Laurent81784c32012-11-19 14:55:58 -08001750
1751 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1752
1753 if (!mActive && frames != 0) {
Andy Hung5bedff62015-01-16 11:05:32 -08001754 (void) start();
Eric Laurent81784c32012-11-19 14:55:58 -08001755 }
1756
1757 while (waitTimeLeftMs) {
1758 // First write pending buffers, then new data
1759 if (mBufferQueue.size()) {
1760 pInBuffer = mBufferQueue.itemAt(0);
1761 } else {
1762 pInBuffer = &inBuffer;
1763 }
1764
1765 if (pInBuffer->frameCount == 0) {
1766 break;
1767 }
1768
1769 if (mOutBuffer.frameCount == 0) {
1770 mOutBuffer.frameCount = pInBuffer->frameCount;
1771 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001772 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1773 if (status != NO_ERROR) {
1774 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1775 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001776 outputBufferFull = true;
1777 break;
1778 }
1779 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1780 if (waitTimeLeftMs >= waitTimeMs) {
1781 waitTimeLeftMs -= waitTimeMs;
1782 } else {
1783 waitTimeLeftMs = 0;
1784 }
1785 }
1786
1787 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1788 pInBuffer->frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001789 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001790 Proxy::Buffer buf;
1791 buf.mFrameCount = outFrames;
1792 buf.mRaw = NULL;
1793 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001794 pInBuffer->frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001795 pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001796 mOutBuffer.frameCount -= outFrames;
Andy Hungc25b84a2015-01-14 19:04:10 -08001797 mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001798
1799 if (pInBuffer->frameCount == 0) {
1800 if (mBufferQueue.size()) {
1801 mBufferQueue.removeAt(0);
Andy Hungc25b84a2015-01-14 19:04:10 -08001802 free(pInBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001803 delete pInBuffer;
1804 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1805 mThread.unsafe_get(), mBufferQueue.size());
1806 } else {
1807 break;
1808 }
1809 }
1810 }
1811
1812 // If we could not write all frames, allocate a buffer and queue it for next time.
1813 if (inBuffer.frameCount) {
1814 sp<ThreadBase> thread = mThread.promote();
1815 if (thread != 0 && !thread->standby()) {
1816 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1817 pInBuffer = new Buffer;
Andy Hungc25b84a2015-01-14 19:04:10 -08001818 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001819 pInBuffer->frameCount = inBuffer.frameCount;
Andy Hungc25b84a2015-01-14 19:04:10 -08001820 pInBuffer->raw = pInBuffer->mBuffer;
1821 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08001822 mBufferQueue.add(pInBuffer);
1823 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1824 mThread.unsafe_get(), mBufferQueue.size());
1825 } else {
1826 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1827 mThread.unsafe_get(), this);
1828 }
1829 }
1830 }
1831
Andy Hungc25b84a2015-01-14 19:04:10 -08001832 // Calling write() with a 0 length buffer means that no more data will be written:
1833 // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1834 if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1835 stop();
Eric Laurent81784c32012-11-19 14:55:58 -08001836 }
1837
1838 return outputBufferFull;
1839}
1840
1841status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1842 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1843{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001844 ClientProxy::Buffer buf;
1845 buf.mFrameCount = buffer->frameCount;
1846 struct timespec timeout;
1847 timeout.tv_sec = waitTimeMs / 1000;
1848 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1849 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1850 buffer->frameCount = buf.mFrameCount;
1851 buffer->raw = buf.mRaw;
1852 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001853}
1854
Eric Laurent81784c32012-11-19 14:55:58 -08001855void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1856{
1857 size_t size = mBufferQueue.size();
1858
1859 for (size_t i = 0; i < size; i++) {
1860 Buffer *pBuffer = mBufferQueue.itemAt(i);
Andy Hungc25b84a2015-01-14 19:04:10 -08001861 free(pBuffer->mBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001862 delete pBuffer;
1863 }
1864 mBufferQueue.clear();
1865}
1866
1867
Eric Laurent83b88082014-06-20 18:31:16 -07001868AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
Eric Laurent3bcf8592015-04-03 12:13:24 -07001869 audio_stream_type_t streamType,
Eric Laurent83b88082014-06-20 18:31:16 -07001870 uint32_t sampleRate,
1871 audio_channel_mask_t channelMask,
1872 audio_format_t format,
1873 size_t frameCount,
1874 void *buffer,
1875 IAudioFlinger::track_flags_t flags)
Eric Laurent3bcf8592015-04-03 12:13:24 -07001876 : Track(playbackThread, NULL, streamType,
Eric Laurent223fd5c2014-11-11 13:43:36 -08001877 sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001878 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1879 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1880{
1881 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1882 playbackThread->sampleRate();
1883 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1884 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1885
1886 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1887 this, sampleRate,
1888 (int)mPeerTimeout.tv_sec,
1889 (int)(mPeerTimeout.tv_nsec / 1000000));
1890}
1891
1892AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1893{
1894}
1895
1896// AudioBufferProvider interface
1897status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
1898 AudioBufferProvider::Buffer* buffer, int64_t pts)
1899{
1900 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1901 Proxy::Buffer buf;
1902 buf.mFrameCount = buffer->frameCount;
1903 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1904 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001905 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001906 if (buf.mFrameCount == 0) {
1907 return WOULD_BLOCK;
1908 }
Eric Laurent83b88082014-06-20 18:31:16 -07001909 status = Track::getNextBuffer(buffer, pts);
1910 return status;
1911}
1912
1913void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1914{
1915 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1916 Proxy::Buffer buf;
1917 buf.mFrameCount = buffer->frameCount;
1918 buf.mRaw = buffer->raw;
1919 mPeerProxy->releaseBuffer(&buf);
1920 TrackBase::releaseBuffer(buffer);
1921}
1922
1923status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1924 const struct timespec *timeOut)
1925{
1926 return mProxy->obtainBuffer(buffer, timeOut);
1927}
1928
1929void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1930{
1931 mProxy->releaseBuffer(buffer);
1932 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1933 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1934 start();
1935 }
1936 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1937}
1938
Eric Laurent81784c32012-11-19 14:55:58 -08001939// ----------------------------------------------------------------------------
1940// Record
1941// ----------------------------------------------------------------------------
1942
1943AudioFlinger::RecordHandle::RecordHandle(
1944 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1945 : BnAudioRecord(),
1946 mRecordTrack(recordTrack)
1947{
1948}
1949
1950AudioFlinger::RecordHandle::~RecordHandle() {
1951 stop_nonvirtual();
1952 mRecordTrack->destroy();
1953}
1954
Eric Laurent81784c32012-11-19 14:55:58 -08001955status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1956 int triggerSession) {
1957 ALOGV("RecordHandle::start()");
1958 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1959}
1960
1961void AudioFlinger::RecordHandle::stop() {
1962 stop_nonvirtual();
1963}
1964
1965void AudioFlinger::RecordHandle::stop_nonvirtual() {
1966 ALOGV("RecordHandle::stop()");
1967 mRecordTrack->stop();
1968}
1969
1970status_t AudioFlinger::RecordHandle::onTransact(
1971 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1972{
1973 return BnAudioRecord::onTransact(code, data, reply, flags);
1974}
1975
1976// ----------------------------------------------------------------------------
1977
Glenn Kasten05997e22014-03-13 15:08:33 -07001978// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001979AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1980 RecordThread *thread,
1981 const sp<Client>& client,
1982 uint32_t sampleRate,
1983 audio_format_t format,
1984 audio_channel_mask_t channelMask,
1985 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001986 void *buffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001987 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001988 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -07001989 IAudioFlinger::track_flags_t flags,
1990 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001991 : TrackBase(thread, client, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001992 channelMask, frameCount, buffer, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001993 flags, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001994 (type == TYPE_DEFAULT) ?
1995 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1996 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1997 type),
Andy Hung97a893e2015-03-29 01:03:07 -07001998 mOverflow(false),
Andy Hung73c02e42015-03-29 01:13:58 -07001999 mFramesToDrop(0)
Eric Laurent81784c32012-11-19 14:55:58 -08002000{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07002001 if (mCblk == NULL) {
2002 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002003 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002004
Andy Hung97a893e2015-03-29 01:03:07 -07002005 mRecordBufferConverter = new RecordBufferConverter(
2006 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
2007 channelMask, format, sampleRate);
2008 // Check if the RecordBufferConverter construction was successful.
2009 // If not, don't continue with construction.
2010 //
2011 // NOTE: It would be extremely rare that the record track cannot be created
2012 // for the current device, but a pending or future device change would make
2013 // the record track configuration valid.
2014 if (mRecordBufferConverter->initCheck() != NO_ERROR) {
2015 ALOGE("RecordTrack unable to create record buffer converter");
2016 return;
2017 }
2018
Eric Laurent83b88082014-06-20 18:31:16 -07002019 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
2020 mFrameSize, !isExternalTrack());
Andy Hung97a893e2015-03-29 01:03:07 -07002021 mResamplerBufferProvider = new ResamplerBufferProvider(this);
Glenn Kastenc263ca02014-06-04 20:31:46 -07002022
2023 if (flags & IAudioFlinger::TRACK_FAST) {
2024 ALOG_ASSERT(thread->mFastTrackAvail);
2025 thread->mFastTrackAvail = false;
2026 }
Eric Laurent81784c32012-11-19 14:55:58 -08002027}
2028
2029AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
2030{
2031 ALOGV("%s", __func__);
Andy Hung97a893e2015-03-29 01:03:07 -07002032 delete mRecordBufferConverter;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002033 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08002034}
2035
Andy Hung97a893e2015-03-29 01:03:07 -07002036status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
2037{
2038 status_t status = TrackBase::initCheck();
2039 if (status == NO_ERROR && mServerProxy == 0) {
2040 status = BAD_VALUE;
2041 }
2042 return status;
2043}
2044
Eric Laurent81784c32012-11-19 14:55:58 -08002045// AudioBufferProvider interface
2046status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002047 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002048{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002049 ServerProxy::Buffer buf;
2050 buf.mFrameCount = buffer->frameCount;
2051 status_t status = mServerProxy->obtainBuffer(&buf);
2052 buffer->frameCount = buf.mFrameCount;
2053 buffer->raw = buf.mRaw;
2054 if (buf.mFrameCount == 0) {
2055 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07002056 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002057 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002058 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002059}
2060
2061status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
2062 int triggerSession)
2063{
2064 sp<ThreadBase> thread = mThread.promote();
2065 if (thread != 0) {
2066 RecordThread *recordThread = (RecordThread *)thread.get();
2067 return recordThread->start(this, event, triggerSession);
2068 } else {
2069 return BAD_VALUE;
2070 }
2071}
2072
2073void AudioFlinger::RecordThread::RecordTrack::stop()
2074{
2075 sp<ThreadBase> thread = mThread.promote();
2076 if (thread != 0) {
2077 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07002078 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07002079 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002080 }
2081 }
2082}
2083
2084void AudioFlinger::RecordThread::RecordTrack::destroy()
2085{
2086 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
2087 sp<RecordTrack> keep(this);
2088 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002089 if (isExternalTrack()) {
2090 if (mState == ACTIVE || mState == RESUMING) {
2091 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
2092 }
2093 AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
2094 }
Eric Laurent81784c32012-11-19 14:55:58 -08002095 sp<ThreadBase> thread = mThread.promote();
2096 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002097 Mutex::Autolock _l(thread->mLock);
2098 RecordThread *recordThread = (RecordThread *) thread.get();
2099 recordThread->destroyTrack_l(this);
2100 }
2101 }
2102}
2103
Eric Laurent9a54bc22013-09-09 09:08:44 -07002104void AudioFlinger::RecordThread::RecordTrack::invalidate()
2105{
2106 // FIXME should use proxy, and needs work
2107 audio_track_cblk_t* cblk = mCblk;
2108 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2109 android_atomic_release_store(0x40000000, &cblk->mFutex);
2110 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07002111 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07002112}
2113
Eric Laurent81784c32012-11-19 14:55:58 -08002114
2115/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
2116{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002117 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08002118}
2119
Marco Nelissenb2208842014-02-07 14:00:50 -08002120void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08002121{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002122 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08002123 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08002124 (mClient == 0) ? getpid_cached : mClient->pid(),
2125 mFormat,
2126 mChannelMask,
2127 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08002128 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002129 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002130 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002131 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002132
Eric Laurent81784c32012-11-19 14:55:58 -08002133}
2134
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002135void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2136{
2137 if (event == mSyncStartEvent) {
2138 ssize_t framesToDrop = 0;
2139 sp<ThreadBase> threadBase = mThread.promote();
2140 if (threadBase != 0) {
2141 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2142 // from audio HAL
2143 framesToDrop = threadBase->mFrameCount * 2;
2144 }
2145 mFramesToDrop = framesToDrop;
2146 }
2147}
2148
2149void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2150{
2151 if (mSyncStartEvent != 0) {
2152 mSyncStartEvent->cancel();
2153 mSyncStartEvent.clear();
2154 }
2155 mFramesToDrop = 0;
2156}
2157
Eric Laurent83b88082014-06-20 18:31:16 -07002158
2159AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
2160 uint32_t sampleRate,
2161 audio_channel_mask_t channelMask,
2162 audio_format_t format,
2163 size_t frameCount,
2164 void *buffer,
2165 IAudioFlinger::track_flags_t flags)
2166 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
2167 buffer, 0, getuid(), flags, TYPE_PATCH),
2168 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
2169{
2170 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
2171 recordThread->sampleRate();
2172 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
2173 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
2174
2175 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
2176 this, sampleRate,
2177 (int)mPeerTimeout.tv_sec,
2178 (int)(mPeerTimeout.tv_nsec / 1000000));
2179}
2180
2181AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
2182{
2183}
2184
2185// AudioBufferProvider interface
2186status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
2187 AudioBufferProvider::Buffer* buffer, int64_t pts)
2188{
2189 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
2190 Proxy::Buffer buf;
2191 buf.mFrameCount = buffer->frameCount;
2192 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
2193 ALOGV_IF(status != NO_ERROR,
2194 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07002195 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07002196 if (buf.mFrameCount == 0) {
2197 return WOULD_BLOCK;
2198 }
Eric Laurent83b88082014-06-20 18:31:16 -07002199 status = RecordTrack::getNextBuffer(buffer, pts);
2200 return status;
2201}
2202
2203void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2204{
2205 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
2206 Proxy::Buffer buf;
2207 buf.mFrameCount = buffer->frameCount;
2208 buf.mRaw = buffer->raw;
2209 mPeerProxy->releaseBuffer(&buf);
2210 TrackBase::releaseBuffer(buffer);
2211}
2212
2213status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
2214 const struct timespec *timeOut)
2215{
2216 return mProxy->obtainBuffer(buffer, timeOut);
2217}
2218
2219void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2220{
2221 mProxy->releaseBuffer(buffer);
2222}
2223
Glenn Kasten63238ef2015-03-02 15:50:29 -08002224} // namespace android