blob: d1ab3c84dda9ec3f265ef1b64b473576a3fbef89 [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{
288 return INVALID_OPERATION;
289}
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
501// Note that framesReady() takes a mutex on the control block using tryLock().
502// This could result in priority inversion if framesReady() is called by the normal mixer,
503// as the normal mixer thread runs at lower
504// priority than the client's callback thread: there is a short window within framesReady()
505// during which the normal mixer could be preempted, and the client callback would block.
506// Another problem can occur if framesReady() is called by the fast mixer:
507// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
508// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
509size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800510 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800511}
512
513// Don't call for fast tracks; the framesReady() could result in priority inversion
514bool AudioFlinger::PlaybackThread::Track::isReady() const {
515 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
516 return true;
517 }
518
519 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700520 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800521 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700522 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800523 return true;
524 }
525 return false;
526}
527
528status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
529 int triggerSession)
530{
531 status_t status = NO_ERROR;
532 ALOGV("start(%d), calling pid %d session %d",
533 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
534
535 sp<ThreadBase> thread = mThread.promote();
536 if (thread != 0) {
537 Mutex::Autolock _l(thread->mLock);
538 track_state state = mState;
539 // here the track could be either new, or restarted
540 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800541
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800542 if (state == PAUSED) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800543 if (mResumeToStopping) {
544 // happened we need to resume to STOPPING_1
545 mState = TrackBase::STOPPING_1;
546 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
547 } else {
548 mState = TrackBase::RESUMING;
549 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
550 }
Eric Laurent81784c32012-11-19 14:55:58 -0800551 } else {
552 mState = TrackBase::ACTIVE;
553 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
554 }
555
Eric Laurentbfb1b832013-01-07 09:53:42 -0800556 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
557 status = playbackThread->addTrack_l(this);
558 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800559 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800560 // restore previous state if start was rejected by policy manager
561 if (status == PERMISSION_DENIED) {
562 mState = state;
563 }
564 }
565 // track was already in the active list, not a problem
566 if (status == ALREADY_EXISTS) {
567 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -0800568 }
569 } else {
570 status = BAD_VALUE;
571 }
572 return status;
573}
574
575void AudioFlinger::PlaybackThread::Track::stop()
576{
577 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
578 sp<ThreadBase> thread = mThread.promote();
579 if (thread != 0) {
580 Mutex::Autolock _l(thread->mLock);
581 track_state state = mState;
582 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
583 // If the track is not active (PAUSED and buffers full), flush buffers
584 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
585 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
586 reset();
587 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800588 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800589 mState = STOPPED;
590 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800591 // For fast tracks prepareTracks_l() will set state to STOPPING_2
592 // presentation is complete
593 // For an offloaded track this starts a drain and state will
594 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800595 mState = STOPPING_1;
596 }
597 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
598 playbackThread);
599 }
Eric Laurent81784c32012-11-19 14:55:58 -0800600 }
601}
602
603void AudioFlinger::PlaybackThread::Track::pause()
604{
605 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
606 sp<ThreadBase> thread = mThread.promote();
607 if (thread != 0) {
608 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800609 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
610 switch (mState) {
611 case STOPPING_1:
612 case STOPPING_2:
613 if (!isOffloaded()) {
614 /* nothing to do if track is not offloaded */
615 break;
616 }
617
618 // Offloaded track was draining, we need to carry on draining when resumed
619 mResumeToStopping = true;
620 // fall through...
621 case ACTIVE:
622 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800623 mState = PAUSING;
624 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -0800625 playbackThread->signal_l();
626 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800627
Eric Laurentbfb1b832013-01-07 09:53:42 -0800628 default:
629 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800630 }
631 }
632}
633
634void AudioFlinger::PlaybackThread::Track::flush()
635{
636 ALOGV("flush(%d)", mName);
637 sp<ThreadBase> thread = mThread.promote();
638 if (thread != 0) {
639 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800640 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800641
642 if (isOffloaded()) {
643 // If offloaded we allow flush during any state except terminated
644 // and keep the track active to avoid problems if user is seeking
645 // rapidly and underlying hardware has a significant delay handling
646 // a pause
647 if (isTerminated()) {
648 return;
649 }
650
651 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800652 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800653
654 if (mState == STOPPING_1 || mState == STOPPING_2) {
655 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
656 mState = ACTIVE;
657 }
658
659 if (mState == ACTIVE) {
660 ALOGV("flush called in active state, resetting buffer time out retry count");
661 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
662 }
663
664 mResumeToStopping = false;
665 } else {
666 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
667 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
668 return;
669 }
670 // No point remaining in PAUSED state after a flush => go to
671 // FLUSHED state
672 mState = FLUSHED;
673 // do not reset the track if it is still in the process of being stopped or paused.
674 // this will be done by prepareTracks_l() when the track is stopped.
675 // prepareTracks_l() will see mState == FLUSHED, then
676 // remove from active track list, reset(), and trigger presentation complete
677 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
678 reset();
679 }
Eric Laurent81784c32012-11-19 14:55:58 -0800680 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800681 // Prevent flush being lost if the track is flushed and then resumed
682 // before mixer thread can run. This is important when offloading
683 // because the hardware buffer could hold a large amount of audio
684 playbackThread->flushOutput_l();
685 playbackThread->signal_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800686 }
687}
688
689void AudioFlinger::PlaybackThread::Track::reset()
690{
691 // Do not reset twice to avoid discarding data written just after a flush and before
692 // the audioflinger thread detects the track is stopped.
693 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800694 // Force underrun condition to avoid false underrun callback until first data is
695 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700696 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800697 mFillingUpStatus = FS_FILLING;
698 mResetDone = true;
699 if (mState == FLUSHED) {
700 mState = IDLE;
701 }
702 }
703}
704
Eric Laurentbfb1b832013-01-07 09:53:42 -0800705status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
706{
707 sp<ThreadBase> thread = mThread.promote();
708 if (thread == 0) {
709 ALOGE("thread is dead");
710 return FAILED_TRANSACTION;
711 } else if ((thread->type() == ThreadBase::DIRECT) ||
712 (thread->type() == ThreadBase::OFFLOAD)) {
713 return thread->setParameters(keyValuePairs);
714 } else {
715 return PERMISSION_DENIED;
716 }
717}
718
Eric Laurent81784c32012-11-19 14:55:58 -0800719status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
720{
721 status_t status = DEAD_OBJECT;
722 sp<ThreadBase> thread = mThread.promote();
723 if (thread != 0) {
724 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
725 sp<AudioFlinger> af = mClient->audioFlinger();
726
727 Mutex::Autolock _l(af->mLock);
728
729 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
730
731 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
732 Mutex::Autolock _dl(playbackThread->mLock);
733 Mutex::Autolock _sl(srcThread->mLock);
734 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
735 if (chain == 0) {
736 return INVALID_OPERATION;
737 }
738
739 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
740 if (effect == 0) {
741 return INVALID_OPERATION;
742 }
743 srcThread->removeEffect_l(effect);
744 playbackThread->addEffect_l(effect);
745 // removeEffect_l() has stopped the effect if it was active so it must be restarted
746 if (effect->state() == EffectModule::ACTIVE ||
747 effect->state() == EffectModule::STOPPING) {
748 effect->start();
749 }
750
751 sp<EffectChain> dstChain = effect->chain().promote();
752 if (dstChain == 0) {
753 srcThread->addEffect_l(effect);
754 return INVALID_OPERATION;
755 }
756 AudioSystem::unregisterEffect(effect->id());
757 AudioSystem::registerEffect(&effect->desc(),
758 srcThread->id(),
759 dstChain->strategy(),
760 AUDIO_SESSION_OUTPUT_MIX,
761 effect->id());
762 }
763 status = playbackThread->attachAuxEffect(this, EffectId);
764 }
765 return status;
766}
767
768void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
769{
770 mAuxEffectId = EffectId;
771 mAuxBuffer = buffer;
772}
773
774bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
775 size_t audioHalFrames)
776{
777 // a track is considered presented when the total number of frames written to audio HAL
778 // corresponds to the number of frames written when presentationComplete() is called for the
779 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800780 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
781 // to detect when all frames have been played. In this case framesWritten isn't
782 // useful because it doesn't always reflect whether there is data in the h/w
783 // buffers, particularly if a track has been paused and resumed during draining
784 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
785 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800786 if (mPresentationCompleteFrames == 0) {
787 mPresentationCompleteFrames = framesWritten + audioHalFrames;
788 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
789 mPresentationCompleteFrames, audioHalFrames);
790 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800791
792 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800793 ALOGV("presentationComplete() session %d complete: framesWritten %d",
794 mSessionId, framesWritten);
795 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800796 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800797 return true;
798 }
799 return false;
800}
801
802void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
803{
804 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
805 if (mSyncEvents[i]->type() == type) {
806 mSyncEvents[i]->trigger();
807 mSyncEvents.removeAt(i);
808 i--;
809 }
810 }
811}
812
813// implement VolumeBufferProvider interface
814
815uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
816{
817 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
818 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800819 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800820 uint32_t vl = vlr & 0xFFFF;
821 uint32_t vr = vlr >> 16;
822 // track volumes come from shared memory, so can't be trusted and must be clamped
823 if (vl > MAX_GAIN_INT) {
824 vl = MAX_GAIN_INT;
825 }
826 if (vr > MAX_GAIN_INT) {
827 vr = MAX_GAIN_INT;
828 }
829 // now apply the cached master volume and stream type volume;
830 // this is trusted but lacks any synchronization or barrier so may be stale
831 float v = mCachedVolume;
832 vl *= v;
833 vr *= v;
834 // re-combine into U4.16
835 vlr = (vr << 16) | (vl & 0xFFFF);
836 // FIXME look at mute, pause, and stop flags
837 return vlr;
838}
839
840status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
841{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800842 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800843 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
844 (mState == STOPPED)))) {
845 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
846 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
847 event->cancel();
848 return INVALID_OPERATION;
849 }
850 (void) TrackBase::setSyncEvent(event);
851 return NO_ERROR;
852}
853
Glenn Kasten5736c352012-12-04 12:12:34 -0800854void AudioFlinger::PlaybackThread::Track::invalidate()
855{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800856 // FIXME should use proxy, and needs work
857 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700858 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800859 android_atomic_release_store(0x40000000, &cblk->mFutex);
860 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
861 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -0800862 mIsInvalid = true;
863}
864
Eric Laurent81784c32012-11-19 14:55:58 -0800865// ----------------------------------------------------------------------------
866
867sp<AudioFlinger::PlaybackThread::TimedTrack>
868AudioFlinger::PlaybackThread::TimedTrack::create(
869 PlaybackThread *thread,
870 const sp<Client>& client,
871 audio_stream_type_t streamType,
872 uint32_t sampleRate,
873 audio_format_t format,
874 audio_channel_mask_t channelMask,
875 size_t frameCount,
876 const sp<IMemory>& sharedBuffer,
877 int sessionId) {
878 if (!client->reserveTimedTrack())
879 return 0;
880
881 return new TimedTrack(
882 thread, client, streamType, sampleRate, format, channelMask, frameCount,
883 sharedBuffer, sessionId);
884}
885
886AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
887 PlaybackThread *thread,
888 const sp<Client>& client,
889 audio_stream_type_t streamType,
890 uint32_t sampleRate,
891 audio_format_t format,
892 audio_channel_mask_t channelMask,
893 size_t frameCount,
894 const sp<IMemory>& sharedBuffer,
895 int sessionId)
896 : Track(thread, client, streamType, sampleRate, format, channelMask,
897 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
898 mQueueHeadInFlight(false),
899 mTrimQueueHeadOnRelease(false),
900 mFramesPendingInQueue(0),
901 mTimedSilenceBuffer(NULL),
902 mTimedSilenceBufferSize(0),
903 mTimedAudioOutputOnTime(false),
904 mMediaTimeTransformValid(false)
905{
906 LocalClock lc;
907 mLocalTimeFreq = lc.getLocalFreq();
908
909 mLocalTimeToSampleTransform.a_zero = 0;
910 mLocalTimeToSampleTransform.b_zero = 0;
911 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
912 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
913 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
914 &mLocalTimeToSampleTransform.a_to_b_denom);
915
916 mMediaTimeToSampleTransform.a_zero = 0;
917 mMediaTimeToSampleTransform.b_zero = 0;
918 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
919 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
920 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
921 &mMediaTimeToSampleTransform.a_to_b_denom);
922}
923
924AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
925 mClient->releaseTimedTrack();
926 delete [] mTimedSilenceBuffer;
927}
928
929status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
930 size_t size, sp<IMemory>* buffer) {
931
932 Mutex::Autolock _l(mTimedBufferQueueLock);
933
934 trimTimedBufferQueue_l();
935
936 // lazily initialize the shared memory heap for timed buffers
937 if (mTimedMemoryDealer == NULL) {
938 const int kTimedBufferHeapSize = 512 << 10;
939
940 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
941 "AudioFlingerTimed");
942 if (mTimedMemoryDealer == NULL)
943 return NO_MEMORY;
944 }
945
946 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
947 if (newBuffer == NULL) {
948 newBuffer = mTimedMemoryDealer->allocate(size);
949 if (newBuffer == NULL)
950 return NO_MEMORY;
951 }
952
953 *buffer = newBuffer;
954 return NO_ERROR;
955}
956
957// caller must hold mTimedBufferQueueLock
958void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
959 int64_t mediaTimeNow;
960 {
961 Mutex::Autolock mttLock(mMediaTimeTransformLock);
962 if (!mMediaTimeTransformValid)
963 return;
964
965 int64_t targetTimeNow;
966 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
967 ? mCCHelper.getCommonTime(&targetTimeNow)
968 : mCCHelper.getLocalTime(&targetTimeNow);
969
970 if (OK != res)
971 return;
972
973 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
974 &mediaTimeNow)) {
975 return;
976 }
977 }
978
979 size_t trimEnd;
980 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
981 int64_t bufEnd;
982
983 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
984 // We have a next buffer. Just use its PTS as the PTS of the frame
985 // following the last frame in this buffer. If the stream is sparse
986 // (ie, there are deliberate gaps left in the stream which should be
987 // filled with silence by the TimedAudioTrack), then this can result
988 // in one extra buffer being left un-trimmed when it could have
989 // been. In general, this is not typical, and we would rather
990 // optimized away the TS calculation below for the more common case
991 // where PTSes are contiguous.
992 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
993 } else {
994 // We have no next buffer. Compute the PTS of the frame following
995 // the last frame in this buffer by computing the duration of of
996 // this frame in media time units and adding it to the PTS of the
997 // buffer.
998 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
999 / mFrameSize;
1000
1001 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1002 &bufEnd)) {
1003 ALOGE("Failed to convert frame count of %lld to media time"
1004 " duration" " (scale factor %d/%u) in %s",
1005 frameCount,
1006 mMediaTimeToSampleTransform.a_to_b_numer,
1007 mMediaTimeToSampleTransform.a_to_b_denom,
1008 __PRETTY_FUNCTION__);
1009 break;
1010 }
1011 bufEnd += mTimedBufferQueue[trimEnd].pts();
1012 }
1013
1014 if (bufEnd > mediaTimeNow)
1015 break;
1016
1017 // Is the buffer we want to use in the middle of a mix operation right
1018 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1019 // from the mixer which should be coming back shortly.
1020 if (!trimEnd && mQueueHeadInFlight) {
1021 mTrimQueueHeadOnRelease = true;
1022 }
1023 }
1024
1025 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1026 if (trimStart < trimEnd) {
1027 // Update the bookkeeping for framesReady()
1028 for (size_t i = trimStart; i < trimEnd; ++i) {
1029 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1030 }
1031
1032 // Now actually remove the buffers from the queue.
1033 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1034 }
1035}
1036
1037void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1038 const char* logTag) {
1039 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1040 "%s called (reason \"%s\"), but timed buffer queue has no"
1041 " elements to trim.", __FUNCTION__, logTag);
1042
1043 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1044 mTimedBufferQueue.removeAt(0);
1045}
1046
1047void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1048 const TimedBuffer& buf,
1049 const char* logTag) {
1050 uint32_t bufBytes = buf.buffer()->size();
1051 uint32_t consumedAlready = buf.position();
1052
1053 ALOG_ASSERT(consumedAlready <= bufBytes,
1054 "Bad bookkeeping while updating frames pending. Timed buffer is"
1055 " only %u bytes long, but claims to have consumed %u"
1056 " bytes. (update reason: \"%s\")",
1057 bufBytes, consumedAlready, logTag);
1058
1059 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1060 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1061 "Bad bookkeeping while updating frames pending. Should have at"
1062 " least %u queued frames, but we think we have only %u. (update"
1063 " reason: \"%s\")",
1064 bufFrames, mFramesPendingInQueue, logTag);
1065
1066 mFramesPendingInQueue -= bufFrames;
1067}
1068
1069status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1070 const sp<IMemory>& buffer, int64_t pts) {
1071
1072 {
1073 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1074 if (!mMediaTimeTransformValid)
1075 return INVALID_OPERATION;
1076 }
1077
1078 Mutex::Autolock _l(mTimedBufferQueueLock);
1079
1080 uint32_t bufFrames = buffer->size() / mFrameSize;
1081 mFramesPendingInQueue += bufFrames;
1082 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1083
1084 return NO_ERROR;
1085}
1086
1087status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1088 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1089
1090 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1091 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1092 target);
1093
1094 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1095 target == TimedAudioTrack::COMMON_TIME)) {
1096 return BAD_VALUE;
1097 }
1098
1099 Mutex::Autolock lock(mMediaTimeTransformLock);
1100 mMediaTimeTransform = xform;
1101 mMediaTimeTransformTarget = target;
1102 mMediaTimeTransformValid = true;
1103
1104 return NO_ERROR;
1105}
1106
1107#define min(a, b) ((a) < (b) ? (a) : (b))
1108
1109// implementation of getNextBuffer for tracks whose buffers have timestamps
1110status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1111 AudioBufferProvider::Buffer* buffer, int64_t pts)
1112{
1113 if (pts == AudioBufferProvider::kInvalidPTS) {
1114 buffer->raw = NULL;
1115 buffer->frameCount = 0;
1116 mTimedAudioOutputOnTime = false;
1117 return INVALID_OPERATION;
1118 }
1119
1120 Mutex::Autolock _l(mTimedBufferQueueLock);
1121
1122 ALOG_ASSERT(!mQueueHeadInFlight,
1123 "getNextBuffer called without releaseBuffer!");
1124
1125 while (true) {
1126
1127 // if we have no timed buffers, then fail
1128 if (mTimedBufferQueue.isEmpty()) {
1129 buffer->raw = NULL;
1130 buffer->frameCount = 0;
1131 return NOT_ENOUGH_DATA;
1132 }
1133
1134 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1135
1136 // calculate the PTS of the head of the timed buffer queue expressed in
1137 // local time
1138 int64_t headLocalPTS;
1139 {
1140 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1141
1142 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1143
1144 if (mMediaTimeTransform.a_to_b_denom == 0) {
1145 // the transform represents a pause, so yield silence
1146 timedYieldSilence_l(buffer->frameCount, buffer);
1147 return NO_ERROR;
1148 }
1149
1150 int64_t transformedPTS;
1151 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1152 &transformedPTS)) {
1153 // the transform failed. this shouldn't happen, but if it does
1154 // then just drop this buffer
1155 ALOGW("timedGetNextBuffer transform failed");
1156 buffer->raw = NULL;
1157 buffer->frameCount = 0;
1158 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1159 return NO_ERROR;
1160 }
1161
1162 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1163 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1164 &headLocalPTS)) {
1165 buffer->raw = NULL;
1166 buffer->frameCount = 0;
1167 return INVALID_OPERATION;
1168 }
1169 } else {
1170 headLocalPTS = transformedPTS;
1171 }
1172 }
1173
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001174 uint32_t sr = sampleRate();
1175
Eric Laurent81784c32012-11-19 14:55:58 -08001176 // adjust the head buffer's PTS to reflect the portion of the head buffer
1177 // that has already been consumed
1178 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001179 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001180
1181 // Calculate the delta in samples between the head of the input buffer
1182 // queue and the start of the next output buffer that will be written.
1183 // If the transformation fails because of over or underflow, it means
1184 // that the sample's position in the output stream is so far out of
1185 // whack that it should just be dropped.
1186 int64_t sampleDelta;
1187 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1188 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1189 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1190 " mix");
1191 continue;
1192 }
1193 if (!mLocalTimeToSampleTransform.doForwardTransform(
1194 (effectivePTS - pts) << 32, &sampleDelta)) {
1195 ALOGV("*** too late during sample rate transform: dropped buffer");
1196 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1197 continue;
1198 }
1199
1200 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1201 " sampleDelta=[%d.%08x]",
1202 head.pts(), head.position(), pts,
1203 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1204 + (sampleDelta >> 32)),
1205 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1206
1207 // if the delta between the ideal placement for the next input sample and
1208 // the current output position is within this threshold, then we will
1209 // concatenate the next input samples to the previous output
1210 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001211 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001212
1213 // if this is the first buffer of audio that we're emitting from this track
1214 // then it should be almost exactly on time.
1215 const int64_t kSampleStartupThreshold = 1LL << 32;
1216
1217 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1218 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1219 // the next input is close enough to being on time, so concatenate it
1220 // with the last output
1221 timedYieldSamples_l(buffer);
1222
1223 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1224 head.position(), buffer->frameCount);
1225 return NO_ERROR;
1226 }
1227
1228 // Looks like our output is not on time. Reset our on timed status.
1229 // Next time we mix samples from our input queue, then should be within
1230 // the StartupThreshold.
1231 mTimedAudioOutputOnTime = false;
1232 if (sampleDelta > 0) {
1233 // the gap between the current output position and the proper start of
1234 // the next input sample is too big, so fill it with silence
1235 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1236
1237 timedYieldSilence_l(framesUntilNextInput, buffer);
1238 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1239 return NO_ERROR;
1240 } else {
1241 // the next input sample is late
1242 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1243 size_t onTimeSamplePosition =
1244 head.position() + lateFrames * mFrameSize;
1245
1246 if (onTimeSamplePosition > head.buffer()->size()) {
1247 // all the remaining samples in the head are too late, so
1248 // drop it and move on
1249 ALOGV("*** too late: dropped buffer");
1250 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1251 continue;
1252 } else {
1253 // skip over the late samples
1254 head.setPosition(onTimeSamplePosition);
1255
1256 // yield the available samples
1257 timedYieldSamples_l(buffer);
1258
1259 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1260 return NO_ERROR;
1261 }
1262 }
1263 }
1264}
1265
1266// Yield samples from the timed buffer queue head up to the given output
1267// buffer's capacity.
1268//
1269// Caller must hold mTimedBufferQueueLock
1270void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1271 AudioBufferProvider::Buffer* buffer) {
1272
1273 const TimedBuffer& head = mTimedBufferQueue[0];
1274
1275 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1276 head.position());
1277
1278 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1279 mFrameSize);
1280 size_t framesRequested = buffer->frameCount;
1281 buffer->frameCount = min(framesLeftInHead, framesRequested);
1282
1283 mQueueHeadInFlight = true;
1284 mTimedAudioOutputOnTime = true;
1285}
1286
1287// Yield samples of silence up to the given output buffer's capacity
1288//
1289// Caller must hold mTimedBufferQueueLock
1290void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1291 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1292
1293 // lazily allocate a buffer filled with silence
1294 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1295 delete [] mTimedSilenceBuffer;
1296 mTimedSilenceBufferSize = numFrames * mFrameSize;
1297 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1298 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1299 }
1300
1301 buffer->raw = mTimedSilenceBuffer;
1302 size_t framesRequested = buffer->frameCount;
1303 buffer->frameCount = min(numFrames, framesRequested);
1304
1305 mTimedAudioOutputOnTime = false;
1306}
1307
1308// AudioBufferProvider interface
1309void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1310 AudioBufferProvider::Buffer* buffer) {
1311
1312 Mutex::Autolock _l(mTimedBufferQueueLock);
1313
1314 // If the buffer which was just released is part of the buffer at the head
1315 // of the queue, be sure to update the amt of the buffer which has been
1316 // consumed. If the buffer being returned is not part of the head of the
1317 // queue, its either because the buffer is part of the silence buffer, or
1318 // because the head of the timed queue was trimmed after the mixer called
1319 // getNextBuffer but before the mixer called releaseBuffer.
1320 if (buffer->raw == mTimedSilenceBuffer) {
1321 ALOG_ASSERT(!mQueueHeadInFlight,
1322 "Queue head in flight during release of silence buffer!");
1323 goto done;
1324 }
1325
1326 ALOG_ASSERT(mQueueHeadInFlight,
1327 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1328 " head in flight.");
1329
1330 if (mTimedBufferQueue.size()) {
1331 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1332
1333 void* start = head.buffer()->pointer();
1334 void* end = reinterpret_cast<void*>(
1335 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1336 + head.buffer()->size());
1337
1338 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1339 "released buffer not within the head of the timed buffer"
1340 " queue; qHead = [%p, %p], released buffer = %p",
1341 start, end, buffer->raw);
1342
1343 head.setPosition(head.position() +
1344 (buffer->frameCount * mFrameSize));
1345 mQueueHeadInFlight = false;
1346
1347 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1348 "Bad bookkeeping during releaseBuffer! Should have at"
1349 " least %u queued frames, but we think we have only %u",
1350 buffer->frameCount, mFramesPendingInQueue);
1351
1352 mFramesPendingInQueue -= buffer->frameCount;
1353
1354 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1355 || mTrimQueueHeadOnRelease) {
1356 trimTimedBufferQueueHead_l("releaseBuffer");
1357 mTrimQueueHeadOnRelease = false;
1358 }
1359 } else {
1360 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1361 " buffers in the timed buffer queue");
1362 }
1363
1364done:
1365 buffer->raw = 0;
1366 buffer->frameCount = 0;
1367}
1368
1369size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1370 Mutex::Autolock _l(mTimedBufferQueueLock);
1371 return mFramesPendingInQueue;
1372}
1373
1374AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1375 : mPTS(0), mPosition(0) {}
1376
1377AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1378 const sp<IMemory>& buffer, int64_t pts)
1379 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1380
1381
1382// ----------------------------------------------------------------------------
1383
1384AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1385 PlaybackThread *playbackThread,
1386 DuplicatingThread *sourceThread,
1387 uint32_t sampleRate,
1388 audio_format_t format,
1389 audio_channel_mask_t channelMask,
1390 size_t frameCount)
1391 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1392 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001393 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001394{
1395
1396 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001397 mOutBuffer.frameCount = 0;
1398 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001399 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001400 "mCblk->frameCount_ %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001401 mCblk, mBuffer,
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001402 mCblk->frameCount_, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001403 // since client and server are in the same process,
1404 // the buffer has the same virtual address on both sides
1405 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001406 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1407 mClientProxy->setSendLevel(0.0);
1408 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001409 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1410 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001411 } else {
1412 ALOGW("Error creating output track on thread %p", playbackThread);
1413 }
1414}
1415
1416AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1417{
1418 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001419 delete mClientProxy;
1420 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001421}
1422
1423status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1424 int triggerSession)
1425{
1426 status_t status = Track::start(event, triggerSession);
1427 if (status != NO_ERROR) {
1428 return status;
1429 }
1430
1431 mActive = true;
1432 mRetryCount = 127;
1433 return status;
1434}
1435
1436void AudioFlinger::PlaybackThread::OutputTrack::stop()
1437{
1438 Track::stop();
1439 clearBufferQueue();
1440 mOutBuffer.frameCount = 0;
1441 mActive = false;
1442}
1443
1444bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1445{
1446 Buffer *pInBuffer;
1447 Buffer inBuffer;
1448 uint32_t channelCount = mChannelCount;
1449 bool outputBufferFull = false;
1450 inBuffer.frameCount = frames;
1451 inBuffer.i16 = data;
1452
1453 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1454
1455 if (!mActive && frames != 0) {
1456 start();
1457 sp<ThreadBase> thread = mThread.promote();
1458 if (thread != 0) {
1459 MixerThread *mixerThread = (MixerThread *)thread.get();
1460 if (mFrameCount > frames) {
1461 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1462 uint32_t startFrames = (mFrameCount - frames);
1463 pInBuffer = new Buffer;
1464 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1465 pInBuffer->frameCount = startFrames;
1466 pInBuffer->i16 = pInBuffer->mBuffer;
1467 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1468 mBufferQueue.add(pInBuffer);
1469 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001470 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001471 }
1472 }
1473 }
1474 }
1475
1476 while (waitTimeLeftMs) {
1477 // First write pending buffers, then new data
1478 if (mBufferQueue.size()) {
1479 pInBuffer = mBufferQueue.itemAt(0);
1480 } else {
1481 pInBuffer = &inBuffer;
1482 }
1483
1484 if (pInBuffer->frameCount == 0) {
1485 break;
1486 }
1487
1488 if (mOutBuffer.frameCount == 0) {
1489 mOutBuffer.frameCount = pInBuffer->frameCount;
1490 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001491 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1492 if (status != NO_ERROR) {
1493 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1494 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001495 outputBufferFull = true;
1496 break;
1497 }
1498 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1499 if (waitTimeLeftMs >= waitTimeMs) {
1500 waitTimeLeftMs -= waitTimeMs;
1501 } else {
1502 waitTimeLeftMs = 0;
1503 }
1504 }
1505
1506 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1507 pInBuffer->frameCount;
1508 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001509 Proxy::Buffer buf;
1510 buf.mFrameCount = outFrames;
1511 buf.mRaw = NULL;
1512 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001513 pInBuffer->frameCount -= outFrames;
1514 pInBuffer->i16 += outFrames * channelCount;
1515 mOutBuffer.frameCount -= outFrames;
1516 mOutBuffer.i16 += outFrames * channelCount;
1517
1518 if (pInBuffer->frameCount == 0) {
1519 if (mBufferQueue.size()) {
1520 mBufferQueue.removeAt(0);
1521 delete [] pInBuffer->mBuffer;
1522 delete pInBuffer;
1523 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1524 mThread.unsafe_get(), mBufferQueue.size());
1525 } else {
1526 break;
1527 }
1528 }
1529 }
1530
1531 // If we could not write all frames, allocate a buffer and queue it for next time.
1532 if (inBuffer.frameCount) {
1533 sp<ThreadBase> thread = mThread.promote();
1534 if (thread != 0 && !thread->standby()) {
1535 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1536 pInBuffer = new Buffer;
1537 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1538 pInBuffer->frameCount = inBuffer.frameCount;
1539 pInBuffer->i16 = pInBuffer->mBuffer;
1540 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1541 sizeof(int16_t));
1542 mBufferQueue.add(pInBuffer);
1543 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1544 mThread.unsafe_get(), mBufferQueue.size());
1545 } else {
1546 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1547 mThread.unsafe_get(), this);
1548 }
1549 }
1550 }
1551
1552 // Calling write() with a 0 length buffer, means that no more data will be written:
1553 // If no more buffers are pending, fill output track buffer to make sure it is started
1554 // by output mixer.
1555 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001556 // FIXME borken, replace by getting framesReady() from proxy
1557 size_t user = 0; // was mCblk->user
1558 if (user < mFrameCount) {
1559 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001560 pInBuffer = new Buffer;
1561 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1562 pInBuffer->frameCount = frames;
1563 pInBuffer->i16 = pInBuffer->mBuffer;
1564 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1565 mBufferQueue.add(pInBuffer);
1566 } else if (mActive) {
1567 stop();
1568 }
1569 }
1570
1571 return outputBufferFull;
1572}
1573
1574status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1575 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1576{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001577 ClientProxy::Buffer buf;
1578 buf.mFrameCount = buffer->frameCount;
1579 struct timespec timeout;
1580 timeout.tv_sec = waitTimeMs / 1000;
1581 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1582 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1583 buffer->frameCount = buf.mFrameCount;
1584 buffer->raw = buf.mRaw;
1585 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001586}
1587
Eric Laurent81784c32012-11-19 14:55:58 -08001588void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1589{
1590 size_t size = mBufferQueue.size();
1591
1592 for (size_t i = 0; i < size; i++) {
1593 Buffer *pBuffer = mBufferQueue.itemAt(i);
1594 delete [] pBuffer->mBuffer;
1595 delete pBuffer;
1596 }
1597 mBufferQueue.clear();
1598}
1599
1600
1601// ----------------------------------------------------------------------------
1602// Record
1603// ----------------------------------------------------------------------------
1604
1605AudioFlinger::RecordHandle::RecordHandle(
1606 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1607 : BnAudioRecord(),
1608 mRecordTrack(recordTrack)
1609{
1610}
1611
1612AudioFlinger::RecordHandle::~RecordHandle() {
1613 stop_nonvirtual();
1614 mRecordTrack->destroy();
1615}
1616
1617sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1618 return mRecordTrack->getCblk();
1619}
1620
1621status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1622 int triggerSession) {
1623 ALOGV("RecordHandle::start()");
1624 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1625}
1626
1627void AudioFlinger::RecordHandle::stop() {
1628 stop_nonvirtual();
1629}
1630
1631void AudioFlinger::RecordHandle::stop_nonvirtual() {
1632 ALOGV("RecordHandle::stop()");
1633 mRecordTrack->stop();
1634}
1635
1636status_t AudioFlinger::RecordHandle::onTransact(
1637 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1638{
1639 return BnAudioRecord::onTransact(code, data, reply, flags);
1640}
1641
1642// ----------------------------------------------------------------------------
1643
1644// RecordTrack constructor must be called with AudioFlinger::mLock held
1645AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1646 RecordThread *thread,
1647 const sp<Client>& client,
1648 uint32_t sampleRate,
1649 audio_format_t format,
1650 audio_channel_mask_t channelMask,
1651 size_t frameCount,
1652 int sessionId)
1653 : TrackBase(thread, client, sampleRate, format,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001654 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -08001655 mOverflow(false)
1656{
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001657 ALOGV("RecordTrack constructor");
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001658 if (mCblk != NULL) {
1659 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1660 mFrameSize);
1661 mServerProxy = mAudioRecordServerProxy;
1662 }
Eric Laurent81784c32012-11-19 14:55:58 -08001663}
1664
1665AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1666{
1667 ALOGV("%s", __func__);
1668}
1669
1670// AudioBufferProvider interface
1671status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1672 int64_t pts)
1673{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001674 ServerProxy::Buffer buf;
1675 buf.mFrameCount = buffer->frameCount;
1676 status_t status = mServerProxy->obtainBuffer(&buf);
1677 buffer->frameCount = buf.mFrameCount;
1678 buffer->raw = buf.mRaw;
1679 if (buf.mFrameCount == 0) {
1680 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001681 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001682 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001683 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001684}
1685
1686status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1687 int triggerSession)
1688{
1689 sp<ThreadBase> thread = mThread.promote();
1690 if (thread != 0) {
1691 RecordThread *recordThread = (RecordThread *)thread.get();
1692 return recordThread->start(this, event, triggerSession);
1693 } else {
1694 return BAD_VALUE;
1695 }
1696}
1697
1698void AudioFlinger::RecordThread::RecordTrack::stop()
1699{
1700 sp<ThreadBase> thread = mThread.promote();
1701 if (thread != 0) {
1702 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001703 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001704 AudioSystem::stopInput(recordThread->id());
1705 }
1706 }
1707}
1708
1709void AudioFlinger::RecordThread::RecordTrack::destroy()
1710{
1711 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1712 sp<RecordTrack> keep(this);
1713 {
1714 sp<ThreadBase> thread = mThread.promote();
1715 if (thread != 0) {
1716 if (mState == ACTIVE || mState == RESUMING) {
1717 AudioSystem::stopInput(thread->id());
1718 }
1719 AudioSystem::releaseInput(thread->id());
1720 Mutex::Autolock _l(thread->mLock);
1721 RecordThread *recordThread = (RecordThread *) thread.get();
1722 recordThread->destroyTrack_l(this);
1723 }
1724 }
1725}
1726
1727
1728/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1729{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001730 result.append("Client Fmt Chn mask Session S Server fCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001731}
1732
1733void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1734{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001735 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001736 (mClient == 0) ? getpid_cached : mClient->pid(),
1737 mFormat,
1738 mChannelMask,
1739 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001740 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001741 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -08001742 mFrameCount);
1743}
1744
Eric Laurent81784c32012-11-19 14:55:58 -08001745}; // namespace android