blob: dfae5d9ea954d66d54b386054bd3675c5096a56e [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>
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <utils/Log.h>
25
26#include <private/media/AudioTrackShared.h>
27
28#include <common_time/cc_helper.h>
29#include <common_time/local_clock.h>
30
31#include "AudioMixer.h"
32#include "AudioFlinger.h"
33#include "ServiceUtilities.h"
34
Glenn Kastenda6ef132013-01-10 12:31:01 -080035#include <media/nbaio/Pipe.h>
36#include <media/nbaio/PipeReader.h>
37
Eric Laurent81784c32012-11-19 14:55:58 -080038// ----------------------------------------------------------------------------
39
40// Note: the following macro is used for extremely verbose logging message. In
41// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
42// 0; but one side effect of this is to turn all LOGV's as well. Some messages
43// are so verbose that we want to suppress them even when we have ALOG_ASSERT
44// turned on. Do not uncomment the #def below unless you really know what you
45// are doing and want to see all of the extremely verbose messages.
46//#define VERY_VERY_VERBOSE_LOGGING
47#ifdef VERY_VERY_VERBOSE_LOGGING
48#define ALOGVV ALOGV
49#else
50#define ALOGVV(a...) do { } while(0)
51#endif
52
53namespace android {
54
55// ----------------------------------------------------------------------------
56// TrackBase
57// ----------------------------------------------------------------------------
58
Glenn Kastenda6ef132013-01-10 12:31:01 -080059static volatile int32_t nextTrackId = 55;
60
Eric Laurent81784c32012-11-19 14:55:58 -080061// TrackBase constructor must be called with AudioFlinger::mLock held
62AudioFlinger::ThreadBase::TrackBase::TrackBase(
63 ThreadBase *thread,
64 const sp<Client>& client,
65 uint32_t sampleRate,
66 audio_format_t format,
67 audio_channel_mask_t channelMask,
68 size_t frameCount,
Ethan Chen8d420ed2013-11-14 00:40:54 -080069#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +053070 uint32_t flags,
Ethan Chen8d420ed2013-11-14 00:40:54 -080071#endif
Eric Laurent81784c32012-11-19 14:55:58 -080072 const sp<IMemory>& sharedBuffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080073 int sessionId,
74 bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -080075 : RefBase(),
76 mThread(thread),
77 mClient(client),
78 mCblk(NULL),
79 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080080 mState(IDLE),
81 mSampleRate(sampleRate),
82 mFormat(format),
83 mChannelMask(channelMask),
84 mChannelCount(popcount(channelMask)),
Ethan Chen8d420ed2013-11-14 00:40:54 -080085#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +053086 mFrameSize((audio_is_linear_pcm(format) || audio_is_supported_compressed(format)) ?
87 ((flags & IAudioFlinger::TRACK_VOICE_COMMUNICATION)? mChannelCount * sizeof(int16_t) : mChannelCount * audio_bytes_per_sample(format)) : sizeof(int8_t)),
Ethan Chen8d420ed2013-11-14 00:40:54 -080088#else
89 mFrameSize(audio_is_linear_pcm(format) ?
90 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
91#endif
Eric Laurent81784c32012-11-19 14:55:58 -080092 mFrameCount(frameCount),
Ethan Chen8d420ed2013-11-14 00:40:54 -080093#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +053094 mFlags(0),
Ethan Chen8d420ed2013-11-14 00:40:54 -080095#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -080096 mSessionId(sessionId),
97 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080098 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080099 mId(android_atomic_inc(&nextTrackId)),
100 mTerminated(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800101{
102 // client == 0 implies sharedBuffer == 0
103 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
104
105 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
106 sharedBuffer->size());
107
108 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
109 size_t size = sizeof(audio_track_cblk_t);
Ethan Chen8d420ed2013-11-14 00:40:54 -0800110#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +0530111 uint8_t channelCount = popcount(channelMask);
112 size_t bufferSize = 0;
113 if (flags & IAudioFlinger::TRACK_VOICE_COMMUNICATION) {
114 bufferSize = roundup(frameCount) * channelCount * mFrameSize;
115 } else {
116 if ( (format == AUDIO_FORMAT_PCM_16_BIT) ||
117 (format == AUDIO_FORMAT_PCM_8_BIT)) {
118 bufferSize = frameCount * channelCount * sizeof(int16_t);
119 } else if (format == AUDIO_FORMAT_AMR_NB) {
120 bufferSize = frameCount * channelCount * AMR_FRAMESIZE; // full rate frame size
121 } else if (format == AUDIO_FORMAT_EVRC) {
122 bufferSize = frameCount * channelCount * EVRC_FRAMESIZE; // full rate frame size
123 } else if (format == AUDIO_FORMAT_QCELP) {
124 bufferSize = frameCount * channelCount * QCELP_FRAMESIZE; // full rate frame size
125 } else if (format == AUDIO_FORMAT_AAC) {
126 bufferSize = frameCount * AAC_FRAMESIZE; // full rate frame size
127 } else if (format == AUDIO_FORMAT_AMR_WB) {
128 bufferSize = frameCount * channelCount * AMR_WB_FRAMESIZE; // full rate frame size
129 }
130 }
Ethan Chen8d420ed2013-11-14 00:40:54 -0800131#else
132 size_t bufferSize = (sharedBuffer == 0 ? roundup(frameCount) : frameCount) * mFrameSize;
133#endif
Alok Kediya601e9b52013-09-27 11:55:10 +0530134
Eric Laurent81784c32012-11-19 14:55:58 -0800135 if (sharedBuffer == 0) {
136 size += bufferSize;
137 }
138
139 if (client != 0) {
140 mCblkMemory = client->heap()->allocate(size);
141 if (mCblkMemory != 0) {
142 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
143 // can't assume mCblk != NULL
144 } else {
145 ALOGE("not enough memory for AudioTrack size=%u", size);
146 client->heap()->dump("AudioTrack");
147 return;
148 }
149 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800150 // this syntax avoids calling the audio_track_cblk_t constructor twice
151 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800152 // assume mCblk != NULL
153 }
154
155 // construct the shared structure in-place.
156 if (mCblk != NULL) {
157 new(mCblk) audio_track_cblk_t();
158 // clear all buffers
159 mCblk->frameCount_ = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800160 if (sharedBuffer == 0) {
161 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
Ethan Chen8d420ed2013-11-14 00:40:54 -0800162#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +0530163 if (flags & IAudioFlinger::TRACK_VOICE_COMMUNICATION) {
164 memset(mBuffer, 0, bufferSize);
165 } else {
166 if ((format == AUDIO_FORMAT_PCM_16_BIT) ||
167 (format == AUDIO_FORMAT_PCM_8_BIT)) {
168 memset(mBuffer, 0, bufferSize);
169 } else if (format == AUDIO_FORMAT_AMR_NB) {
170 // full rate frame size
171 memset(mBuffer, 0, frameCount * channelCount * AMR_FRAMESIZE);
172 } else if (format == AUDIO_FORMAT_EVRC) {
173 // full rate frame size
174 memset(mBuffer, 0, frameCount * channelCount * EVRC_FRAMESIZE);
175 } else if (format == AUDIO_FORMAT_QCELP) {
176 // full rate frame size
177 memset(mBuffer, 0, frameCount * channelCount * QCELP_FRAMESIZE);
178 } else if (format == AUDIO_FORMAT_AAC) {
179 // full rate frame size
180 memset(mBuffer, 0, frameCount * AAC_FRAMESIZE);
181 } else if (format == AUDIO_FORMAT_AMR_WB) {
182 // full rate frame size
183 memset(mBuffer, 0, frameCount * channelCount * AMR_WB_FRAMESIZE);
184 }
185 }
Ethan Chen8d420ed2013-11-14 00:40:54 -0800186#else
187 memset(mBuffer, 0, bufferSize);
188#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800189 } else {
190 mBuffer = sharedBuffer->pointer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800191#if 0
Glenn Kasten96f60d82013-07-12 10:21:18 -0700192 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800193#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800194 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800195
Glenn Kasten46909e72013-02-26 09:20:22 -0800196#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800197 if (mTeeSinkTrackEnabled) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800198 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount);
199 if (pipeFormat != Format_Invalid) {
200 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
201 size_t numCounterOffers = 0;
202 const NBAIO_Format offers[1] = {pipeFormat};
203 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
204 ALOG_ASSERT(index == 0);
205 PipeReader *pipeReader = new PipeReader(*pipe);
206 numCounterOffers = 0;
207 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
208 ALOG_ASSERT(index == 0);
209 mTeeSink = pipe;
210 mTeeSource = pipeReader;
211 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800212 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800213#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800214
Eric Laurent81784c32012-11-19 14:55:58 -0800215 }
216}
217
218AudioFlinger::ThreadBase::TrackBase::~TrackBase()
219{
Glenn Kasten46909e72013-02-26 09:20:22 -0800220#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800221 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800222#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800223 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
224 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800225 if (mCblk != NULL) {
226 if (mClient == 0) {
227 delete mCblk;
228 } else {
229 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
230 }
231 }
232 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
233 if (mClient != 0) {
234 // Client destructor must run with AudioFlinger mutex locked
235 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
236 // If the client's reference count drops to zero, the associated destructor
237 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
238 // relying on the automatic clear() at end of scope.
239 mClient.clear();
240 }
241}
242
243// AudioBufferProvider interface
244// getNextBuffer() = 0;
245// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
246void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
247{
Glenn Kasten46909e72013-02-26 09:20:22 -0800248#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800249 if (mTeeSink != 0) {
250 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
251 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800252#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800253
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800254 ServerProxy::Buffer buf;
255 buf.mFrameCount = buffer->frameCount;
256 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800257 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800258 buffer->raw = NULL;
259 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800260}
261
Eric Laurent81784c32012-11-19 14:55:58 -0800262status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
263{
264 mSyncEvents.add(event);
265 return NO_ERROR;
266}
267
268// ----------------------------------------------------------------------------
269// Playback
270// ----------------------------------------------------------------------------
271
272AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
273 : BnAudioTrack(),
274 mTrack(track)
275{
276}
277
278AudioFlinger::TrackHandle::~TrackHandle() {
279 // just stop the track on deletion, associated resources
280 // will be freed from the main thread once all pending buffers have
281 // been played. Unless it's not in the active track list, in which
282 // case we free everything now...
283 mTrack->destroy();
284}
285
286sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
287 return mTrack->getCblk();
288}
289
290status_t AudioFlinger::TrackHandle::start() {
291 return mTrack->start();
292}
293
294void AudioFlinger::TrackHandle::stop() {
295 mTrack->stop();
296}
297
298void AudioFlinger::TrackHandle::flush() {
299 mTrack->flush();
300}
301
Eric Laurent81784c32012-11-19 14:55:58 -0800302void AudioFlinger::TrackHandle::pause() {
303 mTrack->pause();
304}
305
306status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
307{
308 return mTrack->attachAuxEffect(EffectId);
309}
310
311status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
312 sp<IMemory>* buffer) {
313 if (!mTrack->isTimedTrack())
314 return INVALID_OPERATION;
315
316 PlaybackThread::TimedTrack* tt =
317 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
318 return tt->allocateTimedBuffer(size, buffer);
319}
320
321status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
322 int64_t pts) {
323 if (!mTrack->isTimedTrack())
324 return INVALID_OPERATION;
325
326 PlaybackThread::TimedTrack* tt =
327 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
328 return tt->queueTimedBuffer(buffer, pts);
329}
330
331status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
332 const LinearTransform& xform, int target) {
333
334 if (!mTrack->isTimedTrack())
335 return INVALID_OPERATION;
336
337 PlaybackThread::TimedTrack* tt =
338 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
339 return tt->setMediaTimeTransform(
340 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
341}
342
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700343status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
344 return mTrack->setParameters(keyValuePairs);
345}
346
Glenn Kasten53cec222013-08-29 09:01:02 -0700347status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
348{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700349 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700350}
351
Eric Laurent59fe0102013-09-27 18:48:26 -0700352
353void AudioFlinger::TrackHandle::signal()
354{
355 return mTrack->signal();
356}
357
Eric Laurent81784c32012-11-19 14:55:58 -0800358status_t AudioFlinger::TrackHandle::onTransact(
359 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
360{
361 return BnAudioTrack::onTransact(code, data, reply, flags);
362}
363
364// ----------------------------------------------------------------------------
365
366// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
367AudioFlinger::PlaybackThread::Track::Track(
368 PlaybackThread *thread,
369 const sp<Client>& client,
370 audio_stream_type_t streamType,
371 uint32_t sampleRate,
372 audio_format_t format,
373 audio_channel_mask_t channelMask,
374 size_t frameCount,
375 const sp<IMemory>& sharedBuffer,
376 int sessionId,
377 IAudioFlinger::track_flags_t flags)
Ethan Chen8d420ed2013-11-14 00:40:54 -0800378#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +0530379 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
380 ((audio_stream_type_t)streamType == AUDIO_STREAM_VOICE_CALL)? IAudioFlinger::TRACK_VOICE_COMMUNICATION:0x0,
381 sharedBuffer, sessionId, true /*isOut*/),
Ethan Chen8d420ed2013-11-14 00:40:54 -0800382#else
383 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
384 sessionId, true /*isOut*/),
385#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800386 mFillingUpStatus(FS_INVALID),
387 // mRetryCount initialized later when needed
388 mSharedBuffer(sharedBuffer),
389 mStreamType(streamType),
390 mName(-1), // see note below
391 mMainBuffer(thread->mixBuffer()),
392 mAuxBuffer(NULL),
393 mAuxEffectId(0), mHasVolumeController(false),
394 mPresentationCompleteFrames(0),
395 mFlags(flags),
396 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800397 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800398 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800399 mAudioTrackServerProxy(NULL),
400 mResumeToStopping(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800401{
402 if (mCblk != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800403 if (sharedBuffer == 0) {
404 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
405 mFrameSize);
406 } else {
407 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
408 mFrameSize);
409 }
410 mServerProxy = mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800411 // to avoid leaking a track name, do not allocate one unless there is an mCblk
412 mName = thread->getTrackName_l(channelMask, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800413 if (mName < 0) {
414 ALOGE("no more track names available");
415 return;
416 }
417 // only allocate a fast track index if we were able to allocate a normal track name
418 if (flags & IAudioFlinger::TRACK_FAST) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800419 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Eric Laurent81784c32012-11-19 14:55:58 -0800420 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
421 int i = __builtin_ctz(thread->mFastTrackAvailMask);
422 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
423 // FIXME This is too eager. We allocate a fast track index before the
424 // fast track becomes active. Since fast tracks are a scarce resource,
425 // this means we are potentially denying other more important fast tracks from
426 // being created. It would be better to allocate the index dynamically.
427 mFastIndex = i;
Eric Laurent81784c32012-11-19 14:55:58 -0800428 // Read the initial underruns because this field is never cleared by the fast mixer
429 mObservedUnderruns = thread->getFastTrackUnderruns(i);
430 thread->mFastTrackAvailMask &= ~(1 << i);
431 }
432 }
433 ALOGV("Track constructor name %d, calling pid %d", mName,
434 IPCThreadState::self()->getCallingPid());
435}
436
437AudioFlinger::PlaybackThread::Track::~Track()
438{
439 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700440
441 // The destructor would clear mSharedBuffer,
442 // but it will not push the decremented reference count,
443 // leaving the client's IMemory dangling indefinitely.
444 // This prevents that leak.
445 if (mSharedBuffer != 0) {
446 mSharedBuffer.clear();
447 // flush the binder command buffer
448 IPCThreadState::self()->flushCommands();
449 }
Eric Laurent81784c32012-11-19 14:55:58 -0800450}
451
452void AudioFlinger::PlaybackThread::Track::destroy()
453{
454 // NOTE: destroyTrack_l() can remove a strong reference to this Track
455 // by removing it from mTracks vector, so there is a risk that this Tracks's
456 // destructor is called. As the destructor needs to lock mLock,
457 // we must acquire a strong reference on this Track before locking mLock
458 // here so that the destructor is called only when exiting this function.
459 // On the other hand, as long as Track::destroy() is only called by
460 // TrackHandle destructor, the TrackHandle still holds a strong ref on
461 // this Track with its member mTrack.
462 sp<Track> keep(this);
463 { // scope for mLock
464 sp<ThreadBase> thread = mThread.promote();
465 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800466 Mutex::Autolock _l(thread->mLock);
467 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800468 bool wasActive = playbackThread->destroyTrack_l(this);
469 if (!isOutputTrack() && !wasActive) {
470 AudioSystem::releaseOutput(thread->id());
471 }
Eric Laurent81784c32012-11-19 14:55:58 -0800472 }
473 }
474}
475
476/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
477{
Eric Laurent972a1732013-09-04 09:42:59 -0700478 result.append(" Name Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700479 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800480}
481
482void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
483{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800484 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800485 if (isFastTrack()) {
486 sprintf(buffer, " F %2d", mFastIndex);
487 } else {
488 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
489 }
490 track_state state = mState;
491 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800492 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800493 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800494 } else {
495 switch (state) {
496 case IDLE:
497 stateChar = 'I';
498 break;
499 case STOPPING_1:
500 stateChar = 's';
501 break;
502 case STOPPING_2:
503 stateChar = '5';
504 break;
505 case STOPPED:
506 stateChar = 'S';
507 break;
508 case RESUMING:
509 stateChar = 'R';
510 break;
511 case ACTIVE:
512 stateChar = 'A';
513 break;
514 case PAUSING:
515 stateChar = 'p';
516 break;
517 case PAUSED:
518 stateChar = 'P';
519 break;
520 case FLUSHED:
521 stateChar = 'F';
522 break;
523 default:
524 stateChar = '?';
525 break;
526 }
Eric Laurent81784c32012-11-19 14:55:58 -0800527 }
528 char nowInUnderrun;
529 switch (mObservedUnderruns.mBitFields.mMostRecent) {
530 case UNDERRUN_FULL:
531 nowInUnderrun = ' ';
532 break;
533 case UNDERRUN_PARTIAL:
534 nowInUnderrun = '<';
535 break;
536 case UNDERRUN_EMPTY:
537 nowInUnderrun = '*';
538 break;
539 default:
540 nowInUnderrun = '?';
541 break;
542 }
Eric Laurent972a1732013-09-04 09:42:59 -0700543 snprintf(&buffer[7], size-7, " %6u %4u %08X %08X %7u %6u %1c %1d %5u %5.2g %5.2g "
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -0700544 "%08X %08X %08X 0x%03X %9u%c\n",
Eric Laurent81784c32012-11-19 14:55:58 -0800545 (mClient == 0) ? getpid_cached : mClient->pid(),
546 mStreamType,
547 mFormat,
548 mChannelMask,
549 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800550 mFrameCount,
551 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800552 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800553 mAudioTrackServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800554 20.0 * log10((vlr & 0xFFFF) / 4096.0),
555 20.0 * log10((vlr >> 16) / 4096.0),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700556 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -0800557 (int)mMainBuffer,
558 (int)mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700559 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700560 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800561 nowInUnderrun);
562}
563
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800564uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
565 return mAudioTrackServerProxy->getSampleRate();
566}
567
Eric Laurent81784c32012-11-19 14:55:58 -0800568// AudioBufferProvider interface
569status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
570 AudioBufferProvider::Buffer* buffer, int64_t pts)
571{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800572 ServerProxy::Buffer buf;
573 size_t desiredFrames = buffer->frameCount;
574 buf.mFrameCount = desiredFrames;
575 status_t status = mServerProxy->obtainBuffer(&buf);
576 buffer->frameCount = buf.mFrameCount;
577 buffer->raw = buf.mRaw;
578 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700579 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800580 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800581 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800582}
583
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700584// releaseBuffer() is not overridden
585
586// ExtendedAudioBufferProvider interface
587
Eric Laurent81784c32012-11-19 14:55:58 -0800588// Note that framesReady() takes a mutex on the control block using tryLock().
589// This could result in priority inversion if framesReady() is called by the normal mixer,
590// as the normal mixer thread runs at lower
591// priority than the client's callback thread: there is a short window within framesReady()
592// during which the normal mixer could be preempted, and the client callback would block.
593// Another problem can occur if framesReady() is called by the fast mixer:
594// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
595// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
596size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800597 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800598}
599
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700600size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
601{
602 return mAudioTrackServerProxy->framesReleased();
603}
604
Eric Laurent81784c32012-11-19 14:55:58 -0800605// Don't call for fast tracks; the framesReady() could result in priority inversion
606bool AudioFlinger::PlaybackThread::Track::isReady() const {
607 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
608 return true;
609 }
610
611 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700612 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800613 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700614 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800615 return true;
616 }
617 return false;
618}
619
620status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
621 int triggerSession)
622{
623 status_t status = NO_ERROR;
624 ALOGV("start(%d), calling pid %d session %d",
625 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
626
627 sp<ThreadBase> thread = mThread.promote();
628 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700629 if (isOffloaded()) {
630 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
631 Mutex::Autolock _lth(thread->mLock);
632 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700633 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
634 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700635 invalidate();
636 return PERMISSION_DENIED;
637 }
638 }
639 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800640 track_state state = mState;
641 // here the track could be either new, or restarted
642 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800643
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800644 if (state == PAUSED) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800645 if (mResumeToStopping) {
646 // happened we need to resume to STOPPING_1
647 mState = TrackBase::STOPPING_1;
648 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
649 } else {
650 mState = TrackBase::RESUMING;
651 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
652 }
Eric Laurent81784c32012-11-19 14:55:58 -0800653 } else {
654 mState = TrackBase::ACTIVE;
655 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
656 }
657
Eric Laurentbfb1b832013-01-07 09:53:42 -0800658 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
659 status = playbackThread->addTrack_l(this);
660 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800661 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800662 // restore previous state if start was rejected by policy manager
663 if (status == PERMISSION_DENIED) {
664 mState = state;
665 }
666 }
667 // track was already in the active list, not a problem
668 if (status == ALREADY_EXISTS) {
669 status = NO_ERROR;
Glenn Kasten4ce5dd92013-10-17 11:32:39 -0700670 } else {
671 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
672 // It is usually unsafe to access the server proxy from a binder thread.
673 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
674 // isn't looking at this track yet: we still hold the normal mixer thread lock,
675 // and for fast tracks the track is not yet in the fast mixer thread's active set.
676 ServerProxy::Buffer buffer;
677 buffer.mFrameCount = 1;
Glenn Kastena6f2c7b2013-10-18 13:00:29 -0700678 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800679 }
680 } else {
681 status = BAD_VALUE;
682 }
683 return status;
684}
685
686void AudioFlinger::PlaybackThread::Track::stop()
687{
688 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
689 sp<ThreadBase> thread = mThread.promote();
690 if (thread != 0) {
691 Mutex::Autolock _l(thread->mLock);
692 track_state state = mState;
693 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
694 // If the track is not active (PAUSED and buffers full), flush buffers
695 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
696 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
697 reset();
698 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800699 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800700 mState = STOPPED;
701 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800702 // For fast tracks prepareTracks_l() will set state to STOPPING_2
703 // presentation is complete
704 // For an offloaded track this starts a drain and state will
705 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800706 mState = STOPPING_1;
707 }
708 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
709 playbackThread);
710 }
Eric Laurent81784c32012-11-19 14:55:58 -0800711 }
712}
713
714void AudioFlinger::PlaybackThread::Track::pause()
715{
716 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
717 sp<ThreadBase> thread = mThread.promote();
718 if (thread != 0) {
719 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800720 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
721 switch (mState) {
722 case STOPPING_1:
723 case STOPPING_2:
724 if (!isOffloaded()) {
725 /* nothing to do if track is not offloaded */
726 break;
727 }
728
729 // Offloaded track was draining, we need to carry on draining when resumed
730 mResumeToStopping = true;
731 // fall through...
732 case ACTIVE:
733 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800734 mState = PAUSING;
735 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700736 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800737 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800738
Eric Laurentbfb1b832013-01-07 09:53:42 -0800739 default:
740 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800741 }
742 }
743}
744
745void AudioFlinger::PlaybackThread::Track::flush()
746{
747 ALOGV("flush(%d)", mName);
748 sp<ThreadBase> thread = mThread.promote();
749 if (thread != 0) {
750 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800751 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800752
753 if (isOffloaded()) {
754 // If offloaded we allow flush during any state except terminated
755 // and keep the track active to avoid problems if user is seeking
756 // rapidly and underlying hardware has a significant delay handling
757 // a pause
758 if (isTerminated()) {
759 return;
760 }
761
762 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800763 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800764
765 if (mState == STOPPING_1 || mState == STOPPING_2) {
766 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
767 mState = ACTIVE;
768 }
769
770 if (mState == ACTIVE) {
771 ALOGV("flush called in active state, resetting buffer time out retry count");
772 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
773 }
774
775 mResumeToStopping = false;
776 } else {
777 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
778 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
779 return;
780 }
781 // No point remaining in PAUSED state after a flush => go to
782 // FLUSHED state
783 mState = FLUSHED;
784 // do not reset the track if it is still in the process of being stopped or paused.
785 // this will be done by prepareTracks_l() when the track is stopped.
786 // prepareTracks_l() will see mState == FLUSHED, then
787 // remove from active track list, reset(), and trigger presentation complete
788 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
789 reset();
790 }
Eric Laurent81784c32012-11-19 14:55:58 -0800791 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800792 // Prevent flush being lost if the track is flushed and then resumed
793 // before mixer thread can run. This is important when offloading
794 // because the hardware buffer could hold a large amount of audio
795 playbackThread->flushOutput_l();
Eric Laurentede6c3b2013-09-19 14:37:46 -0700796 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800797 }
798}
799
800void AudioFlinger::PlaybackThread::Track::reset()
801{
802 // Do not reset twice to avoid discarding data written just after a flush and before
803 // the audioflinger thread detects the track is stopped.
804 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800805 // Force underrun condition to avoid false underrun callback until first data is
806 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700807 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800808 mFillingUpStatus = FS_FILLING;
809 mResetDone = true;
810 if (mState == FLUSHED) {
811 mState = IDLE;
812 }
813 }
814}
815
Eric Laurentbfb1b832013-01-07 09:53:42 -0800816status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
817{
818 sp<ThreadBase> thread = mThread.promote();
819 if (thread == 0) {
820 ALOGE("thread is dead");
821 return FAILED_TRANSACTION;
822 } else if ((thread->type() == ThreadBase::DIRECT) ||
823 (thread->type() == ThreadBase::OFFLOAD)) {
824 return thread->setParameters(keyValuePairs);
825 } else {
826 return PERMISSION_DENIED;
827 }
828}
829
Glenn Kasten573d80a2013-08-26 09:36:23 -0700830status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
831{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700832 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
833 if (isFastTrack()) {
834 return INVALID_OPERATION;
835 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700836 sp<ThreadBase> thread = mThread.promote();
837 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700838 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700839 }
840 Mutex::Autolock _l(thread->mLock);
841 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaccc1472013-09-20 09:36:34 -0700842 if (!isOffloaded()) {
843 if (!playbackThread->mLatchQValid) {
844 return INVALID_OPERATION;
845 }
846 uint32_t unpresentedFrames =
847 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
848 playbackThread->mSampleRate;
849 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
850 if (framesWritten < unpresentedFrames) {
851 return INVALID_OPERATION;
852 }
853 timestamp.mPosition = framesWritten - unpresentedFrames;
854 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
855 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700856 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700857
858 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700859}
860
Eric Laurent81784c32012-11-19 14:55:58 -0800861status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
862{
863 status_t status = DEAD_OBJECT;
864 sp<ThreadBase> thread = mThread.promote();
865 if (thread != 0) {
866 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
867 sp<AudioFlinger> af = mClient->audioFlinger();
868
869 Mutex::Autolock _l(af->mLock);
870
871 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
872
873 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
874 Mutex::Autolock _dl(playbackThread->mLock);
875 Mutex::Autolock _sl(srcThread->mLock);
876 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
877 if (chain == 0) {
878 return INVALID_OPERATION;
879 }
880
881 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
882 if (effect == 0) {
883 return INVALID_OPERATION;
884 }
885 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700886 status = playbackThread->addEffect_l(effect);
887 if (status != NO_ERROR) {
888 srcThread->addEffect_l(effect);
889 return INVALID_OPERATION;
890 }
Eric Laurent81784c32012-11-19 14:55:58 -0800891 // removeEffect_l() has stopped the effect if it was active so it must be restarted
892 if (effect->state() == EffectModule::ACTIVE ||
893 effect->state() == EffectModule::STOPPING) {
894 effect->start();
895 }
896
897 sp<EffectChain> dstChain = effect->chain().promote();
898 if (dstChain == 0) {
899 srcThread->addEffect_l(effect);
900 return INVALID_OPERATION;
901 }
902 AudioSystem::unregisterEffect(effect->id());
903 AudioSystem::registerEffect(&effect->desc(),
904 srcThread->id(),
905 dstChain->strategy(),
906 AUDIO_SESSION_OUTPUT_MIX,
907 effect->id());
908 }
909 status = playbackThread->attachAuxEffect(this, EffectId);
910 }
911 return status;
912}
913
914void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
915{
916 mAuxEffectId = EffectId;
917 mAuxBuffer = buffer;
918}
919
920bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
921 size_t audioHalFrames)
922{
923 // a track is considered presented when the total number of frames written to audio HAL
924 // corresponds to the number of frames written when presentationComplete() is called for the
925 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800926 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
927 // to detect when all frames have been played. In this case framesWritten isn't
928 // useful because it doesn't always reflect whether there is data in the h/w
929 // buffers, particularly if a track has been paused and resumed during draining
930 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
931 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800932 if (mPresentationCompleteFrames == 0) {
933 mPresentationCompleteFrames = framesWritten + audioHalFrames;
934 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
935 mPresentationCompleteFrames, audioHalFrames);
936 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800937
938 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800939 ALOGV("presentationComplete() session %d complete: framesWritten %d",
940 mSessionId, framesWritten);
941 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800942 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800943 return true;
944 }
945 return false;
946}
947
948void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
949{
950 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
951 if (mSyncEvents[i]->type() == type) {
952 mSyncEvents[i]->trigger();
953 mSyncEvents.removeAt(i);
954 i--;
955 }
956 }
957}
958
959// implement VolumeBufferProvider interface
960
961uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
962{
963 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
964 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800965 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800966 uint32_t vl = vlr & 0xFFFF;
967 uint32_t vr = vlr >> 16;
968 // track volumes come from shared memory, so can't be trusted and must be clamped
969 if (vl > MAX_GAIN_INT) {
970 vl = MAX_GAIN_INT;
971 }
972 if (vr > MAX_GAIN_INT) {
973 vr = MAX_GAIN_INT;
974 }
975 // now apply the cached master volume and stream type volume;
976 // this is trusted but lacks any synchronization or barrier so may be stale
977 float v = mCachedVolume;
978 vl *= v;
979 vr *= v;
980 // re-combine into U4.16
981 vlr = (vr << 16) | (vl & 0xFFFF);
982 // FIXME look at mute, pause, and stop flags
983 return vlr;
984}
985
986status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
987{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800988 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800989 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
990 (mState == STOPPED)))) {
991 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
992 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
993 event->cancel();
994 return INVALID_OPERATION;
995 }
996 (void) TrackBase::setSyncEvent(event);
997 return NO_ERROR;
998}
999
Glenn Kasten5736c352012-12-04 12:12:34 -08001000void AudioFlinger::PlaybackThread::Track::invalidate()
1001{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001002 // FIXME should use proxy, and needs work
1003 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -07001004 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001005 android_atomic_release_store(0x40000000, &cblk->mFutex);
1006 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1007 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -08001008 mIsInvalid = true;
1009}
1010
Eric Laurent59fe0102013-09-27 18:48:26 -07001011void AudioFlinger::PlaybackThread::Track::signal()
1012{
1013 sp<ThreadBase> thread = mThread.promote();
1014 if (thread != 0) {
1015 PlaybackThread *t = (PlaybackThread *)thread.get();
1016 Mutex::Autolock _l(t->mLock);
1017 t->broadcast_l();
1018 }
1019}
1020
Eric Laurent81784c32012-11-19 14:55:58 -08001021// ----------------------------------------------------------------------------
1022
1023sp<AudioFlinger::PlaybackThread::TimedTrack>
1024AudioFlinger::PlaybackThread::TimedTrack::create(
1025 PlaybackThread *thread,
1026 const sp<Client>& client,
1027 audio_stream_type_t streamType,
1028 uint32_t sampleRate,
1029 audio_format_t format,
1030 audio_channel_mask_t channelMask,
1031 size_t frameCount,
1032 const sp<IMemory>& sharedBuffer,
1033 int sessionId) {
1034 if (!client->reserveTimedTrack())
1035 return 0;
1036
1037 return new TimedTrack(
1038 thread, client, streamType, sampleRate, format, channelMask, frameCount,
1039 sharedBuffer, sessionId);
1040}
1041
1042AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
1043 PlaybackThread *thread,
1044 const sp<Client>& client,
1045 audio_stream_type_t streamType,
1046 uint32_t sampleRate,
1047 audio_format_t format,
1048 audio_channel_mask_t channelMask,
1049 size_t frameCount,
1050 const sp<IMemory>& sharedBuffer,
1051 int sessionId)
1052 : Track(thread, client, streamType, sampleRate, format, channelMask,
1053 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
1054 mQueueHeadInFlight(false),
1055 mTrimQueueHeadOnRelease(false),
1056 mFramesPendingInQueue(0),
1057 mTimedSilenceBuffer(NULL),
1058 mTimedSilenceBufferSize(0),
1059 mTimedAudioOutputOnTime(false),
1060 mMediaTimeTransformValid(false)
1061{
1062 LocalClock lc;
1063 mLocalTimeFreq = lc.getLocalFreq();
1064
1065 mLocalTimeToSampleTransform.a_zero = 0;
1066 mLocalTimeToSampleTransform.b_zero = 0;
1067 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1068 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1069 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1070 &mLocalTimeToSampleTransform.a_to_b_denom);
1071
1072 mMediaTimeToSampleTransform.a_zero = 0;
1073 mMediaTimeToSampleTransform.b_zero = 0;
1074 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1075 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1076 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1077 &mMediaTimeToSampleTransform.a_to_b_denom);
1078}
1079
1080AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1081 mClient->releaseTimedTrack();
1082 delete [] mTimedSilenceBuffer;
1083}
1084
1085status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1086 size_t size, sp<IMemory>* buffer) {
1087
1088 Mutex::Autolock _l(mTimedBufferQueueLock);
1089
1090 trimTimedBufferQueue_l();
1091
1092 // lazily initialize the shared memory heap for timed buffers
1093 if (mTimedMemoryDealer == NULL) {
1094 const int kTimedBufferHeapSize = 512 << 10;
1095
1096 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1097 "AudioFlingerTimed");
1098 if (mTimedMemoryDealer == NULL)
1099 return NO_MEMORY;
1100 }
1101
1102 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
1103 if (newBuffer == NULL) {
1104 newBuffer = mTimedMemoryDealer->allocate(size);
1105 if (newBuffer == NULL)
1106 return NO_MEMORY;
1107 }
1108
1109 *buffer = newBuffer;
1110 return NO_ERROR;
1111}
1112
1113// caller must hold mTimedBufferQueueLock
1114void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1115 int64_t mediaTimeNow;
1116 {
1117 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1118 if (!mMediaTimeTransformValid)
1119 return;
1120
1121 int64_t targetTimeNow;
1122 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1123 ? mCCHelper.getCommonTime(&targetTimeNow)
1124 : mCCHelper.getLocalTime(&targetTimeNow);
1125
1126 if (OK != res)
1127 return;
1128
1129 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1130 &mediaTimeNow)) {
1131 return;
1132 }
1133 }
1134
1135 size_t trimEnd;
1136 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1137 int64_t bufEnd;
1138
1139 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1140 // We have a next buffer. Just use its PTS as the PTS of the frame
1141 // following the last frame in this buffer. If the stream is sparse
1142 // (ie, there are deliberate gaps left in the stream which should be
1143 // filled with silence by the TimedAudioTrack), then this can result
1144 // in one extra buffer being left un-trimmed when it could have
1145 // been. In general, this is not typical, and we would rather
1146 // optimized away the TS calculation below for the more common case
1147 // where PTSes are contiguous.
1148 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1149 } else {
1150 // We have no next buffer. Compute the PTS of the frame following
1151 // the last frame in this buffer by computing the duration of of
1152 // this frame in media time units and adding it to the PTS of the
1153 // buffer.
1154 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1155 / mFrameSize;
1156
1157 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1158 &bufEnd)) {
1159 ALOGE("Failed to convert frame count of %lld to media time"
1160 " duration" " (scale factor %d/%u) in %s",
1161 frameCount,
1162 mMediaTimeToSampleTransform.a_to_b_numer,
1163 mMediaTimeToSampleTransform.a_to_b_denom,
1164 __PRETTY_FUNCTION__);
1165 break;
1166 }
1167 bufEnd += mTimedBufferQueue[trimEnd].pts();
1168 }
1169
1170 if (bufEnd > mediaTimeNow)
1171 break;
1172
1173 // Is the buffer we want to use in the middle of a mix operation right
1174 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1175 // from the mixer which should be coming back shortly.
1176 if (!trimEnd && mQueueHeadInFlight) {
1177 mTrimQueueHeadOnRelease = true;
1178 }
1179 }
1180
1181 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1182 if (trimStart < trimEnd) {
1183 // Update the bookkeeping for framesReady()
1184 for (size_t i = trimStart; i < trimEnd; ++i) {
1185 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1186 }
1187
1188 // Now actually remove the buffers from the queue.
1189 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1190 }
1191}
1192
1193void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1194 const char* logTag) {
1195 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1196 "%s called (reason \"%s\"), but timed buffer queue has no"
1197 " elements to trim.", __FUNCTION__, logTag);
1198
1199 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1200 mTimedBufferQueue.removeAt(0);
1201}
1202
1203void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1204 const TimedBuffer& buf,
1205 const char* logTag) {
1206 uint32_t bufBytes = buf.buffer()->size();
1207 uint32_t consumedAlready = buf.position();
1208
1209 ALOG_ASSERT(consumedAlready <= bufBytes,
1210 "Bad bookkeeping while updating frames pending. Timed buffer is"
1211 " only %u bytes long, but claims to have consumed %u"
1212 " bytes. (update reason: \"%s\")",
1213 bufBytes, consumedAlready, logTag);
1214
1215 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1216 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1217 "Bad bookkeeping while updating frames pending. Should have at"
1218 " least %u queued frames, but we think we have only %u. (update"
1219 " reason: \"%s\")",
1220 bufFrames, mFramesPendingInQueue, logTag);
1221
1222 mFramesPendingInQueue -= bufFrames;
1223}
1224
1225status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1226 const sp<IMemory>& buffer, int64_t pts) {
1227
1228 {
1229 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1230 if (!mMediaTimeTransformValid)
1231 return INVALID_OPERATION;
1232 }
1233
1234 Mutex::Autolock _l(mTimedBufferQueueLock);
1235
1236 uint32_t bufFrames = buffer->size() / mFrameSize;
1237 mFramesPendingInQueue += bufFrames;
1238 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1239
1240 return NO_ERROR;
1241}
1242
1243status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1244 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1245
1246 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1247 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1248 target);
1249
1250 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1251 target == TimedAudioTrack::COMMON_TIME)) {
1252 return BAD_VALUE;
1253 }
1254
1255 Mutex::Autolock lock(mMediaTimeTransformLock);
1256 mMediaTimeTransform = xform;
1257 mMediaTimeTransformTarget = target;
1258 mMediaTimeTransformValid = true;
1259
1260 return NO_ERROR;
1261}
1262
1263#define min(a, b) ((a) < (b) ? (a) : (b))
1264
1265// implementation of getNextBuffer for tracks whose buffers have timestamps
1266status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1267 AudioBufferProvider::Buffer* buffer, int64_t pts)
1268{
1269 if (pts == AudioBufferProvider::kInvalidPTS) {
1270 buffer->raw = NULL;
1271 buffer->frameCount = 0;
1272 mTimedAudioOutputOnTime = false;
1273 return INVALID_OPERATION;
1274 }
1275
1276 Mutex::Autolock _l(mTimedBufferQueueLock);
1277
1278 ALOG_ASSERT(!mQueueHeadInFlight,
1279 "getNextBuffer called without releaseBuffer!");
1280
1281 while (true) {
1282
1283 // if we have no timed buffers, then fail
1284 if (mTimedBufferQueue.isEmpty()) {
1285 buffer->raw = NULL;
1286 buffer->frameCount = 0;
1287 return NOT_ENOUGH_DATA;
1288 }
1289
1290 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1291
1292 // calculate the PTS of the head of the timed buffer queue expressed in
1293 // local time
1294 int64_t headLocalPTS;
1295 {
1296 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1297
1298 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1299
1300 if (mMediaTimeTransform.a_to_b_denom == 0) {
1301 // the transform represents a pause, so yield silence
1302 timedYieldSilence_l(buffer->frameCount, buffer);
1303 return NO_ERROR;
1304 }
1305
1306 int64_t transformedPTS;
1307 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1308 &transformedPTS)) {
1309 // the transform failed. this shouldn't happen, but if it does
1310 // then just drop this buffer
1311 ALOGW("timedGetNextBuffer transform failed");
1312 buffer->raw = NULL;
1313 buffer->frameCount = 0;
1314 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1315 return NO_ERROR;
1316 }
1317
1318 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1319 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1320 &headLocalPTS)) {
1321 buffer->raw = NULL;
1322 buffer->frameCount = 0;
1323 return INVALID_OPERATION;
1324 }
1325 } else {
1326 headLocalPTS = transformedPTS;
1327 }
1328 }
1329
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001330 uint32_t sr = sampleRate();
1331
Eric Laurent81784c32012-11-19 14:55:58 -08001332 // adjust the head buffer's PTS to reflect the portion of the head buffer
1333 // that has already been consumed
1334 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001335 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001336
1337 // Calculate the delta in samples between the head of the input buffer
1338 // queue and the start of the next output buffer that will be written.
1339 // If the transformation fails because of over or underflow, it means
1340 // that the sample's position in the output stream is so far out of
1341 // whack that it should just be dropped.
1342 int64_t sampleDelta;
1343 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1344 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1345 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1346 " mix");
1347 continue;
1348 }
1349 if (!mLocalTimeToSampleTransform.doForwardTransform(
1350 (effectivePTS - pts) << 32, &sampleDelta)) {
1351 ALOGV("*** too late during sample rate transform: dropped buffer");
1352 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1353 continue;
1354 }
1355
1356 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1357 " sampleDelta=[%d.%08x]",
1358 head.pts(), head.position(), pts,
1359 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1360 + (sampleDelta >> 32)),
1361 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1362
1363 // if the delta between the ideal placement for the next input sample and
1364 // the current output position is within this threshold, then we will
1365 // concatenate the next input samples to the previous output
1366 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001367 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001368
1369 // if this is the first buffer of audio that we're emitting from this track
1370 // then it should be almost exactly on time.
1371 const int64_t kSampleStartupThreshold = 1LL << 32;
1372
1373 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1374 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1375 // the next input is close enough to being on time, so concatenate it
1376 // with the last output
1377 timedYieldSamples_l(buffer);
1378
1379 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1380 head.position(), buffer->frameCount);
1381 return NO_ERROR;
1382 }
1383
1384 // Looks like our output is not on time. Reset our on timed status.
1385 // Next time we mix samples from our input queue, then should be within
1386 // the StartupThreshold.
1387 mTimedAudioOutputOnTime = false;
1388 if (sampleDelta > 0) {
1389 // the gap between the current output position and the proper start of
1390 // the next input sample is too big, so fill it with silence
1391 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1392
1393 timedYieldSilence_l(framesUntilNextInput, buffer);
1394 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1395 return NO_ERROR;
1396 } else {
1397 // the next input sample is late
1398 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1399 size_t onTimeSamplePosition =
1400 head.position() + lateFrames * mFrameSize;
1401
1402 if (onTimeSamplePosition > head.buffer()->size()) {
1403 // all the remaining samples in the head are too late, so
1404 // drop it and move on
1405 ALOGV("*** too late: dropped buffer");
1406 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1407 continue;
1408 } else {
1409 // skip over the late samples
1410 head.setPosition(onTimeSamplePosition);
1411
1412 // yield the available samples
1413 timedYieldSamples_l(buffer);
1414
1415 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1416 return NO_ERROR;
1417 }
1418 }
1419 }
1420}
1421
1422// Yield samples from the timed buffer queue head up to the given output
1423// buffer's capacity.
1424//
1425// Caller must hold mTimedBufferQueueLock
1426void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1427 AudioBufferProvider::Buffer* buffer) {
1428
1429 const TimedBuffer& head = mTimedBufferQueue[0];
1430
1431 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1432 head.position());
1433
1434 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1435 mFrameSize);
1436 size_t framesRequested = buffer->frameCount;
1437 buffer->frameCount = min(framesLeftInHead, framesRequested);
1438
1439 mQueueHeadInFlight = true;
1440 mTimedAudioOutputOnTime = true;
1441}
1442
1443// Yield samples of silence up to the given output buffer's capacity
1444//
1445// Caller must hold mTimedBufferQueueLock
1446void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1447 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1448
1449 // lazily allocate a buffer filled with silence
1450 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1451 delete [] mTimedSilenceBuffer;
1452 mTimedSilenceBufferSize = numFrames * mFrameSize;
1453 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1454 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1455 }
1456
1457 buffer->raw = mTimedSilenceBuffer;
1458 size_t framesRequested = buffer->frameCount;
1459 buffer->frameCount = min(numFrames, framesRequested);
1460
1461 mTimedAudioOutputOnTime = false;
1462}
1463
1464// AudioBufferProvider interface
1465void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1466 AudioBufferProvider::Buffer* buffer) {
1467
1468 Mutex::Autolock _l(mTimedBufferQueueLock);
1469
1470 // If the buffer which was just released is part of the buffer at the head
1471 // of the queue, be sure to update the amt of the buffer which has been
1472 // consumed. If the buffer being returned is not part of the head of the
1473 // queue, its either because the buffer is part of the silence buffer, or
1474 // because the head of the timed queue was trimmed after the mixer called
1475 // getNextBuffer but before the mixer called releaseBuffer.
1476 if (buffer->raw == mTimedSilenceBuffer) {
1477 ALOG_ASSERT(!mQueueHeadInFlight,
1478 "Queue head in flight during release of silence buffer!");
1479 goto done;
1480 }
1481
1482 ALOG_ASSERT(mQueueHeadInFlight,
1483 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1484 " head in flight.");
1485
1486 if (mTimedBufferQueue.size()) {
1487 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1488
1489 void* start = head.buffer()->pointer();
1490 void* end = reinterpret_cast<void*>(
1491 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1492 + head.buffer()->size());
1493
1494 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1495 "released buffer not within the head of the timed buffer"
1496 " queue; qHead = [%p, %p], released buffer = %p",
1497 start, end, buffer->raw);
1498
1499 head.setPosition(head.position() +
1500 (buffer->frameCount * mFrameSize));
1501 mQueueHeadInFlight = false;
1502
1503 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1504 "Bad bookkeeping during releaseBuffer! Should have at"
1505 " least %u queued frames, but we think we have only %u",
1506 buffer->frameCount, mFramesPendingInQueue);
1507
1508 mFramesPendingInQueue -= buffer->frameCount;
1509
1510 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1511 || mTrimQueueHeadOnRelease) {
1512 trimTimedBufferQueueHead_l("releaseBuffer");
1513 mTrimQueueHeadOnRelease = false;
1514 }
1515 } else {
1516 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1517 " buffers in the timed buffer queue");
1518 }
1519
1520done:
1521 buffer->raw = 0;
1522 buffer->frameCount = 0;
1523}
1524
1525size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1526 Mutex::Autolock _l(mTimedBufferQueueLock);
1527 return mFramesPendingInQueue;
1528}
1529
1530AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1531 : mPTS(0), mPosition(0) {}
1532
1533AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1534 const sp<IMemory>& buffer, int64_t pts)
1535 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1536
1537
1538// ----------------------------------------------------------------------------
1539
1540AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1541 PlaybackThread *playbackThread,
1542 DuplicatingThread *sourceThread,
1543 uint32_t sampleRate,
1544 audio_format_t format,
1545 audio_channel_mask_t channelMask,
1546 size_t frameCount)
1547 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1548 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001549 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001550{
1551
1552 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001553 mOutBuffer.frameCount = 0;
1554 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001555 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001556 "mCblk->frameCount_ %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001557 mCblk, mBuffer,
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001558 mCblk->frameCount_, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001559 // since client and server are in the same process,
1560 // the buffer has the same virtual address on both sides
1561 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001562 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1563 mClientProxy->setSendLevel(0.0);
1564 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001565 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1566 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001567 } else {
1568 ALOGW("Error creating output track on thread %p", playbackThread);
1569 }
1570}
1571
1572AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1573{
1574 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001575 delete mClientProxy;
1576 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001577}
1578
1579status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1580 int triggerSession)
1581{
1582 status_t status = Track::start(event, triggerSession);
1583 if (status != NO_ERROR) {
1584 return status;
1585 }
1586
1587 mActive = true;
1588 mRetryCount = 127;
1589 return status;
1590}
1591
1592void AudioFlinger::PlaybackThread::OutputTrack::stop()
1593{
1594 Track::stop();
1595 clearBufferQueue();
1596 mOutBuffer.frameCount = 0;
1597 mActive = false;
1598}
1599
1600bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1601{
1602 Buffer *pInBuffer;
1603 Buffer inBuffer;
1604 uint32_t channelCount = mChannelCount;
1605 bool outputBufferFull = false;
1606 inBuffer.frameCount = frames;
1607 inBuffer.i16 = data;
1608
1609 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1610
1611 if (!mActive && frames != 0) {
1612 start();
1613 sp<ThreadBase> thread = mThread.promote();
1614 if (thread != 0) {
1615 MixerThread *mixerThread = (MixerThread *)thread.get();
1616 if (mFrameCount > frames) {
1617 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1618 uint32_t startFrames = (mFrameCount - frames);
1619 pInBuffer = new Buffer;
1620 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1621 pInBuffer->frameCount = startFrames;
1622 pInBuffer->i16 = pInBuffer->mBuffer;
1623 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1624 mBufferQueue.add(pInBuffer);
1625 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001626 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001627 }
1628 }
1629 }
1630 }
1631
1632 while (waitTimeLeftMs) {
1633 // First write pending buffers, then new data
1634 if (mBufferQueue.size()) {
1635 pInBuffer = mBufferQueue.itemAt(0);
1636 } else {
1637 pInBuffer = &inBuffer;
1638 }
1639
1640 if (pInBuffer->frameCount == 0) {
1641 break;
1642 }
1643
1644 if (mOutBuffer.frameCount == 0) {
1645 mOutBuffer.frameCount = pInBuffer->frameCount;
1646 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001647 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1648 if (status != NO_ERROR) {
1649 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1650 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001651 outputBufferFull = true;
1652 break;
1653 }
1654 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1655 if (waitTimeLeftMs >= waitTimeMs) {
1656 waitTimeLeftMs -= waitTimeMs;
1657 } else {
1658 waitTimeLeftMs = 0;
1659 }
1660 }
1661
1662 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1663 pInBuffer->frameCount;
1664 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001665 Proxy::Buffer buf;
1666 buf.mFrameCount = outFrames;
1667 buf.mRaw = NULL;
1668 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001669 pInBuffer->frameCount -= outFrames;
1670 pInBuffer->i16 += outFrames * channelCount;
1671 mOutBuffer.frameCount -= outFrames;
1672 mOutBuffer.i16 += outFrames * channelCount;
1673
1674 if (pInBuffer->frameCount == 0) {
1675 if (mBufferQueue.size()) {
1676 mBufferQueue.removeAt(0);
1677 delete [] pInBuffer->mBuffer;
1678 delete pInBuffer;
1679 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1680 mThread.unsafe_get(), mBufferQueue.size());
1681 } else {
1682 break;
1683 }
1684 }
1685 }
1686
1687 // If we could not write all frames, allocate a buffer and queue it for next time.
1688 if (inBuffer.frameCount) {
1689 sp<ThreadBase> thread = mThread.promote();
1690 if (thread != 0 && !thread->standby()) {
1691 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1692 pInBuffer = new Buffer;
1693 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1694 pInBuffer->frameCount = inBuffer.frameCount;
1695 pInBuffer->i16 = pInBuffer->mBuffer;
1696 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1697 sizeof(int16_t));
1698 mBufferQueue.add(pInBuffer);
1699 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1700 mThread.unsafe_get(), mBufferQueue.size());
1701 } else {
1702 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1703 mThread.unsafe_get(), this);
1704 }
1705 }
1706 }
1707
1708 // Calling write() with a 0 length buffer, means that no more data will be written:
1709 // If no more buffers are pending, fill output track buffer to make sure it is started
1710 // by output mixer.
1711 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001712 // FIXME borken, replace by getting framesReady() from proxy
1713 size_t user = 0; // was mCblk->user
1714 if (user < mFrameCount) {
1715 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001716 pInBuffer = new Buffer;
1717 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1718 pInBuffer->frameCount = frames;
1719 pInBuffer->i16 = pInBuffer->mBuffer;
1720 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1721 mBufferQueue.add(pInBuffer);
1722 } else if (mActive) {
1723 stop();
1724 }
1725 }
1726
1727 return outputBufferFull;
1728}
1729
1730status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1731 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1732{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001733 ClientProxy::Buffer buf;
1734 buf.mFrameCount = buffer->frameCount;
1735 struct timespec timeout;
1736 timeout.tv_sec = waitTimeMs / 1000;
1737 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1738 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1739 buffer->frameCount = buf.mFrameCount;
1740 buffer->raw = buf.mRaw;
1741 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001742}
1743
Eric Laurent81784c32012-11-19 14:55:58 -08001744void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1745{
1746 size_t size = mBufferQueue.size();
1747
1748 for (size_t i = 0; i < size; i++) {
1749 Buffer *pBuffer = mBufferQueue.itemAt(i);
1750 delete [] pBuffer->mBuffer;
1751 delete pBuffer;
1752 }
1753 mBufferQueue.clear();
1754}
1755
1756
1757// ----------------------------------------------------------------------------
1758// Record
1759// ----------------------------------------------------------------------------
1760
1761AudioFlinger::RecordHandle::RecordHandle(
1762 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1763 : BnAudioRecord(),
1764 mRecordTrack(recordTrack)
1765{
1766}
1767
1768AudioFlinger::RecordHandle::~RecordHandle() {
1769 stop_nonvirtual();
1770 mRecordTrack->destroy();
1771}
1772
1773sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1774 return mRecordTrack->getCblk();
1775}
1776
1777status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1778 int triggerSession) {
1779 ALOGV("RecordHandle::start()");
1780 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1781}
1782
1783void AudioFlinger::RecordHandle::stop() {
1784 stop_nonvirtual();
1785}
1786
1787void AudioFlinger::RecordHandle::stop_nonvirtual() {
1788 ALOGV("RecordHandle::stop()");
1789 mRecordTrack->stop();
1790}
1791
1792status_t AudioFlinger::RecordHandle::onTransact(
1793 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1794{
1795 return BnAudioRecord::onTransact(code, data, reply, flags);
1796}
1797
1798// ----------------------------------------------------------------------------
1799
1800// RecordTrack constructor must be called with AudioFlinger::mLock held
1801AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1802 RecordThread *thread,
1803 const sp<Client>& client,
1804 uint32_t sampleRate,
1805 audio_format_t format,
1806 audio_channel_mask_t channelMask,
1807 size_t frameCount,
Ethan Chen8d420ed2013-11-14 00:40:54 -08001808#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +05301809 uint32_t flags,
Ethan Chen8d420ed2013-11-14 00:40:54 -08001810#endif
Eric Laurent81784c32012-11-19 14:55:58 -08001811 int sessionId)
Ethan Chen8d420ed2013-11-14 00:40:54 -08001812#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +05301813 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
1814 flags, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
Ethan Chen8d420ed2013-11-14 00:40:54 -08001815#else
1816 : TrackBase(thread, client, sampleRate, format,
1817 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
1818#endif
Eric Laurent81784c32012-11-19 14:55:58 -08001819 mOverflow(false)
1820{
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001821 ALOGV("RecordTrack constructor");
Ethan Chen8d420ed2013-11-14 00:40:54 -08001822#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +05301823 mFlags = flags;
Ethan Chen8d420ed2013-11-14 00:40:54 -08001824#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001825 if (mCblk != NULL) {
1826 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1827 mFrameSize);
1828 mServerProxy = mAudioRecordServerProxy;
1829 }
Eric Laurent81784c32012-11-19 14:55:58 -08001830}
1831
1832AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1833{
1834 ALOGV("%s", __func__);
1835}
1836
1837// AudioBufferProvider interface
1838status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1839 int64_t pts)
1840{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001841 ServerProxy::Buffer buf;
1842 buf.mFrameCount = buffer->frameCount;
1843 status_t status = mServerProxy->obtainBuffer(&buf);
1844 buffer->frameCount = buf.mFrameCount;
1845 buffer->raw = buf.mRaw;
1846 if (buf.mFrameCount == 0) {
1847 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001848 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001849 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001850 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001851}
1852
1853status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1854 int triggerSession)
1855{
1856 sp<ThreadBase> thread = mThread.promote();
1857 if (thread != 0) {
1858 RecordThread *recordThread = (RecordThread *)thread.get();
1859 return recordThread->start(this, event, triggerSession);
1860 } else {
1861 return BAD_VALUE;
1862 }
1863}
1864
1865void AudioFlinger::RecordThread::RecordTrack::stop()
1866{
1867 sp<ThreadBase> thread = mThread.promote();
1868 if (thread != 0) {
1869 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001870 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001871 AudioSystem::stopInput(recordThread->id());
1872 }
1873 }
1874}
1875
1876void AudioFlinger::RecordThread::RecordTrack::destroy()
1877{
1878 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1879 sp<RecordTrack> keep(this);
1880 {
1881 sp<ThreadBase> thread = mThread.promote();
1882 if (thread != 0) {
1883 if (mState == ACTIVE || mState == RESUMING) {
1884 AudioSystem::stopInput(thread->id());
1885 }
1886 AudioSystem::releaseInput(thread->id());
1887 Mutex::Autolock _l(thread->mLock);
1888 RecordThread *recordThread = (RecordThread *) thread.get();
1889 recordThread->destroyTrack_l(this);
1890 }
1891 }
1892}
1893
Eric Laurent9a54bc22013-09-09 09:08:44 -07001894void AudioFlinger::RecordThread::RecordTrack::invalidate()
1895{
1896 // FIXME should use proxy, and needs work
1897 audio_track_cblk_t* cblk = mCblk;
1898 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1899 android_atomic_release_store(0x40000000, &cblk->mFutex);
1900 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1901 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
1902}
1903
Eric Laurent81784c32012-11-19 14:55:58 -08001904
1905/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1906{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001907 result.append("Client Fmt Chn mask Session S Server fCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001908}
1909
1910void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1911{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001912 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001913 (mClient == 0) ? getpid_cached : mClient->pid(),
1914 mFormat,
1915 mChannelMask,
1916 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001917 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001918 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -08001919 mFrameCount);
1920}
1921
Eric Laurent81784c32012-11-19 14:55:58 -08001922}; // namespace android