blob: cedd79db7ce963ff8b74b66cee8831966430afbb [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/MemoryDealer.h>
36#include <binder/Parcel.h>
37#include <binder/IPCThreadState.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038#include <utils/Timers.h>
39#include <cutils/atomic.h>
40
41#define LIKELY( exp ) (__builtin_expect( (exp) != 0, true ))
42#define UNLIKELY( exp ) (__builtin_expect( (exp) != 0, false ))
43
44namespace android {
45
46// ---------------------------------------------------------------------------
47
48AudioTrack::AudioTrack()
49 : mStatus(NO_INIT)
50{
51}
52
53AudioTrack::AudioTrack(
54 int streamType,
55 uint32_t sampleRate,
56 int format,
Eric Laurenta553c252009-07-17 12:17:14 -070057 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058 int frameCount,
59 uint32_t flags,
60 callback_t cbf,
61 void* user,
62 int notificationFrames)
63 : mStatus(NO_INIT)
64{
Eric Laurenta553c252009-07-17 12:17:14 -070065 mStatus = set(streamType, sampleRate, format, channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 frameCount, flags, cbf, user, notificationFrames, 0);
67}
68
69AudioTrack::AudioTrack(
70 int streamType,
71 uint32_t sampleRate,
72 int format,
Eric Laurenta553c252009-07-17 12:17:14 -070073 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 const sp<IMemory>& sharedBuffer,
75 uint32_t flags,
76 callback_t cbf,
77 void* user,
78 int notificationFrames)
79 : mStatus(NO_INIT)
80{
Eric Laurenta553c252009-07-17 12:17:14 -070081 mStatus = set(streamType, sampleRate, format, channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 0, flags, cbf, user, notificationFrames, sharedBuffer);
83}
84
85AudioTrack::~AudioTrack()
86{
87 LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
88
89 if (mStatus == NO_ERROR) {
90 // Make sure that callback function exits in the case where
91 // it is looping on buffer full condition in obtainBuffer().
92 // Otherwise the callback thread will never exit.
93 stop();
94 if (mAudioTrackThread != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 mAudioTrackThread->requestExitAndWait();
96 mAudioTrackThread.clear();
97 }
98 mAudioTrack.clear();
99 IPCThreadState::self()->flushCommands();
Eric Laurenta553c252009-07-17 12:17:14 -0700100 AudioSystem::releaseOutput(getOutput());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 }
102}
103
104status_t AudioTrack::set(
105 int streamType,
106 uint32_t sampleRate,
107 int format,
Eric Laurenta553c252009-07-17 12:17:14 -0700108 int channels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 int frameCount,
110 uint32_t flags,
111 callback_t cbf,
112 void* user,
113 int notificationFrames,
114 const sp<IMemory>& sharedBuffer,
115 bool threadCanCallJava)
116{
117
118 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
119
Eric Laurentef028272009-04-21 07:56:33 -0700120 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 LOGE("Track already in use");
122 return INVALID_OPERATION;
123 }
124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 int afSampleRate;
126 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
127 return NO_INIT;
128 }
129 int afFrameCount;
130 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
131 return NO_INIT;
132 }
133 uint32_t afLatency;
134 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
135 return NO_INIT;
136 }
137
138 // handle default values first.
139 if (streamType == AudioSystem::DEFAULT) {
140 streamType = AudioSystem::MUSIC;
141 }
142 if (sampleRate == 0) {
143 sampleRate = afSampleRate;
144 }
145 // these below should probably come from the audioFlinger too...
146 if (format == 0) {
147 format = AudioSystem::PCM_16_BIT;
148 }
Eric Laurenta553c252009-07-17 12:17:14 -0700149 if (channels == 0) {
150 channels = AudioSystem::CHANNEL_OUT_STEREO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 }
152
153 // validate parameters
Eric Laurenta553c252009-07-17 12:17:14 -0700154 if (!AudioSystem::isValidFormat(format)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 LOGE("Invalid format");
156 return BAD_VALUE;
157 }
Eric Laurenta553c252009-07-17 12:17:14 -0700158
159 // force direct flag if format is not linear PCM
160 if (!AudioSystem::isLinearPCM(format)) {
161 flags |= AudioSystem::OUTPUT_FLAG_DIRECT;
162 }
163
164 if (!AudioSystem::isOutputChannel(channels)) {
165 LOGE("Invalid channel mask");
166 return BAD_VALUE;
167 }
168 uint32_t channelCount = AudioSystem::popCount(channels);
169
170 audio_io_handle_t output = AudioSystem::getOutput((AudioSystem::stream_type)streamType,
171 sampleRate, format, channels, (AudioSystem::output_flags)flags);
172
173 if (output == 0) {
174 LOGE("Could not get audio output for stream type %d", streamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 return BAD_VALUE;
176 }
177
Eric Laurenta553c252009-07-17 12:17:14 -0700178 if (!AudioSystem::isLinearPCM(format)) {
179 if (sharedBuffer != 0) {
180 frameCount = sharedBuffer->size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 }
182 } else {
Eric Laurenta553c252009-07-17 12:17:14 -0700183 // Ensure that buffer depth covers at least audio hardware latency
184 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
185 if (minBufCount < 2) minBufCount = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Eric Laurenta553c252009-07-17 12:17:14 -0700187 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
188
189 if (sharedBuffer == 0) {
190 if (frameCount == 0) {
191 frameCount = minFrameCount;
192 }
193 if (notificationFrames == 0) {
194 notificationFrames = frameCount/2;
195 }
196 // Make sure that application is notified with sufficient margin
197 // before underrun
198 if (notificationFrames > frameCount/2) {
199 notificationFrames = frameCount/2;
200 }
201 if (frameCount < minFrameCount) {
202 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
203 return BAD_VALUE;
204 }
205 } else {
206 // Ensure that buffer alignment matches channelcount
207 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
208 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
209 return BAD_VALUE;
210 }
211 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 }
214
Eric Laurentbda74692009-11-04 08:27:26 -0800215 mVolume[LEFT] = 1.0f;
216 mVolume[RIGHT] = 1.0f;
217 // create the IAudioTrack
218 status_t status = createTrack(streamType, sampleRate, format, channelCount,
219 frameCount, flags, sharedBuffer, output);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220
Eric Laurentbda74692009-11-04 08:27:26 -0800221 if (status != NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 return status;
223 }
Eric Laurentbda74692009-11-04 08:27:26 -0800224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 if (cbf != 0) {
226 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
227 if (mAudioTrackThread == 0) {
228 LOGE("Could not create callback thread");
229 return NO_INIT;
230 }
231 }
232
233 mStatus = NO_ERROR;
234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 mStreamType = streamType;
236 mFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -0700237 mChannels = channels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 mChannelCount = channelCount;
239 mSharedBuffer = sharedBuffer;
240 mMuted = false;
241 mActive = 0;
242 mCbf = cbf;
243 mNotificationFrames = notificationFrames;
244 mRemainingFrames = notificationFrames;
245 mUserData = user;
Eric Laurent88e209d2009-07-07 07:10:45 -0700246 mLatency = afLatency + (1000*mFrameCount) / sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 mLoopCount = 0;
248 mMarkerPosition = 0;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700249 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 mNewPosition = 0;
251 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700252 mFlags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253
254 return NO_ERROR;
255}
256
257status_t AudioTrack::initCheck() const
258{
259 return mStatus;
260}
261
262// -------------------------------------------------------------------------
263
264uint32_t AudioTrack::latency() const
265{
266 return mLatency;
267}
268
269int AudioTrack::streamType() const
270{
271 return mStreamType;
272}
273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274int AudioTrack::format() const
275{
276 return mFormat;
277}
278
279int AudioTrack::channelCount() const
280{
281 return mChannelCount;
282}
283
284uint32_t AudioTrack::frameCount() const
285{
286 return mFrameCount;
287}
288
289int AudioTrack::frameSize() const
290{
Eric Laurenta553c252009-07-17 12:17:14 -0700291 if (AudioSystem::isLinearPCM(mFormat)) {
292 return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
293 } else {
294 return sizeof(uint8_t);
295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296}
297
298sp<IMemory>& AudioTrack::sharedBuffer()
299{
300 return mSharedBuffer;
301}
302
303// -------------------------------------------------------------------------
304
305void AudioTrack::start()
306{
307 sp<AudioTrackThread> t = mAudioTrackThread;
308
309 LOGV("start %p", this);
310 if (t != 0) {
311 if (t->exitPending()) {
312 if (t->requestExitAndWait() == WOULD_BLOCK) {
313 LOGE("AudioTrack::start called from thread");
314 return;
315 }
316 }
317 t->mLock.lock();
318 }
319
320 if (android_atomic_or(1, &mActive) == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -0800321 audio_io_handle_t output = getOutput();
322 AudioSystem::startOutput(output, (AudioSystem::stream_type)mStreamType);
323 mNewPosition = mCblk->server + mUpdatePeriod;
324 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
325 mCblk->waitTimeMs = 0;
326 if (t != 0) {
327 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
328 } else {
329 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
330 }
331
Eric Laurentbda74692009-11-04 08:27:26 -0800332 status_t status = mAudioTrack->start();
333 if (status == DEAD_OBJECT) {
334 LOGV("start() dead IAudioTrack: creating a new one");
335 status = createTrack(mStreamType, mCblk->sampleRate, mFormat, mChannelCount,
336 mFrameCount, mFlags, mSharedBuffer, output);
Eric Laurentbda74692009-11-04 08:27:26 -0800337 mNewPosition = mCblk->server + mUpdatePeriod;
338 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
339 mCblk->waitTimeMs = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -0800340 }
341 if (status != NO_ERROR) {
Eric Laurentbda74692009-11-04 08:27:26 -0800342 LOGV("start() failed");
343 android_atomic_and(~1, &mActive);
Eric Laurent059b4be2009-11-09 23:32:22 -0800344 if (t != 0) {
345 t->requestExit();
346 } else {
347 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
348 }
349 AudioSystem::stopOutput(output, (AudioSystem::stream_type)mStreamType);
Eric Laurentbda74692009-11-04 08:27:26 -0800350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 }
352
353 if (t != 0) {
354 t->mLock.unlock();
355 }
356}
357
358void AudioTrack::stop()
359{
360 sp<AudioTrackThread> t = mAudioTrackThread;
361
362 LOGV("stop %p", this);
363 if (t != 0) {
364 t->mLock.lock();
365 }
366
367 if (android_atomic_and(~1, &mActive) == 1) {
Eric Laurentef028272009-04-21 07:56:33 -0700368 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 mAudioTrack->stop();
370 // Cancel loops (If we are in the middle of a loop, playback
371 // would not stop until loopCount reaches 0).
372 setLoop(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700373 // the playback head position will reset to 0, so if a marker is set, we need
374 // to activate it again
375 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 // Force flush if a shared buffer is used otherwise audioflinger
377 // will not stop before end of buffer is reached.
378 if (mSharedBuffer != 0) {
379 flush();
380 }
381 if (t != 0) {
382 t->requestExit();
383 } else {
384 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
385 }
Eric Laurenta553c252009-07-17 12:17:14 -0700386 AudioSystem::stopOutput(getOutput(), (AudioSystem::stream_type)mStreamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 }
388
389 if (t != 0) {
390 t->mLock.unlock();
391 }
392}
393
394bool AudioTrack::stopped() const
395{
396 return !mActive;
397}
398
399void AudioTrack::flush()
400{
401 LOGV("flush");
Eric Laurenta553c252009-07-17 12:17:14 -0700402
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700403 // clear playback marker and periodic update counter
404 mMarkerPosition = 0;
405 mMarkerReached = false;
406 mUpdatePeriod = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408
409 if (!mActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 mAudioTrack->flush();
411 // Release AudioTrack callback thread in case it was waiting for new buffers
412 // in AudioTrack::obtainBuffer()
413 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 }
415}
416
417void AudioTrack::pause()
418{
419 LOGV("pause");
420 if (android_atomic_and(~1, &mActive) == 1) {
421 mActive = 0;
422 mAudioTrack->pause();
Eric Laurenta553c252009-07-17 12:17:14 -0700423 AudioSystem::stopOutput(getOutput(), (AudioSystem::stream_type)mStreamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 }
425}
426
427void AudioTrack::mute(bool e)
428{
429 mAudioTrack->mute(e);
430 mMuted = e;
431}
432
433bool AudioTrack::muted() const
434{
435 return mMuted;
436}
437
438void AudioTrack::setVolume(float left, float right)
439{
440 mVolume[LEFT] = left;
441 mVolume[RIGHT] = right;
442
443 // write must be atomic
444 mCblk->volumeLR = (int32_t(int16_t(left * 0x1000)) << 16) | int16_t(right * 0x1000);
445}
446
447void AudioTrack::getVolume(float* left, float* right)
448{
449 *left = mVolume[LEFT];
450 *right = mVolume[RIGHT];
451}
452
Eric Laurent88e209d2009-07-07 07:10:45 -0700453status_t AudioTrack::setSampleRate(int rate)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454{
455 int afSamplingRate;
456
457 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
Eric Laurent88e209d2009-07-07 07:10:45 -0700458 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 }
460 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -0700461 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462
Eric Laurent88e209d2009-07-07 07:10:45 -0700463 mCblk->sampleRate = rate;
464 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465}
466
467uint32_t AudioTrack::getSampleRate()
468{
Eric Laurent88e209d2009-07-07 07:10:45 -0700469 return mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470}
471
472status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
473{
474 audio_track_cblk_t* cblk = mCblk;
475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 Mutex::Autolock _l(cblk->lock);
477
478 if (loopCount == 0) {
479 cblk->loopStart = UINT_MAX;
480 cblk->loopEnd = UINT_MAX;
481 cblk->loopCount = 0;
482 mLoopCount = 0;
483 return NO_ERROR;
484 }
485
486 if (loopStart >= loopEnd ||
487 loopEnd - loopStart > mFrameCount) {
488 LOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user);
489 return BAD_VALUE;
490 }
491
492 if ((mSharedBuffer != 0) && (loopEnd > mFrameCount)) {
493 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
494 loopStart, loopEnd, mFrameCount);
495 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -0700496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497
498 cblk->loopStart = loopStart;
499 cblk->loopEnd = loopEnd;
500 cblk->loopCount = loopCount;
501 mLoopCount = loopCount;
502
503 return NO_ERROR;
504}
505
506status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
507{
508 if (loopStart != 0) {
509 *loopStart = mCblk->loopStart;
510 }
511 if (loopEnd != 0) {
512 *loopEnd = mCblk->loopEnd;
513 }
514 if (loopCount != 0) {
515 if (mCblk->loopCount < 0) {
516 *loopCount = -1;
517 } else {
518 *loopCount = mCblk->loopCount;
519 }
520 }
521
522 return NO_ERROR;
523}
524
525status_t AudioTrack::setMarkerPosition(uint32_t marker)
526{
527 if (mCbf == 0) return INVALID_OPERATION;
528
529 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700530 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531
532 return NO_ERROR;
533}
534
535status_t AudioTrack::getMarkerPosition(uint32_t *marker)
536{
537 if (marker == 0) return BAD_VALUE;
538
539 *marker = mMarkerPosition;
540
541 return NO_ERROR;
542}
543
544status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
545{
546 if (mCbf == 0) return INVALID_OPERATION;
547
548 uint32_t curPosition;
549 getPosition(&curPosition);
550 mNewPosition = curPosition + updatePeriod;
551 mUpdatePeriod = updatePeriod;
552
553 return NO_ERROR;
554}
555
556status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
557{
558 if (updatePeriod == 0) return BAD_VALUE;
559
560 *updatePeriod = mUpdatePeriod;
561
562 return NO_ERROR;
563}
564
565status_t AudioTrack::setPosition(uint32_t position)
566{
567 Mutex::Autolock _l(mCblk->lock);
568
569 if (!stopped()) return INVALID_OPERATION;
570
571 if (position > mCblk->user) return BAD_VALUE;
572
573 mCblk->server = position;
574 mCblk->forceReady = 1;
Eric Laurenta553c252009-07-17 12:17:14 -0700575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 return NO_ERROR;
577}
578
579status_t AudioTrack::getPosition(uint32_t *position)
580{
581 if (position == 0) return BAD_VALUE;
582
583 *position = mCblk->server;
584
585 return NO_ERROR;
586}
587
588status_t AudioTrack::reload()
589{
590 if (!stopped()) return INVALID_OPERATION;
Eric Laurenta553c252009-07-17 12:17:14 -0700591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 flush();
593
594 mCblk->stepUser(mFrameCount);
595
596 return NO_ERROR;
597}
598
Eric Laurenta553c252009-07-17 12:17:14 -0700599audio_io_handle_t AudioTrack::getOutput()
600{
601 return AudioSystem::getOutput((AudioSystem::stream_type)mStreamType,
602 mCblk->sampleRate, mFormat, mChannels, (AudioSystem::output_flags)mFlags);
603}
604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605// -------------------------------------------------------------------------
606
Eric Laurentbda74692009-11-04 08:27:26 -0800607status_t AudioTrack::createTrack(
608 int streamType,
609 uint32_t sampleRate,
610 int format,
611 int channelCount,
612 int frameCount,
613 uint32_t flags,
614 const sp<IMemory>& sharedBuffer,
615 audio_io_handle_t output)
616{
617 status_t status;
618 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
619 if (audioFlinger == 0) {
620 LOGE("Could not get audioflinger");
621 return NO_INIT;
622 }
623
624 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
625 streamType,
626 sampleRate,
627 format,
628 channelCount,
629 frameCount,
630 ((uint16_t)flags) << 16,
631 sharedBuffer,
632 output,
633 &status);
634
635 if (track == 0) {
636 LOGE("AudioFlinger could not create track, status: %d", status);
637 return status;
638 }
639 sp<IMemory> cblk = track->getCblk();
640 if (cblk == 0) {
641 LOGE("Could not get control block");
642 return NO_INIT;
643 }
644 mAudioTrack.clear();
645 mAudioTrack = track;
646 mCblkMemory.clear();
647 mCblkMemory = cblk;
648 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
649 mCblk->out = 1;
650 // Update buffer size in case it has been limited by AudioFlinger during track creation
651 mFrameCount = mCblk->frameCount;
652 if (sharedBuffer == 0) {
653 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
654 } else {
655 mCblk->buffers = sharedBuffer->pointer();
656 // Force buffer full condition as data is already present in shared memory
657 mCblk->stepUser(mFrameCount);
658 }
659
660 mCblk->volumeLR = (int32_t(int16_t(mVolume[LEFT] * 0x1000)) << 16) | int16_t(mVolume[RIGHT] * 0x1000);
661
662 return NO_ERROR;
663}
664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
666{
667 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 status_t result;
669 audio_track_cblk_t* cblk = mCblk;
670 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700671 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672
673 audioBuffer->frameCount = 0;
674 audioBuffer->size = 0;
675
676 uint32_t framesAvail = cblk->framesAvailable();
677
678 if (framesAvail == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800679 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 goto start_loop_here;
681 while (framesAvail == 0) {
682 active = mActive;
683 if (UNLIKELY(!active)) {
684 LOGV("Not active and NO_MORE_BUFFERS");
Eric Laurentbda74692009-11-04 08:27:26 -0800685 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 return NO_MORE_BUFFERS;
687 }
Eric Laurentbda74692009-11-04 08:27:26 -0800688 if (UNLIKELY(!waitCount)) {
689 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 return WOULD_BLOCK;
Eric Laurentbda74692009-11-04 08:27:26 -0800691 }
692
Eric Laurentef028272009-04-21 07:56:33 -0700693 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
Eric Laurenta553c252009-07-17 12:17:14 -0700694 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700695 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
697 // timing out when a loop has been set and we have already written upto loop end
698 // is a normal condition: no need to wake AudioFlinger up.
699 if (cblk->user < cblk->loopEnd) {
700 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
701 "user=%08x, server=%08x", this, cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -0700702 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 cblk->lock.unlock();
Eric Laurentbda74692009-11-04 08:27:26 -0800704 result = mAudioTrack->start();
705 if (result == DEAD_OBJECT) {
706 LOGW("obtainBuffer() dead IAudioTrack: creating a new one");
707 result = createTrack(mStreamType, cblk->sampleRate, mFormat, mChannelCount,
708 mFrameCount, mFlags, mSharedBuffer, getOutput());
709 if (result == NO_ERROR) {
710 cblk = mCblk;
711 cblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
712 }
713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 cblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 }
716 cblk->waitTimeMs = 0;
717 }
Eric Laurenta553c252009-07-17 12:17:14 -0700718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 if (--waitCount == 0) {
Eric Laurentbda74692009-11-04 08:27:26 -0800720 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 return TIMED_OUT;
722 }
723 }
724 // read the server count again
725 start_loop_here:
726 framesAvail = cblk->framesAvailable_l();
727 }
Eric Laurentbda74692009-11-04 08:27:26 -0800728 cblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 }
730
731 cblk->waitTimeMs = 0;
Eric Laurenta553c252009-07-17 12:17:14 -0700732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 if (framesReq > framesAvail) {
734 framesReq = framesAvail;
735 }
736
737 uint32_t u = cblk->user;
738 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
739
740 if (u + framesReq > bufferEnd) {
741 framesReq = bufferEnd - u;
742 }
743
Eric Laurenta553c252009-07-17 12:17:14 -0700744 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
745 audioBuffer->channelCount = mChannelCount;
746 audioBuffer->frameCount = framesReq;
747 audioBuffer->size = framesReq * cblk->frameSize;
748 if (AudioSystem::isLinearPCM(mFormat)) {
749 audioBuffer->format = AudioSystem::PCM_16_BIT;
750 } else {
751 audioBuffer->format = mFormat;
752 }
753 audioBuffer->raw = (int8_t *)cblk->buffer(u);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 active = mActive;
755 return active ? status_t(NO_ERROR) : status_t(STOPPED);
756}
757
758void AudioTrack::releaseBuffer(Buffer* audioBuffer)
759{
760 audio_track_cblk_t* cblk = mCblk;
761 cblk->stepUser(audioBuffer->frameCount);
762}
763
764// -------------------------------------------------------------------------
765
766ssize_t AudioTrack::write(const void* buffer, size_t userSize)
767{
768
769 if (mSharedBuffer != 0) return INVALID_OPERATION;
770
771 if (ssize_t(userSize) < 0) {
772 // sanity-check. user is most-likely passing an error code.
773 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
774 buffer, userSize, userSize);
775 return BAD_VALUE;
776 }
777
778 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
779
780 ssize_t written = 0;
781 const int8_t *src = (const int8_t *)buffer;
782 Buffer audioBuffer;
783
784 do {
Eric Laurenta553c252009-07-17 12:17:14 -0700785 audioBuffer.frameCount = userSize/frameSize();
786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 // Calling obtainBuffer() with a negative wait count causes
788 // an (almost) infinite wait time.
789 status_t err = obtainBuffer(&audioBuffer, -1);
790 if (err < 0) {
791 // out of buffers, return #bytes written
792 if (err == status_t(NO_MORE_BUFFERS))
793 break;
794 return ssize_t(err);
795 }
796
797 size_t toWrite;
Eric Laurenta553c252009-07-17 12:17:14 -0700798
Eric Laurent28ad42b2009-08-04 10:42:26 -0700799 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 // Divide capacity by 2 to take expansion into account
801 toWrite = audioBuffer.size>>1;
802 // 8 to 16 bit conversion
803 int count = toWrite;
804 int16_t *dst = (int16_t *)(audioBuffer.i8);
805 while(count--) {
806 *dst++ = (int16_t)(*src++^0x80) << 8;
807 }
Eric Laurent28ad42b2009-08-04 10:42:26 -0700808 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 toWrite = audioBuffer.size;
810 memcpy(audioBuffer.i8, src, toWrite);
811 src += toWrite;
812 }
813 userSize -= toWrite;
814 written += toWrite;
815
816 releaseBuffer(&audioBuffer);
817 } while (userSize);
818
819 return written;
820}
821
822// -------------------------------------------------------------------------
823
824bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
825{
826 Buffer audioBuffer;
827 uint32_t frames;
828 size_t writtenSize;
829
830 // Manage underrun callback
831 if (mActive && (mCblk->framesReady() == 0)) {
832 LOGV("Underrun user: %x, server: %x, flowControlFlag %d", mCblk->user, mCblk->server, mCblk->flowControlFlag);
833 if (mCblk->flowControlFlag == 0) {
834 mCbf(EVENT_UNDERRUN, mUserData, 0);
835 if (mCblk->server == mCblk->frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -0700836 mCbf(EVENT_BUFFER_END, mUserData, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 }
838 mCblk->flowControlFlag = 1;
839 if (mSharedBuffer != 0) return false;
840 }
841 }
Eric Laurenta553c252009-07-17 12:17:14 -0700842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 // Manage loop end callback
844 while (mLoopCount > mCblk->loopCount) {
845 int loopCount = -1;
846 mLoopCount--;
847 if (mLoopCount >= 0) loopCount = mLoopCount;
848
849 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
850 }
851
852 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700853 if (!mMarkerReached && (mMarkerPosition > 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 if (mCblk->server >= mMarkerPosition) {
855 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700856 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 }
858 }
859
860 // Manage new position callback
Eric Laurenta553c252009-07-17 12:17:14 -0700861 if (mUpdatePeriod > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 while (mCblk->server >= mNewPosition) {
863 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
864 mNewPosition += mUpdatePeriod;
865 }
866 }
867
868 // If Shared buffer is used, no data is requested from client.
869 if (mSharedBuffer != 0) {
870 frames = 0;
871 } else {
872 frames = mRemainingFrames;
873 }
874
875 do {
876
877 audioBuffer.frameCount = frames;
Eric Laurenta553c252009-07-17 12:17:14 -0700878
879 // Calling obtainBuffer() with a wait count of 1
880 // limits wait time to WAIT_PERIOD_MS. This prevents from being
881 // stuck here not being able to handle timed events (position, markers, loops).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 status_t err = obtainBuffer(&audioBuffer, 1);
883 if (err < NO_ERROR) {
884 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -0700885 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 -0800886 return false;
887 }
888 break;
889 }
890 if (err == status_t(STOPPED)) return false;
891
892 // Divide buffer size by 2 to take into account the expansion
893 // due to 8 to 16 bit conversion: the callback must fill only half
894 // of the destination buffer
Eric Laurent28ad42b2009-08-04 10:42:26 -0700895 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 audioBuffer.size >>= 1;
897 }
898
899 size_t reqSize = audioBuffer.size;
900 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
901 writtenSize = audioBuffer.size;
902
903 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -0800904 if (ssize_t(writtenSize) <= 0) {
905 // The callback is done filling buffers
906 // Keep this thread going to handle timed events and
907 // still try to get more data in intervals of WAIT_PERIOD_MS
908 // but don't just loop and block the CPU, so wait
909 usleep(WAIT_PERIOD_MS*1000);
910 break;
911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 if (writtenSize > reqSize) writtenSize = reqSize;
913
Eric Laurent28ad42b2009-08-04 10:42:26 -0700914 if (mFormat == AudioSystem::PCM_8_BIT && !(mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 // 8 to 16 bit conversion
916 const int8_t *src = audioBuffer.i8 + writtenSize-1;
917 int count = writtenSize;
918 int16_t *dst = audioBuffer.i16 + writtenSize-1;
919 while(count--) {
920 *dst-- = (int16_t)(*src--^0x80) << 8;
921 }
922 writtenSize <<= 1;
923 }
924
925 audioBuffer.size = writtenSize;
Eric Laurenta553c252009-07-17 12:17:14 -0700926 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
927 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sampel size of
928 // 16 bit.
929 audioBuffer.frameCount = writtenSize/mCblk->frameSize;
930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 frames -= audioBuffer.frameCount;
932
933 releaseBuffer(&audioBuffer);
934 }
935 while (frames);
936
937 if (frames == 0) {
938 mRemainingFrames = mNotificationFrames;
939 } else {
940 mRemainingFrames = frames;
941 }
942 return true;
943}
944
945status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
946{
947
948 const size_t SIZE = 256;
949 char buffer[SIZE];
950 String8 result;
951
952 result.append(" AudioTrack::dump\n");
953 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
954 result.append(buffer);
955 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mFrameCount);
956 result.append(buffer);
Eric Laurent88e209d2009-07-07 07:10:45 -0700957 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 -0800958 result.append(buffer);
959 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
960 result.append(buffer);
961 ::write(fd, result.string(), result.size());
962 return NO_ERROR;
963}
964
965// =========================================================================
966
967AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
968 : Thread(bCanCallJava), mReceiver(receiver)
969{
970}
971
972bool AudioTrack::AudioTrackThread::threadLoop()
973{
974 return mReceiver.processAudioBuffer(this);
975}
976
977status_t AudioTrack::AudioTrackThread::readyToRun()
978{
979 return NO_ERROR;
980}
981
982void AudioTrack::AudioTrackThread::onFirstRef()
983{
984}
985
986// =========================================================================
987
988audio_track_cblk_t::audio_track_cblk_t()
Mathias Agopianfb4f2662009-07-13 21:59:37 -0700989 : lock(Mutex::SHARED), user(0), server(0), userBase(0), serverBase(0), buffers(0), frameCount(0),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0), flowControlFlag(1), forceReady(0)
991{
992}
993
994uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
995{
996 uint32_t u = this->user;
997
998 u += frameCount;
999 // Ensure that user is never ahead of server for AudioRecord
1000 if (out) {
1001 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1002 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1003 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1004 }
1005 } else if (u > this->server) {
1006 LOGW("stepServer occured after track reset");
1007 u = this->server;
1008 }
1009
1010 if (u >= userBase + this->frameCount) {
1011 userBase += this->frameCount;
1012 }
1013
1014 this->user = u;
1015
1016 // Clear flow control error condition as new data has been written/read to/from buffer.
1017 flowControlFlag = 0;
1018
1019 return u;
1020}
1021
1022bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1023{
1024 // the code below simulates lock-with-timeout
1025 // we MUST do this to protect the AudioFlinger server
1026 // as this lock is shared with the client.
1027 status_t err;
1028
1029 err = lock.tryLock();
1030 if (err == -EBUSY) { // just wait a bit
1031 usleep(1000);
1032 err = lock.tryLock();
1033 }
1034 if (err != NO_ERROR) {
1035 // probably, the client just died.
1036 return false;
1037 }
1038
1039 uint32_t s = this->server;
1040
1041 s += frameCount;
1042 if (out) {
1043 // Mark that we have read the first buffer so that next time stepUser() is called
1044 // we switch to normal obtainBuffer() timeout period
1045 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
Eric Laurentbda74692009-11-04 08:27:26 -08001046 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
Eric Laurenta553c252009-07-17 12:17:14 -07001047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 // It is possible that we receive a flush()
1049 // while the mixer is processing a block: in this case,
1050 // stepServer() is called After the flush() has reset u & s and
1051 // we have s > u
1052 if (s > this->user) {
1053 LOGW("stepServer occured after track reset");
1054 s = this->user;
1055 }
1056 }
1057
1058 if (s >= loopEnd) {
1059 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1060 s = loopStart;
1061 if (--loopCount == 0) {
1062 loopEnd = UINT_MAX;
1063 loopStart = UINT_MAX;
1064 }
1065 }
1066 if (s >= serverBase + this->frameCount) {
1067 serverBase += this->frameCount;
1068 }
1069
1070 this->server = s;
1071
1072 cv.signal();
1073 lock.unlock();
1074 return true;
1075}
1076
1077void* audio_track_cblk_t::buffer(uint32_t offset) const
1078{
Eric Laurenta553c252009-07-17 12:17:14 -07001079 return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080}
1081
1082uint32_t audio_track_cblk_t::framesAvailable()
1083{
1084 Mutex::Autolock _l(lock);
1085 return framesAvailable_l();
1086}
1087
1088uint32_t audio_track_cblk_t::framesAvailable_l()
1089{
1090 uint32_t u = this->user;
1091 uint32_t s = this->server;
1092
1093 if (out) {
1094 uint32_t limit = (s < loopStart) ? s : loopStart;
1095 return limit + frameCount - u;
1096 } else {
1097 return frameCount + u - s;
1098 }
1099}
1100
1101uint32_t audio_track_cblk_t::framesReady()
1102{
1103 uint32_t u = this->user;
1104 uint32_t s = this->server;
1105
1106 if (out) {
1107 if (u < loopEnd) {
1108 return u - s;
1109 } else {
1110 Mutex::Autolock _l(lock);
1111 if (loopCount >= 0) {
1112 return (loopEnd - loopStart)*loopCount + u - s;
1113 } else {
1114 return UINT_MAX;
1115 }
1116 }
1117 } else {
1118 return s - u;
1119 }
1120}
1121
1122// -------------------------------------------------------------------------
1123
1124}; // namespace android
1125