blob: e93833f13c4252911a17ce784bdb83b510ce4882 [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 Laurent59fe0102013-09-27 18:48:26 -0700291
292void AudioFlinger::TrackHandle::signal()
293{
294 return mTrack->signal();
295}
296
Eric Laurent81784c32012-11-19 14:55:58 -0800297status_t AudioFlinger::TrackHandle::onTransact(
298 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
299{
300 return BnAudioTrack::onTransact(code, data, reply, flags);
301}
302
303// ----------------------------------------------------------------------------
304
305// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
306AudioFlinger::PlaybackThread::Track::Track(
307 PlaybackThread *thread,
308 const sp<Client>& client,
309 audio_stream_type_t streamType,
310 uint32_t sampleRate,
311 audio_format_t format,
312 audio_channel_mask_t channelMask,
313 size_t frameCount,
314 const sp<IMemory>& sharedBuffer,
315 int sessionId,
316 IAudioFlinger::track_flags_t flags)
317 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
Glenn Kastene3aa6592012-12-04 12:22:46 -0800318 sessionId, true /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -0800319 mFillingUpStatus(FS_INVALID),
320 // mRetryCount initialized later when needed
321 mSharedBuffer(sharedBuffer),
322 mStreamType(streamType),
323 mName(-1), // see note below
324 mMainBuffer(thread->mixBuffer()),
325 mAuxBuffer(NULL),
326 mAuxEffectId(0), mHasVolumeController(false),
327 mPresentationCompleteFrames(0),
328 mFlags(flags),
329 mFastIndex(-1),
Glenn Kasten5736c352012-12-04 12:12:34 -0800330 mCachedVolume(1.0),
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800331 mIsInvalid(false),
Eric Laurentbfb1b832013-01-07 09:53:42 -0800332 mAudioTrackServerProxy(NULL),
333 mResumeToStopping(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800334{
335 if (mCblk != NULL) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800336 if (sharedBuffer == 0) {
337 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
338 mFrameSize);
339 } else {
340 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
341 mFrameSize);
342 }
343 mServerProxy = mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -0800344 // to avoid leaking a track name, do not allocate one unless there is an mCblk
345 mName = thread->getTrackName_l(channelMask, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800346 if (mName < 0) {
347 ALOGE("no more track names available");
348 return;
349 }
350 // only allocate a fast track index if we were able to allocate a normal track name
351 if (flags & IAudioFlinger::TRACK_FAST) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800352 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
Eric Laurent81784c32012-11-19 14:55:58 -0800353 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
354 int i = __builtin_ctz(thread->mFastTrackAvailMask);
355 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
356 // FIXME This is too eager. We allocate a fast track index before the
357 // fast track becomes active. Since fast tracks are a scarce resource,
358 // this means we are potentially denying other more important fast tracks from
359 // being created. It would be better to allocate the index dynamically.
360 mFastIndex = i;
Eric Laurent81784c32012-11-19 14:55:58 -0800361 // Read the initial underruns because this field is never cleared by the fast mixer
362 mObservedUnderruns = thread->getFastTrackUnderruns(i);
363 thread->mFastTrackAvailMask &= ~(1 << i);
364 }
365 }
366 ALOGV("Track constructor name %d, calling pid %d", mName,
367 IPCThreadState::self()->getCallingPid());
368}
369
370AudioFlinger::PlaybackThread::Track::~Track()
371{
372 ALOGV("PlaybackThread::Track destructor");
Glenn Kasten0c72b242013-09-11 09:14:16 -0700373
374 // The destructor would clear mSharedBuffer,
375 // but it will not push the decremented reference count,
376 // leaving the client's IMemory dangling indefinitely.
377 // This prevents that leak.
378 if (mSharedBuffer != 0) {
379 mSharedBuffer.clear();
380 // flush the binder command buffer
381 IPCThreadState::self()->flushCommands();
382 }
Eric Laurent81784c32012-11-19 14:55:58 -0800383}
384
385void AudioFlinger::PlaybackThread::Track::destroy()
386{
387 // NOTE: destroyTrack_l() can remove a strong reference to this Track
388 // by removing it from mTracks vector, so there is a risk that this Tracks's
389 // destructor is called. As the destructor needs to lock mLock,
390 // we must acquire a strong reference on this Track before locking mLock
391 // here so that the destructor is called only when exiting this function.
392 // On the other hand, as long as Track::destroy() is only called by
393 // TrackHandle destructor, the TrackHandle still holds a strong ref on
394 // this Track with its member mTrack.
395 sp<Track> keep(this);
396 { // scope for mLock
397 sp<ThreadBase> thread = mThread.promote();
398 if (thread != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -0800399 Mutex::Autolock _l(thread->mLock);
400 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800401 bool wasActive = playbackThread->destroyTrack_l(this);
402 if (!isOutputTrack() && !wasActive) {
403 AudioSystem::releaseOutput(thread->id());
404 }
Eric Laurent81784c32012-11-19 14:55:58 -0800405 }
406 }
407}
408
409/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
410{
Eric Laurent972a1732013-09-04 09:42:59 -0700411 result.append(" Name Client Type Fmt Chn mask Session fCount S F SRate "
Glenn Kasten82aaf942013-07-17 16:05:07 -0700412 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800413}
414
415void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
416{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800417 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800418 if (isFastTrack()) {
419 sprintf(buffer, " F %2d", mFastIndex);
420 } else {
421 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
422 }
423 track_state state = mState;
424 char stateChar;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800425 if (isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800426 stateChar = 'T';
Eric Laurentbfb1b832013-01-07 09:53:42 -0800427 } else {
428 switch (state) {
429 case IDLE:
430 stateChar = 'I';
431 break;
432 case STOPPING_1:
433 stateChar = 's';
434 break;
435 case STOPPING_2:
436 stateChar = '5';
437 break;
438 case STOPPED:
439 stateChar = 'S';
440 break;
441 case RESUMING:
442 stateChar = 'R';
443 break;
444 case ACTIVE:
445 stateChar = 'A';
446 break;
447 case PAUSING:
448 stateChar = 'p';
449 break;
450 case PAUSED:
451 stateChar = 'P';
452 break;
453 case FLUSHED:
454 stateChar = 'F';
455 break;
456 default:
457 stateChar = '?';
458 break;
459 }
Eric Laurent81784c32012-11-19 14:55:58 -0800460 }
461 char nowInUnderrun;
462 switch (mObservedUnderruns.mBitFields.mMostRecent) {
463 case UNDERRUN_FULL:
464 nowInUnderrun = ' ';
465 break;
466 case UNDERRUN_PARTIAL:
467 nowInUnderrun = '<';
468 break;
469 case UNDERRUN_EMPTY:
470 nowInUnderrun = '*';
471 break;
472 default:
473 nowInUnderrun = '?';
474 break;
475 }
Eric Laurent972a1732013-09-04 09:42:59 -0700476 snprintf(&buffer[7], size-7, " %6u %4u %08X %08X %7u %6u %1c %1d %5u %5.2g %5.2g "
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -0700477 "%08X %08X %08X 0x%03X %9u%c\n",
Eric Laurent81784c32012-11-19 14:55:58 -0800478 (mClient == 0) ? getpid_cached : mClient->pid(),
479 mStreamType,
480 mFormat,
481 mChannelMask,
482 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800483 mFrameCount,
484 stateChar,
Eric Laurent81784c32012-11-19 14:55:58 -0800485 mFillingUpStatus,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800486 mAudioTrackServerProxy->getSampleRate(),
Eric Laurent81784c32012-11-19 14:55:58 -0800487 20.0 * log10((vlr & 0xFFFF) / 4096.0),
488 20.0 * log10((vlr >> 16) / 4096.0),
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700489 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -0800490 (int)mMainBuffer,
491 (int)mAuxBuffer,
Glenn Kasten96f60d82013-07-12 10:21:18 -0700492 mCblk->mFlags,
Glenn Kasten82aaf942013-07-17 16:05:07 -0700493 mAudioTrackServerProxy->getUnderrunFrames(),
Eric Laurent81784c32012-11-19 14:55:58 -0800494 nowInUnderrun);
495}
496
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800497uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
498 return mAudioTrackServerProxy->getSampleRate();
499}
500
Eric Laurent81784c32012-11-19 14:55:58 -0800501// AudioBufferProvider interface
502status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
503 AudioBufferProvider::Buffer* buffer, int64_t pts)
504{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800505 ServerProxy::Buffer buf;
506 size_t desiredFrames = buffer->frameCount;
507 buf.mFrameCount = desiredFrames;
508 status_t status = mServerProxy->obtainBuffer(&buf);
509 buffer->frameCount = buf.mFrameCount;
510 buffer->raw = buf.mRaw;
511 if (buf.mFrameCount == 0) {
Glenn Kasten82aaf942013-07-17 16:05:07 -0700512 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Eric Laurent81784c32012-11-19 14:55:58 -0800513 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800514 return status;
Eric Laurent81784c32012-11-19 14:55:58 -0800515}
516
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700517// releaseBuffer() is not overridden
518
519// ExtendedAudioBufferProvider interface
520
Eric Laurent81784c32012-11-19 14:55:58 -0800521// Note that framesReady() takes a mutex on the control block using tryLock().
522// This could result in priority inversion if framesReady() is called by the normal mixer,
523// as the normal mixer thread runs at lower
524// priority than the client's callback thread: there is a short window within framesReady()
525// during which the normal mixer could be preempted, and the client callback would block.
526// Another problem can occur if framesReady() is called by the fast mixer:
527// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
528// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
529size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800530 return mAudioTrackServerProxy->framesReady();
Eric Laurent81784c32012-11-19 14:55:58 -0800531}
532
Glenn Kasten6466c9e2013-08-23 10:54:07 -0700533size_t AudioFlinger::PlaybackThread::Track::framesReleased() const
534{
535 return mAudioTrackServerProxy->framesReleased();
536}
537
Eric Laurent81784c32012-11-19 14:55:58 -0800538// Don't call for fast tracks; the framesReady() could result in priority inversion
539bool AudioFlinger::PlaybackThread::Track::isReady() const {
540 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
541 return true;
542 }
543
544 if (framesReady() >= mFrameCount ||
Glenn Kasten96f60d82013-07-12 10:21:18 -0700545 (mCblk->mFlags & CBLK_FORCEREADY)) {
Eric Laurent81784c32012-11-19 14:55:58 -0800546 mFillingUpStatus = FS_FILLED;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700547 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800548 return true;
549 }
550 return false;
551}
552
553status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
554 int triggerSession)
555{
556 status_t status = NO_ERROR;
557 ALOGV("start(%d), calling pid %d session %d",
558 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
559
560 sp<ThreadBase> thread = mThread.promote();
561 if (thread != 0) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700562 if (isOffloaded()) {
563 Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
564 Mutex::Autolock _lth(thread->mLock);
565 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700566 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
567 (ec != 0 && ec->isNonOffloadableEnabled())) {
Eric Laurent813e2a72013-08-31 12:59:48 -0700568 invalidate();
569 return PERMISSION_DENIED;
570 }
571 }
572 Mutex::Autolock _lth(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800573 track_state state = mState;
574 // here the track could be either new, or restarted
575 // in both cases "unstop" the track
Eric Laurentbfb1b832013-01-07 09:53:42 -0800576
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800577 if (state == PAUSED) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800578 if (mResumeToStopping) {
579 // happened we need to resume to STOPPING_1
580 mState = TrackBase::STOPPING_1;
581 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
582 } else {
583 mState = TrackBase::RESUMING;
584 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
585 }
Eric Laurent81784c32012-11-19 14:55:58 -0800586 } else {
587 mState = TrackBase::ACTIVE;
588 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
589 }
590
Eric Laurentbfb1b832013-01-07 09:53:42 -0800591 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
592 status = playbackThread->addTrack_l(this);
593 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
Eric Laurent81784c32012-11-19 14:55:58 -0800594 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800595 // restore previous state if start was rejected by policy manager
596 if (status == PERMISSION_DENIED) {
597 mState = state;
598 }
599 }
600 // track was already in the active list, not a problem
601 if (status == ALREADY_EXISTS) {
602 status = NO_ERROR;
Glenn Kasten12022ff2013-10-17 11:32:39 -0700603 } else {
604 // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
605 // It is usually unsafe to access the server proxy from a binder thread.
606 // But in this case we know the mixer thread (whether normal mixer or fast mixer)
607 // isn't looking at this track yet: we still hold the normal mixer thread lock,
608 // and for fast tracks the track is not yet in the fast mixer thread's active set.
609 ServerProxy::Buffer buffer;
610 buffer.mFrameCount = 1;
611 (void) mAudioTrackServerProxy->obtainBuffer(&buffer);
Eric Laurent81784c32012-11-19 14:55:58 -0800612 }
613 } else {
614 status = BAD_VALUE;
615 }
616 return status;
617}
618
619void AudioFlinger::PlaybackThread::Track::stop()
620{
621 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
622 sp<ThreadBase> thread = mThread.promote();
623 if (thread != 0) {
624 Mutex::Autolock _l(thread->mLock);
625 track_state state = mState;
626 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
627 // If the track is not active (PAUSED and buffers full), flush buffers
628 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
629 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
630 reset();
631 mState = STOPPED;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800632 } else if (!isFastTrack() && !isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800633 mState = STOPPED;
634 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800635 // For fast tracks prepareTracks_l() will set state to STOPPING_2
636 // presentation is complete
637 // For an offloaded track this starts a drain and state will
638 // move to STOPPING_2 when drain completes and then STOPPED
Eric Laurent81784c32012-11-19 14:55:58 -0800639 mState = STOPPING_1;
640 }
641 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
642 playbackThread);
643 }
Eric Laurent81784c32012-11-19 14:55:58 -0800644 }
645}
646
647void AudioFlinger::PlaybackThread::Track::pause()
648{
649 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
650 sp<ThreadBase> thread = mThread.promote();
651 if (thread != 0) {
652 Mutex::Autolock _l(thread->mLock);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800653 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
654 switch (mState) {
655 case STOPPING_1:
656 case STOPPING_2:
657 if (!isOffloaded()) {
658 /* nothing to do if track is not offloaded */
659 break;
660 }
661
662 // Offloaded track was draining, we need to carry on draining when resumed
663 mResumeToStopping = true;
664 // fall through...
665 case ACTIVE:
666 case RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -0800667 mState = PAUSING;
668 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurentede6c3b2013-09-19 14:37:46 -0700669 playbackThread->broadcast_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800670 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800671
Eric Laurentbfb1b832013-01-07 09:53:42 -0800672 default:
673 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800674 }
675 }
676}
677
678void AudioFlinger::PlaybackThread::Track::flush()
679{
680 ALOGV("flush(%d)", mName);
681 sp<ThreadBase> thread = mThread.promote();
682 if (thread != 0) {
683 Mutex::Autolock _l(thread->mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800684 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800685
686 if (isOffloaded()) {
687 // If offloaded we allow flush during any state except terminated
688 // and keep the track active to avoid problems if user is seeking
689 // rapidly and underlying hardware has a significant delay handling
690 // a pause
691 if (isTerminated()) {
692 return;
693 }
694
695 ALOGV("flush: offload flush");
Eric Laurent81784c32012-11-19 14:55:58 -0800696 reset();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800697
698 if (mState == STOPPING_1 || mState == STOPPING_2) {
699 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
700 mState = ACTIVE;
701 }
702
703 if (mState == ACTIVE) {
704 ALOGV("flush called in active state, resetting buffer time out retry count");
705 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload;
706 }
707
708 mResumeToStopping = false;
709 } else {
710 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
711 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
712 return;
713 }
714 // No point remaining in PAUSED state after a flush => go to
715 // FLUSHED state
716 mState = FLUSHED;
717 // do not reset the track if it is still in the process of being stopped or paused.
718 // this will be done by prepareTracks_l() when the track is stopped.
719 // prepareTracks_l() will see mState == FLUSHED, then
720 // remove from active track list, reset(), and trigger presentation complete
721 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
722 reset();
723 }
Eric Laurent81784c32012-11-19 14:55:58 -0800724 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800725 // Prevent flush being lost if the track is flushed and then resumed
726 // before mixer thread can run. This is important when offloading
727 // because the hardware buffer could hold a large amount of audio
728 playbackThread->flushOutput_l();
Eric Laurentede6c3b2013-09-19 14:37:46 -0700729 playbackThread->broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800730 }
731}
732
733void AudioFlinger::PlaybackThread::Track::reset()
734{
735 // Do not reset twice to avoid discarding data written just after a flush and before
736 // the audioflinger thread detects the track is stopped.
737 if (!mResetDone) {
Eric Laurent81784c32012-11-19 14:55:58 -0800738 // Force underrun condition to avoid false underrun callback until first data is
739 // written to buffer
Glenn Kasten96f60d82013-07-12 10:21:18 -0700740 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -0800741 mFillingUpStatus = FS_FILLING;
742 mResetDone = true;
743 if (mState == FLUSHED) {
744 mState = IDLE;
745 }
746 }
747}
748
Eric Laurentbfb1b832013-01-07 09:53:42 -0800749status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
750{
751 sp<ThreadBase> thread = mThread.promote();
752 if (thread == 0) {
753 ALOGE("thread is dead");
754 return FAILED_TRANSACTION;
755 } else if ((thread->type() == ThreadBase::DIRECT) ||
756 (thread->type() == ThreadBase::OFFLOAD)) {
757 return thread->setParameters(keyValuePairs);
758 } else {
759 return PERMISSION_DENIED;
760 }
761}
762
Glenn Kasten573d80a2013-08-26 09:36:23 -0700763status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
764{
Glenn Kastenfe346c72013-08-30 13:28:22 -0700765 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant
766 if (isFastTrack()) {
767 return INVALID_OPERATION;
768 }
Glenn Kasten573d80a2013-08-26 09:36:23 -0700769 sp<ThreadBase> thread = mThread.promote();
770 if (thread == 0) {
Glenn Kastenfe346c72013-08-30 13:28:22 -0700771 return INVALID_OPERATION;
Glenn Kasten573d80a2013-08-26 09:36:23 -0700772 }
773 Mutex::Autolock _l(thread->mLock);
774 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurentaccc1472013-09-20 09:36:34 -0700775 if (!isOffloaded()) {
776 if (!playbackThread->mLatchQValid) {
777 return INVALID_OPERATION;
778 }
779 uint32_t unpresentedFrames =
780 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) /
781 playbackThread->mSampleRate;
782 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased();
783 if (framesWritten < unpresentedFrames) {
784 return INVALID_OPERATION;
785 }
786 timestamp.mPosition = framesWritten - unpresentedFrames;
787 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime;
788 return NO_ERROR;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700789 }
Eric Laurentaccc1472013-09-20 09:36:34 -0700790
791 return playbackThread->getTimestamp_l(timestamp);
Glenn Kasten573d80a2013-08-26 09:36:23 -0700792}
793
Eric Laurent81784c32012-11-19 14:55:58 -0800794status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
795{
796 status_t status = DEAD_OBJECT;
797 sp<ThreadBase> thread = mThread.promote();
798 if (thread != 0) {
799 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
800 sp<AudioFlinger> af = mClient->audioFlinger();
801
802 Mutex::Autolock _l(af->mLock);
803
804 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
805
806 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
807 Mutex::Autolock _dl(playbackThread->mLock);
808 Mutex::Autolock _sl(srcThread->mLock);
809 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
810 if (chain == 0) {
811 return INVALID_OPERATION;
812 }
813
814 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
815 if (effect == 0) {
816 return INVALID_OPERATION;
817 }
818 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700819 status = playbackThread->addEffect_l(effect);
820 if (status != NO_ERROR) {
821 srcThread->addEffect_l(effect);
822 return INVALID_OPERATION;
823 }
Eric Laurent81784c32012-11-19 14:55:58 -0800824 // removeEffect_l() has stopped the effect if it was active so it must be restarted
825 if (effect->state() == EffectModule::ACTIVE ||
826 effect->state() == EffectModule::STOPPING) {
827 effect->start();
828 }
829
830 sp<EffectChain> dstChain = effect->chain().promote();
831 if (dstChain == 0) {
832 srcThread->addEffect_l(effect);
833 return INVALID_OPERATION;
834 }
835 AudioSystem::unregisterEffect(effect->id());
836 AudioSystem::registerEffect(&effect->desc(),
837 srcThread->id(),
838 dstChain->strategy(),
839 AUDIO_SESSION_OUTPUT_MIX,
840 effect->id());
841 }
842 status = playbackThread->attachAuxEffect(this, EffectId);
843 }
844 return status;
845}
846
847void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
848{
849 mAuxEffectId = EffectId;
850 mAuxBuffer = buffer;
851}
852
853bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
854 size_t audioHalFrames)
855{
856 // a track is considered presented when the total number of frames written to audio HAL
857 // corresponds to the number of frames written when presentationComplete() is called for the
858 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
Eric Laurentbfb1b832013-01-07 09:53:42 -0800859 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
860 // to detect when all frames have been played. In this case framesWritten isn't
861 // useful because it doesn't always reflect whether there is data in the h/w
862 // buffers, particularly if a track has been paused and resumed during draining
863 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
864 mPresentationCompleteFrames, framesWritten);
Eric Laurent81784c32012-11-19 14:55:58 -0800865 if (mPresentationCompleteFrames == 0) {
866 mPresentationCompleteFrames = framesWritten + audioHalFrames;
867 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
868 mPresentationCompleteFrames, audioHalFrames);
869 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800870
871 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
Eric Laurent81784c32012-11-19 14:55:58 -0800872 ALOGV("presentationComplete() session %d complete: framesWritten %d",
873 mSessionId, framesWritten);
874 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800875 mAudioTrackServerProxy->setStreamEndDone();
Eric Laurent81784c32012-11-19 14:55:58 -0800876 return true;
877 }
878 return false;
879}
880
881void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
882{
883 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
884 if (mSyncEvents[i]->type() == type) {
885 mSyncEvents[i]->trigger();
886 mSyncEvents.removeAt(i);
887 i--;
888 }
889 }
890}
891
892// implement VolumeBufferProvider interface
893
894uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
895{
896 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
897 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800898 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
Eric Laurent81784c32012-11-19 14:55:58 -0800899 uint32_t vl = vlr & 0xFFFF;
900 uint32_t vr = vlr >> 16;
901 // track volumes come from shared memory, so can't be trusted and must be clamped
902 if (vl > MAX_GAIN_INT) {
903 vl = MAX_GAIN_INT;
904 }
905 if (vr > MAX_GAIN_INT) {
906 vr = MAX_GAIN_INT;
907 }
908 // now apply the cached master volume and stream type volume;
909 // this is trusted but lacks any synchronization or barrier so may be stale
910 float v = mCachedVolume;
911 vl *= v;
912 vr *= v;
913 // re-combine into U4.16
914 vlr = (vr << 16) | (vl & 0xFFFF);
915 // FIXME look at mute, pause, and stop flags
916 return vlr;
917}
918
919status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
920{
Eric Laurentbfb1b832013-01-07 09:53:42 -0800921 if (isTerminated() || mState == PAUSED ||
Eric Laurent81784c32012-11-19 14:55:58 -0800922 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
923 (mState == STOPPED)))) {
924 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
925 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
926 event->cancel();
927 return INVALID_OPERATION;
928 }
929 (void) TrackBase::setSyncEvent(event);
930 return NO_ERROR;
931}
932
Glenn Kasten5736c352012-12-04 12:12:34 -0800933void AudioFlinger::PlaybackThread::Track::invalidate()
934{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800935 // FIXME should use proxy, and needs work
936 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700937 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800938 android_atomic_release_store(0x40000000, &cblk->mFutex);
939 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
940 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
Glenn Kasten5736c352012-12-04 12:12:34 -0800941 mIsInvalid = true;
942}
943
Eric Laurent59fe0102013-09-27 18:48:26 -0700944void AudioFlinger::PlaybackThread::Track::signal()
945{
946 sp<ThreadBase> thread = mThread.promote();
947 if (thread != 0) {
948 PlaybackThread *t = (PlaybackThread *)thread.get();
949 Mutex::Autolock _l(t->mLock);
950 t->broadcast_l();
951 }
952}
953
Eric Laurent81784c32012-11-19 14:55:58 -0800954// ----------------------------------------------------------------------------
955
956sp<AudioFlinger::PlaybackThread::TimedTrack>
957AudioFlinger::PlaybackThread::TimedTrack::create(
958 PlaybackThread *thread,
959 const sp<Client>& client,
960 audio_stream_type_t streamType,
961 uint32_t sampleRate,
962 audio_format_t format,
963 audio_channel_mask_t channelMask,
964 size_t frameCount,
965 const sp<IMemory>& sharedBuffer,
966 int sessionId) {
967 if (!client->reserveTimedTrack())
968 return 0;
969
970 return new TimedTrack(
971 thread, client, streamType, sampleRate, format, channelMask, frameCount,
972 sharedBuffer, sessionId);
973}
974
975AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
976 PlaybackThread *thread,
977 const sp<Client>& client,
978 audio_stream_type_t streamType,
979 uint32_t sampleRate,
980 audio_format_t format,
981 audio_channel_mask_t channelMask,
982 size_t frameCount,
983 const sp<IMemory>& sharedBuffer,
984 int sessionId)
985 : Track(thread, client, streamType, sampleRate, format, channelMask,
986 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
987 mQueueHeadInFlight(false),
988 mTrimQueueHeadOnRelease(false),
989 mFramesPendingInQueue(0),
990 mTimedSilenceBuffer(NULL),
991 mTimedSilenceBufferSize(0),
992 mTimedAudioOutputOnTime(false),
993 mMediaTimeTransformValid(false)
994{
995 LocalClock lc;
996 mLocalTimeFreq = lc.getLocalFreq();
997
998 mLocalTimeToSampleTransform.a_zero = 0;
999 mLocalTimeToSampleTransform.b_zero = 0;
1000 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
1001 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
1002 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
1003 &mLocalTimeToSampleTransform.a_to_b_denom);
1004
1005 mMediaTimeToSampleTransform.a_zero = 0;
1006 mMediaTimeToSampleTransform.b_zero = 0;
1007 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1008 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1009 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1010 &mMediaTimeToSampleTransform.a_to_b_denom);
1011}
1012
1013AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1014 mClient->releaseTimedTrack();
1015 delete [] mTimedSilenceBuffer;
1016}
1017
1018status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1019 size_t size, sp<IMemory>* buffer) {
1020
1021 Mutex::Autolock _l(mTimedBufferQueueLock);
1022
1023 trimTimedBufferQueue_l();
1024
1025 // lazily initialize the shared memory heap for timed buffers
1026 if (mTimedMemoryDealer == NULL) {
1027 const int kTimedBufferHeapSize = 512 << 10;
1028
1029 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1030 "AudioFlingerTimed");
1031 if (mTimedMemoryDealer == NULL)
1032 return NO_MEMORY;
1033 }
1034
1035 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
1036 if (newBuffer == NULL) {
1037 newBuffer = mTimedMemoryDealer->allocate(size);
1038 if (newBuffer == NULL)
1039 return NO_MEMORY;
1040 }
1041
1042 *buffer = newBuffer;
1043 return NO_ERROR;
1044}
1045
1046// caller must hold mTimedBufferQueueLock
1047void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1048 int64_t mediaTimeNow;
1049 {
1050 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1051 if (!mMediaTimeTransformValid)
1052 return;
1053
1054 int64_t targetTimeNow;
1055 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1056 ? mCCHelper.getCommonTime(&targetTimeNow)
1057 : mCCHelper.getLocalTime(&targetTimeNow);
1058
1059 if (OK != res)
1060 return;
1061
1062 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1063 &mediaTimeNow)) {
1064 return;
1065 }
1066 }
1067
1068 size_t trimEnd;
1069 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1070 int64_t bufEnd;
1071
1072 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1073 // We have a next buffer. Just use its PTS as the PTS of the frame
1074 // following the last frame in this buffer. If the stream is sparse
1075 // (ie, there are deliberate gaps left in the stream which should be
1076 // filled with silence by the TimedAudioTrack), then this can result
1077 // in one extra buffer being left un-trimmed when it could have
1078 // been. In general, this is not typical, and we would rather
1079 // optimized away the TS calculation below for the more common case
1080 // where PTSes are contiguous.
1081 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1082 } else {
1083 // We have no next buffer. Compute the PTS of the frame following
1084 // the last frame in this buffer by computing the duration of of
1085 // this frame in media time units and adding it to the PTS of the
1086 // buffer.
1087 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1088 / mFrameSize;
1089
1090 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1091 &bufEnd)) {
1092 ALOGE("Failed to convert frame count of %lld to media time"
1093 " duration" " (scale factor %d/%u) in %s",
1094 frameCount,
1095 mMediaTimeToSampleTransform.a_to_b_numer,
1096 mMediaTimeToSampleTransform.a_to_b_denom,
1097 __PRETTY_FUNCTION__);
1098 break;
1099 }
1100 bufEnd += mTimedBufferQueue[trimEnd].pts();
1101 }
1102
1103 if (bufEnd > mediaTimeNow)
1104 break;
1105
1106 // Is the buffer we want to use in the middle of a mix operation right
1107 // now? If so, don't actually trim it. Just wait for the releaseBuffer
1108 // from the mixer which should be coming back shortly.
1109 if (!trimEnd && mQueueHeadInFlight) {
1110 mTrimQueueHeadOnRelease = true;
1111 }
1112 }
1113
1114 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1115 if (trimStart < trimEnd) {
1116 // Update the bookkeeping for framesReady()
1117 for (size_t i = trimStart; i < trimEnd; ++i) {
1118 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1119 }
1120
1121 // Now actually remove the buffers from the queue.
1122 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1123 }
1124}
1125
1126void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1127 const char* logTag) {
1128 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1129 "%s called (reason \"%s\"), but timed buffer queue has no"
1130 " elements to trim.", __FUNCTION__, logTag);
1131
1132 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1133 mTimedBufferQueue.removeAt(0);
1134}
1135
1136void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1137 const TimedBuffer& buf,
1138 const char* logTag) {
1139 uint32_t bufBytes = buf.buffer()->size();
1140 uint32_t consumedAlready = buf.position();
1141
1142 ALOG_ASSERT(consumedAlready <= bufBytes,
1143 "Bad bookkeeping while updating frames pending. Timed buffer is"
1144 " only %u bytes long, but claims to have consumed %u"
1145 " bytes. (update reason: \"%s\")",
1146 bufBytes, consumedAlready, logTag);
1147
1148 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1149 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1150 "Bad bookkeeping while updating frames pending. Should have at"
1151 " least %u queued frames, but we think we have only %u. (update"
1152 " reason: \"%s\")",
1153 bufFrames, mFramesPendingInQueue, logTag);
1154
1155 mFramesPendingInQueue -= bufFrames;
1156}
1157
1158status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1159 const sp<IMemory>& buffer, int64_t pts) {
1160
1161 {
1162 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1163 if (!mMediaTimeTransformValid)
1164 return INVALID_OPERATION;
1165 }
1166
1167 Mutex::Autolock _l(mTimedBufferQueueLock);
1168
1169 uint32_t bufFrames = buffer->size() / mFrameSize;
1170 mFramesPendingInQueue += bufFrames;
1171 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1172
1173 return NO_ERROR;
1174}
1175
1176status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1177 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1178
1179 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1180 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1181 target);
1182
1183 if (!(target == TimedAudioTrack::LOCAL_TIME ||
1184 target == TimedAudioTrack::COMMON_TIME)) {
1185 return BAD_VALUE;
1186 }
1187
1188 Mutex::Autolock lock(mMediaTimeTransformLock);
1189 mMediaTimeTransform = xform;
1190 mMediaTimeTransformTarget = target;
1191 mMediaTimeTransformValid = true;
1192
1193 return NO_ERROR;
1194}
1195
1196#define min(a, b) ((a) < (b) ? (a) : (b))
1197
1198// implementation of getNextBuffer for tracks whose buffers have timestamps
1199status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1200 AudioBufferProvider::Buffer* buffer, int64_t pts)
1201{
1202 if (pts == AudioBufferProvider::kInvalidPTS) {
1203 buffer->raw = NULL;
1204 buffer->frameCount = 0;
1205 mTimedAudioOutputOnTime = false;
1206 return INVALID_OPERATION;
1207 }
1208
1209 Mutex::Autolock _l(mTimedBufferQueueLock);
1210
1211 ALOG_ASSERT(!mQueueHeadInFlight,
1212 "getNextBuffer called without releaseBuffer!");
1213
1214 while (true) {
1215
1216 // if we have no timed buffers, then fail
1217 if (mTimedBufferQueue.isEmpty()) {
1218 buffer->raw = NULL;
1219 buffer->frameCount = 0;
1220 return NOT_ENOUGH_DATA;
1221 }
1222
1223 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1224
1225 // calculate the PTS of the head of the timed buffer queue expressed in
1226 // local time
1227 int64_t headLocalPTS;
1228 {
1229 Mutex::Autolock mttLock(mMediaTimeTransformLock);
1230
1231 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1232
1233 if (mMediaTimeTransform.a_to_b_denom == 0) {
1234 // the transform represents a pause, so yield silence
1235 timedYieldSilence_l(buffer->frameCount, buffer);
1236 return NO_ERROR;
1237 }
1238
1239 int64_t transformedPTS;
1240 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1241 &transformedPTS)) {
1242 // the transform failed. this shouldn't happen, but if it does
1243 // then just drop this buffer
1244 ALOGW("timedGetNextBuffer transform failed");
1245 buffer->raw = NULL;
1246 buffer->frameCount = 0;
1247 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1248 return NO_ERROR;
1249 }
1250
1251 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1252 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1253 &headLocalPTS)) {
1254 buffer->raw = NULL;
1255 buffer->frameCount = 0;
1256 return INVALID_OPERATION;
1257 }
1258 } else {
1259 headLocalPTS = transformedPTS;
1260 }
1261 }
1262
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001263 uint32_t sr = sampleRate();
1264
Eric Laurent81784c32012-11-19 14:55:58 -08001265 // adjust the head buffer's PTS to reflect the portion of the head buffer
1266 // that has already been consumed
1267 int64_t effectivePTS = headLocalPTS +
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001268 ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
Eric Laurent81784c32012-11-19 14:55:58 -08001269
1270 // Calculate the delta in samples between the head of the input buffer
1271 // queue and the start of the next output buffer that will be written.
1272 // If the transformation fails because of over or underflow, it means
1273 // that the sample's position in the output stream is so far out of
1274 // whack that it should just be dropped.
1275 int64_t sampleDelta;
1276 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1277 ALOGV("*** head buffer is too far from PTS: dropped buffer");
1278 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1279 " mix");
1280 continue;
1281 }
1282 if (!mLocalTimeToSampleTransform.doForwardTransform(
1283 (effectivePTS - pts) << 32, &sampleDelta)) {
1284 ALOGV("*** too late during sample rate transform: dropped buffer");
1285 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1286 continue;
1287 }
1288
1289 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1290 " sampleDelta=[%d.%08x]",
1291 head.pts(), head.position(), pts,
1292 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1293 + (sampleDelta >> 32)),
1294 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1295
1296 // if the delta between the ideal placement for the next input sample and
1297 // the current output position is within this threshold, then we will
1298 // concatenate the next input samples to the previous output
1299 const int64_t kSampleContinuityThreshold =
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07001300 (static_cast<int64_t>(sr) << 32) / 250;
Eric Laurent81784c32012-11-19 14:55:58 -08001301
1302 // if this is the first buffer of audio that we're emitting from this track
1303 // then it should be almost exactly on time.
1304 const int64_t kSampleStartupThreshold = 1LL << 32;
1305
1306 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1307 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1308 // the next input is close enough to being on time, so concatenate it
1309 // with the last output
1310 timedYieldSamples_l(buffer);
1311
1312 ALOGVV("*** on time: head.pos=%d frameCount=%u",
1313 head.position(), buffer->frameCount);
1314 return NO_ERROR;
1315 }
1316
1317 // Looks like our output is not on time. Reset our on timed status.
1318 // Next time we mix samples from our input queue, then should be within
1319 // the StartupThreshold.
1320 mTimedAudioOutputOnTime = false;
1321 if (sampleDelta > 0) {
1322 // the gap between the current output position and the proper start of
1323 // the next input sample is too big, so fill it with silence
1324 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1325
1326 timedYieldSilence_l(framesUntilNextInput, buffer);
1327 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1328 return NO_ERROR;
1329 } else {
1330 // the next input sample is late
1331 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1332 size_t onTimeSamplePosition =
1333 head.position() + lateFrames * mFrameSize;
1334
1335 if (onTimeSamplePosition > head.buffer()->size()) {
1336 // all the remaining samples in the head are too late, so
1337 // drop it and move on
1338 ALOGV("*** too late: dropped buffer");
1339 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1340 continue;
1341 } else {
1342 // skip over the late samples
1343 head.setPosition(onTimeSamplePosition);
1344
1345 // yield the available samples
1346 timedYieldSamples_l(buffer);
1347
1348 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1349 return NO_ERROR;
1350 }
1351 }
1352 }
1353}
1354
1355// Yield samples from the timed buffer queue head up to the given output
1356// buffer's capacity.
1357//
1358// Caller must hold mTimedBufferQueueLock
1359void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1360 AudioBufferProvider::Buffer* buffer) {
1361
1362 const TimedBuffer& head = mTimedBufferQueue[0];
1363
1364 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1365 head.position());
1366
1367 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1368 mFrameSize);
1369 size_t framesRequested = buffer->frameCount;
1370 buffer->frameCount = min(framesLeftInHead, framesRequested);
1371
1372 mQueueHeadInFlight = true;
1373 mTimedAudioOutputOnTime = true;
1374}
1375
1376// Yield samples of silence up to the given output buffer's capacity
1377//
1378// Caller must hold mTimedBufferQueueLock
1379void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1380 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1381
1382 // lazily allocate a buffer filled with silence
1383 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1384 delete [] mTimedSilenceBuffer;
1385 mTimedSilenceBufferSize = numFrames * mFrameSize;
1386 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1387 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1388 }
1389
1390 buffer->raw = mTimedSilenceBuffer;
1391 size_t framesRequested = buffer->frameCount;
1392 buffer->frameCount = min(numFrames, framesRequested);
1393
1394 mTimedAudioOutputOnTime = false;
1395}
1396
1397// AudioBufferProvider interface
1398void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1399 AudioBufferProvider::Buffer* buffer) {
1400
1401 Mutex::Autolock _l(mTimedBufferQueueLock);
1402
1403 // If the buffer which was just released is part of the buffer at the head
1404 // of the queue, be sure to update the amt of the buffer which has been
1405 // consumed. If the buffer being returned is not part of the head of the
1406 // queue, its either because the buffer is part of the silence buffer, or
1407 // because the head of the timed queue was trimmed after the mixer called
1408 // getNextBuffer but before the mixer called releaseBuffer.
1409 if (buffer->raw == mTimedSilenceBuffer) {
1410 ALOG_ASSERT(!mQueueHeadInFlight,
1411 "Queue head in flight during release of silence buffer!");
1412 goto done;
1413 }
1414
1415 ALOG_ASSERT(mQueueHeadInFlight,
1416 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1417 " head in flight.");
1418
1419 if (mTimedBufferQueue.size()) {
1420 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1421
1422 void* start = head.buffer()->pointer();
1423 void* end = reinterpret_cast<void*>(
1424 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1425 + head.buffer()->size());
1426
1427 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1428 "released buffer not within the head of the timed buffer"
1429 " queue; qHead = [%p, %p], released buffer = %p",
1430 start, end, buffer->raw);
1431
1432 head.setPosition(head.position() +
1433 (buffer->frameCount * mFrameSize));
1434 mQueueHeadInFlight = false;
1435
1436 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1437 "Bad bookkeeping during releaseBuffer! Should have at"
1438 " least %u queued frames, but we think we have only %u",
1439 buffer->frameCount, mFramesPendingInQueue);
1440
1441 mFramesPendingInQueue -= buffer->frameCount;
1442
1443 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1444 || mTrimQueueHeadOnRelease) {
1445 trimTimedBufferQueueHead_l("releaseBuffer");
1446 mTrimQueueHeadOnRelease = false;
1447 }
1448 } else {
1449 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1450 " buffers in the timed buffer queue");
1451 }
1452
1453done:
1454 buffer->raw = 0;
1455 buffer->frameCount = 0;
1456}
1457
1458size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1459 Mutex::Autolock _l(mTimedBufferQueueLock);
1460 return mFramesPendingInQueue;
1461}
1462
1463AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1464 : mPTS(0), mPosition(0) {}
1465
1466AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1467 const sp<IMemory>& buffer, int64_t pts)
1468 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1469
1470
1471// ----------------------------------------------------------------------------
1472
1473AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1474 PlaybackThread *playbackThread,
1475 DuplicatingThread *sourceThread,
1476 uint32_t sampleRate,
1477 audio_format_t format,
1478 audio_channel_mask_t channelMask,
1479 size_t frameCount)
1480 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1481 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kastene3aa6592012-12-04 12:22:46 -08001482 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
Eric Laurent81784c32012-11-19 14:55:58 -08001483{
1484
1485 if (mCblk != NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08001486 mOutBuffer.frameCount = 0;
1487 playbackThread->mTracks.add(this);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001488 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001489 "mCblk->frameCount_ %u, mChannelMask 0x%08x",
Glenn Kastene3aa6592012-12-04 12:22:46 -08001490 mCblk, mBuffer,
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001491 mCblk->frameCount_, mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08001492 // since client and server are in the same process,
1493 // the buffer has the same virtual address on both sides
1494 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
Eric Laurent8d2d4932013-04-25 12:56:18 -07001495 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1496 mClientProxy->setSendLevel(0.0);
1497 mClientProxy->setSampleRate(sampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001498 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1499 true /*clientInServer*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001500 } else {
1501 ALOGW("Error creating output track on thread %p", playbackThread);
1502 }
1503}
1504
1505AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1506{
1507 clearBufferQueue();
Glenn Kastene3aa6592012-12-04 12:22:46 -08001508 delete mClientProxy;
1509 // superclass destructor will now delete the server proxy and shared memory both refer to
Eric Laurent81784c32012-11-19 14:55:58 -08001510}
1511
1512status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1513 int triggerSession)
1514{
1515 status_t status = Track::start(event, triggerSession);
1516 if (status != NO_ERROR) {
1517 return status;
1518 }
1519
1520 mActive = true;
1521 mRetryCount = 127;
1522 return status;
1523}
1524
1525void AudioFlinger::PlaybackThread::OutputTrack::stop()
1526{
1527 Track::stop();
1528 clearBufferQueue();
1529 mOutBuffer.frameCount = 0;
1530 mActive = false;
1531}
1532
1533bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1534{
1535 Buffer *pInBuffer;
1536 Buffer inBuffer;
1537 uint32_t channelCount = mChannelCount;
1538 bool outputBufferFull = false;
1539 inBuffer.frameCount = frames;
1540 inBuffer.i16 = data;
1541
1542 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1543
1544 if (!mActive && frames != 0) {
1545 start();
1546 sp<ThreadBase> thread = mThread.promote();
1547 if (thread != 0) {
1548 MixerThread *mixerThread = (MixerThread *)thread.get();
1549 if (mFrameCount > frames) {
1550 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1551 uint32_t startFrames = (mFrameCount - frames);
1552 pInBuffer = new Buffer;
1553 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1554 pInBuffer->frameCount = startFrames;
1555 pInBuffer->i16 = pInBuffer->mBuffer;
1556 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1557 mBufferQueue.add(pInBuffer);
1558 } else {
Glenn Kasten7c027242012-12-26 14:43:16 -08001559 ALOGW("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurent81784c32012-11-19 14:55:58 -08001560 }
1561 }
1562 }
1563 }
1564
1565 while (waitTimeLeftMs) {
1566 // First write pending buffers, then new data
1567 if (mBufferQueue.size()) {
1568 pInBuffer = mBufferQueue.itemAt(0);
1569 } else {
1570 pInBuffer = &inBuffer;
1571 }
1572
1573 if (pInBuffer->frameCount == 0) {
1574 break;
1575 }
1576
1577 if (mOutBuffer.frameCount == 0) {
1578 mOutBuffer.frameCount = pInBuffer->frameCount;
1579 nsecs_t startTime = systemTime();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001580 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1581 if (status != NO_ERROR) {
1582 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1583 mThread.unsafe_get(), status);
Eric Laurent81784c32012-11-19 14:55:58 -08001584 outputBufferFull = true;
1585 break;
1586 }
1587 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1588 if (waitTimeLeftMs >= waitTimeMs) {
1589 waitTimeLeftMs -= waitTimeMs;
1590 } else {
1591 waitTimeLeftMs = 0;
1592 }
1593 }
1594
1595 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1596 pInBuffer->frameCount;
1597 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001598 Proxy::Buffer buf;
1599 buf.mFrameCount = outFrames;
1600 buf.mRaw = NULL;
1601 mClientProxy->releaseBuffer(&buf);
Eric Laurent81784c32012-11-19 14:55:58 -08001602 pInBuffer->frameCount -= outFrames;
1603 pInBuffer->i16 += outFrames * channelCount;
1604 mOutBuffer.frameCount -= outFrames;
1605 mOutBuffer.i16 += outFrames * channelCount;
1606
1607 if (pInBuffer->frameCount == 0) {
1608 if (mBufferQueue.size()) {
1609 mBufferQueue.removeAt(0);
1610 delete [] pInBuffer->mBuffer;
1611 delete pInBuffer;
1612 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1613 mThread.unsafe_get(), mBufferQueue.size());
1614 } else {
1615 break;
1616 }
1617 }
1618 }
1619
1620 // If we could not write all frames, allocate a buffer and queue it for next time.
1621 if (inBuffer.frameCount) {
1622 sp<ThreadBase> thread = mThread.promote();
1623 if (thread != 0 && !thread->standby()) {
1624 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1625 pInBuffer = new Buffer;
1626 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1627 pInBuffer->frameCount = inBuffer.frameCount;
1628 pInBuffer->i16 = pInBuffer->mBuffer;
1629 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1630 sizeof(int16_t));
1631 mBufferQueue.add(pInBuffer);
1632 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1633 mThread.unsafe_get(), mBufferQueue.size());
1634 } else {
1635 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1636 mThread.unsafe_get(), this);
1637 }
1638 }
1639 }
1640
1641 // Calling write() with a 0 length buffer, means that no more data will be written:
1642 // If no more buffers are pending, fill output track buffer to make sure it is started
1643 // by output mixer.
1644 if (frames == 0 && mBufferQueue.size() == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001645 // FIXME borken, replace by getting framesReady() from proxy
1646 size_t user = 0; // was mCblk->user
1647 if (user < mFrameCount) {
1648 frames = mFrameCount - user;
Eric Laurent81784c32012-11-19 14:55:58 -08001649 pInBuffer = new Buffer;
1650 pInBuffer->mBuffer = new int16_t[frames * channelCount];
1651 pInBuffer->frameCount = frames;
1652 pInBuffer->i16 = pInBuffer->mBuffer;
1653 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1654 mBufferQueue.add(pInBuffer);
1655 } else if (mActive) {
1656 stop();
1657 }
1658 }
1659
1660 return outputBufferFull;
1661}
1662
1663status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1664 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1665{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001666 ClientProxy::Buffer buf;
1667 buf.mFrameCount = buffer->frameCount;
1668 struct timespec timeout;
1669 timeout.tv_sec = waitTimeMs / 1000;
1670 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1671 status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1672 buffer->frameCount = buf.mFrameCount;
1673 buffer->raw = buf.mRaw;
1674 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001675}
1676
Eric Laurent81784c32012-11-19 14:55:58 -08001677void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1678{
1679 size_t size = mBufferQueue.size();
1680
1681 for (size_t i = 0; i < size; i++) {
1682 Buffer *pBuffer = mBufferQueue.itemAt(i);
1683 delete [] pBuffer->mBuffer;
1684 delete pBuffer;
1685 }
1686 mBufferQueue.clear();
1687}
1688
1689
1690// ----------------------------------------------------------------------------
1691// Record
1692// ----------------------------------------------------------------------------
1693
1694AudioFlinger::RecordHandle::RecordHandle(
1695 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1696 : BnAudioRecord(),
1697 mRecordTrack(recordTrack)
1698{
1699}
1700
1701AudioFlinger::RecordHandle::~RecordHandle() {
1702 stop_nonvirtual();
1703 mRecordTrack->destroy();
1704}
1705
1706sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1707 return mRecordTrack->getCblk();
1708}
1709
1710status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1711 int triggerSession) {
1712 ALOGV("RecordHandle::start()");
1713 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1714}
1715
1716void AudioFlinger::RecordHandle::stop() {
1717 stop_nonvirtual();
1718}
1719
1720void AudioFlinger::RecordHandle::stop_nonvirtual() {
1721 ALOGV("RecordHandle::stop()");
1722 mRecordTrack->stop();
1723}
1724
1725status_t AudioFlinger::RecordHandle::onTransact(
1726 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1727{
1728 return BnAudioRecord::onTransact(code, data, reply, flags);
1729}
1730
1731// ----------------------------------------------------------------------------
1732
1733// RecordTrack constructor must be called with AudioFlinger::mLock held
1734AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1735 RecordThread *thread,
1736 const sp<Client>& client,
1737 uint32_t sampleRate,
1738 audio_format_t format,
1739 audio_channel_mask_t channelMask,
1740 size_t frameCount,
1741 int sessionId)
1742 : TrackBase(thread, client, sampleRate, format,
Glenn Kastene3aa6592012-12-04 12:22:46 -08001743 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
Eric Laurent81784c32012-11-19 14:55:58 -08001744 mOverflow(false)
1745{
Glenn Kasten35cc4f32013-07-25 14:21:35 -07001746 ALOGV("RecordTrack constructor");
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001747 if (mCblk != NULL) {
1748 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1749 mFrameSize);
1750 mServerProxy = mAudioRecordServerProxy;
1751 }
Eric Laurent81784c32012-11-19 14:55:58 -08001752}
1753
1754AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1755{
1756 ALOGV("%s", __func__);
1757}
1758
1759// AudioBufferProvider interface
1760status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1761 int64_t pts)
1762{
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001763 ServerProxy::Buffer buf;
1764 buf.mFrameCount = buffer->frameCount;
1765 status_t status = mServerProxy->obtainBuffer(&buf);
1766 buffer->frameCount = buf.mFrameCount;
1767 buffer->raw = buf.mRaw;
1768 if (buf.mFrameCount == 0) {
1769 // FIXME also wake futex so that overrun is noticed more quickly
Glenn Kasten96f60d82013-07-12 10:21:18 -07001770 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08001771 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001772 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08001773}
1774
1775status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1776 int triggerSession)
1777{
1778 sp<ThreadBase> thread = mThread.promote();
1779 if (thread != 0) {
1780 RecordThread *recordThread = (RecordThread *)thread.get();
1781 return recordThread->start(this, event, triggerSession);
1782 } else {
1783 return BAD_VALUE;
1784 }
1785}
1786
1787void AudioFlinger::RecordThread::RecordTrack::stop()
1788{
1789 sp<ThreadBase> thread = mThread.promote();
1790 if (thread != 0) {
1791 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kastena8356f62013-07-25 14:37:52 -07001792 if (recordThread->stop(this)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001793 AudioSystem::stopInput(recordThread->id());
1794 }
1795 }
1796}
1797
1798void AudioFlinger::RecordThread::RecordTrack::destroy()
1799{
1800 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1801 sp<RecordTrack> keep(this);
1802 {
1803 sp<ThreadBase> thread = mThread.promote();
1804 if (thread != 0) {
1805 if (mState == ACTIVE || mState == RESUMING) {
1806 AudioSystem::stopInput(thread->id());
1807 }
1808 AudioSystem::releaseInput(thread->id());
1809 Mutex::Autolock _l(thread->mLock);
1810 RecordThread *recordThread = (RecordThread *) thread.get();
1811 recordThread->destroyTrack_l(this);
1812 }
1813 }
1814}
1815
Eric Laurent9a54bc22013-09-09 09:08:44 -07001816void AudioFlinger::RecordThread::RecordTrack::invalidate()
1817{
1818 // FIXME should use proxy, and needs work
1819 audio_track_cblk_t* cblk = mCblk;
1820 android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1821 android_atomic_release_store(0x40000000, &cblk->mFutex);
1822 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1823 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
1824}
1825
Eric Laurent81784c32012-11-19 14:55:58 -08001826
1827/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1828{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001829 result.append("Client Fmt Chn mask Session S Server fCount\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001830}
1831
1832void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1833{
Glenn Kastenbd4c4fb2013-07-25 14:21:14 -07001834 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001835 (mClient == 0) ? getpid_cached : mClient->pid(),
1836 mFormat,
1837 mChannelMask,
1838 mSessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001839 mState,
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001840 mCblk->mServer,
Eric Laurent81784c32012-11-19 14:55:58 -08001841 mFrameCount);
1842}
1843
Eric Laurent81784c32012-11-19 14:55:58 -08001844}; // namespace android