blob: b2d53cf38d0e30b5759f525d7185713ae89d083e [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080023#include <math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070024#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080025#include <utils/Log.h>
26
27#include <private/media/AudioTrackShared.h>
28
29#include <common_time/cc_helper.h>
30#include <common_time/local_clock.h>
31
32#include "AudioMixer.h"
33#include "AudioFlinger.h"
34#include "ServiceUtilities.h"
35
Glenn Kastenda6ef132013-01-10 12:31:01 -080036#include <media/nbaio/Pipe.h>
37#include <media/nbaio/PipeReader.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070038#include <audio_utils/minifloat.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080039
Eric Laurent81784c32012-11-19 14:55:58 -080040// ----------------------------------------------------------------------------
41
42// Note: the following macro is used for extremely verbose logging message. In
43// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
44// 0; but one side effect of this is to turn all LOGV's as well. Some messages
45// are so verbose that we want to suppress them even when we have ALOG_ASSERT
46// turned on. Do not uncomment the #def below unless you really know what you
47// are doing and want to see all of the extremely verbose messages.
48//#define VERY_VERY_VERBOSE_LOGGING
49#ifdef VERY_VERY_VERBOSE_LOGGING
50#define ALOGVV ALOGV
51#else
52#define ALOGVV(a...) do { } while(0)
53#endif
54
55namespace android {
56
57// ----------------------------------------------------------------------------
58// TrackBase
59// ----------------------------------------------------------------------------
60
Glenn Kastenda6ef132013-01-10 12:31:01 -080061static volatile int32_t nextTrackId = 55;
62
Eric Laurent81784c32012-11-19 14:55:58 -080063// TrackBase constructor must be called with AudioFlinger::mLock held
64AudioFlinger::ThreadBase::TrackBase::TrackBase(
65 ThreadBase *thread,
66 const sp<Client>& client,
67 uint32_t sampleRate,
68 audio_format_t format,
69 audio_channel_mask_t channelMask,
70 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -070071 void *buffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080072 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -080073 int clientUid,
Glenn Kasten755b0a62014-05-13 11:30:28 -070074 IAudioFlinger::track_flags_t flags,
Glenn Kastend776ac62014-05-07 09:16:09 -070075 bool isOut,
Eric Laurent83b88082014-06-20 18:31:16 -070076 alloc_type alloc,
77 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -080078 : RefBase(),
79 mThread(thread),
80 mClient(client),
81 mCblk(NULL),
82 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080083 mState(IDLE),
84 mSampleRate(sampleRate),
85 mFormat(format),
86 mChannelMask(channelMask),
Andy Hunge5412692014-05-16 11:25:07 -070087 mChannelCount(isOut ?
88 audio_channel_count_from_out_mask(channelMask) :
89 audio_channel_count_from_in_mask(channelMask)),
Eric Laurent81784c32012-11-19 14:55:58 -080090 mFrameSize(audio_is_linear_pcm(format) ?
91 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
92 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080093 mSessionId(sessionId),
Glenn Kasten755b0a62014-05-13 11:30:28 -070094 mFlags(flags),
Glenn Kastene3aa6592012-12-04 12:22:46 -080095 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080096 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080097 mId(android_atomic_inc(&nextTrackId)),
Eric Laurent83b88082014-06-20 18:31:16 -070098 mTerminated(false),
Eric Laurentaaa44472014-09-12 17:41:50 -070099 mType(type),
100 mThreadIoHandle(thread->id())
Eric Laurent81784c32012-11-19 14:55:58 -0800101{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800102 // if the caller is us, trust the specified uid
103 if (IPCThreadState::self()->getCallingPid() != getpid_cached || clientUid == -1) {
104 int newclientUid = IPCThreadState::self()->getCallingUid();
105 if (clientUid != -1 && clientUid != newclientUid) {
106 ALOGW("uid %d tried to pass itself off as %d", newclientUid, clientUid);
107 }
108 clientUid = newclientUid;
109 }
110 // clientUid contains the uid of the app that is responsible for this track, so we can blame
111 // battery usage on it.
112 mUid = clientUid;
113
Eric Laurent81784c32012-11-19 14:55:58 -0800114 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
115 size_t size = sizeof(audio_track_cblk_t);
Eric Laurent83b88082014-06-20 18:31:16 -0700116 size_t bufferSize = (buffer == NULL ? roundup(frameCount) : frameCount) * mFrameSize;
117 if (buffer == NULL && alloc == ALLOC_CBLK) {
Eric Laurent81784c32012-11-19 14:55:58 -0800118 size += bufferSize;
119 }
120
121 if (client != 0) {
122 mCblkMemory = client->heap()->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -0700123 if (mCblkMemory == 0 ||
124 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -0800125 ALOGE("not enough memory for AudioTrack size=%u", size);
126 client->heap()->dump("AudioTrack");
Glenn Kasten663c2242013-09-24 11:52:37 -0700127 mCblkMemory.clear();
Eric Laurent81784c32012-11-19 14:55:58 -0800128 return;
129 }
130 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800131 // this syntax avoids calling the audio_track_cblk_t constructor twice
132 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800133 // assume mCblk != NULL
134 }
135
136 // construct the shared structure in-place.
137 if (mCblk != NULL) {
138 new(mCblk) audio_track_cblk_t();
Glenn Kastenc263ca02014-06-04 20:31:46 -0700139 switch (alloc) {
140 case ALLOC_READONLY: {
Glenn Kastend776ac62014-05-07 09:16:09 -0700141 const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
142 if (roHeap == 0 ||
143 (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
144 (mBuffer = mBufferMemory->pointer()) == NULL) {
145 ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
146 if (roHeap != 0) {
147 roHeap->dump("buffer");
148 }
149 mCblkMemory.clear();
150 mBufferMemory.clear();
151 return;
152 }
Eric Laurent81784c32012-11-19 14:55:58 -0800153 memset(mBuffer, 0, bufferSize);
Glenn Kastenc263ca02014-06-04 20:31:46 -0700154 } break;
155 case ALLOC_PIPE:
156 mBufferMemory = thread->pipeMemory();
157 // mBuffer is the virtual address as seen from current process (mediaserver),
158 // and should normally be coming from mBufferMemory->pointer().
159 // However in this case the TrackBase does not reference the buffer directly.
160 // It should references the buffer via the pipe.
161 // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
162 mBuffer = NULL;
163 break;
164 case ALLOC_CBLK:
Glenn Kastend776ac62014-05-07 09:16:09 -0700165 // clear all buffers
Eric Laurent83b88082014-06-20 18:31:16 -0700166 if (buffer == NULL) {
Glenn Kastend776ac62014-05-07 09:16:09 -0700167 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
168 memset(mBuffer, 0, bufferSize);
169 } else {
Eric Laurent83b88082014-06-20 18:31:16 -0700170 mBuffer = buffer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800171#if 0
Glenn Kastend776ac62014-05-07 09:16:09 -0700172 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800173#endif
Glenn Kastend776ac62014-05-07 09:16:09 -0700174 }
Glenn Kastenc263ca02014-06-04 20:31:46 -0700175 break;
Eric Laurent83b88082014-06-20 18:31:16 -0700176 case ALLOC_LOCAL:
177 mBuffer = calloc(1, bufferSize);
178 break;
179 case ALLOC_NONE:
180 mBuffer = buffer;
181 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800182 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800183
Glenn Kasten46909e72013-02-26 09:20:22 -0800184#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800185 if (mTeeSinkTrackEnabled) {
Glenn Kasten329f6512014-08-28 16:23:16 -0700186 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800187 if (Format_isValid(pipeFormat)) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800188 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
189 size_t numCounterOffers = 0;
190 const NBAIO_Format offers[1] = {pipeFormat};
191 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
192 ALOG_ASSERT(index == 0);
193 PipeReader *pipeReader = new PipeReader(*pipe);
194 numCounterOffers = 0;
195 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
196 ALOG_ASSERT(index == 0);
197 mTeeSink = pipe;
198 mTeeSource = pipeReader;
199 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800200 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800201#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800202
Eric Laurent81784c32012-11-19 14:55:58 -0800203 }
204}
205
Eric Laurent83b88082014-06-20 18:31:16 -0700206status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
207{
208 status_t status;
209 if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
210 status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
211 } else {
212 status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
213 }
214 return status;
215}
216
Eric Laurent81784c32012-11-19 14:55:58 -0800217AudioFlinger::ThreadBase::TrackBase::~TrackBase()
218{
Glenn Kasten46909e72013-02-26 09:20:22 -0800219#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800220 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800221#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800222 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
223 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800224 if (mCblk != NULL) {
225 if (mClient == 0) {
226 delete mCblk;
227 } else {
228 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
229 }
230 }
231 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
232 if (mClient != 0) {
Eric Laurent021cf962014-05-13 10:18:14 -0700233 // Client destructor must run with AudioFlinger client mutex locked
234 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800235 // If the client's reference count drops to zero, the associated destructor
236 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
237 // relying on the automatic clear() at end of scope.
238 mClient.clear();
239 }
Eric Laurent3bcffa12014-06-12 18:38:45 -0700240 // flush the binder command buffer
241 IPCThreadState::self()->flushCommands();
Eric Laurent81784c32012-11-19 14:55:58 -0800242}
243
244// AudioBufferProvider interface
245// getNextBuffer() = 0;
246// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
247void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
248{
Glenn Kasten46909e72013-02-26 09:20:22 -0800249#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800250 if (mTeeSink != 0) {
251 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
252 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800253#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800254
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800255 ServerProxy::Buffer buf;
256 buf.mFrameCount = buffer->frameCount;
257 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800258 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800259 buffer->raw = NULL;
260 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800261}
262
Eric Laurent81784c32012-11-19 14:55:58 -0800263status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
264{
265 mSyncEvents.add(event);
266 return NO_ERROR;
267}
268
269// ----------------------------------------------------------------------------
270// Playback
271// ----------------------------------------------------------------------------
272
273AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
274 : BnAudioTrack(),
275 mTrack(track)
276{
277}
278
279AudioFlinger::TrackHandle::~TrackHandle() {
280 // just stop the track on deletion, associated resources
281 // will be freed from the main thread once all pending buffers have
282 // been played. Unless it's not in the active track list, in which
283 // case we free everything now...
284 mTrack->destroy();
285}
286
287sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
288 return mTrack->getCblk();
289}
290
291status_t AudioFlinger::TrackHandle::start() {
292 return mTrack->start();
293}
294
295void AudioFlinger::TrackHandle::stop() {
296 mTrack->stop();
297}
298
299void AudioFlinger::TrackHandle::flush() {
300 mTrack->flush();
301}
302
Eric Laurent81784c32012-11-19 14:55:58 -0800303void AudioFlinger::TrackHandle::pause() {
304 mTrack->pause();
305}
306
307status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
308{
309 return mTrack->attachAuxEffect(EffectId);
310}
311
312status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
313 sp<IMemory>* buffer) {
314 if (!mTrack->isTimedTrack())
315 return INVALID_OPERATION;
316
317 PlaybackThread::TimedTrack* tt =
318 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
319 return tt->allocateTimedBuffer(size, buffer);
320}
321
322status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
323 int64_t pts) {
324 if (!mTrack->isTimedTrack())
325 return INVALID_OPERATION;
326
Glenn Kasten663c2242013-09-24 11:52:37 -0700327 if (buffer == 0 || buffer->pointer() == NULL) {
328 ALOGE("queueTimedBuffer() buffer is 0 or has NULL pointer()");
329 return BAD_VALUE;
330 }
331
Eric Laurent81784c32012-11-19 14:55:58 -0800332 PlaybackThread::TimedTrack* tt =
333 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
334 return tt->queueTimedBuffer(buffer, pts);
335}
336
337status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
338 const LinearTransform& xform, int target) {
339
340 if (!mTrack->isTimedTrack())
341 return INVALID_OPERATION;
342
343 PlaybackThread::TimedTrack* tt =
344 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
345 return tt->setMediaTimeTransform(
346 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
347}
348
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700349status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
350 return mTrack->setParameters(keyValuePairs);
351}
352
Glenn Kasten53cec222013-08-29 09:01:02 -0700353status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
354{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700355 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700356}
357
Eric Laurent59fe0102013-09-27 18:48:26 -0700358
359void AudioFlinger::TrackHandle::signal()
360{
361 return mTrack->signal();
362}
363
Eric Laurent81784c32012-11-19 14:55:58 -0800364status_t AudioFlinger::TrackHandle::onTransact(
365 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
366{
367 return BnAudioTrack::onTransact(code, data, reply, flags);
368}
369
370// ----------------------------------------------------------------------------
371
372// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
373AudioFlinger::PlaybackThread::Track::Track(
374 PlaybackThread *thread,
375 const sp<Client>& client,
376 audio_stream_type_t streamType,
377 uint32_t sampleRate,
378 audio_format_t format,
379 audio_channel_mask_t channelMask,
380 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700381 void *buffer,
Eric Laurent81784c32012-11-19 14:55:58 -0800382 const sp<IMemory>& sharedBuffer,
383 int sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800384 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -0700385 IAudioFlinger::track_flags_t flags,
386 track_type type)
387 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
388 (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
389 sessionId, uid, flags, true /*isOut*/,
390 (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
391 type),
Eric Laurent81784c32012-11-19 14:55:58 -0800392 mFillingUpStatus(FS_INVALID),
393 // mRetryCount initialized later when needed
394 mSharedBuffer(sharedBuffer),
395 mStreamType(streamType),
396 mName(-1), // see note below
397 mMainBuffer(thread->mixBuffer()),
398 mAuxBuffer(NULL),
399 mAuxEffectId(0), mHasVolumeController(false),
400 mPresentationCompleteFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -0800401 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800402 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800403 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800404 mAudioTrackServerProxy(NULL),
Haynes Mathew George7844f672014-01-15 12:32:55 -0800405 mResumeToStopping(false),
Glenn Kastenced6e742014-06-09 17:12:32 -0700406 mFlushHwPending(false),
407 mPreviousValid(false),
408 mPreviousFramesWritten(0)
409 // mPreviousTimestamp
Eric Laurent81784c32012-11-19 14:55:58 -0800410{
Eric Laurent83b88082014-06-20 18:31:16 -0700411 // client == 0 implies sharedBuffer == 0
412 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
413
414 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
415 sharedBuffer->size());
416
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700417 if (mCblk == NULL) {
418 return;
Eric Laurent81784c32012-11-19 14:55:58 -0800419 }
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700420
421 if (sharedBuffer == 0) {
422 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700423 mFrameSize, !isExternalTrack(), sampleRate);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700424 } else {
425 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
426 mFrameSize);
427 }
428 mServerProxy = mAudioTrackServerProxy;
429
Glenn Kastenc263ca02014-06-04 20:31:46 -0700430 mName = thread->getTrackName_l(channelMask, format, sessionId);
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700431 if (mName < 0) {
432 ALOGE("no more track names available");
433 return;
434 }
435 // only allocate a fast track index if we were able to allocate a normal track name
436 if (flags & IAudioFlinger::TRACK_FAST) {
437 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
438 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
439 int i = __builtin_ctz(thread->mFastTrackAvailMask);
440 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
441 // FIXME This is too eager. We allocate a fast track index before the
442 // fast track becomes active. Since fast tracks are a scarce resource,
443 // this means we are potentially denying other more important fast tracks from
444 // being created. It would be better to allocate the index dynamically.
445 mFastIndex = i;
446 // Read the initial underruns because this field is never cleared by the fast mixer
447 mObservedUnderruns = thread->getFastTrackUnderruns(i);
448 thread->mFastTrackAvailMask &= ~(1 << i);
449 }
Eric Laurent81784c32012-11-19 14:55:58 -0800450}
451
452AudioFlinger::PlaybackThread::Track::~Track()
453{
454 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700455
456 // The destructor would clear mSharedBuffer,
457 // but it will not push the decremented reference count,
458 // leaving the client's IMemory dangling indefinitely.
459 // This prevents that leak.
460 if (mSharedBuffer != 0) {
461 mSharedBuffer.clear();
Glenn Kasten0c72b242013-09-11 09:14:16 -0700462 }
Eric Laurent81784c32012-11-19 14:55:58 -0800463}
464
Glenn Kasten03003332013-08-06 15:40:54 -0700465status_t AudioFlinger::PlaybackThread::Track::initCheck() const
466{
467 status_t status = TrackBase::initCheck();
468 if (status == NO_ERROR && mName < 0) {
469 status = NO_MEMORY;
470 }
471 return status;
472}
473
Eric Laurent81784c32012-11-19 14:55:58 -0800474void AudioFlinger::PlaybackThread::Track::destroy()
475{
476 // NOTE: destroyTrack_l() can remove a strong reference to this Track
477 // by removing it from mTracks vector, so there is a risk that this Tracks's
478 // destructor is called. As the destructor needs to lock mLock,
479 // we must acquire a strong reference on this Track before locking mLock
480 // here so that the destructor is called only when exiting this function.
481 // On the other hand, as long as Track::destroy() is only called by
482 // TrackHandle destructor, the TrackHandle still holds a strong ref on
483 // this Track with its member mTrack.
484 sp<Track> keep(this);
485 { // scope for mLock
Eric Laurentaaa44472014-09-12 17:41:50 -0700486 bool wasActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -0800487 sp<ThreadBase> thread = mThread.promote();
488 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800489 Mutex::Autolock _l(thread->mLock);
490 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaaa44472014-09-12 17:41:50 -0700491 wasActive = playbackThread->destroyTrack_l(this);
492 }
493 if (isExternalTrack() && !wasActive) {
494 AudioSystem::releaseOutput(mThreadIoHandle);
Eric Laurent81784c32012-11-19 14:55:58 -0800495 }
496 }
497}
498
499/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
500{
Marco Nelissenb2208842014-02-07 14:00:50 -0800501 result.append(" Name Active Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700502 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800503}
504
Marco Nelissenb2208842014-02-07 14:00:50 -0800505void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -0800506{
Glenn Kastenc56f3422014-03-21 17:53:17 -0700507 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800508 if (isFastTrack()) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800509 sprintf(buffer, " F %2d", mFastIndex);
510 } else if (mName >= AudioMixer::TRACK0) {
511 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
Eric Laurent81784c32012-11-19 14:55:58 -0800512 } else {
Marco Nelissenb2208842014-02-07 14:00:50 -0800513 sprintf(buffer, " none");
Eric Laurent81784c32012-11-19 14:55:58 -0800514 }
515 track_state state = mState;
516 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800517 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800518 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800519 } else {
520 switch (state) {
521 case IDLE:
522 stateChar = 'I';
523 break;
524 case STOPPING_1:
525 stateChar = 's';
526 break;
527 case STOPPING_2:
528 stateChar = '5';
529 break;
530 case STOPPED:
531 stateChar = 'S';
532 break;
533 case RESUMING:
534 stateChar = 'R';
535 break;
536 case ACTIVE:
537 stateChar = 'A';
538 break;
539 case PAUSING:
540 stateChar = 'p';
541 break;
542 case PAUSED:
543 stateChar = 'P';
544 break;
545 case FLUSHED:
546 stateChar = 'F';
547 break;
548 default:
549 stateChar = '?';
550 break;
551 }
Eric Laurent81784c32012-11-19 14:55:58 -0800552 }
553 char nowInUnderrun;
554 switch (mObservedUnderruns.mBitFields.mMostRecent) {
555 case UNDERRUN_FULL:
556 nowInUnderrun = ' ';
557 break;
558 case UNDERRUN_PARTIAL:
559 nowInUnderrun = '<';
560 break;
561 case UNDERRUN_EMPTY:
562 nowInUnderrun = '*';
563 break;
564 default:
565 nowInUnderrun = '?';
566 break;
567 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000568 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 +0000569 "%08X %p %p 0x%03X %9u%c\n",
Marco Nelissenb2208842014-02-07 14:00:50 -0800570 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -0800571 (mClient == 0) ? getpid_cached : mClient->pid(),
572 mStreamType,
573 mFormat,
574 mChannelMask,
575 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800576 mFrameCount,
577 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800578 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800579 mAudioTrackServerProxy->getSampleRate(),
Glenn Kastenc56f3422014-03-21 17:53:17 -0700580 20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
581 20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700582 mCblk->mServer,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000583 mMainBuffer,
584 mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700585 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700586 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800587 nowInUnderrun);
588}
589
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800590uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
591 return mAudioTrackServerProxy->getSampleRate();
592}
593
Eric Laurent81784c32012-11-19 14:55:58 -0800594// AudioBufferProvider interface
595status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kasten0f11b512014-01-31 16:18:54 -0800596 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800597{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800598 ServerProxy::Buffer buf;
599 size_t desiredFrames = buffer->frameCount;
600 buf.mFrameCount = desiredFrames;
601 status_t status = mServerProxy->obtainBuffer(&buf);
602 buffer->frameCount = buf.mFrameCount;
603 buffer->raw = buf.mRaw;
604 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700605 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800606 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800607 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800608}
609
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700610// releaseBuffer() is not overridden
611
612// ExtendedAudioBufferProvider interface
613
Eric Laurent81784c32012-11-19 14:55:58 -0800614// Note that framesReady() takes a mutex on the control block using tryLock().
615// This could result in priority inversion if framesReady() is called by the normal mixer,
616// as the normal mixer thread runs at lower
617// priority than the client's callback thread: there is a short window within framesReady()
618// during which the normal mixer could be preempted, and the client callback would block.
619// Another problem can occur if framesReady() is called by the fast mixer:
620// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
621// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
622size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800623 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800624}
625
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700626size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
627{
628 return mAudioTrackServerProxy->framesReleased();
629}
630
Eric Laurent81784c32012-11-19 14:55:58 -0800631// Don't call for fast tracks; the framesReady() could result in priority inversion
632bool AudioFlinger::PlaybackThread::Track::isReady() const {
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800633 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
634 return true;
635 }
636
Eric Laurent16498512014-03-17 17:22:08 -0700637 if (isStopping()) {
638 if (framesReady() > 0) {
639 mFillingUpStatus = FS_FILLED;
640 }
Eric Laurent81784c32012-11-19 14:55:58 -0800641 return true;
642 }
643
644 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700645 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800646 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700647 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800648 return true;
649 }
650 return false;
651}
652
Glenn Kasten0f11b512014-01-31 16:18:54 -0800653status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
654 int triggerSession __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800655{
656 status_t status = NO_ERROR;
657 ALOGV("start(%d), calling pid %d session %d",
658 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
659
660 sp<ThreadBase> thread = mThread.promote();
661 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700662 if (isOffloaded()) {
663 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
664 Mutex::Autolock _lth(thread->mLock);
665 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700666 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
667 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700668 invalidate();
669 return PERMISSION_DENIED;
670 }
671 }
672 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800673 track_state state = mState;
674 // here the track could be either new, or restarted
675 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800676
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -0800677 // initial state-stopping. next state-pausing.
678 // What if resume is called ?
679
680 if (state == PAUSED || state == PAUSING) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800681 if (mResumeToStopping) {
682 // happened we need to resume to STOPPING_1
683 mState = TrackBase::STOPPING_1;
684 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
685 } else {
686 mState = TrackBase::RESUMING;
687 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
688 }
Eric Laurent81784c32012-11-19 14:55:58 -0800689 } else {
690 mState = TrackBase::ACTIVE;
691 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
692 }
693
Eric Laurentbfb1b832013-01-07 09:53:42 -0800694 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
695 status = playbackThread->addTrack_l(this);
696 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800697 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800698 // restore previous state if start was rejected by policy manager
699 if (status == PERMISSION_DENIED) {
700 mState = state;
701 }
702 }
703 // track was already in the active list, not a problem
704 if (status == ALREADY_EXISTS) {
705 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700706 } else {
707 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
708 // It is usually unsafe to access the server proxy from a binder thread.
709 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
710 // isn't looking at this track yet: we still hold the normal mixer thread lock,
711 // and for fast tracks the track is not yet in the fast mixer thread's active set.
712 ServerProxy::Buffer buffer;
713 buffer.mFrameCount = 1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700714 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800715 }
716 } else {
717 status = BAD_VALUE;
718 }
719 return status;
720}
721
722void AudioFlinger::PlaybackThread::Track::stop()
723{
724 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
725 sp<ThreadBase> thread = mThread.promote();
726 if (thread != 0) {
727 Mutex::Autolock _l(thread->mLock);
728 track_state state = mState;
729 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
730 // If the track is not active (PAUSED and buffers full), flush buffers
731 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
732 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
733 reset();
734 mState = STOPPED;
Eric Laurentab5cdba2014-06-09 17:22:27 -0700735 } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800736 mState = STOPPED;
737 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800738 // For fast tracks prepareTracks_l() will set state to STOPPING_2
739 // presentation is complete
740 // For an offloaded track this starts a drain and state will
741 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800742 mState = STOPPING_1;
743 }
744 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
745 playbackThread);
746 }
Eric Laurent81784c32012-11-19 14:55:58 -0800747 }
748}
749
750void AudioFlinger::PlaybackThread::Track::pause()
751{
752 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
753 sp<ThreadBase> thread = mThread.promote();
754 if (thread != 0) {
755 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800756 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
757 switch (mState) {
758 case STOPPING_1:
759 case STOPPING_2:
760 if (!isOffloaded()) {
761 /* nothing to do if track is not offloaded */
762 break;
763 }
764
765 // Offloaded track was draining, we need to carry on draining when resumed
766 mResumeToStopping = true;
767 // fall through...
768 case ACTIVE:
769 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800770 mState = PAUSING;
771 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700772 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800773 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800774
Eric Laurentbfb1b832013-01-07 09:53:42 -0800775 default:
776 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800777 }
778 }
779}
780
781void AudioFlinger::PlaybackThread::Track::flush()
782{
783 ALOGV("flush(%d)", mName);
784 sp<ThreadBase> thread = mThread.promote();
785 if (thread != 0) {
786 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800787 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800788
789 if (isOffloaded()) {
790 // If offloaded we allow flush during any state except terminated
791 // and keep the track active to avoid problems if user is seeking
792 // rapidly and underlying hardware has a significant delay handling
793 // a pause
794 if (isTerminated()) {
795 return;
796 }
797
798 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800799 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800800
801 if (mState == STOPPING_1 || mState == STOPPING_2) {
802 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
803 mState = ACTIVE;
804 }
805
806 if (mState == ACTIVE) {
807 ALOGV("flush called in active state, resetting buffer time out retry count");
808 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
809 }
810
Haynes Mathew George7844f672014-01-15 12:32:55 -0800811 mFlushHwPending = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800812 mResumeToStopping = false;
813 } else {
814 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
815 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
816 return;
817 }
818 // No point remaining in PAUSED state after a flush => go to
819 // FLUSHED state
820 mState = FLUSHED;
821 // do not reset the track if it is still in the process of being stopped or paused.
822 // this will be done by prepareTracks_l() when the track is stopped.
823 // prepareTracks_l() will see mState == FLUSHED, then
824 // remove from active track list, reset(), and trigger presentation complete
825 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
826 reset();
Eric Laurente659ef42014-09-29 13:06:46 -0700827 if (thread->type() == ThreadBase::DIRECT) {
828 DirectOutputThread *t = (DirectOutputThread *)playbackThread;
829 t->flushHw_l();
830 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800831 }
Eric Laurent81784c32012-11-19 14:55:58 -0800832 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800833 // Prevent flush being lost if the track is flushed and then resumed
834 // before mixer thread can run. This is important when offloading
835 // because the hardware buffer could hold a large amount of audio
Eric Laurentede6c3b2013-09-19 14:37:46 -0700836 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800837 }
838}
839
Haynes Mathew George7844f672014-01-15 12:32:55 -0800840// must be called with thread lock held
841void AudioFlinger::PlaybackThread::Track::flushAck()
842{
843 if (!isOffloaded())
844 return;
845
846 mFlushHwPending = false;
847}
848
Eric Laurent81784c32012-11-19 14:55:58 -0800849void AudioFlinger::PlaybackThread::Track::reset()
850{
851 // Do not reset twice to avoid discarding data written just after a flush and before
852 // the audioflinger thread detects the track is stopped.
853 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800854 // Force underrun condition to avoid false underrun callback until first data is
855 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700856 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800857 mFillingUpStatus = FS_FILLING;
858 mResetDone = true;
859 if (mState == FLUSHED) {
860 mState = IDLE;
861 }
862 }
863}
864
Eric Laurentbfb1b832013-01-07 09:53:42 -0800865status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
866{
867 sp<ThreadBase> thread = mThread.promote();
868 if (thread == 0) {
869 ALOGE("thread is dead");
870 return FAILED_TRANSACTION;
871 } else if ((thread->type() == ThreadBase::DIRECT) ||
872 (thread->type() == ThreadBase::OFFLOAD)) {
873 return thread->setParameters(keyValuePairs);
874 } else {
875 return PERMISSION_DENIED;
876 }
877}
878
Glenn Kasten573d80a2013-08-26 09:36:23 -0700879status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
880{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700881 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
882 if (isFastTrack()) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700883 // FIXME no lock held to set mPreviousValid = false
Glenn Kastenfe346c72013-08-30 13:28:22 -0700884 return INVALID_OPERATION;
885 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700886 sp<ThreadBase> thread = mThread.promote();
887 if (thread == 0) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700888 // FIXME no lock held to set mPreviousValid = false
Glenn Kastenfe346c72013-08-30 13:28:22 -0700889 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700890 }
891 Mutex::Autolock _l(thread->mLock);
892 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentab5cdba2014-06-09 17:22:27 -0700893 if (!isOffloaded() && !isDirect()) {
Eric Laurentaccc1472013-09-20 09:36:34 -0700894 if (!playbackThread->mLatchQValid) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700895 mPreviousValid = false;
Eric Laurentaccc1472013-09-20 09:36:34 -0700896 return INVALID_OPERATION;
897 }
898 uint32_t unpresentedFrames =
899 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
900 playbackThread->mSampleRate;
Glenn Kasten54464ba2014-09-28 14:41:07 -0700901 // FIXME Since we're using a raw pointer as the key, it is theoretically possible
902 // for a brand new track to share the same address as a recently destroyed
903 // track, and thus for us to get the frames released of the wrong track.
904 // It is unlikely that we would be able to call getTimestamp() so quickly
905 // right after creating a new track. Nevertheless, the index here should
906 // be changed to something that is unique. Or use a completely different strategy.
907 ssize_t i = playbackThread->mLatchQ.mFramesReleased.indexOfKey(this);
908 uint32_t framesWritten = i >= 0 ?
909 playbackThread->mLatchQ.mFramesReleased[i] : mAudioTrackServerProxy->framesReleased();
Glenn Kastenced6e742014-06-09 17:12:32 -0700910 bool checkPreviousTimestamp = mPreviousValid && framesWritten >= mPreviousFramesWritten;
Eric Laurentaccc1472013-09-20 09:36:34 -0700911 if (framesWritten < unpresentedFrames) {
Glenn Kastenced6e742014-06-09 17:12:32 -0700912 mPreviousValid = false;
Eric Laurentaccc1472013-09-20 09:36:34 -0700913 return INVALID_OPERATION;
914 }
Glenn Kastenced6e742014-06-09 17:12:32 -0700915 mPreviousFramesWritten = framesWritten;
916 uint32_t position = framesWritten - unpresentedFrames;
917 struct timespec time = playbackThread->mLatchQ.mTimestamp.mTime;
918 if (checkPreviousTimestamp) {
919 if (time.tv_sec < mPreviousTimestamp.mTime.tv_sec ||
920 (time.tv_sec == mPreviousTimestamp.mTime.tv_sec &&
921 time.tv_nsec < mPreviousTimestamp.mTime.tv_nsec)) {
922 ALOGW("Time is going backwards");
923 }
924 // position can bobble slightly as an artifact; this hides the bobble
925 static const uint32_t MINIMUM_POSITION_DELTA = 8u;
926 if ((position <= mPreviousTimestamp.mPosition) ||
927 (position - mPreviousTimestamp.mPosition) < MINIMUM_POSITION_DELTA) {
928 position = mPreviousTimestamp.mPosition;
929 time = mPreviousTimestamp.mTime;
930 }
931 }
932 timestamp.mPosition = position;
933 timestamp.mTime = time;
934 mPreviousTimestamp = timestamp;
935 mPreviousValid = true;
Eric Laurentaccc1472013-09-20 09:36:34 -0700936 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700937 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700938
939 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700940}
941
Eric Laurent81784c32012-11-19 14:55:58 -0800942status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
943{
944 status_t status = DEAD_OBJECT;
945 sp<ThreadBase> thread = mThread.promote();
946 if (thread != 0) {
947 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
948 sp<AudioFlinger> af = mClient->audioFlinger();
949
950 Mutex::Autolock _l(af->mLock);
951
952 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
953
954 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
955 Mutex::Autolock _dl(playbackThread->mLock);
956 Mutex::Autolock _sl(srcThread->mLock);
957 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
958 if (chain == 0) {
959 return INVALID_OPERATION;
960 }
961
962 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
963 if (effect == 0) {
964 return INVALID_OPERATION;
965 }
966 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700967 status = playbackThread->addEffect_l(effect);
968 if (status != NO_ERROR) {
969 srcThread->addEffect_l(effect);
970 return INVALID_OPERATION;
971 }
Eric Laurent81784c32012-11-19 14:55:58 -0800972 // removeEffect_l() has stopped the effect if it was active so it must be restarted
973 if (effect->state() == EffectModule::ACTIVE ||
974 effect->state() == EffectModule::STOPPING) {
975 effect->start();
976 }
977
978 sp<EffectChain> dstChain = effect->chain().promote();
979 if (dstChain == 0) {
980 srcThread->addEffect_l(effect);
981 return INVALID_OPERATION;
982 }
983 AudioSystem::unregisterEffect(effect->id());
984 AudioSystem::registerEffect(&effect->desc(),
985 srcThread->id(),
986 dstChain->strategy(),
987 AUDIO_SESSION_OUTPUT_MIX,
988 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -0700989 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent81784c32012-11-19 14:55:58 -0800990 }
991 status = playbackThread->attachAuxEffect(this, EffectId);
992 }
993 return status;
994}
995
996void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
997{
998 mAuxEffectId = EffectId;
999 mAuxBuffer = buffer;
1000}
1001
1002bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
1003 size_t audioHalFrames)
1004{
1005 // a track is considered presented when the total number of frames written to audio HAL
1006 // corresponds to the number of frames written when presentationComplete() is called for the
1007 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001008 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1009 // to detect when all frames have been played. In this case framesWritten isn't
1010 // useful because it doesn't always reflect whether there is data in the h/w
1011 // buffers, particularly if a track has been paused and resumed during draining
1012 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
1013 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -08001014 if (mPresentationCompleteFrames == 0) {
1015 mPresentationCompleteFrames = framesWritten + audioHalFrames;
1016 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
1017 mPresentationCompleteFrames, audioHalFrames);
1018 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001019
1020 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001021 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001022 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -08001023 return true;
1024 }
1025 return false;
1026}
1027
1028void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1029{
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001030 for (size_t i = 0; i < mSyncEvents.size(); i++) {
Eric Laurent81784c32012-11-19 14:55:58 -08001031 if (mSyncEvents[i]->type() == type) {
1032 mSyncEvents[i]->trigger();
1033 mSyncEvents.removeAt(i);
1034 i--;
1035 }
1036 }
1037}
1038
1039// implement VolumeBufferProvider interface
1040
Glenn Kastenc56f3422014-03-21 17:53:17 -07001041gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
Eric Laurent81784c32012-11-19 14:55:58 -08001042{
1043 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1044 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kastenc56f3422014-03-21 17:53:17 -07001045 gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1046 float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1047 float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08001048 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07001049 if (vl > GAIN_FLOAT_UNITY) {
1050 vl = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001051 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07001052 if (vr > GAIN_FLOAT_UNITY) {
1053 vr = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08001054 }
1055 // now apply the cached master volume and stream type volume;
1056 // this is trusted but lacks any synchronization or barrier so may be stale
1057 float v = mCachedVolume;
1058 vl *= v;
1059 vr *= v;
Glenn Kastenc56f3422014-03-21 17:53:17 -07001060 // re-combine into packed minifloat
1061 vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
Eric Laurent81784c32012-11-19 14:55:58 -08001062 // FIXME look at mute, pause, and stop flags
1063 return vlr;
1064}
1065
1066status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1067{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001068 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -08001069 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1070 (mState == STOPPED)))) {
1071 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1072 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1073 event->cancel();
1074 return INVALID_OPERATION;
1075 }
1076 (void) TrackBase::setSyncEvent(event);
1077 return NO_ERROR;
1078}
1079
Glenn Kasten5736c352012-12-04 12:12:34 -08001080void AudioFlinger::PlaybackThread::Track::invalidate()
1081{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001082 // FIXME should use proxy, and needs work
1083 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001084 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001085 android_atomic_release_store(0x40000000, &cblk->mFutex);
1086 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07001087 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001088 mIsInvalid = true;
1089}
1090
Eric Laurent59fe0102013-09-27 18:48:26 -07001091void AudioFlinger::PlaybackThread::Track::signal()
1092{
1093 sp<ThreadBase> thread = mThread.promote();
1094 if (thread != 0) {
1095 PlaybackThread *t = (PlaybackThread *)thread.get();
1096 Mutex::Autolock _l(t->mLock);
1097 t->broadcast_l();
1098 }
1099}
1100
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001101//To be called with thread lock held
1102bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1103
1104 if (mState == RESUMING)
1105 return true;
1106 /* Resume is pending if track was stopping before pause was called */
1107 if (mState == STOPPING_1 &&
1108 mResumeToStopping)
1109 return true;
1110
1111 return false;
1112}
1113
1114//To be called with thread lock held
1115void AudioFlinger::PlaybackThread::Track::resumeAck() {
1116
1117
1118 if (mState == RESUMING)
1119 mState = ACTIVE;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001120
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001121 // Other possibility of pending resume is stopping_1 state
1122 // Do not update the state from stopping as this prevents
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08001123 // drain being called.
1124 if (mState == STOPPING_1) {
1125 mResumeToStopping = false;
1126 }
Krishnankutty Kolathappilly8d6c2922014-02-04 16:23:42 -08001127}
Eric Laurent81784c32012-11-19 14:55:58 -08001128// ----------------------------------------------------------------------------
1129
1130sp<AudioFlinger::PlaybackThread::TimedTrack>
1131AudioFlinger::PlaybackThread::TimedTrack::create(
1132 PlaybackThread *thread,
1133 const sp<Client>& client,
1134 audio_stream_type_t streamType,
1135 uint32_t sampleRate,
1136 audio_format_t format,
1137 audio_channel_mask_t channelMask,
1138 size_t frameCount,
1139 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001140 int sessionId,
Glenn Kasten4944acb2013-08-19 08:39:20 -07001141 int uid)
1142{
Eric Laurent81784c32012-11-19 14:55:58 -08001143 if (!client->reserveTimedTrack())
1144 return 0;
1145
1146 return new TimedTrack(
1147 thread, client, streamType, sampleRate, format, channelMask, frameCount,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001148 sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001149}
1150
1151AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1152 PlaybackThread *thread,
1153 const sp<Client>& client,
1154 audio_stream_type_t streamType,
1155 uint32_t sampleRate,
1156 audio_format_t format,
1157 audio_channel_mask_t channelMask,
1158 size_t frameCount,
1159 const sp<IMemory>& sharedBuffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001160 int sessionId,
1161 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001162 : Track(thread, client, streamType, sampleRate, format, channelMask,
Eric Laurent83b88082014-06-20 18:31:16 -07001163 frameCount, (sharedBuffer != 0) ? sharedBuffer->pointer() : NULL, sharedBuffer,
1164 sessionId, uid, IAudioFlinger::TRACK_TIMED, TYPE_TIMED),
Eric Laurent81784c32012-11-19 14:55:58 -08001165 mQueueHeadInFlight(false),
1166 mTrimQueueHeadOnRelease(false),
1167 mFramesPendingInQueue(0),
1168 mTimedSilenceBuffer(NULL),
1169 mTimedSilenceBufferSize(0),
1170 mTimedAudioOutputOnTime(false),
1171 mMediaTimeTransformValid(false)
1172{
1173 LocalClock lc;
1174 mLocalTimeFreq = lc.getLocalFreq();
1175
1176 mLocalTimeToSampleTransform.a_zero = 0;
1177 mLocalTimeToSampleTransform.b_zero = 0;
1178 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1179 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1180 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1181 &mLocalTimeToSampleTransform.a_to_b_denom);
1182
1183 mMediaTimeToSampleTransform.a_zero = 0;
1184 mMediaTimeToSampleTransform.b_zero = 0;
1185 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1186 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1187 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1188 &mMediaTimeToSampleTransform.a_to_b_denom);
1189}
1190
1191AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1192 mClient->releaseTimedTrack();
1193 delete [] mTimedSilenceBuffer;
1194}
1195
1196status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1197 size_t size, sp<IMemory>* buffer) {
1198
1199 Mutex::Autolock _l(mTimedBufferQueueLock);
1200
1201 trimTimedBufferQueue_l();
1202
1203 // lazily initialize the shared memory heap for timed buffers
1204 if (mTimedMemoryDealer == NULL) {
1205 const int kTimedBufferHeapSize = 512 << 10;
1206
1207 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1208 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001209 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001210 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001211 }
Eric Laurent81784c32012-11-19 14:55:58 -08001212 }
1213
1214 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten663c2242013-09-24 11:52:37 -07001215 if (newBuffer == 0 || newBuffer->pointer() == NULL) {
Glenn Kasten30ff92c2013-11-20 11:57:08 -08001216 return NO_MEMORY;
Eric Laurent81784c32012-11-19 14:55:58 -08001217 }
1218
1219 *buffer = newBuffer;
1220 return NO_ERROR;
1221}
1222
1223// caller must hold mTimedBufferQueueLock
1224void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1225 int64_t mediaTimeNow;
1226 {
1227 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1228 if (!mMediaTimeTransformValid)
1229 return;
1230
1231 int64_t targetTimeNow;
1232 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1233 ? mCCHelper.getCommonTime(&targetTimeNow)
1234 : mCCHelper.getLocalTime(&targetTimeNow);
1235
1236 if (OK != res)
1237 return;
1238
1239 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1240 &mediaTimeNow)) {
1241 return;
1242 }
1243 }
1244
1245 size_t trimEnd;
1246 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1247 int64_t bufEnd;
1248
1249 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1250 // We have a next buffer. Just use its PTS as the PTS of the frame
1251 // following the last frame in this buffer. If the stream is sparse
1252 // (ie, there are deliberate gaps left in the stream which should be
1253 // filled with silence by the TimedAudioTrack), then this can result
1254 // in one extra buffer being left un-trimmed when it could have
1255 // been. In general, this is not typical, and we would rather
1256 // optimized away the TS calculation below for the more common case
1257 // where PTSes are contiguous.
1258 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1259 } else {
1260 // We have no next buffer. Compute the PTS of the frame following
1261 // the last frame in this buffer by computing the duration of of
1262 // this frame in media time units and adding it to the PTS of the
1263 // buffer.
1264 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1265 / mFrameSize;
1266
1267 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1268 &bufEnd)) {
1269 ALOGE("Failed to convert frame count of %lld to media time"
1270 " duration" " (scale factor %d/%u) in %s",
1271 frameCount,
1272 mMediaTimeToSampleTransform.a_to_b_numer,
1273 mMediaTimeToSampleTransform.a_to_b_denom,
1274 __PRETTY_FUNCTION__);
1275 break;
1276 }
1277 bufEnd += mTimedBufferQueue[trimEnd].pts();
1278 }
1279
1280 if (bufEnd > mediaTimeNow)
1281 break;
1282
1283 // Is the buffer we want to use in the middle of a mix operation right
1284 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1285 // from the mixer which should be coming back shortly.
1286 if (!trimEnd && mQueueHeadInFlight) {
1287 mTrimQueueHeadOnRelease = true;
1288 }
1289 }
1290
1291 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1292 if (trimStart < trimEnd) {
1293 // Update the bookkeeping for framesReady()
1294 for (size_t i = trimStart; i < trimEnd; ++i) {
1295 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1296 }
1297
1298 // Now actually remove the buffers from the queue.
1299 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1300 }
1301}
1302
1303void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1304 const char* logTag) {
1305 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1306 "%s called (reason \"%s\"), but timed buffer queue has no"
1307 " elements to trim.", __FUNCTION__, logTag);
1308
1309 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1310 mTimedBufferQueue.removeAt(0);
1311}
1312
1313void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1314 const TimedBuffer& buf,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001315 const char* logTag __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08001316 uint32_t bufBytes = buf.buffer()->size();
1317 uint32_t consumedAlready = buf.position();
1318
1319 ALOG_ASSERT(consumedAlready <= bufBytes,
1320 "Bad bookkeeping while updating frames pending. Timed buffer is"
1321 " only %u bytes long, but claims to have consumed %u"
1322 " bytes. (update reason: \"%s\")",
1323 bufBytes, consumedAlready, logTag);
1324
1325 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1326 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1327 "Bad bookkeeping while updating frames pending. Should have at"
1328 " least %u queued frames, but we think we have only %u. (update"
1329 " reason: \"%s\")",
1330 bufFrames, mFramesPendingInQueue, logTag);
1331
1332 mFramesPendingInQueue -= bufFrames;
1333}
1334
1335status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1336 const sp<IMemory>& buffer, int64_t pts) {
1337
1338 {
1339 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1340 if (!mMediaTimeTransformValid)
1341 return INVALID_OPERATION;
1342 }
1343
1344 Mutex::Autolock _l(mTimedBufferQueueLock);
1345
1346 uint32_t bufFrames = buffer->size() / mFrameSize;
1347 mFramesPendingInQueue += bufFrames;
1348 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1349
1350 return NO_ERROR;
1351}
1352
1353status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1354 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1355
1356 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1357 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1358 target);
1359
1360 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1361 target == TimedAudioTrack::COMMON_TIME)) {
1362 return BAD_VALUE;
1363 }
1364
1365 Mutex::Autolock lock(mMediaTimeTransformLock);
1366 mMediaTimeTransform = xform;
1367 mMediaTimeTransformTarget = target;
1368 mMediaTimeTransformValid = true;
1369
1370 return NO_ERROR;
1371}
1372
1373#define min(a, b) ((a) < (b) ? (a) : (b))
1374
1375// implementation of getNextBuffer for tracks whose buffers have timestamps
1376status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1377 AudioBufferProvider::Buffer* buffer, int64_t pts)
1378{
1379 if (pts == AudioBufferProvider::kInvalidPTS) {
1380 buffer->raw = NULL;
1381 buffer->frameCount = 0;
1382 mTimedAudioOutputOnTime = false;
1383 return INVALID_OPERATION;
1384 }
1385
1386 Mutex::Autolock _l(mTimedBufferQueueLock);
1387
1388 ALOG_ASSERT(!mQueueHeadInFlight,
1389 "getNextBuffer called without releaseBuffer!");
1390
1391 while (true) {
1392
1393 // if we have no timed buffers, then fail
1394 if (mTimedBufferQueue.isEmpty()) {
1395 buffer->raw = NULL;
1396 buffer->frameCount = 0;
1397 return NOT_ENOUGH_DATA;
1398 }
1399
1400 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1401
1402 // calculate the PTS of the head of the timed buffer queue expressed in
1403 // local time
1404 int64_t headLocalPTS;
1405 {
1406 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1407
1408 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1409
1410 if (mMediaTimeTransform.a_to_b_denom == 0) {
1411 // the transform represents a pause, so yield silence
1412 timedYieldSilence_l(buffer->frameCount, buffer);
1413 return NO_ERROR;
1414 }
1415
1416 int64_t transformedPTS;
1417 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1418 &transformedPTS)) {
1419 // the transform failed. this shouldn't happen, but if it does
1420 // then just drop this buffer
1421 ALOGW("timedGetNextBuffer transform failed");
1422 buffer->raw = NULL;
1423 buffer->frameCount = 0;
1424 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1425 return NO_ERROR;
1426 }
1427
1428 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1429 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1430 &headLocalPTS)) {
1431 buffer->raw = NULL;
1432 buffer->frameCount = 0;
1433 return INVALID_OPERATION;
1434 }
1435 } else {
1436 headLocalPTS = transformedPTS;
1437 }
1438 }
1439
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001440 uint32_t sr = sampleRate();
1441
Eric Laurent81784c32012-11-19 14:55:58 -08001442 // adjust the head buffer's PTS to reflect the portion of the head buffer
1443 // that has already been consumed
1444 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001445 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001446
1447 // Calculate the delta in samples between the head of the input buffer
1448 // queue and the start of the next output buffer that will be written.
1449 // If the transformation fails because of over or underflow, it means
1450 // that the sample's position in the output stream is so far out of
1451 // whack that it should just be dropped.
1452 int64_t sampleDelta;
1453 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1454 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1455 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1456 " mix");
1457 continue;
1458 }
1459 if (!mLocalTimeToSampleTransform.doForwardTransform(
1460 (effectivePTS - pts) << 32, &sampleDelta)) {
1461 ALOGV("*** too late during sample rate transform: dropped buffer");
1462 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1463 continue;
1464 }
1465
1466 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1467 " sampleDelta=[%d.%08x]",
1468 head.pts(), head.position(), pts,
1469 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1470 + (sampleDelta >> 32)),
1471 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1472
1473 // if the delta between the ideal placement for the next input sample and
1474 // the current output position is within this threshold, then we will
1475 // concatenate the next input samples to the previous output
1476 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001477 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001478
1479 // if this is the first buffer of audio that we're emitting from this track
1480 // then it should be almost exactly on time.
1481 const int64_t kSampleStartupThreshold = 1LL << 32;
1482
1483 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1484 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1485 // the next input is close enough to being on time, so concatenate it
1486 // with the last output
1487 timedYieldSamples_l(buffer);
1488
1489 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1490 head.position(), buffer->frameCount);
1491 return NO_ERROR;
1492 }
1493
1494 // Looks like our output is not on time. Reset our on timed status.
1495 // Next time we mix samples from our input queue, then should be within
1496 // the StartupThreshold.
1497 mTimedAudioOutputOnTime = false;
1498 if (sampleDelta > 0) {
1499 // the gap between the current output position and the proper start of
1500 // the next input sample is too big, so fill it with silence
1501 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1502
1503 timedYieldSilence_l(framesUntilNextInput, buffer);
1504 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1505 return NO_ERROR;
1506 } else {
1507 // the next input sample is late
1508 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1509 size_t onTimeSamplePosition =
1510 head.position() + lateFrames * mFrameSize;
1511
1512 if (onTimeSamplePosition > head.buffer()->size()) {
1513 // all the remaining samples in the head are too late, so
1514 // drop it and move on
1515 ALOGV("*** too late: dropped buffer");
1516 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1517 continue;
1518 } else {
1519 // skip over the late samples
1520 head.setPosition(onTimeSamplePosition);
1521
1522 // yield the available samples
1523 timedYieldSamples_l(buffer);
1524
1525 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1526 return NO_ERROR;
1527 }
1528 }
1529 }
1530}
1531
1532// Yield samples from the timed buffer queue head up to the given output
1533// buffer's capacity.
1534//
1535// Caller must hold mTimedBufferQueueLock
1536void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1537 AudioBufferProvider::Buffer* buffer) {
1538
1539 const TimedBuffer& head = mTimedBufferQueue[0];
1540
1541 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1542 head.position());
1543
1544 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1545 mFrameSize);
1546 size_t framesRequested = buffer->frameCount;
1547 buffer->frameCount = min(framesLeftInHead, framesRequested);
1548
1549 mQueueHeadInFlight = true;
1550 mTimedAudioOutputOnTime = true;
1551}
1552
1553// Yield samples of silence up to the given output buffer's capacity
1554//
1555// Caller must hold mTimedBufferQueueLock
1556void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1557 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1558
1559 // lazily allocate a buffer filled with silence
1560 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1561 delete [] mTimedSilenceBuffer;
1562 mTimedSilenceBufferSize = numFrames * mFrameSize;
1563 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1564 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1565 }
1566
1567 buffer->raw = mTimedSilenceBuffer;
1568 size_t framesRequested = buffer->frameCount;
1569 buffer->frameCount = min(numFrames, framesRequested);
1570
1571 mTimedAudioOutputOnTime = false;
1572}
1573
1574// AudioBufferProvider interface
1575void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1576 AudioBufferProvider::Buffer* buffer) {
1577
1578 Mutex::Autolock _l(mTimedBufferQueueLock);
1579
1580 // If the buffer which was just released is part of the buffer at the head
1581 // of the queue, be sure to update the amt of the buffer which has been
1582 // consumed. If the buffer being returned is not part of the head of the
1583 // queue, its either because the buffer is part of the silence buffer, or
1584 // because the head of the timed queue was trimmed after the mixer called
1585 // getNextBuffer but before the mixer called releaseBuffer.
1586 if (buffer->raw == mTimedSilenceBuffer) {
1587 ALOG_ASSERT(!mQueueHeadInFlight,
1588 "Queue head in flight during release of silence buffer!");
1589 goto done;
1590 }
1591
1592 ALOG_ASSERT(mQueueHeadInFlight,
1593 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1594 " head in flight.");
1595
1596 if (mTimedBufferQueue.size()) {
1597 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1598
1599 void* start = head.buffer()->pointer();
1600 void* end = reinterpret_cast<void*>(
1601 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1602 + head.buffer()->size());
1603
1604 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1605 "released buffer not within the head of the timed buffer"
1606 " queue; qHead = [%p, %p], released buffer = %p",
1607 start, end, buffer->raw);
1608
1609 head.setPosition(head.position() +
1610 (buffer->frameCount * mFrameSize));
1611 mQueueHeadInFlight = false;
1612
1613 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1614 "Bad bookkeeping during releaseBuffer! Should have at"
1615 " least %u queued frames, but we think we have only %u",
1616 buffer->frameCount, mFramesPendingInQueue);
1617
1618 mFramesPendingInQueue -= buffer->frameCount;
1619
1620 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1621 || mTrimQueueHeadOnRelease) {
1622 trimTimedBufferQueueHead_l("releaseBuffer");
1623 mTrimQueueHeadOnRelease = false;
1624 }
1625 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001626 LOG_ALWAYS_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
Eric Laurent81784c32012-11-19 14:55:58 -08001627 " buffers in the timed buffer queue");
1628 }
1629
1630done:
1631 buffer->raw = 0;
1632 buffer->frameCount = 0;
1633}
1634
1635size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1636 Mutex::Autolock _l(mTimedBufferQueueLock);
1637 return mFramesPendingInQueue;
1638}
1639
1640AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1641 : mPTS(0), mPosition(0) {}
1642
1643AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1644 const sp<IMemory>& buffer, int64_t pts)
1645 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1646
1647
1648// ----------------------------------------------------------------------------
1649
1650AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1651 PlaybackThread *playbackThread,
1652 DuplicatingThread *sourceThread,
1653 uint32_t sampleRate,
1654 audio_format_t format,
1655 audio_channel_mask_t channelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001656 size_t frameCount,
1657 int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001658 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001659 NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001660 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001661{
1662
1663 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001664 mOutBuffer.frameCount = 0;
1665 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001666 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten74935e42013-12-19 08:56:45 -08001667 "frameCount %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001668 mCblk, mBuffer,
Glenn Kasten74935e42013-12-19 08:56:45 -08001669 frameCount, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001670 // since client and server are in the same process,
1671 // the buffer has the same virtual address on both sides
Glenn Kasten529c61b2014-07-18 15:31:02 -07001672 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1673 true /*clientInServer*/);
Glenn Kastenc56f3422014-03-21 17:53:17 -07001674 mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001675 mClientProxy->setSendLevel(0.0);
1676 mClientProxy->setSampleRate(sampleRate);
Eric Laurent81784c32012-11-19 14:55:58 -08001677 } else {
1678 ALOGW("Error creating output track on thread %p", playbackThread);
1679 }
1680}
1681
1682AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1683{
1684 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001685 delete mClientProxy;
1686 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001687}
1688
1689status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1690 int triggerSession)
1691{
1692 status_t status = Track::start(event, triggerSession);
1693 if (status != NO_ERROR) {
1694 return status;
1695 }
1696
1697 mActive = true;
1698 mRetryCount = 127;
1699 return status;
1700}
1701
1702void AudioFlinger::PlaybackThread::OutputTrack::stop()
1703{
1704 Track::stop();
1705 clearBufferQueue();
1706 mOutBuffer.frameCount = 0;
1707 mActive = false;
1708}
1709
1710bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1711{
1712 Buffer *pInBuffer;
1713 Buffer inBuffer;
1714 uint32_t channelCount = mChannelCount;
1715 bool outputBufferFull = false;
1716 inBuffer.frameCount = frames;
1717 inBuffer.i16 = data;
1718
1719 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1720
1721 if (!mActive && frames != 0) {
1722 start();
1723 sp<ThreadBase> thread = mThread.promote();
1724 if (thread != 0) {
1725 MixerThread *mixerThread = (MixerThread *)thread.get();
1726 if (mFrameCount > frames) {
1727 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1728 uint32_t startFrames = (mFrameCount - frames);
1729 pInBuffer = new Buffer;
1730 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1731 pInBuffer->frameCount = startFrames;
1732 pInBuffer->i16 = pInBuffer->mBuffer;
1733 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1734 mBufferQueue.add(pInBuffer);
1735 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001736 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001737 }
1738 }
1739 }
1740 }
1741
1742 while (waitTimeLeftMs) {
1743 // First write pending buffers, then new data
1744 if (mBufferQueue.size()) {
1745 pInBuffer = mBufferQueue.itemAt(0);
1746 } else {
1747 pInBuffer = &inBuffer;
1748 }
1749
1750 if (pInBuffer->frameCount == 0) {
1751 break;
1752 }
1753
1754 if (mOutBuffer.frameCount == 0) {
1755 mOutBuffer.frameCount = pInBuffer->frameCount;
1756 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001757 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1758 if (status != NO_ERROR) {
1759 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1760 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001761 outputBufferFull = true;
1762 break;
1763 }
1764 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1765 if (waitTimeLeftMs >= waitTimeMs) {
1766 waitTimeLeftMs -= waitTimeMs;
1767 } else {
1768 waitTimeLeftMs = 0;
1769 }
1770 }
1771
1772 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1773 pInBuffer->frameCount;
1774 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001775 Proxy::Buffer buf;
1776 buf.mFrameCount = outFrames;
1777 buf.mRaw = NULL;
1778 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001779 pInBuffer->frameCount -= outFrames;
1780 pInBuffer->i16 += outFrames * channelCount;
1781 mOutBuffer.frameCount -= outFrames;
1782 mOutBuffer.i16 += outFrames * channelCount;
1783
1784 if (pInBuffer->frameCount == 0) {
1785 if (mBufferQueue.size()) {
1786 mBufferQueue.removeAt(0);
1787 delete [] pInBuffer->mBuffer;
1788 delete pInBuffer;
1789 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1790 mThread.unsafe_get(), mBufferQueue.size());
1791 } else {
1792 break;
1793 }
1794 }
1795 }
1796
1797 // If we could not write all frames, allocate a buffer and queue it for next time.
1798 if (inBuffer.frameCount) {
1799 sp<ThreadBase> thread = mThread.promote();
1800 if (thread != 0 && !thread->standby()) {
1801 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1802 pInBuffer = new Buffer;
1803 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1804 pInBuffer->frameCount = inBuffer.frameCount;
1805 pInBuffer->i16 = pInBuffer->mBuffer;
1806 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1807 sizeof(int16_t));
1808 mBufferQueue.add(pInBuffer);
1809 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1810 mThread.unsafe_get(), mBufferQueue.size());
1811 } else {
1812 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1813 mThread.unsafe_get(), this);
1814 }
1815 }
1816 }
1817
1818 // Calling write() with a 0 length buffer, means that no more data will be written:
1819 // If no more buffers are pending, fill output track buffer to make sure it is started
1820 // by output mixer.
1821 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001822 // FIXME borken, replace by getting framesReady() from proxy
1823 size_t user = 0; // was mCblk->user
1824 if (user < mFrameCount) {
1825 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001826 pInBuffer = new Buffer;
1827 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1828 pInBuffer->frameCount = frames;
1829 pInBuffer->i16 = pInBuffer->mBuffer;
1830 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1831 mBufferQueue.add(pInBuffer);
1832 } else if (mActive) {
1833 stop();
1834 }
1835 }
1836
1837 return outputBufferFull;
1838}
1839
1840status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1841 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1842{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001843 ClientProxy::Buffer buf;
1844 buf.mFrameCount = buffer->frameCount;
1845 struct timespec timeout;
1846 timeout.tv_sec = waitTimeMs / 1000;
1847 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1848 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1849 buffer->frameCount = buf.mFrameCount;
1850 buffer->raw = buf.mRaw;
1851 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001852}
1853
Eric Laurent81784c32012-11-19 14:55:58 -08001854void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1855{
1856 size_t size = mBufferQueue.size();
1857
1858 for (size_t i = 0; i < size; i++) {
1859 Buffer *pBuffer = mBufferQueue.itemAt(i);
1860 delete [] pBuffer->mBuffer;
1861 delete pBuffer;
1862 }
1863 mBufferQueue.clear();
1864}
1865
1866
Eric Laurent83b88082014-06-20 18:31:16 -07001867AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
1868 uint32_t sampleRate,
1869 audio_channel_mask_t channelMask,
1870 audio_format_t format,
1871 size_t frameCount,
1872 void *buffer,
1873 IAudioFlinger::track_flags_t flags)
1874 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1875 buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1876 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1877{
1878 uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1879 playbackThread->sampleRate();
1880 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1881 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1882
1883 ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1884 this, sampleRate,
1885 (int)mPeerTimeout.tv_sec,
1886 (int)(mPeerTimeout.tv_nsec / 1000000));
1887}
1888
1889AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1890{
1891}
1892
1893// AudioBufferProvider interface
1894status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
1895 AudioBufferProvider::Buffer* buffer, int64_t pts)
1896{
1897 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1898 Proxy::Buffer buf;
1899 buf.mFrameCount = buffer->frameCount;
1900 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1901 ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07001902 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07001903 if (buf.mFrameCount == 0) {
1904 return WOULD_BLOCK;
1905 }
Eric Laurent83b88082014-06-20 18:31:16 -07001906 status = Track::getNextBuffer(buffer, pts);
1907 return status;
1908}
1909
1910void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1911{
1912 ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1913 Proxy::Buffer buf;
1914 buf.mFrameCount = buffer->frameCount;
1915 buf.mRaw = buffer->raw;
1916 mPeerProxy->releaseBuffer(&buf);
1917 TrackBase::releaseBuffer(buffer);
1918}
1919
1920status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1921 const struct timespec *timeOut)
1922{
1923 return mProxy->obtainBuffer(buffer, timeOut);
1924}
1925
1926void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1927{
1928 mProxy->releaseBuffer(buffer);
1929 if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1930 ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1931 start();
1932 }
1933 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1934}
1935
Eric Laurent81784c32012-11-19 14:55:58 -08001936// ----------------------------------------------------------------------------
1937// Record
1938// ----------------------------------------------------------------------------
1939
1940AudioFlinger::RecordHandle::RecordHandle(
1941 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1942 : BnAudioRecord(),
1943 mRecordTrack(recordTrack)
1944{
1945}
1946
1947AudioFlinger::RecordHandle::~RecordHandle() {
1948 stop_nonvirtual();
1949 mRecordTrack->destroy();
1950}
1951
Eric Laurent81784c32012-11-19 14:55:58 -08001952status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1953 int triggerSession) {
1954 ALOGV("RecordHandle::start()");
1955 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1956}
1957
1958void AudioFlinger::RecordHandle::stop() {
1959 stop_nonvirtual();
1960}
1961
1962void AudioFlinger::RecordHandle::stop_nonvirtual() {
1963 ALOGV("RecordHandle::stop()");
1964 mRecordTrack->stop();
1965}
1966
1967status_t AudioFlinger::RecordHandle::onTransact(
1968 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1969{
1970 return BnAudioRecord::onTransact(code, data, reply, flags);
1971}
1972
1973// ----------------------------------------------------------------------------
1974
Glenn Kasten05997e22014-03-13 15:08:33 -07001975// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Eric Laurent81784c32012-11-19 14:55:58 -08001976AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1977 RecordThread *thread,
1978 const sp<Client>& client,
1979 uint32_t sampleRate,
1980 audio_format_t format,
1981 audio_channel_mask_t channelMask,
1982 size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -07001983 void *buffer,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001984 int sessionId,
Glenn Kastend776ac62014-05-07 09:16:09 -07001985 int uid,
Eric Laurent83b88082014-06-20 18:31:16 -07001986 IAudioFlinger::track_flags_t flags,
1987 track_type type)
Eric Laurent81784c32012-11-19 14:55:58 -08001988 : TrackBase(thread, client, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001989 channelMask, frameCount, buffer, sessionId, uid,
Glenn Kasten755b0a62014-05-13 11:30:28 -07001990 flags, false /*isOut*/,
Eric Laurent83b88082014-06-20 18:31:16 -07001991 (type == TYPE_DEFAULT) ?
1992 ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1993 ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1994 type),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001995 mOverflow(false), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0),
1996 // See real initialization of mRsmpInFront at RecordThread::start()
1997 mRsmpInUnrel(0), mRsmpInFront(0), mFramesToDrop(0), mResamplerBufferProvider(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001998{
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001999 if (mCblk == NULL) {
2000 return;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002001 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002002
Eric Laurent83b88082014-06-20 18:31:16 -07002003 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
2004 mFrameSize, !isExternalTrack());
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07002005
Andy Hunge5412692014-05-16 11:25:07 -07002006 uint32_t channelCount = audio_channel_count_from_in_mask(channelMask);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002007 // FIXME I don't understand either of the channel count checks
2008 if (thread->mSampleRate != sampleRate && thread->mChannelCount <= FCC_2 &&
2009 channelCount <= FCC_2) {
2010 // sink SR
Andy Hung3348e362014-07-07 10:21:44 -07002011 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_16_BIT,
2012 thread->mChannelCount, sampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002013 // source SR
2014 mResampler->setSampleRate(thread->mSampleRate);
Andy Hung5e58b0a2014-06-23 19:07:29 -07002015 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002016 mResamplerBufferProvider = new ResamplerBufferProvider(this);
2017 }
Glenn Kastenc263ca02014-06-04 20:31:46 -07002018
2019 if (flags & IAudioFlinger::TRACK_FAST) {
2020 ALOG_ASSERT(thread->mFastTrackAvail);
2021 thread->mFastTrackAvail = false;
2022 }
Eric Laurent81784c32012-11-19 14:55:58 -08002023}
2024
2025AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
2026{
2027 ALOGV("%s", __func__);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002028 delete mResampler;
2029 delete[] mRsmpOutBuffer;
2030 delete mResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08002031}
2032
2033// AudioBufferProvider interface
2034status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002035 int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002036{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002037 ServerProxy::Buffer buf;
2038 buf.mFrameCount = buffer->frameCount;
2039 status_t status = mServerProxy->obtainBuffer(&buf);
2040 buffer->frameCount = buf.mFrameCount;
2041 buffer->raw = buf.mRaw;
2042 if (buf.mFrameCount == 0) {
2043 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07002044 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08002045 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002046 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002047}
2048
2049status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
2050 int triggerSession)
2051{
2052 sp<ThreadBase> thread = mThread.promote();
2053 if (thread != 0) {
2054 RecordThread *recordThread = (RecordThread *)thread.get();
2055 return recordThread->start(this, event, triggerSession);
2056 } else {
2057 return BAD_VALUE;
2058 }
2059}
2060
2061void AudioFlinger::RecordThread::RecordTrack::stop()
2062{
2063 sp<ThreadBase> thread = mThread.promote();
2064 if (thread != 0) {
2065 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurent83b88082014-06-20 18:31:16 -07002066 if (recordThread->stop(this) && isExternalTrack()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07002067 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002068 }
2069 }
2070}
2071
2072void AudioFlinger::RecordThread::RecordTrack::destroy()
2073{
2074 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
2075 sp<RecordTrack> keep(this);
2076 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002077 if (isExternalTrack()) {
2078 if (mState == ACTIVE || mState == RESUMING) {
2079 AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
2080 }
2081 AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
2082 }
Eric Laurent81784c32012-11-19 14:55:58 -08002083 sp<ThreadBase> thread = mThread.promote();
2084 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002085 Mutex::Autolock _l(thread->mLock);
2086 RecordThread *recordThread = (RecordThread *) thread.get();
2087 recordThread->destroyTrack_l(this);
2088 }
2089 }
2090}
2091
Eric Laurent9a54bc22013-09-09 09:08:44 -07002092void AudioFlinger::RecordThread::RecordTrack::invalidate()
2093{
2094 // FIXME should use proxy, and needs work
2095 audio_track_cblk_t* cblk = mCblk;
2096 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2097 android_atomic_release_store(0x40000000, &cblk->mFutex);
2098 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
Elliott Hughesee499292014-05-21 17:55:51 -07002099 (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
Eric Laurent9a54bc22013-09-09 09:08:44 -07002100}
2101
Eric Laurent81784c32012-11-19 14:55:58 -08002102
2103/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
2104{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002105 result.append(" Active Client Fmt Chn mask Session S Server fCount SRate\n");
Eric Laurent81784c32012-11-19 14:55:58 -08002106}
2107
Marco Nelissenb2208842014-02-07 14:00:50 -08002108void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
Eric Laurent81784c32012-11-19 14:55:58 -08002109{
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002110 snprintf(buffer, size, " %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
Marco Nelissenb2208842014-02-07 14:00:50 -08002111 active ? "yes" : "no",
Eric Laurent81784c32012-11-19 14:55:58 -08002112 (mClient == 0) ? getpid_cached : mClient->pid(),
2113 mFormat,
2114 mChannelMask,
2115 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08002116 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07002117 mCblk->mServer,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002118 mFrameCount,
Glenn Kasten6e6704c2014-07-03 10:20:00 -07002119 mSampleRate);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002120
Eric Laurent81784c32012-11-19 14:55:58 -08002121}
2122
Glenn Kasten25f4aa82014-02-07 10:50:43 -08002123void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2124{
2125 if (event == mSyncStartEvent) {
2126 ssize_t framesToDrop = 0;
2127 sp<ThreadBase> threadBase = mThread.promote();
2128 if (threadBase != 0) {
2129 // TODO: use actual buffer filling status instead of 2 buffers when info is available
2130 // from audio HAL
2131 framesToDrop = threadBase->mFrameCount * 2;
2132 }
2133 mFramesToDrop = framesToDrop;
2134 }
2135}
2136
2137void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2138{
2139 if (mSyncStartEvent != 0) {
2140 mSyncStartEvent->cancel();
2141 mSyncStartEvent.clear();
2142 }
2143 mFramesToDrop = 0;
2144}
2145
Eric Laurent83b88082014-06-20 18:31:16 -07002146
2147AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
2148 uint32_t sampleRate,
2149 audio_channel_mask_t channelMask,
2150 audio_format_t format,
2151 size_t frameCount,
2152 void *buffer,
2153 IAudioFlinger::track_flags_t flags)
2154 : RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
2155 buffer, 0, getuid(), flags, TYPE_PATCH),
2156 mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
2157{
2158 uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
2159 recordThread->sampleRate();
2160 mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
2161 mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
2162
2163 ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
2164 this, sampleRate,
2165 (int)mPeerTimeout.tv_sec,
2166 (int)(mPeerTimeout.tv_nsec / 1000000));
2167}
2168
2169AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
2170{
2171}
2172
2173// AudioBufferProvider interface
2174status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
2175 AudioBufferProvider::Buffer* buffer, int64_t pts)
2176{
2177 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
2178 Proxy::Buffer buf;
2179 buf.mFrameCount = buffer->frameCount;
2180 status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
2181 ALOGV_IF(status != NO_ERROR,
2182 "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
Eric Laurentc2730ba2014-07-20 15:47:07 -07002183 buffer->frameCount = buf.mFrameCount;
Eric Laurent83b88082014-06-20 18:31:16 -07002184 if (buf.mFrameCount == 0) {
2185 return WOULD_BLOCK;
2186 }
Eric Laurent83b88082014-06-20 18:31:16 -07002187 status = RecordTrack::getNextBuffer(buffer, pts);
2188 return status;
2189}
2190
2191void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2192{
2193 ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
2194 Proxy::Buffer buf;
2195 buf.mFrameCount = buffer->frameCount;
2196 buf.mRaw = buffer->raw;
2197 mPeerProxy->releaseBuffer(&buf);
2198 TrackBase::releaseBuffer(buffer);
2199}
2200
2201status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
2202 const struct timespec *timeOut)
2203{
2204 return mProxy->obtainBuffer(buffer, timeOut);
2205}
2206
2207void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2208{
2209 mProxy->releaseBuffer(buffer);
2210}
2211
Eric Laurent81784c32012-11-19 14:55:58 -08002212}; // namespace android