blob: 289bd7552cbbdb8cd15351e5ff1702ec5bb844ec [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>
35#include <utils/MemoryDealer.h>
36#include <utils/Parcel.h>
37#include <utils/IPCThreadState.h>
38#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,
57 int channelCount,
58 int frameCount,
59 uint32_t flags,
60 callback_t cbf,
61 void* user,
62 int notificationFrames)
63 : mStatus(NO_INIT)
64{
65 mStatus = set(streamType, sampleRate, format, channelCount,
66 frameCount, flags, cbf, user, notificationFrames, 0);
67}
68
69AudioTrack::AudioTrack(
70 int streamType,
71 uint32_t sampleRate,
72 int format,
73 int channelCount,
74 const sp<IMemory>& sharedBuffer,
75 uint32_t flags,
76 callback_t cbf,
77 void* user,
78 int notificationFrames)
79 : mStatus(NO_INIT)
80{
81 mStatus = set(streamType, sampleRate, format, channelCount,
82 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();
100 }
101}
102
103status_t AudioTrack::set(
104 int streamType,
105 uint32_t sampleRate,
106 int format,
107 int channelCount,
108 int frameCount,
109 uint32_t flags,
110 callback_t cbf,
111 void* user,
112 int notificationFrames,
113 const sp<IMemory>& sharedBuffer,
114 bool threadCanCallJava)
115{
116
117 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
118
Eric Laurentef028272009-04-21 07:56:33 -0700119 if (mAudioTrack != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 LOGE("Track already in use");
121 return INVALID_OPERATION;
122 }
123
124 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
125 if (audioFlinger == 0) {
126 LOGE("Could not get audioflinger");
127 return NO_INIT;
128 }
129 int afSampleRate;
130 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
131 return NO_INIT;
132 }
133 int afFrameCount;
134 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
135 return NO_INIT;
136 }
137 uint32_t afLatency;
138 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
139 return NO_INIT;
140 }
141
142 // handle default values first.
143 if (streamType == AudioSystem::DEFAULT) {
144 streamType = AudioSystem::MUSIC;
145 }
146 if (sampleRate == 0) {
147 sampleRate = afSampleRate;
148 }
149 // these below should probably come from the audioFlinger too...
150 if (format == 0) {
151 format = AudioSystem::PCM_16_BIT;
152 }
153 if (channelCount == 0) {
154 channelCount = 2;
155 }
156
157 // validate parameters
158 if (((format != AudioSystem::PCM_8_BIT) || sharedBuffer != 0) &&
159 (format != AudioSystem::PCM_16_BIT)) {
160 LOGE("Invalid format");
161 return BAD_VALUE;
162 }
163 if (channelCount != 1 && channelCount != 2) {
164 LOGE("Invalid channel number");
165 return BAD_VALUE;
166 }
167
168 // Ensure that buffer depth covers at least audio hardware latency
169 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
170 if (minBufCount < 2) minBufCount = 2;
171
172 // When playing from shared buffer, playback will start even if last audioflinger
173 // block is partly filled.
174 if (sharedBuffer != 0 && minBufCount > 1) {
175 minBufCount--;
176 }
177
178 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
179
180 if (sharedBuffer == 0) {
181 if (frameCount == 0) {
182 frameCount = minFrameCount;
183 }
184 if (notificationFrames == 0) {
185 notificationFrames = frameCount/2;
186 }
187 // Make sure that application is notified with sufficient margin
188 // before underrun
189 if (notificationFrames > frameCount/2) {
190 notificationFrames = frameCount/2;
191 }
192 } else {
193 // Ensure that buffer alignment matches channelcount
194 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) {
195 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount);
196 return BAD_VALUE;
197 }
198 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
199 }
200
201 if (frameCount < minFrameCount) {
202 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount);
203 return BAD_VALUE;
204 }
205
206 // create the track
207 status_t status;
208 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
209 streamType, sampleRate, format, channelCount, frameCount, flags, sharedBuffer, &status);
210
211 if (track == 0) {
212 LOGE("AudioFlinger could not create track, status: %d", status);
213 return status;
214 }
215 sp<IMemory> cblk = track->getCblk();
216 if (cblk == 0) {
217 LOGE("Could not get control block");
218 return NO_INIT;
219 }
220 if (cbf != 0) {
221 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
222 if (mAudioTrackThread == 0) {
223 LOGE("Could not create callback thread");
224 return NO_INIT;
225 }
226 }
227
228 mStatus = NO_ERROR;
229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 mAudioTrack = track;
231 mCblkMemory = cblk;
232 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
233 mCblk->out = 1;
234 // Update buffer size in case it has been limited by AudioFlinger during track creation
235 mFrameCount = mCblk->frameCount;
236 if (sharedBuffer == 0) {
237 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
238 } else {
239 mCblk->buffers = sharedBuffer->pointer();
240 // Force buffer full condition as data is already present in shared memory
241 mCblk->stepUser(mFrameCount);
242 }
243 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
244 mVolume[LEFT] = 1.0f;
245 mVolume[RIGHT] = 1.0f;
246 mSampleRate = sampleRate;
247 mStreamType = streamType;
248 mFormat = format;
249 mChannelCount = channelCount;
250 mSharedBuffer = sharedBuffer;
251 mMuted = false;
252 mActive = 0;
253 mCbf = cbf;
254 mNotificationFrames = notificationFrames;
255 mRemainingFrames = notificationFrames;
256 mUserData = user;
257 mLatency = afLatency + (1000*mFrameCount) / mSampleRate;
258 mLoopCount = 0;
259 mMarkerPosition = 0;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700260 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 mNewPosition = 0;
262 mUpdatePeriod = 0;
263
264 return NO_ERROR;
265}
266
267status_t AudioTrack::initCheck() const
268{
269 return mStatus;
270}
271
272// -------------------------------------------------------------------------
273
274uint32_t AudioTrack::latency() const
275{
276 return mLatency;
277}
278
279int AudioTrack::streamType() const
280{
281 return mStreamType;
282}
283
284uint32_t AudioTrack::sampleRate() const
285{
286 return mSampleRate;
287}
288
289int AudioTrack::format() const
290{
291 return mFormat;
292}
293
294int AudioTrack::channelCount() const
295{
296 return mChannelCount;
297}
298
299uint32_t AudioTrack::frameCount() const
300{
301 return mFrameCount;
302}
303
304int AudioTrack::frameSize() const
305{
306 return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t));
307}
308
309sp<IMemory>& AudioTrack::sharedBuffer()
310{
311 return mSharedBuffer;
312}
313
314// -------------------------------------------------------------------------
315
316void AudioTrack::start()
317{
318 sp<AudioTrackThread> t = mAudioTrackThread;
319
320 LOGV("start %p", this);
321 if (t != 0) {
322 if (t->exitPending()) {
323 if (t->requestExitAndWait() == WOULD_BLOCK) {
324 LOGE("AudioTrack::start called from thread");
325 return;
326 }
327 }
328 t->mLock.lock();
329 }
330
331 if (android_atomic_or(1, &mActive) == 0) {
332 mNewPosition = mCblk->server + mUpdatePeriod;
333 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
334 mCblk->waitTimeMs = 0;
335 if (t != 0) {
336 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT);
337 } else {
338 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
339 }
340 mAudioTrack->start();
341 }
342
343 if (t != 0) {
344 t->mLock.unlock();
345 }
346}
347
348void AudioTrack::stop()
349{
350 sp<AudioTrackThread> t = mAudioTrackThread;
351
352 LOGV("stop %p", this);
353 if (t != 0) {
354 t->mLock.lock();
355 }
356
357 if (android_atomic_and(~1, &mActive) == 1) {
Eric Laurentef028272009-04-21 07:56:33 -0700358 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 mAudioTrack->stop();
360 // Cancel loops (If we are in the middle of a loop, playback
361 // would not stop until loopCount reaches 0).
362 setLoop(0, 0, 0);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700363 // the playback head position will reset to 0, so if a marker is set, we need
364 // to activate it again
365 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 // Force flush if a shared buffer is used otherwise audioflinger
367 // will not stop before end of buffer is reached.
368 if (mSharedBuffer != 0) {
369 flush();
370 }
371 if (t != 0) {
372 t->requestExit();
373 } else {
374 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
375 }
376 }
377
378 if (t != 0) {
379 t->mLock.unlock();
380 }
381}
382
383bool AudioTrack::stopped() const
384{
385 return !mActive;
386}
387
388void AudioTrack::flush()
389{
390 LOGV("flush");
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700391
392 // clear playback marker and periodic update counter
393 mMarkerPosition = 0;
394 mMarkerReached = false;
395 mUpdatePeriod = 0;
396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397
398 if (!mActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 mAudioTrack->flush();
400 // Release AudioTrack callback thread in case it was waiting for new buffers
401 // in AudioTrack::obtainBuffer()
402 mCblk->cv.signal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 }
404}
405
406void AudioTrack::pause()
407{
408 LOGV("pause");
409 if (android_atomic_and(~1, &mActive) == 1) {
410 mActive = 0;
411 mAudioTrack->pause();
412 }
413}
414
415void AudioTrack::mute(bool e)
416{
417 mAudioTrack->mute(e);
418 mMuted = e;
419}
420
421bool AudioTrack::muted() const
422{
423 return mMuted;
424}
425
426void AudioTrack::setVolume(float left, float right)
427{
428 mVolume[LEFT] = left;
429 mVolume[RIGHT] = right;
430
431 // write must be atomic
432 mCblk->volumeLR = (int32_t(int16_t(left * 0x1000)) << 16) | int16_t(right * 0x1000);
433}
434
435void AudioTrack::getVolume(float* left, float* right)
436{
437 *left = mVolume[LEFT];
438 *right = mVolume[RIGHT];
439}
440
441void AudioTrack::setSampleRate(int rate)
442{
443 int afSamplingRate;
444
445 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
446 return;
447 }
448 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
449 if (rate <= 0) rate = 1;
450 if (rate > afSamplingRate*2) rate = afSamplingRate*2;
451 if (rate > MAX_SAMPLE_RATE) rate = MAX_SAMPLE_RATE;
452
The Android Open Source Project10592532009-03-18 17:39:46 -0700453 mCblk->sampleRate = (uint16_t)rate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454}
455
456uint32_t AudioTrack::getSampleRate()
457{
458 return uint32_t(mCblk->sampleRate);
459}
460
461status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
462{
463 audio_track_cblk_t* cblk = mCblk;
464
465
466 Mutex::Autolock _l(cblk->lock);
467
468 if (loopCount == 0) {
469 cblk->loopStart = UINT_MAX;
470 cblk->loopEnd = UINT_MAX;
471 cblk->loopCount = 0;
472 mLoopCount = 0;
473 return NO_ERROR;
474 }
475
476 if (loopStart >= loopEnd ||
477 loopEnd - loopStart > mFrameCount) {
478 LOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user);
479 return BAD_VALUE;
480 }
481
482 if ((mSharedBuffer != 0) && (loopEnd > mFrameCount)) {
483 LOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d",
484 loopStart, loopEnd, mFrameCount);
485 return BAD_VALUE;
486 }
487
488 cblk->loopStart = loopStart;
489 cblk->loopEnd = loopEnd;
490 cblk->loopCount = loopCount;
491 mLoopCount = loopCount;
492
493 return NO_ERROR;
494}
495
496status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount)
497{
498 if (loopStart != 0) {
499 *loopStart = mCblk->loopStart;
500 }
501 if (loopEnd != 0) {
502 *loopEnd = mCblk->loopEnd;
503 }
504 if (loopCount != 0) {
505 if (mCblk->loopCount < 0) {
506 *loopCount = -1;
507 } else {
508 *loopCount = mCblk->loopCount;
509 }
510 }
511
512 return NO_ERROR;
513}
514
515status_t AudioTrack::setMarkerPosition(uint32_t marker)
516{
517 if (mCbf == 0) return INVALID_OPERATION;
518
519 mMarkerPosition = marker;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700520 mMarkerReached = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521
522 return NO_ERROR;
523}
524
525status_t AudioTrack::getMarkerPosition(uint32_t *marker)
526{
527 if (marker == 0) return BAD_VALUE;
528
529 *marker = mMarkerPosition;
530
531 return NO_ERROR;
532}
533
534status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
535{
536 if (mCbf == 0) return INVALID_OPERATION;
537
538 uint32_t curPosition;
539 getPosition(&curPosition);
540 mNewPosition = curPosition + updatePeriod;
541 mUpdatePeriod = updatePeriod;
542
543 return NO_ERROR;
544}
545
546status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod)
547{
548 if (updatePeriod == 0) return BAD_VALUE;
549
550 *updatePeriod = mUpdatePeriod;
551
552 return NO_ERROR;
553}
554
555status_t AudioTrack::setPosition(uint32_t position)
556{
557 Mutex::Autolock _l(mCblk->lock);
558
559 if (!stopped()) return INVALID_OPERATION;
560
561 if (position > mCblk->user) return BAD_VALUE;
562
563 mCblk->server = position;
564 mCblk->forceReady = 1;
565
566 return NO_ERROR;
567}
568
569status_t AudioTrack::getPosition(uint32_t *position)
570{
571 if (position == 0) return BAD_VALUE;
572
573 *position = mCblk->server;
574
575 return NO_ERROR;
576}
577
578status_t AudioTrack::reload()
579{
580 if (!stopped()) return INVALID_OPERATION;
581
582 flush();
583
584 mCblk->stepUser(mFrameCount);
585
586 return NO_ERROR;
587}
588
589// -------------------------------------------------------------------------
590
591status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
592{
593 int active;
594 int timeout = 0;
595 status_t result;
596 audio_track_cblk_t* cblk = mCblk;
597 uint32_t framesReq = audioBuffer->frameCount;
Eric Laurentef028272009-04-21 07:56:33 -0700598 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599
600 audioBuffer->frameCount = 0;
601 audioBuffer->size = 0;
602
603 uint32_t framesAvail = cblk->framesAvailable();
604
605 if (framesAvail == 0) {
606 Mutex::Autolock _l(cblk->lock);
607 goto start_loop_here;
608 while (framesAvail == 0) {
609 active = mActive;
610 if (UNLIKELY(!active)) {
611 LOGV("Not active and NO_MORE_BUFFERS");
612 return NO_MORE_BUFFERS;
613 }
614 if (UNLIKELY(!waitCount))
615 return WOULD_BLOCK;
616 timeout = 0;
Eric Laurentef028272009-04-21 07:56:33 -0700617 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 if (__builtin_expect(result!=NO_ERROR, false)) {
Eric Laurentef028272009-04-21 07:56:33 -0700619 cblk->waitTimeMs += waitTimeMs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
621 // timing out when a loop has been set and we have already written upto loop end
622 // is a normal condition: no need to wake AudioFlinger up.
623 if (cblk->user < cblk->loopEnd) {
624 LOGW( "obtainBuffer timed out (is the CPU pegged?) %p "
625 "user=%08x, server=%08x", this, cblk->user, cblk->server);
626 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
627 cblk->lock.unlock();
628 mAudioTrack->start();
629 cblk->lock.lock();
630 timeout = 1;
631 }
632 cblk->waitTimeMs = 0;
633 }
634
635 if (--waitCount == 0) {
636 return TIMED_OUT;
637 }
638 }
639 // read the server count again
640 start_loop_here:
641 framesAvail = cblk->framesAvailable_l();
642 }
643 }
644
645 cblk->waitTimeMs = 0;
646
647 if (framesReq > framesAvail) {
648 framesReq = framesAvail;
649 }
650
651 uint32_t u = cblk->user;
652 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
653
654 if (u + framesReq > bufferEnd) {
655 framesReq = bufferEnd - u;
656 }
657
658 LOGW_IF(timeout,
659 "*** SERIOUS WARNING *** obtainBuffer() timed out "
660 "but didn't need to be locked. We recovered, but "
661 "this shouldn't happen (user=%08x, server=%08x)", cblk->user, cblk->server);
662
663 audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
664 audioBuffer->channelCount= mChannelCount;
665 audioBuffer->format = AudioSystem::PCM_16_BIT;
666 audioBuffer->frameCount = framesReq;
667 audioBuffer->size = framesReq*mChannelCount*sizeof(int16_t);
668 audioBuffer->raw = (int8_t *)cblk->buffer(u);
669 active = mActive;
670 return active ? status_t(NO_ERROR) : status_t(STOPPED);
671}
672
673void AudioTrack::releaseBuffer(Buffer* audioBuffer)
674{
675 audio_track_cblk_t* cblk = mCblk;
676 cblk->stepUser(audioBuffer->frameCount);
677}
678
679// -------------------------------------------------------------------------
680
681ssize_t AudioTrack::write(const void* buffer, size_t userSize)
682{
683
684 if (mSharedBuffer != 0) return INVALID_OPERATION;
685
686 if (ssize_t(userSize) < 0) {
687 // sanity-check. user is most-likely passing an error code.
688 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
689 buffer, userSize, userSize);
690 return BAD_VALUE;
691 }
692
693 LOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
694
695 ssize_t written = 0;
696 const int8_t *src = (const int8_t *)buffer;
697 Buffer audioBuffer;
698
699 do {
700 audioBuffer.frameCount = userSize/mChannelCount;
701 if (mFormat == AudioSystem::PCM_16_BIT) {
702 audioBuffer.frameCount >>= 1;
703 }
704 // Calling obtainBuffer() with a negative wait count causes
705 // an (almost) infinite wait time.
706 status_t err = obtainBuffer(&audioBuffer, -1);
707 if (err < 0) {
708 // out of buffers, return #bytes written
709 if (err == status_t(NO_MORE_BUFFERS))
710 break;
711 return ssize_t(err);
712 }
713
714 size_t toWrite;
715 if (mFormat == AudioSystem::PCM_8_BIT) {
716 // Divide capacity by 2 to take expansion into account
717 toWrite = audioBuffer.size>>1;
718 // 8 to 16 bit conversion
719 int count = toWrite;
720 int16_t *dst = (int16_t *)(audioBuffer.i8);
721 while(count--) {
722 *dst++ = (int16_t)(*src++^0x80) << 8;
723 }
724 }else {
725 toWrite = audioBuffer.size;
726 memcpy(audioBuffer.i8, src, toWrite);
727 src += toWrite;
728 }
729 userSize -= toWrite;
730 written += toWrite;
731
732 releaseBuffer(&audioBuffer);
733 } while (userSize);
734
735 return written;
736}
737
738// -------------------------------------------------------------------------
739
740bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
741{
742 Buffer audioBuffer;
743 uint32_t frames;
744 size_t writtenSize;
745
746 // Manage underrun callback
747 if (mActive && (mCblk->framesReady() == 0)) {
748 LOGV("Underrun user: %x, server: %x, flowControlFlag %d", mCblk->user, mCblk->server, mCblk->flowControlFlag);
749 if (mCblk->flowControlFlag == 0) {
750 mCbf(EVENT_UNDERRUN, mUserData, 0);
751 if (mCblk->server == mCblk->frameCount) {
752 mCbf(EVENT_BUFFER_END, mUserData, 0);
753 }
754 mCblk->flowControlFlag = 1;
755 if (mSharedBuffer != 0) return false;
756 }
757 }
758
759 // Manage loop end callback
760 while (mLoopCount > mCblk->loopCount) {
761 int loopCount = -1;
762 mLoopCount--;
763 if (mLoopCount >= 0) loopCount = mLoopCount;
764
765 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
766 }
767
768 // Manage marker callback
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700769 if (!mMarkerReached && (mMarkerPosition > 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 if (mCblk->server >= mMarkerPosition) {
771 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700772 mMarkerReached = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 }
774 }
775
776 // Manage new position callback
777 if(mUpdatePeriod > 0) {
778 while (mCblk->server >= mNewPosition) {
779 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
780 mNewPosition += mUpdatePeriod;
781 }
782 }
783
784 // If Shared buffer is used, no data is requested from client.
785 if (mSharedBuffer != 0) {
786 frames = 0;
787 } else {
788 frames = mRemainingFrames;
789 }
790
791 do {
792
793 audioBuffer.frameCount = frames;
794
795 // Calling obtainBuffer() with a wait count of 1
796 // limits wait time to WAIT_PERIOD_MS. This prevents from being
797 // stuck here not being able to handle timed events (position, markers, loops).
798 status_t err = obtainBuffer(&audioBuffer, 1);
799 if (err < NO_ERROR) {
800 if (err != TIMED_OUT) {
Eric Laurentef028272009-04-21 07:56:33 -0700801 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 -0800802 return false;
803 }
804 break;
805 }
806 if (err == status_t(STOPPED)) return false;
807
808 // Divide buffer size by 2 to take into account the expansion
809 // due to 8 to 16 bit conversion: the callback must fill only half
810 // of the destination buffer
811 if (mFormat == AudioSystem::PCM_8_BIT) {
812 audioBuffer.size >>= 1;
813 }
814
815 size_t reqSize = audioBuffer.size;
816 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
817 writtenSize = audioBuffer.size;
818
819 // Sanity check on returned size
The Android Open Source Project4df24232009-03-05 14:34:35 -0800820 if (ssize_t(writtenSize) <= 0) {
821 // The callback is done filling buffers
822 // Keep this thread going to handle timed events and
823 // still try to get more data in intervals of WAIT_PERIOD_MS
824 // but don't just loop and block the CPU, so wait
825 usleep(WAIT_PERIOD_MS*1000);
826 break;
827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 if (writtenSize > reqSize) writtenSize = reqSize;
829
830 if (mFormat == AudioSystem::PCM_8_BIT) {
831 // 8 to 16 bit conversion
832 const int8_t *src = audioBuffer.i8 + writtenSize-1;
833 int count = writtenSize;
834 int16_t *dst = audioBuffer.i16 + writtenSize-1;
835 while(count--) {
836 *dst-- = (int16_t)(*src--^0x80) << 8;
837 }
838 writtenSize <<= 1;
839 }
840
841 audioBuffer.size = writtenSize;
842 audioBuffer.frameCount = writtenSize/mChannelCount/sizeof(int16_t);
843 frames -= audioBuffer.frameCount;
844
845 releaseBuffer(&audioBuffer);
846 }
847 while (frames);
848
849 if (frames == 0) {
850 mRemainingFrames = mNotificationFrames;
851 } else {
852 mRemainingFrames = frames;
853 }
854 return true;
855}
856
857status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
858{
859
860 const size_t SIZE = 256;
861 char buffer[SIZE];
862 String8 result;
863
864 result.append(" AudioTrack::dump\n");
865 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]);
866 result.append(buffer);
867 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mFrameCount);
868 result.append(buffer);
869 snprintf(buffer, 255, " sample rate(%d), status(%d), muted(%d)\n", mSampleRate, mStatus, mMuted);
870 result.append(buffer);
871 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency);
872 result.append(buffer);
873 ::write(fd, result.string(), result.size());
874 return NO_ERROR;
875}
876
877// =========================================================================
878
879AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
880 : Thread(bCanCallJava), mReceiver(receiver)
881{
882}
883
884bool AudioTrack::AudioTrackThread::threadLoop()
885{
886 return mReceiver.processAudioBuffer(this);
887}
888
889status_t AudioTrack::AudioTrackThread::readyToRun()
890{
891 return NO_ERROR;
892}
893
894void AudioTrack::AudioTrackThread::onFirstRef()
895{
896}
897
898// =========================================================================
899
900audio_track_cblk_t::audio_track_cblk_t()
901 : user(0), server(0), userBase(0), serverBase(0), buffers(0), frameCount(0),
902 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0), flowControlFlag(1), forceReady(0)
903{
904}
905
906uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
907{
908 uint32_t u = this->user;
909
910 u += frameCount;
911 // Ensure that user is never ahead of server for AudioRecord
912 if (out) {
913 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
914 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
915 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
916 }
917 } else if (u > this->server) {
918 LOGW("stepServer occured after track reset");
919 u = this->server;
920 }
921
922 if (u >= userBase + this->frameCount) {
923 userBase += this->frameCount;
924 }
925
926 this->user = u;
927
928 // Clear flow control error condition as new data has been written/read to/from buffer.
929 flowControlFlag = 0;
930
931 return u;
932}
933
934bool audio_track_cblk_t::stepServer(uint32_t frameCount)
935{
936 // the code below simulates lock-with-timeout
937 // we MUST do this to protect the AudioFlinger server
938 // as this lock is shared with the client.
939 status_t err;
940
941 err = lock.tryLock();
942 if (err == -EBUSY) { // just wait a bit
943 usleep(1000);
944 err = lock.tryLock();
945 }
946 if (err != NO_ERROR) {
947 // probably, the client just died.
948 return false;
949 }
950
951 uint32_t s = this->server;
952
953 s += frameCount;
954 if (out) {
955 // Mark that we have read the first buffer so that next time stepUser() is called
956 // we switch to normal obtainBuffer() timeout period
957 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
958 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS - 1;
959 }
960 // It is possible that we receive a flush()
961 // while the mixer is processing a block: in this case,
962 // stepServer() is called After the flush() has reset u & s and
963 // we have s > u
964 if (s > this->user) {
965 LOGW("stepServer occured after track reset");
966 s = this->user;
967 }
968 }
969
970 if (s >= loopEnd) {
971 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
972 s = loopStart;
973 if (--loopCount == 0) {
974 loopEnd = UINT_MAX;
975 loopStart = UINT_MAX;
976 }
977 }
978 if (s >= serverBase + this->frameCount) {
979 serverBase += this->frameCount;
980 }
981
982 this->server = s;
983
984 cv.signal();
985 lock.unlock();
986 return true;
987}
988
989void* audio_track_cblk_t::buffer(uint32_t offset) const
990{
991 return (int16_t *)this->buffers + (offset-userBase)*this->channels;
992}
993
994uint32_t audio_track_cblk_t::framesAvailable()
995{
996 Mutex::Autolock _l(lock);
997 return framesAvailable_l();
998}
999
1000uint32_t audio_track_cblk_t::framesAvailable_l()
1001{
1002 uint32_t u = this->user;
1003 uint32_t s = this->server;
1004
1005 if (out) {
1006 uint32_t limit = (s < loopStart) ? s : loopStart;
1007 return limit + frameCount - u;
1008 } else {
1009 return frameCount + u - s;
1010 }
1011}
1012
1013uint32_t audio_track_cblk_t::framesReady()
1014{
1015 uint32_t u = this->user;
1016 uint32_t s = this->server;
1017
1018 if (out) {
1019 if (u < loopEnd) {
1020 return u - s;
1021 } else {
1022 Mutex::Autolock _l(lock);
1023 if (loopCount >= 0) {
1024 return (loopEnd - loopStart)*loopCount + u - s;
1025 } else {
1026 return UINT_MAX;
1027 }
1028 }
1029 } else {
1030 return s - u;
1031 }
1032}
1033
1034// -------------------------------------------------------------------------
1035
1036}; // namespace android
1037