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