blob: cd7bcd5be3bb9ca6bed33395ea3e98a74dedab5c [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/* //device/extlibs/pv/android/AudioTrack.cpp
2**
3** Copyright 2007, 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_NDEBUG 0
20#define LOG_TAG "AudioTrack"
21
22#include <stdint.h>
23#include <sys/types.h>
24#include <limits.h>
25
26#include <sched.h>
27#include <sys/resource.h>
28
29#include <private/media/AudioTrackShared.h>
30
31#include <media/AudioSystem.h>
32#include <media/AudioTrack.h>
33
34#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070035#include <binder/Parcel.h>
36#include <binder/IPCThreadState.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037#include <utils/Timers.h>
38#include <cutils/atomic.h>
39
40#define LIKELY( exp ) (__builtin_expect( (exp) != 0, true ))
41#define UNLIKELY( exp ) (__builtin_expect( (exp) != 0, false ))
42
43namespace android {
44
45// ---------------------------------------------------------------------------
46
47AudioTrack::AudioTrack()
48 : mStatus(NO_INIT)
49{
50}
51
52AudioTrack::AudioTrack(
53 int streamType,
54 uint32_t sampleRate,
55 int format,
Eric Laurenta553c252009-07-17 12:17:14 -070056 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057 int frameCount,
58 uint32_t flags,
59 callback_t cbf,
60 void* user,
61 int notificationFrames)
62 : mStatus(NO_INIT)
63{
Eric Laurenta553c252009-07-17 12:17:14 -070064 mStatus = set(streamType, sampleRate, format, channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065 frameCount, flags, cbf, user, notificationFrames, 0);
66}
67
68AudioTrack::AudioTrack(
69 int streamType,
70 uint32_t sampleRate,
71 int format,
Eric Laurenta553c252009-07-17 12:17:14 -070072 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073 const sp<IMemory>& sharedBuffer,
74 uint32_t flags,
75 callback_t cbf,
76 void* user,
77 int notificationFrames)
78 : mStatus(NO_INIT)
79{
Eric Laurenta553c252009-07-17 12:17:14 -070080 mStatus = set(streamType, sampleRate, format, channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081 0, flags, cbf, user, notificationFrames, sharedBuffer);
82}
83
84AudioTrack::~AudioTrack()
85{
86 LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
87
88 if (mStatus == NO_ERROR) {
89 // Make sure that callback function exits in the case where
90 // it is looping on buffer full condition in obtainBuffer().
91 // Otherwise the callback thread will never exit.
92 stop();
93 if (mAudioTrackThread != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 mAudioTrackThread->requestExitAndWait();
95 mAudioTrackThread.clear();
96 }
97 mAudioTrack.clear();
98 IPCThreadState::self()->flushCommands();
99 }
100}
101
102status_t AudioTrack::set(
103 int streamType,
104 uint32_t sampleRate,
105 int format,
Eric Laurenta553c252009-07-17 12:17:14 -0700106 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 int frameCount,
108 uint32_t flags,
109 callback_t cbf,
110 void* user,
111 int notificationFrames,
112 const sp<IMemory>& sharedBuffer,
113 bool threadCanCallJava)
114{
115
116 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
117
Eric Laurentef028272009-04-21 07:56:33 -0700118 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 LOGE("Track already in use");
120 return INVALID_OPERATION;
121 }
122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 int afSampleRate;
124 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
125 return NO_INIT;
126 }
127 int afFrameCount;
128 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
129 return NO_INIT;
130 }
131 uint32_t afLatency;
132 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
133 return NO_INIT;
134 }
135
136 // handle default values first.
137 if (streamType == AudioSystem::DEFAULT) {
138 streamType = AudioSystem::MUSIC;
139 }
140 if (sampleRate == 0) {
141 sampleRate = afSampleRate;
142 }
143 // these below should probably come from the audioFlinger too...
144 if (format == 0) {
145 format = AudioSystem::PCM_16_BIT;
146 }
Eric Laurenta553c252009-07-17 12:17:14 -0700147 if (channels == 0) {
148 channels = AudioSystem::CHANNEL_OUT_STEREO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 }
150
151 // validate parameters
Eric Laurenta553c252009-07-17 12:17:14 -0700152 if (!AudioSystem::isValidFormat(format)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 LOGE("Invalid format");
154 return BAD_VALUE;
155 }
Eric Laurenta553c252009-07-17 12:17:14 -0700156
157 // force direct flag if format is not linear PCM
158 if (!AudioSystem::isLinearPCM(format)) {
159 flags |= AudioSystem::OUTPUT_FLAG_DIRECT;
160 }
161
162 if (!AudioSystem::isOutputChannel(channels)) {
163 LOGE("Invalid channel mask");
164 return BAD_VALUE;
165 }
166 uint32_t channelCount = AudioSystem::popCount(channels);
167
168 audio_io_handle_t output = AudioSystem::getOutput((AudioSystem::stream_type)streamType,
169 sampleRate, format, channels, (AudioSystem::output_flags)flags);
170
171 if (output == 0) {
172 LOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 return BAD_VALUE;
174 }
175
Eric Laurenta553c252009-07-17 12:17:14 -0700176 if (!AudioSystem::isLinearPCM(format)) {
177 if (sharedBuffer != 0) {
178 frameCount = sharedBuffer->size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 }
180 } else {
Eric Laurenta553c252009-07-17 12:17:14 -0700181 // Ensure that buffer depth covers at least audio hardware latency
182 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
183 if (minBufCount < 2) minBufCount = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Eric Laurenta553c252009-07-17 12:17:14 -0700185 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
186
187 if (sharedBuffer == 0) {
188 if (frameCount == 0) {
189 frameCount = minFrameCount;
190 }
191 if (notificationFrames == 0) {
192 notificationFrames = frameCount/2;
193 }
194 // Make sure that application is notified with sufficient margin
195 // before underrun
196 if (notificationFrames > frameCount/2) {
197 notificationFrames = frameCount/2;
198 }
199 if (frameCount < minFrameCount) {
200 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
201 return BAD_VALUE;
202 }
203 } else {
204 // Ensure that buffer alignment matches channelcount
205 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
206 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
207 return BAD_VALUE;
208 }
209 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 }
212
Eric Laurentbda74692009-11-04 08:27:26 -0800213 mVolume[LEFT] = 1.0f;
214 mVolume[RIGHT] = 1.0f;
215 // create the IAudioTrack
216 status_t status = createTrack(streamType, sampleRate, format, channelCount,
217 frameCount, flags, sharedBuffer, output);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
Eric Laurentbda74692009-11-04 08:27:26 -0800219 if (status != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 return status;
221 }
Eric Laurentbda74692009-11-04 08:27:26 -0800222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 if (cbf != 0) {
224 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
225 if (mAudioTrackThread == 0) {
226 LOGE("Could not create callback thread");
227 return NO_INIT;
228 }
229 }
230
231 mStatus = NO_ERROR;
232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 mStreamType = streamType;
234 mFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -0700235 mChannels = channels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 mChannelCount = channelCount;
237 mSharedBuffer = sharedBuffer;
238 mMuted = false;
239 mActive = 0;
240 mCbf = cbf;
241 mNotificationFrames = notificationFrames;
242 mRemainingFrames = notificationFrames;
243 mUserData = user;
Eric Laurent88e209d2009-07-07 07:10:45 -0700244 mLatency = afLatency + (1000*mFrameCount) / sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 mLoopCount = 0;
246 mMarkerPosition = 0;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700247 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 mNewPosition = 0;
249 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700250 mFlags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
252 return NO_ERROR;
253}
254
255status_t AudioTrack::initCheck() const
256{
257 return mStatus;
258}
259
260// -------------------------------------------------------------------------
261
262uint32_t AudioTrack::latency() const
263{
264 return mLatency;
265}
266
267int AudioTrack::streamType() const
268{
269 return mStreamType;
270}
271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272int AudioTrack::format() const
273{
274 return mFormat;
275}
276
277int AudioTrack::channelCount() const
278{
279 return mChannelCount;
280}
281
282uint32_t AudioTrack::frameCount() const
283{
284 return mFrameCount;
285}
286
287int AudioTrack::frameSize() const
288{
Eric Laurenta553c252009-07-17 12:17:14 -0700289 if (AudioSystem::isLinearPCM(mFormat)) {
290 return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
291 } else {
292 return sizeof(uint8_t);
293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294}
295
296sp<IMemory>& AudioTrack::sharedBuffer()
297{
298 return mSharedBuffer;
299}
300
301// -------------------------------------------------------------------------
302
303void AudioTrack::start()
304{
305 sp<AudioTrackThread> t = mAudioTrackThread;
306
307 LOGV("start %p", this);
308 if (t != 0) {
309 if (t->exitPending()) {
310 if (t->requestExitAndWait() == WOULD_BLOCK) {
311 LOGE("AudioTrack::start called from thread");
312 return;
313 }
314 }
315 t->mLock.lock();
316 }
317
318 if (android_atomic_or(1, &mActive) == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -0800319 mNewPosition = mCblk->server + mUpdatePeriod;
320 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
321 mCblk->waitTimeMs = 0;
322 if (t != 0) {
323 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
324 } else {
325 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
326 }
327
Eric Laurentbda74692009-11-04 08:27:26 -0800328 status_t status = mAudioTrack->start();
329 if (status == DEAD_OBJECT) {
330 LOGV("start() dead IAudioTrack: creating a new one");
331 status = createTrack(mStreamType, mCblk->sampleRate, mFormat, mChannelCount,
Eric Laurent49f02be2009-11-19 09:00:56 -0800332 mFrameCount, mFlags, mSharedBuffer, getOutput());
333 if (status == NO_ERROR) {
334 status = mAudioTrack->start();
335 if (status == NO_ERROR) {
336 mNewPosition = mCblk->server + mUpdatePeriod;
337 }
338 }
Eric Laurent059b4be2009-11-09 23:32:22 -0800339 }
340 if (status != NO_ERROR) {
Eric Laurentbda74692009-11-04 08:27:26 -0800341 LOGV("start() failed");
342 android_atomic_and(~1, &mActive);
Eric Laurent059b4be2009-11-09 23:32:22 -0800343 if (t != 0) {
344 t->requestExit();
345 } else {
346 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
347 }
Eric Laurentbda74692009-11-04 08:27:26 -0800348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 }
350
351 if (t != 0) {
352 t->mLock.unlock();
353 }
354}
355
356void AudioTrack::stop()
357{
358 sp<AudioTrackThread> t = mAudioTrackThread;
359
360 LOGV("stop %p", this);
361 if (t != 0) {
362 t->mLock.lock();
363 }
364
365 if (android_atomic_and(~1, &mActive) == 1) {
Eric Laurentef028272009-04-21 07:56:33 -0700366 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 mAudioTrack->stop();
368 // Cancel loops (If we are in the middle of a loop, playback
369 // would not stop until loopCount reaches 0).
370 setLoop(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700371 // the playback head position will reset to 0, so if a marker is set, we need
372 // to activate it again
373 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 // Force flush if a shared buffer is used otherwise audioflinger
375 // will not stop before end of buffer is reached.
376 if (mSharedBuffer != 0) {
377 flush();
378 }
379 if (t != 0) {
380 t->requestExit();
381 } else {
382 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
383 }
384 }
385
386 if (t != 0) {
387 t->mLock.unlock();
388 }
389}
390
391bool AudioTrack::stopped() const
392{
393 return !mActive;
394}
395
396void AudioTrack::flush()
397{
398 LOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700399
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700400 // clear playback marker and periodic update counter
401 mMarkerPosition = 0;
402 mMarkerReached = false;
403 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405
406 if (!mActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 mAudioTrack->flush();
408 // Release AudioTrack callback thread in case it was waiting for new buffers
409 // in AudioTrack::obtainBuffer()
410 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 }
412}
413
414void AudioTrack::pause()
415{
416 LOGV("pause");
417 if (android_atomic_and(~1, &mActive) == 1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 mAudioTrack->pause();
419 }
420}
421
422void AudioTrack::mute(bool e)
423{
424 mAudioTrack->mute(e);
425 mMuted = e;
426}
427
428bool AudioTrack::muted() const
429{
430 return mMuted;
431}
432
433void AudioTrack::setVolume(float left, float right)
434{
435 mVolume[LEFT] = left;
436 mVolume[RIGHT] = right;
437
438 // write must be atomic
439 mCblk->volumeLR = (int32_t(int16_t(left * 0x1000)) << 16) | int16_t(right * 0x1000);
440}
441
442void AudioTrack::getVolume(float* left, float* right)
443{
444 *left = mVolume[LEFT];
445 *right = mVolume[RIGHT];
446}
447
Eric Laurent88e209d2009-07-07 07:10:45 -0700448status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449{
450 int afSamplingRate;
451
452 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700453 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 }
455 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700456 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457
Eric Laurent88e209d2009-07-07 07:10:45 -0700458 mCblk->sampleRate = rate;
459 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460}
461
462uint32_t AudioTrack::getSampleRate()
463{
Eric Laurent88e209d2009-07-07 07:10:45 -0700464 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465}
466
467status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
468{
469 audio_track_cblk_t* cblk = mCblk;
470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 Mutex::Autolock _l(cblk->lock);
472
473 if (loopCount == 0) {
474 cblk->loopStart = UINT_MAX;
475 cblk->loopEnd = UINT_MAX;
476 cblk->loopCount = 0;
477 mLoopCount = 0;
478 return NO_ERROR;
479 }
480
481 if (loopStart >= loopEnd ||
482 loopEnd - loopStart > mFrameCount) {
483 LOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user);
484 return BAD_VALUE;
485 }
486
487 if ((mSharedBuffer != 0) && (loopEnd > mFrameCount)) {
488 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
489 loopStart, loopEnd, mFrameCount);
490 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492
493 cblk->loopStart = loopStart;
494 cblk->loopEnd = loopEnd;
495 cblk->loopCount = loopCount;
496 mLoopCount = loopCount;
497
498 return NO_ERROR;
499}
500
501status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
502{
503 if (loopStart != 0) {
504 *loopStart = mCblk->loopStart;
505 }
506 if (loopEnd != 0) {
507 *loopEnd = mCblk->loopEnd;
508 }
509 if (loopCount != 0) {
510 if (mCblk->loopCount < 0) {
511 *loopCount = -1;
512 } else {
513 *loopCount = mCblk->loopCount;
514 }
515 }
516
517 return NO_ERROR;
518}
519
520status_t AudioTrack::setMarkerPosition(uint32_t marker)
521{
522 if (mCbf == 0) return INVALID_OPERATION;
523
524 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700525 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526
527 return NO_ERROR;
528}
529
530status_t AudioTrack::getMarkerPosition(uint32_t *marker)
531{
532 if (marker == 0) return BAD_VALUE;
533
534 *marker = mMarkerPosition;
535
536 return NO_ERROR;
537}
538
539status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
540{
541 if (mCbf == 0) return INVALID_OPERATION;
542
543 uint32_t curPosition;
544 getPosition(&curPosition);
545 mNewPosition = curPosition + updatePeriod;
546 mUpdatePeriod = updatePeriod;
547
548 return NO_ERROR;
549}
550
551status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
552{
553 if (updatePeriod == 0) return BAD_VALUE;
554
555 *updatePeriod = mUpdatePeriod;
556
557 return NO_ERROR;
558}
559
560status_t AudioTrack::setPosition(uint32_t position)
561{
562 Mutex::Autolock _l(mCblk->lock);
563
564 if (!stopped()) return INVALID_OPERATION;
565
566 if (position > mCblk->user) return BAD_VALUE;
567
568 mCblk->server = position;
569 mCblk->forceReady = 1;
Eric Laurenta553c252009-07-17 12:17:14 -0700570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 return NO_ERROR;
572}
573
574status_t AudioTrack::getPosition(uint32_t *position)
575{
576 if (position == 0) return BAD_VALUE;
577
578 *position = mCblk->server;
579
580 return NO_ERROR;
581}
582
583status_t AudioTrack::reload()
584{
585 if (!stopped()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 flush();
588
589 mCblk->stepUser(mFrameCount);
590
591 return NO_ERROR;
592}
593
Eric Laurenta553c252009-07-17 12:17:14 -0700594audio_io_handle_t AudioTrack::getOutput()
595{
596 return AudioSystem::getOutput((AudioSystem::stream_type)mStreamType,
597 mCblk->sampleRate, mFormat, mChannels, (AudioSystem::output_flags)mFlags);
598}
599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600// -------------------------------------------------------------------------
601
Eric Laurentbda74692009-11-04 08:27:26 -0800602status_t AudioTrack::createTrack(
603 int streamType,
604 uint32_t sampleRate,
605 int format,
606 int channelCount,
607 int frameCount,
608 uint32_t flags,
609 const sp<IMemory>& sharedBuffer,
610 audio_io_handle_t output)
611{
612 status_t status;
613 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
614 if (audioFlinger == 0) {
615 LOGE("Could not get audioflinger");
616 return NO_INIT;
617 }
618
619 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
620 streamType,
621 sampleRate,
622 format,
623 channelCount,
624 frameCount,
625 ((uint16_t)flags) << 16,
626 sharedBuffer,
627 output,
628 &status);
629
630 if (track == 0) {
631 LOGE("AudioFlinger could not create track, status: %d", status);
632 return status;
633 }
634 sp<IMemory> cblk = track->getCblk();
635 if (cblk == 0) {
636 LOGE("Could not get control block");
637 return NO_INIT;
638 }
639 mAudioTrack.clear();
640 mAudioTrack = track;
641 mCblkMemory.clear();
642 mCblkMemory = cblk;
643 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
644 mCblk->out = 1;
645 // Update buffer size in case it has been limited by AudioFlinger during track creation
646 mFrameCount = mCblk->frameCount;
647 if (sharedBuffer == 0) {
648 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
649 } else {
650 mCblk->buffers = sharedBuffer->pointer();
651 // Force buffer full condition as data is already present in shared memory
652 mCblk->stepUser(mFrameCount);
653 }
654
655 mCblk->volumeLR = (int32_t(int16_t(mVolume[LEFT] * 0x1000)) << 16) | int16_t(mVolume[RIGHT] * 0x1000);
Eric Laurent49f02be2009-11-19 09:00:56 -0800656 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
657 mCblk->waitTimeMs = 0;
Eric Laurentbda74692009-11-04 08:27:26 -0800658 return NO_ERROR;
659}
660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
662{
663 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 status_t result;
665 audio_track_cblk_t* cblk = mCblk;
666 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700667 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668
669 audioBuffer->frameCount = 0;
670 audioBuffer->size = 0;
671
672 uint32_t framesAvail = cblk->framesAvailable();
673
674 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800675 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 goto start_loop_here;
677 while (framesAvail == 0) {
678 active = mActive;
679 if (UNLIKELY(!active)) {
680 LOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800681 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 return NO_MORE_BUFFERS;
683 }
Eric Laurentbda74692009-11-04 08:27:26 -0800684 if (UNLIKELY(!waitCount)) {
685 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800687 }
688
Eric Laurentef028272009-04-21 07:56:33 -0700689 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurenta553c252009-07-17 12:17:14 -0700690 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700691 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
693 // timing out when a loop has been set and we have already written upto loop end
694 // is a normal condition: no need to wake AudioFlinger up.
695 if (cblk->user < cblk->loopEnd) {
696 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
697 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700698 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800700 result = mAudioTrack->start();
701 if (result == DEAD_OBJECT) {
702 LOGW("obtainBuffer() dead IAudioTrack: creating a new one");
703 result = createTrack(mStreamType, cblk->sampleRate, mFormat, mChannelCount,
704 mFrameCount, mFlags, mSharedBuffer, getOutput());
705 if (result == NO_ERROR) {
706 cblk = mCblk;
707 cblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
Eric Laurent49f02be2009-11-19 09:00:56 -0800708 mAudioTrack->start();
Eric Laurentbda74692009-11-04 08:27:26 -0800709 }
710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 }
713 cblk->waitTimeMs = 0;
714 }
Eric Laurenta553c252009-07-17 12:17:14 -0700715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800717 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 return TIMED_OUT;
719 }
720 }
721 // read the server count again
722 start_loop_here:
723 framesAvail = cblk->framesAvailable_l();
724 }
Eric Laurentbda74692009-11-04 08:27:26 -0800725 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 }
727
728 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 if (framesReq > framesAvail) {
731 framesReq = framesAvail;
732 }
733
734 uint32_t u = cblk->user;
735 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
736
737 if (u + framesReq > bufferEnd) {
738 framesReq = bufferEnd - u;
739 }
740
Eric Laurenta553c252009-07-17 12:17:14 -0700741 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
742 audioBuffer->channelCount = mChannelCount;
743 audioBuffer->frameCount = framesReq;
744 audioBuffer->size = framesReq * cblk->frameSize;
745 if (AudioSystem::isLinearPCM(mFormat)) {
746 audioBuffer->format = AudioSystem::PCM_16_BIT;
747 } else {
748 audioBuffer->format = mFormat;
749 }
750 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 active = mActive;
752 return active ? status_t(NO_ERROR) : status_t(STOPPED);
753}
754
755void AudioTrack::releaseBuffer(Buffer* audioBuffer)
756{
757 audio_track_cblk_t* cblk = mCblk;
758 cblk->stepUser(audioBuffer->frameCount);
759}
760
761// -------------------------------------------------------------------------
762
763ssize_t AudioTrack::write(const void* buffer, size_t userSize)
764{
765
766 if (mSharedBuffer != 0) return INVALID_OPERATION;
767
768 if (ssize_t(userSize) < 0) {
769 // sanity-check. user is most-likely passing an error code.
770 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
771 buffer, userSize, userSize);
772 return BAD_VALUE;
773 }
774
775 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
776
777 ssize_t written = 0;
778 const int8_t *src = (const int8_t *)buffer;
779 Buffer audioBuffer;
780
781 do {
Eric Laurenta553c252009-07-17 12:17:14 -0700782 audioBuffer.frameCount = userSize/frameSize();
783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 // Calling obtainBuffer() with a negative wait count causes
785 // an (almost) infinite wait time.
786 status_t err = obtainBuffer(&audioBuffer, -1);
787 if (err < 0) {
788 // out of buffers, return #bytes written
789 if (err == status_t(NO_MORE_BUFFERS))
790 break;
791 return ssize_t(err);
792 }
793
794 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -0700795
Eric Laurent28ad42b2009-08-04 10:42:26 -0700796 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 // Divide capacity by 2 to take expansion into account
798 toWrite = audioBuffer.size>>1;
799 // 8 to 16 bit conversion
800 int count = toWrite;
801 int16_t *dst = (int16_t *)(audioBuffer.i8);
802 while(count--) {
803 *dst++ = (int16_t)(*src++^0x80) << 8;
804 }
Eric Laurent28ad42b2009-08-04 10:42:26 -0700805 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 toWrite = audioBuffer.size;
807 memcpy(audioBuffer.i8, src, toWrite);
808 src += toWrite;
809 }
810 userSize -= toWrite;
811 written += toWrite;
812
813 releaseBuffer(&audioBuffer);
814 } while (userSize);
815
816 return written;
817}
818
819// -------------------------------------------------------------------------
820
821bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
822{
823 Buffer audioBuffer;
824 uint32_t frames;
825 size_t writtenSize;
826
827 // Manage underrun callback
828 if (mActive && (mCblk->framesReady() == 0)) {
829 LOGV("Underrun user: %x, server: %x, flowControlFlag %d", mCblk->user, mCblk->server, mCblk->flowControlFlag);
830 if (mCblk->flowControlFlag == 0) {
831 mCbf(EVENT_UNDERRUN, mUserData, 0);
832 if (mCblk->server == mCblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -0700833 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835 mCblk->flowControlFlag = 1;
836 if (mSharedBuffer != 0) return false;
837 }
838 }
Eric Laurenta553c252009-07-17 12:17:14 -0700839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 // Manage loop end callback
841 while (mLoopCount > mCblk->loopCount) {
842 int loopCount = -1;
843 mLoopCount--;
844 if (mLoopCount >= 0) loopCount = mLoopCount;
845
846 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
847 }
848
849 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700850 if (!mMarkerReached && (mMarkerPosition > 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 if (mCblk->server >= mMarkerPosition) {
852 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700853 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 }
855 }
856
857 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -0700858 if (mUpdatePeriod > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 while (mCblk->server >= mNewPosition) {
860 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
861 mNewPosition += mUpdatePeriod;
862 }
863 }
864
865 // If Shared buffer is used, no data is requested from client.
866 if (mSharedBuffer != 0) {
867 frames = 0;
868 } else {
869 frames = mRemainingFrames;
870 }
871
872 do {
873
874 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -0700875
876 // Calling obtainBuffer() with a wait count of 1
877 // limits wait time to WAIT_PERIOD_MS. This prevents from being
878 // stuck here not being able to handle timed events (position, markers, loops).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 status_t err = obtainBuffer(&audioBuffer, 1);
880 if (err < NO_ERROR) {
881 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -0700882 LOGE_IF(err != status_t(NO_MORE_BUFFERS), "Error obtaining an audio buffer, giving up.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 return false;
884 }
885 break;
886 }
887 if (err == status_t(STOPPED)) return false;
888
889 // Divide buffer size by 2 to take into account the expansion
890 // due to 8 to 16 bit conversion: the callback must fill only half
891 // of the destination buffer
Eric Laurent28ad42b2009-08-04 10:42:26 -0700892 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 audioBuffer.size >>= 1;
894 }
895
896 size_t reqSize = audioBuffer.size;
897 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
898 writtenSize = audioBuffer.size;
899
900 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -0800901 if (ssize_t(writtenSize) <= 0) {
902 // The callback is done filling buffers
903 // Keep this thread going to handle timed events and
904 // still try to get more data in intervals of WAIT_PERIOD_MS
905 // but don't just loop and block the CPU, so wait
906 usleep(WAIT_PERIOD_MS*1000);
907 break;
908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 if (writtenSize > reqSize) writtenSize = reqSize;
910
Eric Laurent28ad42b2009-08-04 10:42:26 -0700911 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 // 8 to 16 bit conversion
913 const int8_t *src = audioBuffer.i8 + writtenSize-1;
914 int count = writtenSize;
915 int16_t *dst = audioBuffer.i16 + writtenSize-1;
916 while(count--) {
917 *dst-- = (int16_t)(*src--^0x80) << 8;
918 }
919 writtenSize <<= 1;
920 }
921
922 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -0700923 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
924 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
925 // 16 bit.
926 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 frames -= audioBuffer.frameCount;
929
930 releaseBuffer(&audioBuffer);
931 }
932 while (frames);
933
934 if (frames == 0) {
935 mRemainingFrames = mNotificationFrames;
936 } else {
937 mRemainingFrames = frames;
938 }
939 return true;
940}
941
942status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
943{
944
945 const size_t SIZE = 256;
946 char buffer[SIZE];
947 String8 result;
948
949 result.append(" AudioTrack::dump\n");
950 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
951 result.append(buffer);
952 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mFrameCount);
953 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -0700954 snprintf(buffer, 255, " sample rate(%d), status(%d), muted(%d)\n", (mCblk == 0) ? 0 : mCblk->sampleRate, mStatus, mMuted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 result.append(buffer);
956 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
957 result.append(buffer);
958 ::write(fd, result.string(), result.size());
959 return NO_ERROR;
960}
961
962// =========================================================================
963
964AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
965 : Thread(bCanCallJava), mReceiver(receiver)
966{
967}
968
969bool AudioTrack::AudioTrackThread::threadLoop()
970{
971 return mReceiver.processAudioBuffer(this);
972}
973
974status_t AudioTrack::AudioTrackThread::readyToRun()
975{
976 return NO_ERROR;
977}
978
979void AudioTrack::AudioTrackThread::onFirstRef()
980{
981}
982
983// =========================================================================
984
985audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopiana729f972010-03-19 16:14:13 -0700986 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
987 userBase(0), serverBase(0), buffers(0), frameCount(0),
988 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
989 flowControlFlag(1), forceReady(0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990{
991}
992
993uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
994{
995 uint32_t u = this->user;
996
997 u += frameCount;
998 // Ensure that user is never ahead of server for AudioRecord
999 if (out) {
1000 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1001 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1002 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1003 }
1004 } else if (u > this->server) {
1005 LOGW("stepServer occured after track reset");
1006 u = this->server;
1007 }
1008
1009 if (u >= userBase + this->frameCount) {
1010 userBase += this->frameCount;
1011 }
1012
1013 this->user = u;
1014
1015 // Clear flow control error condition as new data has been written/read to/from buffer.
1016 flowControlFlag = 0;
1017
1018 return u;
1019}
1020
1021bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1022{
1023 // the code below simulates lock-with-timeout
1024 // we MUST do this to protect the AudioFlinger server
1025 // as this lock is shared with the client.
1026 status_t err;
1027
1028 err = lock.tryLock();
1029 if (err == -EBUSY) { // just wait a bit
1030 usleep(1000);
1031 err = lock.tryLock();
1032 }
1033 if (err != NO_ERROR) {
1034 // probably, the client just died.
1035 return false;
1036 }
1037
1038 uint32_t s = this->server;
1039
1040 s += frameCount;
1041 if (out) {
1042 // Mark that we have read the first buffer so that next time stepUser() is called
1043 // we switch to normal obtainBuffer() timeout period
1044 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001045 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 // It is possible that we receive a flush()
1048 // while the mixer is processing a block: in this case,
1049 // stepServer() is called After the flush() has reset u & s and
1050 // we have s > u
1051 if (s > this->user) {
1052 LOGW("stepServer occured after track reset");
1053 s = this->user;
1054 }
1055 }
1056
1057 if (s >= loopEnd) {
1058 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1059 s = loopStart;
1060 if (--loopCount == 0) {
1061 loopEnd = UINT_MAX;
1062 loopStart = UINT_MAX;
1063 }
1064 }
1065 if (s >= serverBase + this->frameCount) {
1066 serverBase += this->frameCount;
1067 }
1068
1069 this->server = s;
1070
1071 cv.signal();
1072 lock.unlock();
1073 return true;
1074}
1075
1076void* audio_track_cblk_t::buffer(uint32_t offset) const
1077{
Eric Laurenta553c252009-07-17 12:17:14 -07001078 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079}
1080
1081uint32_t audio_track_cblk_t::framesAvailable()
1082{
1083 Mutex::Autolock _l(lock);
1084 return framesAvailable_l();
1085}
1086
1087uint32_t audio_track_cblk_t::framesAvailable_l()
1088{
1089 uint32_t u = this->user;
1090 uint32_t s = this->server;
1091
1092 if (out) {
1093 uint32_t limit = (s < loopStart) ? s : loopStart;
1094 return limit + frameCount - u;
1095 } else {
1096 return frameCount + u - s;
1097 }
1098}
1099
1100uint32_t audio_track_cblk_t::framesReady()
1101{
1102 uint32_t u = this->user;
1103 uint32_t s = this->server;
1104
1105 if (out) {
1106 if (u < loopEnd) {
1107 return u - s;
1108 } else {
1109 Mutex::Autolock _l(lock);
1110 if (loopCount >= 0) {
1111 return (loopEnd - loopStart)*loopCount + u - s;
1112 } else {
1113 return UINT_MAX;
1114 }
1115 }
1116 } else {
1117 return s - u;
1118 }
1119}
1120
1121// -------------------------------------------------------------------------
1122
1123}; // namespace android
1124