blob: db67be657cc4af6e1b02e00db926db69294b0d0c [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");
367}
368
369void AudioFlinger::PlaybackThread::Track::destroy()
370{
371 // NOTE: destroyTrack_l() can remove a strong reference to this Track
372 // by removing it from mTracks vector, so there is a risk that this Tracks's
373 // destructor is called. As the destructor needs to lock mLock,
374 // we must acquire a strong reference on this Track before locking mLock
375 // here so that the destructor is called only when exiting this function.
376 // On the other hand, as long as Track::destroy() is only called by
377 // TrackHandle destructor, the TrackHandle still holds a strong ref on
378 // this Track with its member mTrack.
379 sp<Track> keep(this);
380 { // scope for mLock
381 sp<ThreadBase> thread = mThread.promote();
382 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800383 Mutex::Autolock _l(thread->mLock);
384 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800385 bool wasActive = playbackThread->destroyTrack_l(this);
386 if (!isOutputTrack() && !wasActive) {
387 AudioSystem::releaseOutput(thread->id());
388 }
Eric Laurent81784c32012-11-19 14:55:58 -0800389 }
390 }
391}
392
393/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
394{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -0700395 result.append(" Name Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700396 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800397}
398
399void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
400{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800401 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800402 if (isFastTrack()) {
403 sprintf(buffer, " F %2d", mFastIndex);
404 } else {
405 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
406 }
407 track_state state = mState;
408 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800409 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800410 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800411 } else {
412 switch (state) {
413 case IDLE:
414 stateChar = 'I';
415 break;
416 case STOPPING_1:
417 stateChar = 's';
418 break;
419 case STOPPING_2:
420 stateChar = '5';
421 break;
422 case STOPPED:
423 stateChar = 'S';
424 break;
425 case RESUMING:
426 stateChar = 'R';
427 break;
428 case ACTIVE:
429 stateChar = 'A';
430 break;
431 case PAUSING:
432 stateChar = 'p';
433 break;
434 case PAUSED:
435 stateChar = 'P';
436 break;
437 case FLUSHED:
438 stateChar = 'F';
439 break;
440 default:
441 stateChar = '?';
442 break;
443 }
Eric Laurent81784c32012-11-19 14:55:58 -0800444 }
445 char nowInUnderrun;
446 switch (mObservedUnderruns.mBitFields.mMostRecent) {
447 case UNDERRUN_FULL:
448 nowInUnderrun = ' ';
449 break;
450 case UNDERRUN_PARTIAL:
451 nowInUnderrun = '<';
452 break;
453 case UNDERRUN_EMPTY:
454 nowInUnderrun = '*';
455 break;
456 default:
457 nowInUnderrun = '?';
458 break;
459 }
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -0700460 snprintf(&buffer[7], size-7, " %6u %4u %3u %08X %7u %6u %1c %1d %5u %5.2g %5.2g "
461 "%08X %08X %08X 0x%03X %9u%c\n",
Eric Laurent81784c32012-11-19 14:55:58 -0800462 (mClient == 0) ? getpid_cached : mClient->pid(),
463 mStreamType,
464 mFormat,
465 mChannelMask,
466 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800467 mFrameCount,
468 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800469 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800470 mAudioTrackServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800471 20.0 * log10((vlr & 0xFFFF) / 4096.0),
472 20.0 * log10((vlr >> 16) / 4096.0),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700473 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -0800474 (int)mMainBuffer,
475 (int)mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700476 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700477 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800478 nowInUnderrun);
479}
480
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800481uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
482 return mAudioTrackServerProxy->getSampleRate();
483}
484
Eric Laurent81784c32012-11-19 14:55:58 -0800485// AudioBufferProvider interface
486status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
487 AudioBufferProvider::Buffer* buffer, int64_t pts)
488{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800489 ServerProxy::Buffer buf;
490 size_t desiredFrames = buffer->frameCount;
491 buf.mFrameCount = desiredFrames;
492 status_t status = mServerProxy->obtainBuffer(&buf);
493 buffer->frameCount = buf.mFrameCount;
494 buffer->raw = buf.mRaw;
495 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700496 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800497 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800498 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800499}
500
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700501// releaseBuffer() is not overridden
502
503// ExtendedAudioBufferProvider interface
504
Eric Laurent81784c32012-11-19 14:55:58 -0800505// Note that framesReady() takes a mutex on the control block using tryLock().
506// This could result in priority inversion if framesReady() is called by the normal mixer,
507// as the normal mixer thread runs at lower
508// priority than the client's callback thread: there is a short window within framesReady()
509// during which the normal mixer could be preempted, and the client callback would block.
510// Another problem can occur if framesReady() is called by the fast mixer:
511// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
512// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
513size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800514 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800515}
516
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700517size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
518{
519 return mAudioTrackServerProxy->framesReleased();
520}
521
Eric Laurent81784c32012-11-19 14:55:58 -0800522// Don't call for fast tracks; the framesReady() could result in priority inversion
523bool AudioFlinger::PlaybackThread::Track::isReady() const {
524 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
525 return true;
526 }
527
528 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700529 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800530 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700531 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800532 return true;
533 }
534 return false;
535}
536
537status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
538 int triggerSession)
539{
540 status_t status = NO_ERROR;
541 ALOGV("start(%d), calling pid %d session %d",
542 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
543
544 sp<ThreadBase> thread = mThread.promote();
545 if (thread != 0) {
546 Mutex::Autolock _l(thread->mLock);
547 track_state state = mState;
548 // here the track could be either new, or restarted
549 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800550
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800551 if (state == PAUSED) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800552 if (mResumeToStopping) {
553 // happened we need to resume to STOPPING_1
554 mState = TrackBase::STOPPING_1;
555 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
556 } else {
557 mState = TrackBase::RESUMING;
558 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
559 }
Eric Laurent81784c32012-11-19 14:55:58 -0800560 } else {
561 mState = TrackBase::ACTIVE;
562 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
563 }
564
Eric Laurentbfb1b832013-01-07 09:53:42 -0800565 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
566 status = playbackThread->addTrack_l(this);
567 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800568 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800569 // restore previous state if start was rejected by policy manager
570 if (status == PERMISSION_DENIED) {
571 mState = state;
572 }
573 }
574 // track was already in the active list, not a problem
575 if (status == ALREADY_EXISTS) {
576 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -0800577 }
578 } else {
579 status = BAD_VALUE;
580 }
581 return status;
582}
583
584void AudioFlinger::PlaybackThread::Track::stop()
585{
586 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
587 sp<ThreadBase> thread = mThread.promote();
588 if (thread != 0) {
589 Mutex::Autolock _l(thread->mLock);
590 track_state state = mState;
591 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
592 // If the track is not active (PAUSED and buffers full), flush buffers
593 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
594 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
595 reset();
596 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800597 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800598 mState = STOPPED;
599 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800600 // For fast tracks prepareTracks_l() will set state to STOPPING_2
601 // presentation is complete
602 // For an offloaded track this starts a drain and state will
603 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800604 mState = STOPPING_1;
605 }
606 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
607 playbackThread);
608 }
Eric Laurent81784c32012-11-19 14:55:58 -0800609 }
610}
611
612void AudioFlinger::PlaybackThread::Track::pause()
613{
614 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
615 sp<ThreadBase> thread = mThread.promote();
616 if (thread != 0) {
617 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800618 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
619 switch (mState) {
620 case STOPPING_1:
621 case STOPPING_2:
622 if (!isOffloaded()) {
623 /* nothing to do if track is not offloaded */
624 break;
625 }
626
627 // Offloaded track was draining, we need to carry on draining when resumed
628 mResumeToStopping = true;
629 // fall through...
630 case ACTIVE:
631 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800632 mState = PAUSING;
633 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -0800634 playbackThread->signal_l();
635 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800636
Eric Laurentbfb1b832013-01-07 09:53:42 -0800637 default:
638 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800639 }
640 }
641}
642
643void AudioFlinger::PlaybackThread::Track::flush()
644{
645 ALOGV("flush(%d)", mName);
646 sp<ThreadBase> thread = mThread.promote();
647 if (thread != 0) {
648 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800649 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800650
651 if (isOffloaded()) {
652 // If offloaded we allow flush during any state except terminated
653 // and keep the track active to avoid problems if user is seeking
654 // rapidly and underlying hardware has a significant delay handling
655 // a pause
656 if (isTerminated()) {
657 return;
658 }
659
660 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800661 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800662
663 if (mState == STOPPING_1 || mState == STOPPING_2) {
664 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
665 mState = ACTIVE;
666 }
667
668 if (mState == ACTIVE) {
669 ALOGV("flush called in active state, resetting buffer time out retry count");
670 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
671 }
672
673 mResumeToStopping = false;
674 } else {
675 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
676 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
677 return;
678 }
679 // No point remaining in PAUSED state after a flush => go to
680 // FLUSHED state
681 mState = FLUSHED;
682 // do not reset the track if it is still in the process of being stopped or paused.
683 // this will be done by prepareTracks_l() when the track is stopped.
684 // prepareTracks_l() will see mState == FLUSHED, then
685 // remove from active track list, reset(), and trigger presentation complete
686 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
687 reset();
688 }
Eric Laurent81784c32012-11-19 14:55:58 -0800689 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800690 // Prevent flush being lost if the track is flushed and then resumed
691 // before mixer thread can run. This is important when offloading
692 // because the hardware buffer could hold a large amount of audio
693 playbackThread->flushOutput_l();
694 playbackThread->signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800695 }
696}
697
698void AudioFlinger::PlaybackThread::Track::reset()
699{
700 // Do not reset twice to avoid discarding data written just after a flush and before
701 // the audioflinger thread detects the track is stopped.
702 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800703 // Force underrun condition to avoid false underrun callback until first data is
704 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700705 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800706 mFillingUpStatus = FS_FILLING;
707 mResetDone = true;
708 if (mState == FLUSHED) {
709 mState = IDLE;
710 }
711 }
712}
713
Eric Laurentbfb1b832013-01-07 09:53:42 -0800714status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
715{
716 sp<ThreadBase> thread = mThread.promote();
717 if (thread == 0) {
718 ALOGE("thread is dead");
719 return FAILED_TRANSACTION;
720 } else if ((thread->type() == ThreadBase::DIRECT) ||
721 (thread->type() == ThreadBase::OFFLOAD)) {
722 return thread->setParameters(keyValuePairs);
723 } else {
724 return PERMISSION_DENIED;
725 }
726}
727
Glenn Kasten573d80a2013-08-26 09:36:23 -0700728status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
729{
730 sp<ThreadBase> thread = mThread.promote();
731 if (thread == 0) {
732 return false;
733 }
734 Mutex::Autolock _l(thread->mLock);
735 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700736 if (!playbackThread->mLatchQValid) {
737 return INVALID_OPERATION;
738 }
739 uint32_t unpresentedFrames =
740 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
741 playbackThread->mSampleRate;
742 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
743 if (framesWritten < unpresentedFrames) {
744 return INVALID_OPERATION;
745 }
746 timestamp.mPosition = framesWritten - unpresentedFrames;
747 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
748 return NO_ERROR;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700749}
750
Eric Laurent81784c32012-11-19 14:55:58 -0800751status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
752{
753 status_t status = DEAD_OBJECT;
754 sp<ThreadBase> thread = mThread.promote();
755 if (thread != 0) {
756 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
757 sp<AudioFlinger> af = mClient->audioFlinger();
758
759 Mutex::Autolock _l(af->mLock);
760
761 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
762
763 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
764 Mutex::Autolock _dl(playbackThread->mLock);
765 Mutex::Autolock _sl(srcThread->mLock);
766 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
767 if (chain == 0) {
768 return INVALID_OPERATION;
769 }
770
771 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
772 if (effect == 0) {
773 return INVALID_OPERATION;
774 }
775 srcThread->removeEffect_l(effect);
776 playbackThread->addEffect_l(effect);
777 // removeEffect_l() has stopped the effect if it was active so it must be restarted
778 if (effect->state() == EffectModule::ACTIVE ||
779 effect->state() == EffectModule::STOPPING) {
780 effect->start();
781 }
782
783 sp<EffectChain> dstChain = effect->chain().promote();
784 if (dstChain == 0) {
785 srcThread->addEffect_l(effect);
786 return INVALID_OPERATION;
787 }
788 AudioSystem::unregisterEffect(effect->id());
789 AudioSystem::registerEffect(&effect->desc(),
790 srcThread->id(),
791 dstChain->strategy(),
792 AUDIO_SESSION_OUTPUT_MIX,
793 effect->id());
794 }
795 status = playbackThread->attachAuxEffect(this, EffectId);
796 }
797 return status;
798}
799
800void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
801{
802 mAuxEffectId = EffectId;
803 mAuxBuffer = buffer;
804}
805
806bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
807 size_t audioHalFrames)
808{
809 // a track is considered presented when the total number of frames written to audio HAL
810 // corresponds to the number of frames written when presentationComplete() is called for the
811 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800812 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
813 // to detect when all frames have been played. In this case framesWritten isn't
814 // useful because it doesn't always reflect whether there is data in the h/w
815 // buffers, particularly if a track has been paused and resumed during draining
816 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
817 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800818 if (mPresentationCompleteFrames == 0) {
819 mPresentationCompleteFrames = framesWritten + audioHalFrames;
820 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
821 mPresentationCompleteFrames, audioHalFrames);
822 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800823
824 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800825 ALOGV("presentationComplete() session %d complete: framesWritten %d",
826 mSessionId, framesWritten);
827 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800828 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800829 return true;
830 }
831 return false;
832}
833
834void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
835{
836 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
837 if (mSyncEvents[i]->type() == type) {
838 mSyncEvents[i]->trigger();
839 mSyncEvents.removeAt(i);
840 i--;
841 }
842 }
843}
844
845// implement VolumeBufferProvider interface
846
847uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
848{
849 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
850 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800851 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800852 uint32_t vl = vlr & 0xFFFF;
853 uint32_t vr = vlr >> 16;
854 // track volumes come from shared memory, so can't be trusted and must be clamped
855 if (vl > MAX_GAIN_INT) {
856 vl = MAX_GAIN_INT;
857 }
858 if (vr > MAX_GAIN_INT) {
859 vr = MAX_GAIN_INT;
860 }
861 // now apply the cached master volume and stream type volume;
862 // this is trusted but lacks any synchronization or barrier so may be stale
863 float v = mCachedVolume;
864 vl *= v;
865 vr *= v;
866 // re-combine into U4.16
867 vlr = (vr << 16) | (vl & 0xFFFF);
868 // FIXME look at mute, pause, and stop flags
869 return vlr;
870}
871
872status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
873{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800874 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800875 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
876 (mState == STOPPED)))) {
877 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
878 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
879 event->cancel();
880 return INVALID_OPERATION;
881 }
882 (void) TrackBase::setSyncEvent(event);
883 return NO_ERROR;
884}
885
Glenn Kasten5736c352012-12-04 12:12:34 -0800886void AudioFlinger::PlaybackThread::Track::invalidate()
887{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800888 // FIXME should use proxy, and needs work
889 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700890 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800891 android_atomic_release_store(0x40000000, &cblk->mFutex);
892 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
893 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -0800894 mIsInvalid = true;
895}
896
Eric Laurent81784c32012-11-19 14:55:58 -0800897// ----------------------------------------------------------------------------
898
899sp<AudioFlinger::PlaybackThread::TimedTrack>
900AudioFlinger::PlaybackThread::TimedTrack::create(
901 PlaybackThread *thread,
902 const sp<Client>& client,
903 audio_stream_type_t streamType,
904 uint32_t sampleRate,
905 audio_format_t format,
906 audio_channel_mask_t channelMask,
907 size_t frameCount,
908 const sp<IMemory>& sharedBuffer,
909 int sessionId) {
910 if (!client->reserveTimedTrack())
911 return 0;
912
913 return new TimedTrack(
914 thread, client, streamType, sampleRate, format, channelMask, frameCount,
915 sharedBuffer, sessionId);
916}
917
918AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
919 PlaybackThread *thread,
920 const sp<Client>& client,
921 audio_stream_type_t streamType,
922 uint32_t sampleRate,
923 audio_format_t format,
924 audio_channel_mask_t channelMask,
925 size_t frameCount,
926 const sp<IMemory>& sharedBuffer,
927 int sessionId)
928 : Track(thread, client, streamType, sampleRate, format, channelMask,
929 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
930 mQueueHeadInFlight(false),
931 mTrimQueueHeadOnRelease(false),
932 mFramesPendingInQueue(0),
933 mTimedSilenceBuffer(NULL),
934 mTimedSilenceBufferSize(0),
935 mTimedAudioOutputOnTime(false),
936 mMediaTimeTransformValid(false)
937{
938 LocalClock lc;
939 mLocalTimeFreq = lc.getLocalFreq();
940
941 mLocalTimeToSampleTransform.a_zero = 0;
942 mLocalTimeToSampleTransform.b_zero = 0;
943 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
944 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
945 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
946 &mLocalTimeToSampleTransform.a_to_b_denom);
947
948 mMediaTimeToSampleTransform.a_zero = 0;
949 mMediaTimeToSampleTransform.b_zero = 0;
950 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
951 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
952 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
953 &mMediaTimeToSampleTransform.a_to_b_denom);
954}
955
956AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
957 mClient->releaseTimedTrack();
958 delete [] mTimedSilenceBuffer;
959}
960
961status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
962 size_t size, sp<IMemory>* buffer) {
963
964 Mutex::Autolock _l(mTimedBufferQueueLock);
965
966 trimTimedBufferQueue_l();
967
968 // lazily initialize the shared memory heap for timed buffers
969 if (mTimedMemoryDealer == NULL) {
970 const int kTimedBufferHeapSize = 512 << 10;
971
972 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
973 "AudioFlingerTimed");
974 if (mTimedMemoryDealer == NULL)
975 return NO_MEMORY;
976 }
977
978 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
979 if (newBuffer == NULL) {
980 newBuffer = mTimedMemoryDealer->allocate(size);
981 if (newBuffer == NULL)
982 return NO_MEMORY;
983 }
984
985 *buffer = newBuffer;
986 return NO_ERROR;
987}
988
989// caller must hold mTimedBufferQueueLock
990void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
991 int64_t mediaTimeNow;
992 {
993 Mutex::Autolock mttLock(mMediaTimeTransformLock);
994 if (!mMediaTimeTransformValid)
995 return;
996
997 int64_t targetTimeNow;
998 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
999 ? mCCHelper.getCommonTime(&targetTimeNow)
1000 : mCCHelper.getLocalTime(&targetTimeNow);
1001
1002 if (OK != res)
1003 return;
1004
1005 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1006 &mediaTimeNow)) {
1007 return;
1008 }
1009 }
1010
1011 size_t trimEnd;
1012 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1013 int64_t bufEnd;
1014
1015 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1016 // We have a next buffer. Just use its PTS as the PTS of the frame
1017 // following the last frame in this buffer. If the stream is sparse
1018 // (ie, there are deliberate gaps left in the stream which should be
1019 // filled with silence by the TimedAudioTrack), then this can result
1020 // in one extra buffer being left un-trimmed when it could have
1021 // been. In general, this is not typical, and we would rather
1022 // optimized away the TS calculation below for the more common case
1023 // where PTSes are contiguous.
1024 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1025 } else {
1026 // We have no next buffer. Compute the PTS of the frame following
1027 // the last frame in this buffer by computing the duration of of
1028 // this frame in media time units and adding it to the PTS of the
1029 // buffer.
1030 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1031 / mFrameSize;
1032
1033 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1034 &bufEnd)) {
1035 ALOGE("Failed to convert frame count of %lld to media time"
1036 " duration" " (scale factor %d/%u) in %s",
1037 frameCount,
1038 mMediaTimeToSampleTransform.a_to_b_numer,
1039 mMediaTimeToSampleTransform.a_to_b_denom,
1040 __PRETTY_FUNCTION__);
1041 break;
1042 }
1043 bufEnd += mTimedBufferQueue[trimEnd].pts();
1044 }
1045
1046 if (bufEnd > mediaTimeNow)
1047 break;
1048
1049 // Is the buffer we want to use in the middle of a mix operation right
1050 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1051 // from the mixer which should be coming back shortly.
1052 if (!trimEnd && mQueueHeadInFlight) {
1053 mTrimQueueHeadOnRelease = true;
1054 }
1055 }
1056
1057 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1058 if (trimStart < trimEnd) {
1059 // Update the bookkeeping for framesReady()
1060 for (size_t i = trimStart; i < trimEnd; ++i) {
1061 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1062 }
1063
1064 // Now actually remove the buffers from the queue.
1065 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1066 }
1067}
1068
1069void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1070 const char* logTag) {
1071 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1072 "%s called (reason \"%s\"), but timed buffer queue has no"
1073 " elements to trim.", __FUNCTION__, logTag);
1074
1075 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1076 mTimedBufferQueue.removeAt(0);
1077}
1078
1079void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1080 const TimedBuffer& buf,
1081 const char* logTag) {
1082 uint32_t bufBytes = buf.buffer()->size();
1083 uint32_t consumedAlready = buf.position();
1084
1085 ALOG_ASSERT(consumedAlready <= bufBytes,
1086 "Bad bookkeeping while updating frames pending. Timed buffer is"
1087 " only %u bytes long, but claims to have consumed %u"
1088 " bytes. (update reason: \"%s\")",
1089 bufBytes, consumedAlready, logTag);
1090
1091 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1092 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1093 "Bad bookkeeping while updating frames pending. Should have at"
1094 " least %u queued frames, but we think we have only %u. (update"
1095 " reason: \"%s\")",
1096 bufFrames, mFramesPendingInQueue, logTag);
1097
1098 mFramesPendingInQueue -= bufFrames;
1099}
1100
1101status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1102 const sp<IMemory>& buffer, int64_t pts) {
1103
1104 {
1105 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1106 if (!mMediaTimeTransformValid)
1107 return INVALID_OPERATION;
1108 }
1109
1110 Mutex::Autolock _l(mTimedBufferQueueLock);
1111
1112 uint32_t bufFrames = buffer->size() / mFrameSize;
1113 mFramesPendingInQueue += bufFrames;
1114 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1115
1116 return NO_ERROR;
1117}
1118
1119status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1120 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1121
1122 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1123 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1124 target);
1125
1126 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1127 target == TimedAudioTrack::COMMON_TIME)) {
1128 return BAD_VALUE;
1129 }
1130
1131 Mutex::Autolock lock(mMediaTimeTransformLock);
1132 mMediaTimeTransform = xform;
1133 mMediaTimeTransformTarget = target;
1134 mMediaTimeTransformValid = true;
1135
1136 return NO_ERROR;
1137}
1138
1139#define min(a, b) ((a) < (b) ? (a) : (b))
1140
1141// implementation of getNextBuffer for tracks whose buffers have timestamps
1142status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1143 AudioBufferProvider::Buffer* buffer, int64_t pts)
1144{
1145 if (pts == AudioBufferProvider::kInvalidPTS) {
1146 buffer->raw = NULL;
1147 buffer->frameCount = 0;
1148 mTimedAudioOutputOnTime = false;
1149 return INVALID_OPERATION;
1150 }
1151
1152 Mutex::Autolock _l(mTimedBufferQueueLock);
1153
1154 ALOG_ASSERT(!mQueueHeadInFlight,
1155 "getNextBuffer called without releaseBuffer!");
1156
1157 while (true) {
1158
1159 // if we have no timed buffers, then fail
1160 if (mTimedBufferQueue.isEmpty()) {
1161 buffer->raw = NULL;
1162 buffer->frameCount = 0;
1163 return NOT_ENOUGH_DATA;
1164 }
1165
1166 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1167
1168 // calculate the PTS of the head of the timed buffer queue expressed in
1169 // local time
1170 int64_t headLocalPTS;
1171 {
1172 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1173
1174 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1175
1176 if (mMediaTimeTransform.a_to_b_denom == 0) {
1177 // the transform represents a pause, so yield silence
1178 timedYieldSilence_l(buffer->frameCount, buffer);
1179 return NO_ERROR;
1180 }
1181
1182 int64_t transformedPTS;
1183 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1184 &transformedPTS)) {
1185 // the transform failed. this shouldn't happen, but if it does
1186 // then just drop this buffer
1187 ALOGW("timedGetNextBuffer transform failed");
1188 buffer->raw = NULL;
1189 buffer->frameCount = 0;
1190 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1191 return NO_ERROR;
1192 }
1193
1194 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1195 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1196 &headLocalPTS)) {
1197 buffer->raw = NULL;
1198 buffer->frameCount = 0;
1199 return INVALID_OPERATION;
1200 }
1201 } else {
1202 headLocalPTS = transformedPTS;
1203 }
1204 }
1205
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001206 uint32_t sr = sampleRate();
1207
Eric Laurent81784c32012-11-19 14:55:58 -08001208 // adjust the head buffer's PTS to reflect the portion of the head buffer
1209 // that has already been consumed
1210 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001211 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001212
1213 // Calculate the delta in samples between the head of the input buffer
1214 // queue and the start of the next output buffer that will be written.
1215 // If the transformation fails because of over or underflow, it means
1216 // that the sample's position in the output stream is so far out of
1217 // whack that it should just be dropped.
1218 int64_t sampleDelta;
1219 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1220 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1221 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1222 " mix");
1223 continue;
1224 }
1225 if (!mLocalTimeToSampleTransform.doForwardTransform(
1226 (effectivePTS - pts) << 32, &sampleDelta)) {
1227 ALOGV("*** too late during sample rate transform: dropped buffer");
1228 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1229 continue;
1230 }
1231
1232 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1233 " sampleDelta=[%d.%08x]",
1234 head.pts(), head.position(), pts,
1235 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1236 + (sampleDelta >> 32)),
1237 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1238
1239 // if the delta between the ideal placement for the next input sample and
1240 // the current output position is within this threshold, then we will
1241 // concatenate the next input samples to the previous output
1242 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001243 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001244
1245 // if this is the first buffer of audio that we're emitting from this track
1246 // then it should be almost exactly on time.
1247 const int64_t kSampleStartupThreshold = 1LL << 32;
1248
1249 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1250 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1251 // the next input is close enough to being on time, so concatenate it
1252 // with the last output
1253 timedYieldSamples_l(buffer);
1254
1255 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1256 head.position(), buffer->frameCount);
1257 return NO_ERROR;
1258 }
1259
1260 // Looks like our output is not on time. Reset our on timed status.
1261 // Next time we mix samples from our input queue, then should be within
1262 // the StartupThreshold.
1263 mTimedAudioOutputOnTime = false;
1264 if (sampleDelta > 0) {
1265 // the gap between the current output position and the proper start of
1266 // the next input sample is too big, so fill it with silence
1267 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1268
1269 timedYieldSilence_l(framesUntilNextInput, buffer);
1270 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1271 return NO_ERROR;
1272 } else {
1273 // the next input sample is late
1274 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1275 size_t onTimeSamplePosition =
1276 head.position() + lateFrames * mFrameSize;
1277
1278 if (onTimeSamplePosition > head.buffer()->size()) {
1279 // all the remaining samples in the head are too late, so
1280 // drop it and move on
1281 ALOGV("*** too late: dropped buffer");
1282 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1283 continue;
1284 } else {
1285 // skip over the late samples
1286 head.setPosition(onTimeSamplePosition);
1287
1288 // yield the available samples
1289 timedYieldSamples_l(buffer);
1290
1291 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1292 return NO_ERROR;
1293 }
1294 }
1295 }
1296}
1297
1298// Yield samples from the timed buffer queue head up to the given output
1299// buffer's capacity.
1300//
1301// Caller must hold mTimedBufferQueueLock
1302void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1303 AudioBufferProvider::Buffer* buffer) {
1304
1305 const TimedBuffer& head = mTimedBufferQueue[0];
1306
1307 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1308 head.position());
1309
1310 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1311 mFrameSize);
1312 size_t framesRequested = buffer->frameCount;
1313 buffer->frameCount = min(framesLeftInHead, framesRequested);
1314
1315 mQueueHeadInFlight = true;
1316 mTimedAudioOutputOnTime = true;
1317}
1318
1319// Yield samples of silence up to the given output buffer's capacity
1320//
1321// Caller must hold mTimedBufferQueueLock
1322void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1323 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1324
1325 // lazily allocate a buffer filled with silence
1326 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1327 delete [] mTimedSilenceBuffer;
1328 mTimedSilenceBufferSize = numFrames * mFrameSize;
1329 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1330 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1331 }
1332
1333 buffer->raw = mTimedSilenceBuffer;
1334 size_t framesRequested = buffer->frameCount;
1335 buffer->frameCount = min(numFrames, framesRequested);
1336
1337 mTimedAudioOutputOnTime = false;
1338}
1339
1340// AudioBufferProvider interface
1341void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1342 AudioBufferProvider::Buffer* buffer) {
1343
1344 Mutex::Autolock _l(mTimedBufferQueueLock);
1345
1346 // If the buffer which was just released is part of the buffer at the head
1347 // of the queue, be sure to update the amt of the buffer which has been
1348 // consumed. If the buffer being returned is not part of the head of the
1349 // queue, its either because the buffer is part of the silence buffer, or
1350 // because the head of the timed queue was trimmed after the mixer called
1351 // getNextBuffer but before the mixer called releaseBuffer.
1352 if (buffer->raw == mTimedSilenceBuffer) {
1353 ALOG_ASSERT(!mQueueHeadInFlight,
1354 "Queue head in flight during release of silence buffer!");
1355 goto done;
1356 }
1357
1358 ALOG_ASSERT(mQueueHeadInFlight,
1359 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1360 " head in flight.");
1361
1362 if (mTimedBufferQueue.size()) {
1363 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1364
1365 void* start = head.buffer()->pointer();
1366 void* end = reinterpret_cast<void*>(
1367 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1368 + head.buffer()->size());
1369
1370 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1371 "released buffer not within the head of the timed buffer"
1372 " queue; qHead = [%p, %p], released buffer = %p",
1373 start, end, buffer->raw);
1374
1375 head.setPosition(head.position() +
1376 (buffer->frameCount * mFrameSize));
1377 mQueueHeadInFlight = false;
1378
1379 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1380 "Bad bookkeeping during releaseBuffer! Should have at"
1381 " least %u queued frames, but we think we have only %u",
1382 buffer->frameCount, mFramesPendingInQueue);
1383
1384 mFramesPendingInQueue -= buffer->frameCount;
1385
1386 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1387 || mTrimQueueHeadOnRelease) {
1388 trimTimedBufferQueueHead_l("releaseBuffer");
1389 mTrimQueueHeadOnRelease = false;
1390 }
1391 } else {
1392 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1393 " buffers in the timed buffer queue");
1394 }
1395
1396done:
1397 buffer->raw = 0;
1398 buffer->frameCount = 0;
1399}
1400
1401size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1402 Mutex::Autolock _l(mTimedBufferQueueLock);
1403 return mFramesPendingInQueue;
1404}
1405
1406AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1407 : mPTS(0), mPosition(0) {}
1408
1409AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1410 const sp<IMemory>& buffer, int64_t pts)
1411 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1412
1413
1414// ----------------------------------------------------------------------------
1415
1416AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1417 PlaybackThread *playbackThread,
1418 DuplicatingThread *sourceThread,
1419 uint32_t sampleRate,
1420 audio_format_t format,
1421 audio_channel_mask_t channelMask,
1422 size_t frameCount)
1423 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1424 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001425 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001426{
1427
1428 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001429 mOutBuffer.frameCount = 0;
1430 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001431 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001432 "mCblk->frameCount_ %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001433 mCblk, mBuffer,
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001434 mCblk->frameCount_, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001435 // since client and server are in the same process,
1436 // the buffer has the same virtual address on both sides
1437 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001438 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1439 mClientProxy->setSendLevel(0.0);
1440 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001441 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1442 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001443 } else {
1444 ALOGW("Error creating output track on thread %p", playbackThread);
1445 }
1446}
1447
1448AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1449{
1450 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001451 delete mClientProxy;
1452 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001453}
1454
1455status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1456 int triggerSession)
1457{
1458 status_t status = Track::start(event, triggerSession);
1459 if (status != NO_ERROR) {
1460 return status;
1461 }
1462
1463 mActive = true;
1464 mRetryCount = 127;
1465 return status;
1466}
1467
1468void AudioFlinger::PlaybackThread::OutputTrack::stop()
1469{
1470 Track::stop();
1471 clearBufferQueue();
1472 mOutBuffer.frameCount = 0;
1473 mActive = false;
1474}
1475
1476bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1477{
1478 Buffer *pInBuffer;
1479 Buffer inBuffer;
1480 uint32_t channelCount = mChannelCount;
1481 bool outputBufferFull = false;
1482 inBuffer.frameCount = frames;
1483 inBuffer.i16 = data;
1484
1485 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1486
1487 if (!mActive && frames != 0) {
1488 start();
1489 sp<ThreadBase> thread = mThread.promote();
1490 if (thread != 0) {
1491 MixerThread *mixerThread = (MixerThread *)thread.get();
1492 if (mFrameCount > frames) {
1493 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1494 uint32_t startFrames = (mFrameCount - frames);
1495 pInBuffer = new Buffer;
1496 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1497 pInBuffer->frameCount = startFrames;
1498 pInBuffer->i16 = pInBuffer->mBuffer;
1499 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1500 mBufferQueue.add(pInBuffer);
1501 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001502 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001503 }
1504 }
1505 }
1506 }
1507
1508 while (waitTimeLeftMs) {
1509 // First write pending buffers, then new data
1510 if (mBufferQueue.size()) {
1511 pInBuffer = mBufferQueue.itemAt(0);
1512 } else {
1513 pInBuffer = &inBuffer;
1514 }
1515
1516 if (pInBuffer->frameCount == 0) {
1517 break;
1518 }
1519
1520 if (mOutBuffer.frameCount == 0) {
1521 mOutBuffer.frameCount = pInBuffer->frameCount;
1522 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001523 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1524 if (status != NO_ERROR) {
1525 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1526 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001527 outputBufferFull = true;
1528 break;
1529 }
1530 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1531 if (waitTimeLeftMs >= waitTimeMs) {
1532 waitTimeLeftMs -= waitTimeMs;
1533 } else {
1534 waitTimeLeftMs = 0;
1535 }
1536 }
1537
1538 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1539 pInBuffer->frameCount;
1540 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001541 Proxy::Buffer buf;
1542 buf.mFrameCount = outFrames;
1543 buf.mRaw = NULL;
1544 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001545 pInBuffer->frameCount -= outFrames;
1546 pInBuffer->i16 += outFrames * channelCount;
1547 mOutBuffer.frameCount -= outFrames;
1548 mOutBuffer.i16 += outFrames * channelCount;
1549
1550 if (pInBuffer->frameCount == 0) {
1551 if (mBufferQueue.size()) {
1552 mBufferQueue.removeAt(0);
1553 delete [] pInBuffer->mBuffer;
1554 delete pInBuffer;
1555 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1556 mThread.unsafe_get(), mBufferQueue.size());
1557 } else {
1558 break;
1559 }
1560 }
1561 }
1562
1563 // If we could not write all frames, allocate a buffer and queue it for next time.
1564 if (inBuffer.frameCount) {
1565 sp<ThreadBase> thread = mThread.promote();
1566 if (thread != 0 && !thread->standby()) {
1567 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1568 pInBuffer = new Buffer;
1569 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1570 pInBuffer->frameCount = inBuffer.frameCount;
1571 pInBuffer->i16 = pInBuffer->mBuffer;
1572 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1573 sizeof(int16_t));
1574 mBufferQueue.add(pInBuffer);
1575 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1576 mThread.unsafe_get(), mBufferQueue.size());
1577 } else {
1578 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1579 mThread.unsafe_get(), this);
1580 }
1581 }
1582 }
1583
1584 // Calling write() with a 0 length buffer, means that no more data will be written:
1585 // If no more buffers are pending, fill output track buffer to make sure it is started
1586 // by output mixer.
1587 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001588 // FIXME borken, replace by getting framesReady() from proxy
1589 size_t user = 0; // was mCblk->user
1590 if (user < mFrameCount) {
1591 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001592 pInBuffer = new Buffer;
1593 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1594 pInBuffer->frameCount = frames;
1595 pInBuffer->i16 = pInBuffer->mBuffer;
1596 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1597 mBufferQueue.add(pInBuffer);
1598 } else if (mActive) {
1599 stop();
1600 }
1601 }
1602
1603 return outputBufferFull;
1604}
1605
1606status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1607 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1608{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001609 ClientProxy::Buffer buf;
1610 buf.mFrameCount = buffer->frameCount;
1611 struct timespec timeout;
1612 timeout.tv_sec = waitTimeMs / 1000;
1613 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1614 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1615 buffer->frameCount = buf.mFrameCount;
1616 buffer->raw = buf.mRaw;
1617 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001618}
1619
Eric Laurent81784c32012-11-19 14:55:58 -08001620void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1621{
1622 size_t size = mBufferQueue.size();
1623
1624 for (size_t i = 0; i < size; i++) {
1625 Buffer *pBuffer = mBufferQueue.itemAt(i);
1626 delete [] pBuffer->mBuffer;
1627 delete pBuffer;
1628 }
1629 mBufferQueue.clear();
1630}
1631
1632
1633// ----------------------------------------------------------------------------
1634// Record
1635// ----------------------------------------------------------------------------
1636
1637AudioFlinger::RecordHandle::RecordHandle(
1638 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1639 : BnAudioRecord(),
1640 mRecordTrack(recordTrack)
1641{
1642}
1643
1644AudioFlinger::RecordHandle::~RecordHandle() {
1645 stop_nonvirtual();
1646 mRecordTrack->destroy();
1647}
1648
1649sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1650 return mRecordTrack->getCblk();
1651}
1652
1653status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1654 int triggerSession) {
1655 ALOGV("RecordHandle::start()");
1656 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1657}
1658
1659void AudioFlinger::RecordHandle::stop() {
1660 stop_nonvirtual();
1661}
1662
1663void AudioFlinger::RecordHandle::stop_nonvirtual() {
1664 ALOGV("RecordHandle::stop()");
1665 mRecordTrack->stop();
1666}
1667
1668status_t AudioFlinger::RecordHandle::onTransact(
1669 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1670{
1671 return BnAudioRecord::onTransact(code, data, reply, flags);
1672}
1673
1674// ----------------------------------------------------------------------------
1675
1676// RecordTrack constructor must be called with AudioFlinger::mLock held
1677AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1678 RecordThread *thread,
1679 const sp<Client>& client,
1680 uint32_t sampleRate,
1681 audio_format_t format,
1682 audio_channel_mask_t channelMask,
1683 size_t frameCount,
1684 int sessionId)
1685 : TrackBase(thread, client, sampleRate, format,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001686 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -08001687 mOverflow(false)
1688{
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001689 ALOGV("RecordTrack constructor");
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001690 if (mCblk != NULL) {
1691 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1692 mFrameSize);
1693 mServerProxy = mAudioRecordServerProxy;
1694 }
Eric Laurent81784c32012-11-19 14:55:58 -08001695}
1696
1697AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1698{
1699 ALOGV("%s", __func__);
1700}
1701
1702// AudioBufferProvider interface
1703status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1704 int64_t pts)
1705{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001706 ServerProxy::Buffer buf;
1707 buf.mFrameCount = buffer->frameCount;
1708 status_t status = mServerProxy->obtainBuffer(&buf);
1709 buffer->frameCount = buf.mFrameCount;
1710 buffer->raw = buf.mRaw;
1711 if (buf.mFrameCount == 0) {
1712 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001713 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001714 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001715 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001716}
1717
1718status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1719 int triggerSession)
1720{
1721 sp<ThreadBase> thread = mThread.promote();
1722 if (thread != 0) {
1723 RecordThread *recordThread = (RecordThread *)thread.get();
1724 return recordThread->start(this, event, triggerSession);
1725 } else {
1726 return BAD_VALUE;
1727 }
1728}
1729
1730void AudioFlinger::RecordThread::RecordTrack::stop()
1731{
1732 sp<ThreadBase> thread = mThread.promote();
1733 if (thread != 0) {
1734 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001735 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001736 AudioSystem::stopInput(recordThread->id());
1737 }
1738 }
1739}
1740
1741void AudioFlinger::RecordThread::RecordTrack::destroy()
1742{
1743 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1744 sp<RecordTrack> keep(this);
1745 {
1746 sp<ThreadBase> thread = mThread.promote();
1747 if (thread != 0) {
1748 if (mState == ACTIVE || mState == RESUMING) {
1749 AudioSystem::stopInput(thread->id());
1750 }
1751 AudioSystem::releaseInput(thread->id());
1752 Mutex::Autolock _l(thread->mLock);
1753 RecordThread *recordThread = (RecordThread *) thread.get();
1754 recordThread->destroyTrack_l(this);
1755 }
1756 }
1757}
1758
1759
1760/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1761{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001762 result.append("Client Fmt Chn mask Session S Server fCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001763}
1764
1765void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1766{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001767 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001768 (mClient == 0) ? getpid_cached : mClient->pid(),
1769 mFormat,
1770 mChannelMask,
1771 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001772 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001773 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -08001774 mFrameCount);
1775}
1776
Eric Laurent81784c32012-11-19 14:55:58 -08001777}; // namespace android