blob: 9002f9b20a1b2b96c0811ca9bcff87cbbdd4470a [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,
69 const sp<IMemory>& sharedBuffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -080070 int sessionId,
71 bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -080072 : RefBase(),
73 mThread(thread),
74 mClient(client),
75 mCblk(NULL),
76 // mBuffer
Eric Laurent81784c32012-11-19 14:55:58 -080077 mState(IDLE),
78 mSampleRate(sampleRate),
79 mFormat(format),
80 mChannelMask(channelMask),
81 mChannelCount(popcount(channelMask)),
82 mFrameSize(audio_is_linear_pcm(format) ?
83 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
84 mFrameCount(frameCount),
Glenn Kastene3aa6592012-12-04 12:22:46 -080085 mSessionId(sessionId),
86 mIsOut(isOut),
Glenn Kastenda6ef132013-01-10 12:31:01 -080087 mServerProxy(NULL),
Eric Laurentbfb1b832013-01-07 09:53:42 -080088 mId(android_atomic_inc(&nextTrackId)),
89 mTerminated(false)
Eric Laurent81784c32012-11-19 14:55:58 -080090{
91 // client == 0 implies sharedBuffer == 0
92 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
93
94 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
95 sharedBuffer->size());
96
97 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
98 size_t size = sizeof(audio_track_cblk_t);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080099 size_t bufferSize = (sharedBuffer == 0 ? roundup(frameCount) : frameCount) * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -0800100 if (sharedBuffer == 0) {
101 size += bufferSize;
102 }
103
104 if (client != 0) {
105 mCblkMemory = client->heap()->allocate(size);
106 if (mCblkMemory != 0) {
107 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
108 // can't assume mCblk != NULL
109 } else {
110 ALOGE("not enough memory for AudioTrack size=%u", size);
111 client->heap()->dump("AudioTrack");
112 return;
113 }
114 } else {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800115 // this syntax avoids calling the audio_track_cblk_t constructor twice
116 mCblk = (audio_track_cblk_t *) new uint8_t[size];
Eric Laurent81784c32012-11-19 14:55:58 -0800117 // assume mCblk != NULL
118 }
119
120 // construct the shared structure in-place.
121 if (mCblk != NULL) {
122 new(mCblk) audio_track_cblk_t();
123 // clear all buffers
124 mCblk->frameCount_ = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800125 if (sharedBuffer == 0) {
126 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
127 memset(mBuffer, 0, bufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -0800128 } else {
129 mBuffer = sharedBuffer->pointer();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800130#if 0
Glenn Kasten96f60d82013-07-12 10:21:18 -0700131 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800132#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800133 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800134
Glenn Kasten46909e72013-02-26 09:20:22 -0800135#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800136 if (mTeeSinkTrackEnabled) {
Glenn Kasten46909e72013-02-26 09:20:22 -0800137 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount);
138 if (pipeFormat != Format_Invalid) {
139 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
140 size_t numCounterOffers = 0;
141 const NBAIO_Format offers[1] = {pipeFormat};
142 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
143 ALOG_ASSERT(index == 0);
144 PipeReader *pipeReader = new PipeReader(*pipe);
145 numCounterOffers = 0;
146 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
147 ALOG_ASSERT(index == 0);
148 mTeeSink = pipe;
149 mTeeSource = pipeReader;
150 }
Glenn Kastenda6ef132013-01-10 12:31:01 -0800151 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800152#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800153
Eric Laurent81784c32012-11-19 14:55:58 -0800154 }
155}
156
157AudioFlinger::ThreadBase::TrackBase::~TrackBase()
158{
Glenn Kasten46909e72013-02-26 09:20:22 -0800159#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800160 dumpTee(-1, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -0800161#endif
Glenn Kastene3aa6592012-12-04 12:22:46 -0800162 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
163 delete mServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800164 if (mCblk != NULL) {
165 if (mClient == 0) {
166 delete mCblk;
167 } else {
168 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
169 }
170 }
171 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
172 if (mClient != 0) {
173 // Client destructor must run with AudioFlinger mutex locked
174 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
175 // If the client's reference count drops to zero, the associated destructor
176 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
177 // relying on the automatic clear() at end of scope.
178 mClient.clear();
179 }
180}
181
182// AudioBufferProvider interface
183// getNextBuffer() = 0;
184// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
185void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
186{
Glenn Kasten46909e72013-02-26 09:20:22 -0800187#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800188 if (mTeeSink != 0) {
189 (void) mTeeSink->write(buffer->raw, buffer->frameCount);
190 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800191#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800192
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800193 ServerProxy::Buffer buf;
194 buf.mFrameCount = buffer->frameCount;
195 buf.mRaw = buffer->raw;
Eric Laurent81784c32012-11-19 14:55:58 -0800196 buffer->frameCount = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800197 buffer->raw = NULL;
198 mServerProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -0800199}
200
Eric Laurent81784c32012-11-19 14:55:58 -0800201status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
202{
203 mSyncEvents.add(event);
204 return NO_ERROR;
205}
206
207// ----------------------------------------------------------------------------
208// Playback
209// ----------------------------------------------------------------------------
210
211AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
212 : BnAudioTrack(),
213 mTrack(track)
214{
215}
216
217AudioFlinger::TrackHandle::~TrackHandle() {
218 // just stop the track on deletion, associated resources
219 // will be freed from the main thread once all pending buffers have
220 // been played. Unless it's not in the active track list, in which
221 // case we free everything now...
222 mTrack->destroy();
223}
224
225sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
226 return mTrack->getCblk();
227}
228
229status_t AudioFlinger::TrackHandle::start() {
230 return mTrack->start();
231}
232
233void AudioFlinger::TrackHandle::stop() {
234 mTrack->stop();
235}
236
237void AudioFlinger::TrackHandle::flush() {
238 mTrack->flush();
239}
240
Eric Laurent81784c32012-11-19 14:55:58 -0800241void AudioFlinger::TrackHandle::pause() {
242 mTrack->pause();
243}
244
245status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
246{
247 return mTrack->attachAuxEffect(EffectId);
248}
249
250status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
251 sp<IMemory>* buffer) {
252 if (!mTrack->isTimedTrack())
253 return INVALID_OPERATION;
254
255 PlaybackThread::TimedTrack* tt =
256 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
257 return tt->allocateTimedBuffer(size, buffer);
258}
259
260status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
261 int64_t pts) {
262 if (!mTrack->isTimedTrack())
263 return INVALID_OPERATION;
264
265 PlaybackThread::TimedTrack* tt =
266 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
267 return tt->queueTimedBuffer(buffer, pts);
268}
269
270status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
271 const LinearTransform& xform, int target) {
272
273 if (!mTrack->isTimedTrack())
274 return INVALID_OPERATION;
275
276 PlaybackThread::TimedTrack* tt =
277 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
278 return tt->setMediaTimeTransform(
279 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
280}
281
Glenn Kasten3dcd00d2013-07-17 10:10:23 -0700282status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
283 return mTrack->setParameters(keyValuePairs);
284}
285
Glenn Kasten53cec222013-08-29 09:01:02 -0700286status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
287{
Glenn Kasten573d80a2013-08-26 09:36:23 -0700288 return mTrack->getTimestamp(timestamp);
Glenn Kasten53cec222013-08-29 09:01:02 -0700289}
290
Eric Laurent81784c32012-11-19 14:55:58 -0800291status_t AudioFlinger::TrackHandle::onTransact(
292 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
293{
294 return BnAudioTrack::onTransact(code, data, reply, flags);
295}
296
297// ----------------------------------------------------------------------------
298
299// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
300AudioFlinger::PlaybackThread::Track::Track(
301 PlaybackThread *thread,
302 const sp<Client>& client,
303 audio_stream_type_t streamType,
304 uint32_t sampleRate,
305 audio_format_t format,
306 audio_channel_mask_t channelMask,
307 size_t frameCount,
308 const sp<IMemory>& sharedBuffer,
309 int sessionId,
310 IAudioFlinger::track_flags_t flags)
311 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -0800312 sessionId, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800313 mFillingUpStatus(FS_INVALID),
314 // mRetryCount initialized later when needed
315 mSharedBuffer(sharedBuffer),
316 mStreamType(streamType),
317 mName(-1), // see note below
318 mMainBuffer(thread->mixBuffer()),
319 mAuxBuffer(NULL),
320 mAuxEffectId(0), mHasVolumeController(false),
321 mPresentationCompleteFrames(0),
322 mFlags(flags),
323 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800324 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800325 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800326 mAudioTrackServerProxy(NULL),
327 mResumeToStopping(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800328{
329 if (mCblk != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800330 if (sharedBuffer == 0) {
331 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
332 mFrameSize);
333 } else {
334 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
335 mFrameSize);
336 }
337 mServerProxy = mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800338 // to avoid leaking a track name, do not allocate one unless there is an mCblk
339 mName = thread->getTrackName_l(channelMask, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800340 if (mName < 0) {
341 ALOGE("no more track names available");
342 return;
343 }
344 // only allocate a fast track index if we were able to allocate a normal track name
345 if (flags & IAudioFlinger::TRACK_FAST) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800346 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Eric Laurent81784c32012-11-19 14:55:58 -0800347 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
348 int i = __builtin_ctz(thread->mFastTrackAvailMask);
349 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
350 // FIXME This is too eager. We allocate a fast track index before the
351 // fast track becomes active. Since fast tracks are a scarce resource,
352 // this means we are potentially denying other more important fast tracks from
353 // being created. It would be better to allocate the index dynamically.
354 mFastIndex = i;
Eric Laurent81784c32012-11-19 14:55:58 -0800355 // Read the initial underruns because this field is never cleared by the fast mixer
356 mObservedUnderruns = thread->getFastTrackUnderruns(i);
357 thread->mFastTrackAvailMask &= ~(1 << i);
358 }
359 }
360 ALOGV("Track constructor name %d, calling pid %d", mName,
361 IPCThreadState::self()->getCallingPid());
362}
363
364AudioFlinger::PlaybackThread::Track::~Track()
365{
366 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700367
368 // The destructor would clear mSharedBuffer,
369 // but it will not push the decremented reference count,
370 // leaving the client's IMemory dangling indefinitely.
371 // This prevents that leak.
372 if (mSharedBuffer != 0) {
373 mSharedBuffer.clear();
374 // flush the binder command buffer
375 IPCThreadState::self()->flushCommands();
376 }
Eric Laurent81784c32012-11-19 14:55:58 -0800377}
378
Glenn Kasten03003332013-08-06 15:40:54 -0700379status_t AudioFlinger::PlaybackThread::Track::initCheck() const
380{
381 status_t status = TrackBase::initCheck();
382 if (status == NO_ERROR && mName < 0) {
383 status = NO_MEMORY;
384 }
385 return status;
386}
387
Eric Laurent81784c32012-11-19 14:55:58 -0800388void AudioFlinger::PlaybackThread::Track::destroy()
389{
390 // NOTE: destroyTrack_l() can remove a strong reference to this Track
391 // by removing it from mTracks vector, so there is a risk that this Tracks's
392 // destructor is called. As the destructor needs to lock mLock,
393 // we must acquire a strong reference on this Track before locking mLock
394 // here so that the destructor is called only when exiting this function.
395 // On the other hand, as long as Track::destroy() is only called by
396 // TrackHandle destructor, the TrackHandle still holds a strong ref on
397 // this Track with its member mTrack.
398 sp<Track> keep(this);
399 { // scope for mLock
400 sp<ThreadBase> thread = mThread.promote();
401 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800402 Mutex::Autolock _l(thread->mLock);
403 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800404 bool wasActive = playbackThread->destroyTrack_l(this);
405 if (!isOutputTrack() && !wasActive) {
406 AudioSystem::releaseOutput(thread->id());
407 }
Eric Laurent81784c32012-11-19 14:55:58 -0800408 }
409 }
410}
411
412/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
413{
Eric Laurent972a1732013-09-04 09:42:59 -0700414 result.append(" Name Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700415 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800416}
417
418void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
419{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800420 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800421 if (isFastTrack()) {
422 sprintf(buffer, " F %2d", mFastIndex);
423 } else {
424 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
425 }
426 track_state state = mState;
427 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800428 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800429 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800430 } else {
431 switch (state) {
432 case IDLE:
433 stateChar = 'I';
434 break;
435 case STOPPING_1:
436 stateChar = 's';
437 break;
438 case STOPPING_2:
439 stateChar = '5';
440 break;
441 case STOPPED:
442 stateChar = 'S';
443 break;
444 case RESUMING:
445 stateChar = 'R';
446 break;
447 case ACTIVE:
448 stateChar = 'A';
449 break;
450 case PAUSING:
451 stateChar = 'p';
452 break;
453 case PAUSED:
454 stateChar = 'P';
455 break;
456 case FLUSHED:
457 stateChar = 'F';
458 break;
459 default:
460 stateChar = '?';
461 break;
462 }
Eric Laurent81784c32012-11-19 14:55:58 -0800463 }
464 char nowInUnderrun;
465 switch (mObservedUnderruns.mBitFields.mMostRecent) {
466 case UNDERRUN_FULL:
467 nowInUnderrun = ' ';
468 break;
469 case UNDERRUN_PARTIAL:
470 nowInUnderrun = '<';
471 break;
472 case UNDERRUN_EMPTY:
473 nowInUnderrun = '*';
474 break;
475 default:
476 nowInUnderrun = '?';
477 break;
478 }
Eric Laurent972a1732013-09-04 09:42:59 -0700479 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 -0700480 "%08X %08X %08X 0x%03X %9u%c\n",
Eric Laurent81784c32012-11-19 14:55:58 -0800481 (mClient == 0) ? getpid_cached : mClient->pid(),
482 mStreamType,
483 mFormat,
484 mChannelMask,
485 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800486 mFrameCount,
487 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800488 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800489 mAudioTrackServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800490 20.0 * log10((vlr & 0xFFFF) / 4096.0),
491 20.0 * log10((vlr >> 16) / 4096.0),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700492 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -0800493 (int)mMainBuffer,
494 (int)mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700495 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700496 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800497 nowInUnderrun);
498}
499
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800500uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
501 return mAudioTrackServerProxy->getSampleRate();
502}
503
Eric Laurent81784c32012-11-19 14:55:58 -0800504// AudioBufferProvider interface
505status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
506 AudioBufferProvider::Buffer* buffer, int64_t pts)
507{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800508 ServerProxy::Buffer buf;
509 size_t desiredFrames = buffer->frameCount;
510 buf.mFrameCount = desiredFrames;
511 status_t status = mServerProxy->obtainBuffer(&buf);
512 buffer->frameCount = buf.mFrameCount;
513 buffer->raw = buf.mRaw;
514 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700515 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800516 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800517 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800518}
519
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700520// releaseBuffer() is not overridden
521
522// ExtendedAudioBufferProvider interface
523
Eric Laurent81784c32012-11-19 14:55:58 -0800524// Note that framesReady() takes a mutex on the control block using tryLock().
525// This could result in priority inversion if framesReady() is called by the normal mixer,
526// as the normal mixer thread runs at lower
527// priority than the client's callback thread: there is a short window within framesReady()
528// during which the normal mixer could be preempted, and the client callback would block.
529// Another problem can occur if framesReady() is called by the fast mixer:
530// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
531// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
532size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800533 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800534}
535
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700536size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
537{
538 return mAudioTrackServerProxy->framesReleased();
539}
540
Eric Laurent81784c32012-11-19 14:55:58 -0800541// Don't call for fast tracks; the framesReady() could result in priority inversion
542bool AudioFlinger::PlaybackThread::Track::isReady() const {
543 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
544 return true;
545 }
546
547 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700548 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800549 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700550 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800551 return true;
552 }
553 return false;
554}
555
556status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
557 int triggerSession)
558{
559 status_t status = NO_ERROR;
560 ALOGV("start(%d), calling pid %d session %d",
561 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
562
563 sp<ThreadBase> thread = mThread.promote();
564 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700565 if (isOffloaded()) {
566 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
567 Mutex::Autolock _lth(thread->mLock);
568 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700569 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
570 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700571 invalidate();
572 return PERMISSION_DENIED;
573 }
574 }
575 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800576 track_state state = mState;
577 // here the track could be either new, or restarted
578 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800579
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800580 if (state == PAUSED) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800581 if (mResumeToStopping) {
582 // happened we need to resume to STOPPING_1
583 mState = TrackBase::STOPPING_1;
584 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
585 } else {
586 mState = TrackBase::RESUMING;
587 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
588 }
Eric Laurent81784c32012-11-19 14:55:58 -0800589 } else {
590 mState = TrackBase::ACTIVE;
591 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
592 }
593
Eric Laurentbfb1b832013-01-07 09:53:42 -0800594 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
595 status = playbackThread->addTrack_l(this);
596 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800597 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800598 // restore previous state if start was rejected by policy manager
599 if (status == PERMISSION_DENIED) {
600 mState = state;
601 }
602 }
603 // track was already in the active list, not a problem
604 if (status == ALREADY_EXISTS) {
605 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -0800606 }
607 } else {
608 status = BAD_VALUE;
609 }
610 return status;
611}
612
613void AudioFlinger::PlaybackThread::Track::stop()
614{
615 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
616 sp<ThreadBase> thread = mThread.promote();
617 if (thread != 0) {
618 Mutex::Autolock _l(thread->mLock);
619 track_state state = mState;
620 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
621 // If the track is not active (PAUSED and buffers full), flush buffers
622 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
623 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
624 reset();
625 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800626 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800627 mState = STOPPED;
628 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800629 // For fast tracks prepareTracks_l() will set state to STOPPING_2
630 // presentation is complete
631 // For an offloaded track this starts a drain and state will
632 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800633 mState = STOPPING_1;
634 }
635 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
636 playbackThread);
637 }
Eric Laurent81784c32012-11-19 14:55:58 -0800638 }
639}
640
641void AudioFlinger::PlaybackThread::Track::pause()
642{
643 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
644 sp<ThreadBase> thread = mThread.promote();
645 if (thread != 0) {
646 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800647 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
648 switch (mState) {
649 case STOPPING_1:
650 case STOPPING_2:
651 if (!isOffloaded()) {
652 /* nothing to do if track is not offloaded */
653 break;
654 }
655
656 // Offloaded track was draining, we need to carry on draining when resumed
657 mResumeToStopping = true;
658 // fall through...
659 case ACTIVE:
660 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800661 mState = PAUSING;
662 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700663 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800664 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800665
Eric Laurentbfb1b832013-01-07 09:53:42 -0800666 default:
667 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800668 }
669 }
670}
671
672void AudioFlinger::PlaybackThread::Track::flush()
673{
674 ALOGV("flush(%d)", mName);
675 sp<ThreadBase> thread = mThread.promote();
676 if (thread != 0) {
677 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800678 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800679
680 if (isOffloaded()) {
681 // If offloaded we allow flush during any state except terminated
682 // and keep the track active to avoid problems if user is seeking
683 // rapidly and underlying hardware has a significant delay handling
684 // a pause
685 if (isTerminated()) {
686 return;
687 }
688
689 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800690 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800691
692 if (mState == STOPPING_1 || mState == STOPPING_2) {
693 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
694 mState = ACTIVE;
695 }
696
697 if (mState == ACTIVE) {
698 ALOGV("flush called in active state, resetting buffer time out retry count");
699 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
700 }
701
702 mResumeToStopping = false;
703 } else {
704 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
705 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
706 return;
707 }
708 // No point remaining in PAUSED state after a flush => go to
709 // FLUSHED state
710 mState = FLUSHED;
711 // do not reset the track if it is still in the process of being stopped or paused.
712 // this will be done by prepareTracks_l() when the track is stopped.
713 // prepareTracks_l() will see mState == FLUSHED, then
714 // remove from active track list, reset(), and trigger presentation complete
715 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
716 reset();
717 }
Eric Laurent81784c32012-11-19 14:55:58 -0800718 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800719 // Prevent flush being lost if the track is flushed and then resumed
720 // before mixer thread can run. This is important when offloading
721 // because the hardware buffer could hold a large amount of audio
722 playbackThread->flushOutput_l();
Eric Laurentede6c3b2013-09-19 14:37:46 -0700723 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800724 }
725}
726
727void AudioFlinger::PlaybackThread::Track::reset()
728{
729 // Do not reset twice to avoid discarding data written just after a flush and before
730 // the audioflinger thread detects the track is stopped.
731 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800732 // Force underrun condition to avoid false underrun callback until first data is
733 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700734 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800735 mFillingUpStatus = FS_FILLING;
736 mResetDone = true;
737 if (mState == FLUSHED) {
738 mState = IDLE;
739 }
740 }
741}
742
Eric Laurentbfb1b832013-01-07 09:53:42 -0800743status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
744{
745 sp<ThreadBase> thread = mThread.promote();
746 if (thread == 0) {
747 ALOGE("thread is dead");
748 return FAILED_TRANSACTION;
749 } else if ((thread->type() == ThreadBase::DIRECT) ||
750 (thread->type() == ThreadBase::OFFLOAD)) {
751 return thread->setParameters(keyValuePairs);
752 } else {
753 return PERMISSION_DENIED;
754 }
755}
756
Glenn Kasten573d80a2013-08-26 09:36:23 -0700757status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
758{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700759 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
760 if (isFastTrack()) {
761 return INVALID_OPERATION;
762 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700763 sp<ThreadBase> thread = mThread.promote();
764 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700765 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700766 }
767 Mutex::Autolock _l(thread->mLock);
768 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaccc1472013-09-20 09:36:34 -0700769 if (!isOffloaded()) {
770 if (!playbackThread->mLatchQValid) {
771 return INVALID_OPERATION;
772 }
773 uint32_t unpresentedFrames =
774 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
775 playbackThread->mSampleRate;
776 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
777 if (framesWritten < unpresentedFrames) {
778 return INVALID_OPERATION;
779 }
780 timestamp.mPosition = framesWritten - unpresentedFrames;
781 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
782 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700783 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700784
785 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700786}
787
Eric Laurent81784c32012-11-19 14:55:58 -0800788status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
789{
790 status_t status = DEAD_OBJECT;
791 sp<ThreadBase> thread = mThread.promote();
792 if (thread != 0) {
793 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
794 sp<AudioFlinger> af = mClient->audioFlinger();
795
796 Mutex::Autolock _l(af->mLock);
797
798 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
799
800 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
801 Mutex::Autolock _dl(playbackThread->mLock);
802 Mutex::Autolock _sl(srcThread->mLock);
803 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
804 if (chain == 0) {
805 return INVALID_OPERATION;
806 }
807
808 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
809 if (effect == 0) {
810 return INVALID_OPERATION;
811 }
812 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700813 status = playbackThread->addEffect_l(effect);
814 if (status != NO_ERROR) {
815 srcThread->addEffect_l(effect);
816 return INVALID_OPERATION;
817 }
Eric Laurent81784c32012-11-19 14:55:58 -0800818 // removeEffect_l() has stopped the effect if it was active so it must be restarted
819 if (effect->state() == EffectModule::ACTIVE ||
820 effect->state() == EffectModule::STOPPING) {
821 effect->start();
822 }
823
824 sp<EffectChain> dstChain = effect->chain().promote();
825 if (dstChain == 0) {
826 srcThread->addEffect_l(effect);
827 return INVALID_OPERATION;
828 }
829 AudioSystem::unregisterEffect(effect->id());
830 AudioSystem::registerEffect(&effect->desc(),
831 srcThread->id(),
832 dstChain->strategy(),
833 AUDIO_SESSION_OUTPUT_MIX,
834 effect->id());
835 }
836 status = playbackThread->attachAuxEffect(this, EffectId);
837 }
838 return status;
839}
840
841void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
842{
843 mAuxEffectId = EffectId;
844 mAuxBuffer = buffer;
845}
846
847bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
848 size_t audioHalFrames)
849{
850 // a track is considered presented when the total number of frames written to audio HAL
851 // corresponds to the number of frames written when presentationComplete() is called for the
852 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800853 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
854 // to detect when all frames have been played. In this case framesWritten isn't
855 // useful because it doesn't always reflect whether there is data in the h/w
856 // buffers, particularly if a track has been paused and resumed during draining
857 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
858 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800859 if (mPresentationCompleteFrames == 0) {
860 mPresentationCompleteFrames = framesWritten + audioHalFrames;
861 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
862 mPresentationCompleteFrames, audioHalFrames);
863 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800864
865 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800866 ALOGV("presentationComplete() session %d complete: framesWritten %d",
867 mSessionId, framesWritten);
868 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800869 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800870 return true;
871 }
872 return false;
873}
874
875void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
876{
877 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
878 if (mSyncEvents[i]->type() == type) {
879 mSyncEvents[i]->trigger();
880 mSyncEvents.removeAt(i);
881 i--;
882 }
883 }
884}
885
886// implement VolumeBufferProvider interface
887
888uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
889{
890 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
891 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800892 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800893 uint32_t vl = vlr & 0xFFFF;
894 uint32_t vr = vlr >> 16;
895 // track volumes come from shared memory, so can't be trusted and must be clamped
896 if (vl > MAX_GAIN_INT) {
897 vl = MAX_GAIN_INT;
898 }
899 if (vr > MAX_GAIN_INT) {
900 vr = MAX_GAIN_INT;
901 }
902 // now apply the cached master volume and stream type volume;
903 // this is trusted but lacks any synchronization or barrier so may be stale
904 float v = mCachedVolume;
905 vl *= v;
906 vr *= v;
907 // re-combine into U4.16
908 vlr = (vr << 16) | (vl & 0xFFFF);
909 // FIXME look at mute, pause, and stop flags
910 return vlr;
911}
912
913status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
914{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800915 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800916 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
917 (mState == STOPPED)))) {
918 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
919 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
920 event->cancel();
921 return INVALID_OPERATION;
922 }
923 (void) TrackBase::setSyncEvent(event);
924 return NO_ERROR;
925}
926
Glenn Kasten5736c352012-12-04 12:12:34 -0800927void AudioFlinger::PlaybackThread::Track::invalidate()
928{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800929 // FIXME should use proxy, and needs work
930 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700931 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800932 android_atomic_release_store(0x40000000, &cblk->mFutex);
933 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
934 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -0800935 mIsInvalid = true;
936}
937
Eric Laurent81784c32012-11-19 14:55:58 -0800938// ----------------------------------------------------------------------------
939
940sp<AudioFlinger::PlaybackThread::TimedTrack>
941AudioFlinger::PlaybackThread::TimedTrack::create(
942 PlaybackThread *thread,
943 const sp<Client>& client,
944 audio_stream_type_t streamType,
945 uint32_t sampleRate,
946 audio_format_t format,
947 audio_channel_mask_t channelMask,
948 size_t frameCount,
949 const sp<IMemory>& sharedBuffer,
950 int sessionId) {
951 if (!client->reserveTimedTrack())
952 return 0;
953
954 return new TimedTrack(
955 thread, client, streamType, sampleRate, format, channelMask, frameCount,
956 sharedBuffer, sessionId);
957}
958
959AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
960 PlaybackThread *thread,
961 const sp<Client>& client,
962 audio_stream_type_t streamType,
963 uint32_t sampleRate,
964 audio_format_t format,
965 audio_channel_mask_t channelMask,
966 size_t frameCount,
967 const sp<IMemory>& sharedBuffer,
968 int sessionId)
969 : Track(thread, client, streamType, sampleRate, format, channelMask,
970 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
971 mQueueHeadInFlight(false),
972 mTrimQueueHeadOnRelease(false),
973 mFramesPendingInQueue(0),
974 mTimedSilenceBuffer(NULL),
975 mTimedSilenceBufferSize(0),
976 mTimedAudioOutputOnTime(false),
977 mMediaTimeTransformValid(false)
978{
979 LocalClock lc;
980 mLocalTimeFreq = lc.getLocalFreq();
981
982 mLocalTimeToSampleTransform.a_zero = 0;
983 mLocalTimeToSampleTransform.b_zero = 0;
984 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
985 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
986 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
987 &mLocalTimeToSampleTransform.a_to_b_denom);
988
989 mMediaTimeToSampleTransform.a_zero = 0;
990 mMediaTimeToSampleTransform.b_zero = 0;
991 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
992 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
993 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
994 &mMediaTimeToSampleTransform.a_to_b_denom);
995}
996
997AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
998 mClient->releaseTimedTrack();
999 delete [] mTimedSilenceBuffer;
1000}
1001
1002status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1003 size_t size, sp<IMemory>* buffer) {
1004
1005 Mutex::Autolock _l(mTimedBufferQueueLock);
1006
1007 trimTimedBufferQueue_l();
1008
1009 // lazily initialize the shared memory heap for timed buffers
1010 if (mTimedMemoryDealer == NULL) {
1011 const int kTimedBufferHeapSize = 512 << 10;
1012
1013 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1014 "AudioFlingerTimed");
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001015 if (mTimedMemoryDealer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001016 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001017 }
Eric Laurent81784c32012-11-19 14:55:58 -08001018 }
1019
1020 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
1021 if (newBuffer == NULL) {
1022 newBuffer = mTimedMemoryDealer->allocate(size);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001023 if (newBuffer == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001024 return NO_MEMORY;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07001025 }
Eric Laurent81784c32012-11-19 14:55:58 -08001026 }
1027
1028 *buffer = newBuffer;
1029 return NO_ERROR;
1030}
1031
1032// caller must hold mTimedBufferQueueLock
1033void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1034 int64_t mediaTimeNow;
1035 {
1036 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1037 if (!mMediaTimeTransformValid)
1038 return;
1039
1040 int64_t targetTimeNow;
1041 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1042 ? mCCHelper.getCommonTime(&targetTimeNow)
1043 : mCCHelper.getLocalTime(&targetTimeNow);
1044
1045 if (OK != res)
1046 return;
1047
1048 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1049 &mediaTimeNow)) {
1050 return;
1051 }
1052 }
1053
1054 size_t trimEnd;
1055 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1056 int64_t bufEnd;
1057
1058 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1059 // We have a next buffer. Just use its PTS as the PTS of the frame
1060 // following the last frame in this buffer. If the stream is sparse
1061 // (ie, there are deliberate gaps left in the stream which should be
1062 // filled with silence by the TimedAudioTrack), then this can result
1063 // in one extra buffer being left un-trimmed when it could have
1064 // been. In general, this is not typical, and we would rather
1065 // optimized away the TS calculation below for the more common case
1066 // where PTSes are contiguous.
1067 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1068 } else {
1069 // We have no next buffer. Compute the PTS of the frame following
1070 // the last frame in this buffer by computing the duration of of
1071 // this frame in media time units and adding it to the PTS of the
1072 // buffer.
1073 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1074 / mFrameSize;
1075
1076 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1077 &bufEnd)) {
1078 ALOGE("Failed to convert frame count of %lld to media time"
1079 " duration" " (scale factor %d/%u) in %s",
1080 frameCount,
1081 mMediaTimeToSampleTransform.a_to_b_numer,
1082 mMediaTimeToSampleTransform.a_to_b_denom,
1083 __PRETTY_FUNCTION__);
1084 break;
1085 }
1086 bufEnd += mTimedBufferQueue[trimEnd].pts();
1087 }
1088
1089 if (bufEnd > mediaTimeNow)
1090 break;
1091
1092 // Is the buffer we want to use in the middle of a mix operation right
1093 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1094 // from the mixer which should be coming back shortly.
1095 if (!trimEnd && mQueueHeadInFlight) {
1096 mTrimQueueHeadOnRelease = true;
1097 }
1098 }
1099
1100 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1101 if (trimStart < trimEnd) {
1102 // Update the bookkeeping for framesReady()
1103 for (size_t i = trimStart; i < trimEnd; ++i) {
1104 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1105 }
1106
1107 // Now actually remove the buffers from the queue.
1108 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1109 }
1110}
1111
1112void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1113 const char* logTag) {
1114 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1115 "%s called (reason \"%s\"), but timed buffer queue has no"
1116 " elements to trim.", __FUNCTION__, logTag);
1117
1118 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1119 mTimedBufferQueue.removeAt(0);
1120}
1121
1122void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1123 const TimedBuffer& buf,
1124 const char* logTag) {
1125 uint32_t bufBytes = buf.buffer()->size();
1126 uint32_t consumedAlready = buf.position();
1127
1128 ALOG_ASSERT(consumedAlready <= bufBytes,
1129 "Bad bookkeeping while updating frames pending. Timed buffer is"
1130 " only %u bytes long, but claims to have consumed %u"
1131 " bytes. (update reason: \"%s\")",
1132 bufBytes, consumedAlready, logTag);
1133
1134 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1135 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1136 "Bad bookkeeping while updating frames pending. Should have at"
1137 " least %u queued frames, but we think we have only %u. (update"
1138 " reason: \"%s\")",
1139 bufFrames, mFramesPendingInQueue, logTag);
1140
1141 mFramesPendingInQueue -= bufFrames;
1142}
1143
1144status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1145 const sp<IMemory>& buffer, int64_t pts) {
1146
1147 {
1148 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1149 if (!mMediaTimeTransformValid)
1150 return INVALID_OPERATION;
1151 }
1152
1153 Mutex::Autolock _l(mTimedBufferQueueLock);
1154
1155 uint32_t bufFrames = buffer->size() / mFrameSize;
1156 mFramesPendingInQueue += bufFrames;
1157 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1158
1159 return NO_ERROR;
1160}
1161
1162status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1163 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1164
1165 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1166 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1167 target);
1168
1169 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1170 target == TimedAudioTrack::COMMON_TIME)) {
1171 return BAD_VALUE;
1172 }
1173
1174 Mutex::Autolock lock(mMediaTimeTransformLock);
1175 mMediaTimeTransform = xform;
1176 mMediaTimeTransformTarget = target;
1177 mMediaTimeTransformValid = true;
1178
1179 return NO_ERROR;
1180}
1181
1182#define min(a, b) ((a) < (b) ? (a) : (b))
1183
1184// implementation of getNextBuffer for tracks whose buffers have timestamps
1185status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1186 AudioBufferProvider::Buffer* buffer, int64_t pts)
1187{
1188 if (pts == AudioBufferProvider::kInvalidPTS) {
1189 buffer->raw = NULL;
1190 buffer->frameCount = 0;
1191 mTimedAudioOutputOnTime = false;
1192 return INVALID_OPERATION;
1193 }
1194
1195 Mutex::Autolock _l(mTimedBufferQueueLock);
1196
1197 ALOG_ASSERT(!mQueueHeadInFlight,
1198 "getNextBuffer called without releaseBuffer!");
1199
1200 while (true) {
1201
1202 // if we have no timed buffers, then fail
1203 if (mTimedBufferQueue.isEmpty()) {
1204 buffer->raw = NULL;
1205 buffer->frameCount = 0;
1206 return NOT_ENOUGH_DATA;
1207 }
1208
1209 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1210
1211 // calculate the PTS of the head of the timed buffer queue expressed in
1212 // local time
1213 int64_t headLocalPTS;
1214 {
1215 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1216
1217 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1218
1219 if (mMediaTimeTransform.a_to_b_denom == 0) {
1220 // the transform represents a pause, so yield silence
1221 timedYieldSilence_l(buffer->frameCount, buffer);
1222 return NO_ERROR;
1223 }
1224
1225 int64_t transformedPTS;
1226 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1227 &transformedPTS)) {
1228 // the transform failed. this shouldn't happen, but if it does
1229 // then just drop this buffer
1230 ALOGW("timedGetNextBuffer transform failed");
1231 buffer->raw = NULL;
1232 buffer->frameCount = 0;
1233 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1234 return NO_ERROR;
1235 }
1236
1237 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1238 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1239 &headLocalPTS)) {
1240 buffer->raw = NULL;
1241 buffer->frameCount = 0;
1242 return INVALID_OPERATION;
1243 }
1244 } else {
1245 headLocalPTS = transformedPTS;
1246 }
1247 }
1248
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001249 uint32_t sr = sampleRate();
1250
Eric Laurent81784c32012-11-19 14:55:58 -08001251 // adjust the head buffer's PTS to reflect the portion of the head buffer
1252 // that has already been consumed
1253 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001254 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001255
1256 // Calculate the delta in samples between the head of the input buffer
1257 // queue and the start of the next output buffer that will be written.
1258 // If the transformation fails because of over or underflow, it means
1259 // that the sample's position in the output stream is so far out of
1260 // whack that it should just be dropped.
1261 int64_t sampleDelta;
1262 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1263 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1264 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1265 " mix");
1266 continue;
1267 }
1268 if (!mLocalTimeToSampleTransform.doForwardTransform(
1269 (effectivePTS - pts) << 32, &sampleDelta)) {
1270 ALOGV("*** too late during sample rate transform: dropped buffer");
1271 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1272 continue;
1273 }
1274
1275 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1276 " sampleDelta=[%d.%08x]",
1277 head.pts(), head.position(), pts,
1278 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1279 + (sampleDelta >> 32)),
1280 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1281
1282 // if the delta between the ideal placement for the next input sample and
1283 // the current output position is within this threshold, then we will
1284 // concatenate the next input samples to the previous output
1285 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001286 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001287
1288 // if this is the first buffer of audio that we're emitting from this track
1289 // then it should be almost exactly on time.
1290 const int64_t kSampleStartupThreshold = 1LL << 32;
1291
1292 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1293 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1294 // the next input is close enough to being on time, so concatenate it
1295 // with the last output
1296 timedYieldSamples_l(buffer);
1297
1298 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1299 head.position(), buffer->frameCount);
1300 return NO_ERROR;
1301 }
1302
1303 // Looks like our output is not on time. Reset our on timed status.
1304 // Next time we mix samples from our input queue, then should be within
1305 // the StartupThreshold.
1306 mTimedAudioOutputOnTime = false;
1307 if (sampleDelta > 0) {
1308 // the gap between the current output position and the proper start of
1309 // the next input sample is too big, so fill it with silence
1310 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1311
1312 timedYieldSilence_l(framesUntilNextInput, buffer);
1313 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1314 return NO_ERROR;
1315 } else {
1316 // the next input sample is late
1317 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1318 size_t onTimeSamplePosition =
1319 head.position() + lateFrames * mFrameSize;
1320
1321 if (onTimeSamplePosition > head.buffer()->size()) {
1322 // all the remaining samples in the head are too late, so
1323 // drop it and move on
1324 ALOGV("*** too late: dropped buffer");
1325 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1326 continue;
1327 } else {
1328 // skip over the late samples
1329 head.setPosition(onTimeSamplePosition);
1330
1331 // yield the available samples
1332 timedYieldSamples_l(buffer);
1333
1334 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1335 return NO_ERROR;
1336 }
1337 }
1338 }
1339}
1340
1341// Yield samples from the timed buffer queue head up to the given output
1342// buffer's capacity.
1343//
1344// Caller must hold mTimedBufferQueueLock
1345void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1346 AudioBufferProvider::Buffer* buffer) {
1347
1348 const TimedBuffer& head = mTimedBufferQueue[0];
1349
1350 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1351 head.position());
1352
1353 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1354 mFrameSize);
1355 size_t framesRequested = buffer->frameCount;
1356 buffer->frameCount = min(framesLeftInHead, framesRequested);
1357
1358 mQueueHeadInFlight = true;
1359 mTimedAudioOutputOnTime = true;
1360}
1361
1362// Yield samples of silence up to the given output buffer's capacity
1363//
1364// Caller must hold mTimedBufferQueueLock
1365void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1366 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1367
1368 // lazily allocate a buffer filled with silence
1369 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1370 delete [] mTimedSilenceBuffer;
1371 mTimedSilenceBufferSize = numFrames * mFrameSize;
1372 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1373 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1374 }
1375
1376 buffer->raw = mTimedSilenceBuffer;
1377 size_t framesRequested = buffer->frameCount;
1378 buffer->frameCount = min(numFrames, framesRequested);
1379
1380 mTimedAudioOutputOnTime = false;
1381}
1382
1383// AudioBufferProvider interface
1384void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1385 AudioBufferProvider::Buffer* buffer) {
1386
1387 Mutex::Autolock _l(mTimedBufferQueueLock);
1388
1389 // If the buffer which was just released is part of the buffer at the head
1390 // of the queue, be sure to update the amt of the buffer which has been
1391 // consumed. If the buffer being returned is not part of the head of the
1392 // queue, its either because the buffer is part of the silence buffer, or
1393 // because the head of the timed queue was trimmed after the mixer called
1394 // getNextBuffer but before the mixer called releaseBuffer.
1395 if (buffer->raw == mTimedSilenceBuffer) {
1396 ALOG_ASSERT(!mQueueHeadInFlight,
1397 "Queue head in flight during release of silence buffer!");
1398 goto done;
1399 }
1400
1401 ALOG_ASSERT(mQueueHeadInFlight,
1402 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1403 " head in flight.");
1404
1405 if (mTimedBufferQueue.size()) {
1406 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1407
1408 void* start = head.buffer()->pointer();
1409 void* end = reinterpret_cast<void*>(
1410 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1411 + head.buffer()->size());
1412
1413 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1414 "released buffer not within the head of the timed buffer"
1415 " queue; qHead = [%p, %p], released buffer = %p",
1416 start, end, buffer->raw);
1417
1418 head.setPosition(head.position() +
1419 (buffer->frameCount * mFrameSize));
1420 mQueueHeadInFlight = false;
1421
1422 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1423 "Bad bookkeeping during releaseBuffer! Should have at"
1424 " least %u queued frames, but we think we have only %u",
1425 buffer->frameCount, mFramesPendingInQueue);
1426
1427 mFramesPendingInQueue -= buffer->frameCount;
1428
1429 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1430 || mTrimQueueHeadOnRelease) {
1431 trimTimedBufferQueueHead_l("releaseBuffer");
1432 mTrimQueueHeadOnRelease = false;
1433 }
1434 } else {
1435 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1436 " buffers in the timed buffer queue");
1437 }
1438
1439done:
1440 buffer->raw = 0;
1441 buffer->frameCount = 0;
1442}
1443
1444size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1445 Mutex::Autolock _l(mTimedBufferQueueLock);
1446 return mFramesPendingInQueue;
1447}
1448
1449AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1450 : mPTS(0), mPosition(0) {}
1451
1452AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1453 const sp<IMemory>& buffer, int64_t pts)
1454 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1455
1456
1457// ----------------------------------------------------------------------------
1458
1459AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1460 PlaybackThread *playbackThread,
1461 DuplicatingThread *sourceThread,
1462 uint32_t sampleRate,
1463 audio_format_t format,
1464 audio_channel_mask_t channelMask,
1465 size_t frameCount)
1466 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1467 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001468 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001469{
1470
1471 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001472 mOutBuffer.frameCount = 0;
1473 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001474 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001475 "mCblk->frameCount_ %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001476 mCblk, mBuffer,
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001477 mCblk->frameCount_, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001478 // since client and server are in the same process,
1479 // the buffer has the same virtual address on both sides
1480 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001481 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1482 mClientProxy->setSendLevel(0.0);
1483 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001484 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1485 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001486 } else {
1487 ALOGW("Error creating output track on thread %p", playbackThread);
1488 }
1489}
1490
1491AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1492{
1493 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001494 delete mClientProxy;
1495 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001496}
1497
1498status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1499 int triggerSession)
1500{
1501 status_t status = Track::start(event, triggerSession);
1502 if (status != NO_ERROR) {
1503 return status;
1504 }
1505
1506 mActive = true;
1507 mRetryCount = 127;
1508 return status;
1509}
1510
1511void AudioFlinger::PlaybackThread::OutputTrack::stop()
1512{
1513 Track::stop();
1514 clearBufferQueue();
1515 mOutBuffer.frameCount = 0;
1516 mActive = false;
1517}
1518
1519bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1520{
1521 Buffer *pInBuffer;
1522 Buffer inBuffer;
1523 uint32_t channelCount = mChannelCount;
1524 bool outputBufferFull = false;
1525 inBuffer.frameCount = frames;
1526 inBuffer.i16 = data;
1527
1528 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1529
1530 if (!mActive && frames != 0) {
1531 start();
1532 sp<ThreadBase> thread = mThread.promote();
1533 if (thread != 0) {
1534 MixerThread *mixerThread = (MixerThread *)thread.get();
1535 if (mFrameCount > frames) {
1536 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1537 uint32_t startFrames = (mFrameCount - frames);
1538 pInBuffer = new Buffer;
1539 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1540 pInBuffer->frameCount = startFrames;
1541 pInBuffer->i16 = pInBuffer->mBuffer;
1542 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1543 mBufferQueue.add(pInBuffer);
1544 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001545 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001546 }
1547 }
1548 }
1549 }
1550
1551 while (waitTimeLeftMs) {
1552 // First write pending buffers, then new data
1553 if (mBufferQueue.size()) {
1554 pInBuffer = mBufferQueue.itemAt(0);
1555 } else {
1556 pInBuffer = &inBuffer;
1557 }
1558
1559 if (pInBuffer->frameCount == 0) {
1560 break;
1561 }
1562
1563 if (mOutBuffer.frameCount == 0) {
1564 mOutBuffer.frameCount = pInBuffer->frameCount;
1565 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001566 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1567 if (status != NO_ERROR) {
1568 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1569 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001570 outputBufferFull = true;
1571 break;
1572 }
1573 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1574 if (waitTimeLeftMs >= waitTimeMs) {
1575 waitTimeLeftMs -= waitTimeMs;
1576 } else {
1577 waitTimeLeftMs = 0;
1578 }
1579 }
1580
1581 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1582 pInBuffer->frameCount;
1583 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001584 Proxy::Buffer buf;
1585 buf.mFrameCount = outFrames;
1586 buf.mRaw = NULL;
1587 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001588 pInBuffer->frameCount -= outFrames;
1589 pInBuffer->i16 += outFrames * channelCount;
1590 mOutBuffer.frameCount -= outFrames;
1591 mOutBuffer.i16 += outFrames * channelCount;
1592
1593 if (pInBuffer->frameCount == 0) {
1594 if (mBufferQueue.size()) {
1595 mBufferQueue.removeAt(0);
1596 delete [] pInBuffer->mBuffer;
1597 delete pInBuffer;
1598 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1599 mThread.unsafe_get(), mBufferQueue.size());
1600 } else {
1601 break;
1602 }
1603 }
1604 }
1605
1606 // If we could not write all frames, allocate a buffer and queue it for next time.
1607 if (inBuffer.frameCount) {
1608 sp<ThreadBase> thread = mThread.promote();
1609 if (thread != 0 && !thread->standby()) {
1610 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1611 pInBuffer = new Buffer;
1612 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1613 pInBuffer->frameCount = inBuffer.frameCount;
1614 pInBuffer->i16 = pInBuffer->mBuffer;
1615 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1616 sizeof(int16_t));
1617 mBufferQueue.add(pInBuffer);
1618 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1619 mThread.unsafe_get(), mBufferQueue.size());
1620 } else {
1621 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1622 mThread.unsafe_get(), this);
1623 }
1624 }
1625 }
1626
1627 // Calling write() with a 0 length buffer, means that no more data will be written:
1628 // If no more buffers are pending, fill output track buffer to make sure it is started
1629 // by output mixer.
1630 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001631 // FIXME borken, replace by getting framesReady() from proxy
1632 size_t user = 0; // was mCblk->user
1633 if (user < mFrameCount) {
1634 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001635 pInBuffer = new Buffer;
1636 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1637 pInBuffer->frameCount = frames;
1638 pInBuffer->i16 = pInBuffer->mBuffer;
1639 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1640 mBufferQueue.add(pInBuffer);
1641 } else if (mActive) {
1642 stop();
1643 }
1644 }
1645
1646 return outputBufferFull;
1647}
1648
1649status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1650 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1651{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001652 ClientProxy::Buffer buf;
1653 buf.mFrameCount = buffer->frameCount;
1654 struct timespec timeout;
1655 timeout.tv_sec = waitTimeMs / 1000;
1656 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1657 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1658 buffer->frameCount = buf.mFrameCount;
1659 buffer->raw = buf.mRaw;
1660 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001661}
1662
Eric Laurent81784c32012-11-19 14:55:58 -08001663void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1664{
1665 size_t size = mBufferQueue.size();
1666
1667 for (size_t i = 0; i < size; i++) {
1668 Buffer *pBuffer = mBufferQueue.itemAt(i);
1669 delete [] pBuffer->mBuffer;
1670 delete pBuffer;
1671 }
1672 mBufferQueue.clear();
1673}
1674
1675
1676// ----------------------------------------------------------------------------
1677// Record
1678// ----------------------------------------------------------------------------
1679
1680AudioFlinger::RecordHandle::RecordHandle(
1681 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1682 : BnAudioRecord(),
1683 mRecordTrack(recordTrack)
1684{
1685}
1686
1687AudioFlinger::RecordHandle::~RecordHandle() {
1688 stop_nonvirtual();
1689 mRecordTrack->destroy();
1690}
1691
1692sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1693 return mRecordTrack->getCblk();
1694}
1695
1696status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1697 int triggerSession) {
1698 ALOGV("RecordHandle::start()");
1699 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1700}
1701
1702void AudioFlinger::RecordHandle::stop() {
1703 stop_nonvirtual();
1704}
1705
1706void AudioFlinger::RecordHandle::stop_nonvirtual() {
1707 ALOGV("RecordHandle::stop()");
1708 mRecordTrack->stop();
1709}
1710
1711status_t AudioFlinger::RecordHandle::onTransact(
1712 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1713{
1714 return BnAudioRecord::onTransact(code, data, reply, flags);
1715}
1716
1717// ----------------------------------------------------------------------------
1718
1719// RecordTrack constructor must be called with AudioFlinger::mLock held
1720AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1721 RecordThread *thread,
1722 const sp<Client>& client,
1723 uint32_t sampleRate,
1724 audio_format_t format,
1725 audio_channel_mask_t channelMask,
1726 size_t frameCount,
1727 int sessionId)
1728 : TrackBase(thread, client, sampleRate, format,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001729 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -08001730 mOverflow(false)
1731{
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001732 ALOGV("RecordTrack constructor");
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001733 if (mCblk != NULL) {
Glenn Kasten6ae6b812013-08-05 15:16:21 -07001734 mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount, mFrameSize);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001735 }
Eric Laurent81784c32012-11-19 14:55:58 -08001736}
1737
1738AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1739{
1740 ALOGV("%s", __func__);
1741}
1742
1743// AudioBufferProvider interface
1744status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1745 int64_t pts)
1746{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001747 ServerProxy::Buffer buf;
1748 buf.mFrameCount = buffer->frameCount;
1749 status_t status = mServerProxy->obtainBuffer(&buf);
1750 buffer->frameCount = buf.mFrameCount;
1751 buffer->raw = buf.mRaw;
1752 if (buf.mFrameCount == 0) {
1753 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001754 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001755 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001756 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001757}
1758
1759status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1760 int triggerSession)
1761{
1762 sp<ThreadBase> thread = mThread.promote();
1763 if (thread != 0) {
1764 RecordThread *recordThread = (RecordThread *)thread.get();
1765 return recordThread->start(this, event, triggerSession);
1766 } else {
1767 return BAD_VALUE;
1768 }
1769}
1770
1771void AudioFlinger::RecordThread::RecordTrack::stop()
1772{
1773 sp<ThreadBase> thread = mThread.promote();
1774 if (thread != 0) {
1775 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001776 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001777 AudioSystem::stopInput(recordThread->id());
1778 }
1779 }
1780}
1781
1782void AudioFlinger::RecordThread::RecordTrack::destroy()
1783{
1784 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1785 sp<RecordTrack> keep(this);
1786 {
1787 sp<ThreadBase> thread = mThread.promote();
1788 if (thread != 0) {
1789 if (mState == ACTIVE || mState == RESUMING) {
1790 AudioSystem::stopInput(thread->id());
1791 }
1792 AudioSystem::releaseInput(thread->id());
1793 Mutex::Autolock _l(thread->mLock);
1794 RecordThread *recordThread = (RecordThread *) thread.get();
1795 recordThread->destroyTrack_l(this);
1796 }
1797 }
1798}
1799
Eric Laurent9a54bc22013-09-09 09:08:44 -07001800void AudioFlinger::RecordThread::RecordTrack::invalidate()
1801{
1802 // FIXME should use proxy, and needs work
1803 audio_track_cblk_t* cblk = mCblk;
1804 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1805 android_atomic_release_store(0x40000000, &cblk->mFutex);
1806 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1807 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
1808}
1809
Eric Laurent81784c32012-11-19 14:55:58 -08001810
1811/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1812{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001813 result.append("Client Fmt Chn mask Session S Server fCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001814}
1815
1816void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1817{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001818 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001819 (mClient == 0) ? getpid_cached : mClient->pid(),
1820 mFormat,
1821 mChannelMask,
1822 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001823 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001824 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -08001825 mFrameCount);
1826}
1827
Eric Laurent81784c32012-11-19 14:55:58 -08001828}; // namespace android