blob: f5bdedaa1340c2ad17cbc48e9ade035ad8fa6e98 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/* //device/include/server/AudioFlinger/AudioFlinger.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_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
27#include <utils/IServiceManager.h>
28#include <utils/Log.h>
29#include <utils/Parcel.h>
30#include <utils/IPCThreadState.h>
31#include <utils/String16.h>
32#include <utils/threads.h>
33
34#include <cutils/properties.h>
35
36#include <media/AudioTrack.h>
37#include <media/AudioRecord.h>
38
39#include <private/media/AudioTrackShared.h>
40
41#include <hardware_legacy/AudioHardwareInterface.h>
42
43#include "AudioMixer.h"
44#include "AudioFlinger.h"
45
46#ifdef WITH_A2DP
47#include "A2dpAudioInterface.h"
48#endif
49
50// ----------------------------------------------------------------------------
51// the sim build doesn't have gettid
52
53#ifndef HAVE_GETTID
54# define gettid getpid
55#endif
56
57// ----------------------------------------------------------------------------
58
59namespace android {
60
The Android Open Source Project10592532009-03-18 17:39:46 -070061static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
62static const char* kHardwareLockedString = "Hardware lock is taken\n";
63
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
65static const unsigned long kBufferRecoveryInUsecs = 2000;
66static const unsigned long kMaxBufferRecoveryInUsecs = 20000;
67static const float MAX_GAIN = 4096.0f;
68
69// retry counts for buffer fill timeout
70// 50 * ~20msecs = 1 second
71static const int8_t kMaxTrackRetries = 50;
72static const int8_t kMaxTrackStartupRetries = 50;
73
74static const int kStartSleepTime = 30000;
75static const int kStopSleepTime = 30000;
76
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070077static const int kDumpLockRetries = 50;
78static const int kDumpLockSleep = 20000;
79
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080// Maximum number of pending buffers allocated by OutputTrack::write()
81static const uint8_t kMaxOutputTrackBuffers = 5;
82
83
84#define AUDIOFLINGER_SECURITY_ENABLED 1
85
86// ----------------------------------------------------------------------------
87
88static bool recordingAllowed() {
89#ifndef HAVE_ANDROID_OS
90 return true;
91#endif
92#if AUDIOFLINGER_SECURITY_ENABLED
93 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
94 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
95 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
96 return ok;
97#else
98 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
99 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
100 return true;
101#endif
102}
103
104static bool settingsAllowed() {
105#ifndef HAVE_ANDROID_OS
106 return true;
107#endif
108#if AUDIOFLINGER_SECURITY_ENABLED
109 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
110 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
111 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
112 return ok;
113#else
114 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
115 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
116 return true;
117#endif
118}
119
120// ----------------------------------------------------------------------------
121
122AudioFlinger::AudioFlinger()
123 : BnAudioFlinger(),
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700124 mAudioHardware(0), mA2dpAudioInterface(0), mA2dpEnabled(false), mNotifyA2dpChange(false),
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700125 mForcedSpeakerCount(0), mA2dpDisableCount(0), mA2dpSuppressed(false), mForcedRoute(0),
126 mRouteRestoreTime(0), mMusicMuteSaved(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127{
128 mHardwareStatus = AUDIO_HW_IDLE;
129 mAudioHardware = AudioHardwareInterface::create();
130 mHardwareStatus = AUDIO_HW_INIT;
131 if (mAudioHardware->initCheck() == NO_ERROR) {
132 // open 16-bit output stream for s/w mixer
133 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
134 status_t status;
135 AudioStreamOut *hwOutput = mAudioHardware->openOutputStream(AudioSystem::PCM_16_BIT, 0, 0, &status);
136 mHardwareStatus = AUDIO_HW_IDLE;
137 if (hwOutput) {
138 mHardwareMixerThread = new MixerThread(this, hwOutput, AudioSystem::AUDIO_OUTPUT_HARDWARE);
139 } else {
140 LOGE("Failed to initialize hardware output stream, status: %d", status);
141 }
142
143#ifdef WITH_A2DP
144 // Create A2DP interface
145 mA2dpAudioInterface = new A2dpAudioInterface();
146 AudioStreamOut *a2dpOutput = mA2dpAudioInterface->openOutputStream(AudioSystem::PCM_16_BIT, 0, 0, &status);
147 if (a2dpOutput) {
148 mA2dpMixerThread = new MixerThread(this, a2dpOutput, AudioSystem::AUDIO_OUTPUT_A2DP);
149 if (hwOutput) {
150 uint32_t frameCount = ((a2dpOutput->bufferSize()/a2dpOutput->frameSize()) * hwOutput->sampleRate()) / a2dpOutput->sampleRate();
151 MixerThread::OutputTrack *a2dpOutTrack = new MixerThread::OutputTrack(mA2dpMixerThread,
152 hwOutput->sampleRate(),
153 AudioSystem::PCM_16_BIT,
154 hwOutput->channelCount(),
155 frameCount);
156 mHardwareMixerThread->setOuputTrack(a2dpOutTrack);
157 }
158 } else {
159 LOGE("Failed to initialize A2DP output stream, status: %d", status);
160 }
161#endif
162
163 // FIXME - this should come from settings
164 setRouting(AudioSystem::MODE_NORMAL, AudioSystem::ROUTE_SPEAKER, AudioSystem::ROUTE_ALL);
165 setRouting(AudioSystem::MODE_RINGTONE, AudioSystem::ROUTE_SPEAKER, AudioSystem::ROUTE_ALL);
166 setRouting(AudioSystem::MODE_IN_CALL, AudioSystem::ROUTE_EARPIECE, AudioSystem::ROUTE_ALL);
167 setMode(AudioSystem::MODE_NORMAL);
168
169 setMasterVolume(1.0f);
170 setMasterMute(false);
171
172 // Start record thread
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700173 mAudioRecordThread = new AudioRecordThread(mAudioHardware, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 if (mAudioRecordThread != 0) {
175 mAudioRecordThread->run("AudioRecordThread", PRIORITY_URGENT_AUDIO);
176 }
177 } else {
178 LOGE("Couldn't even initialize the stubbed audio hardware!");
179 }
180}
181
182AudioFlinger::~AudioFlinger()
183{
184 if (mAudioRecordThread != 0) {
185 mAudioRecordThread->exit();
186 mAudioRecordThread.clear();
187 }
188 mHardwareMixerThread.clear();
189 delete mAudioHardware;
190 // deleting mA2dpAudioInterface also deletes mA2dpOutput;
191#ifdef WITH_A2DP
192 mA2dpMixerThread.clear();
193 delete mA2dpAudioInterface;
194#endif
195}
196
197
198#ifdef WITH_A2DP
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700199// setA2dpEnabled_l() must be called with AudioFlinger::mLock held
200void AudioFlinger::setA2dpEnabled_l(bool enable)
The Android Open Source Project10592532009-03-18 17:39:46 -0700201{
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700202 SortedVector < sp<MixerThread::Track> > tracks;
203 SortedVector < wp<MixerThread::Track> > activeTracks;
204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 LOGV_IF(enable, "set output to A2DP\n");
206 LOGV_IF(!enable, "set output to hardware audio\n");
207
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700208 // Transfer tracks playing on MUSIC stream from one mixer to the other
209 if (enable) {
210 mHardwareMixerThread->getTracks_l(tracks, activeTracks);
211 mA2dpMixerThread->putTracks_l(tracks, activeTracks);
212 } else {
213 mA2dpMixerThread->getTracks_l(tracks, activeTracks);
214 mHardwareMixerThread->putTracks_l(tracks, activeTracks);
215 }
216 mA2dpEnabled = enable;
217 mNotifyA2dpChange = true;
218 mWaitWorkCV.broadcast();
219}
220
221// checkA2dpEnabledChange_l() must be called with AudioFlinger::mLock held
222void AudioFlinger::checkA2dpEnabledChange_l()
223{
224 if (mNotifyA2dpChange) {
225 // Notify AudioSystem of the A2DP activation/deactivation
226 size_t size = mNotificationClients.size();
227 for (size_t i = 0; i < size; i++) {
228 sp<IBinder> binder = mNotificationClients.itemAt(i).promote();
229 if (binder != NULL) {
230 LOGV("Notifying output change to client %p", binder.get());
231 sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
232 client->a2dpEnabledChanged(mA2dpEnabled);
233 }
234 }
235 mNotifyA2dpChange = false;
236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237}
238#endif // WITH_A2DP
239
240bool AudioFlinger::streamForcedToSpeaker(int streamType)
241{
242 // NOTE that streams listed here must not be routed to A2DP by default:
243 // AudioSystem::routedToA2dpOutput(streamType) == false
244 return (streamType == AudioSystem::RING ||
245 streamType == AudioSystem::ALARM ||
Eric Laurenta7f1e5c2009-03-27 16:27:16 -0700246 streamType == AudioSystem::NOTIFICATION ||
247 streamType == AudioSystem::ENFORCED_AUDIBLE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248}
249
250status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
251{
252 const size_t SIZE = 256;
253 char buffer[SIZE];
254 String8 result;
255
256 result.append("Clients:\n");
257 for (size_t i = 0; i < mClients.size(); ++i) {
258 wp<Client> wClient = mClients.valueAt(i);
259 if (wClient != 0) {
260 sp<Client> client = wClient.promote();
261 if (client != 0) {
262 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
263 result.append(buffer);
264 }
265 }
266 }
267 write(fd, result.string(), result.size());
268 return NO_ERROR;
269}
270
271
272status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
273{
274 const size_t SIZE = 256;
275 char buffer[SIZE];
276 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700277 int hardwareStatus = mHardwareStatus;
278
279 if (hardwareStatus == AUDIO_HW_IDLE && mHardwareMixerThread->mStandby) {
280 hardwareStatus = AUDIO_HW_STANDBY;
281 }
282 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 result.append(buffer);
284 write(fd, result.string(), result.size());
285 return NO_ERROR;
286}
287
288status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
289{
290 const size_t SIZE = 256;
291 char buffer[SIZE];
292 String8 result;
293 snprintf(buffer, SIZE, "Permission Denial: "
294 "can't dump AudioFlinger from pid=%d, uid=%d\n",
295 IPCThreadState::self()->getCallingPid(),
296 IPCThreadState::self()->getCallingUid());
297 result.append(buffer);
298 write(fd, result.string(), result.size());
299 return NO_ERROR;
300}
301
The Android Open Source Project10592532009-03-18 17:39:46 -0700302static bool tryLock(Mutex& mutex)
303{
304 bool locked = false;
305 for (int i = 0; i < kDumpLockRetries; ++i) {
306 if (mutex.tryLock() == NO_ERROR) {
307 locked = true;
308 break;
309 }
310 usleep(kDumpLockSleep);
311 }
312 return locked;
313}
314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
316{
317 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
318 dumpPermissionDenial(fd, args);
319 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700320 // get state of hardware lock
321 bool hardwareLocked = tryLock(mHardwareLock);
322 if (!hardwareLocked) {
323 String8 result(kHardwareLockedString);
324 write(fd, result.string(), result.size());
325 } else {
326 mHardwareLock.unlock();
327 }
328
329 bool locked = tryLock(mLock);
330
331 // failed to lock - AudioFlinger is probably deadlocked
332 if (!locked) {
333 String8 result(kDeadlockedString);
334 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336
337 dumpClients(fd, args);
338 dumpInternals(fd, args);
339 mHardwareMixerThread->dump(fd, args);
340#ifdef WITH_A2DP
341 mA2dpMixerThread->dump(fd, args);
342#endif
343
344 // dump record client
345 if (mAudioRecordThread != 0) mAudioRecordThread->dump(fd, args);
346
347 if (mAudioHardware) {
348 mAudioHardware->dumpState(fd, args);
349 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700350 if (locked) mLock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 }
352 return NO_ERROR;
353}
354
355// IAudioFlinger interface
356
357
358sp<IAudioTrack> AudioFlinger::createTrack(
359 pid_t pid,
360 int streamType,
361 uint32_t sampleRate,
362 int format,
363 int channelCount,
364 int frameCount,
365 uint32_t flags,
366 const sp<IMemory>& sharedBuffer,
367 status_t *status)
368{
369 sp<MixerThread::Track> track;
370 sp<TrackHandle> trackHandle;
371 sp<Client> client;
372 wp<Client> wclient;
373 status_t lStatus;
374
375 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
376 LOGE("invalid stream type");
377 lStatus = BAD_VALUE;
378 goto Exit;
379 }
380
381 {
382 Mutex::Autolock _l(mLock);
383
384 wclient = mClients.valueFor(pid);
385
386 if (wclient != NULL) {
387 client = wclient.promote();
388 } else {
389 client = new Client(this, pid);
390 mClients.add(pid, client);
391 }
392#ifdef WITH_A2DP
393 if (isA2dpEnabled() && AudioSystem::routedToA2dpOutput(streamType)) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700394 track = mA2dpMixerThread->createTrack_l(client, streamType, sampleRate, format,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 channelCount, frameCount, sharedBuffer, &lStatus);
396 } else
397#endif
398 {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700399 track = mHardwareMixerThread->createTrack_l(client, streamType, sampleRate, format,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 channelCount, frameCount, sharedBuffer, &lStatus);
401 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700402 }
403 if (lStatus == NO_ERROR) {
404 trackHandle = new TrackHandle(track);
405 } else {
406 track.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 }
408
409Exit:
410 if(status) {
411 *status = lStatus;
412 }
413 return trackHandle;
414}
415
416uint32_t AudioFlinger::sampleRate(int output) const
417{
418#ifdef WITH_A2DP
419 if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
420 return mA2dpMixerThread->sampleRate();
421 }
422#endif
423 return mHardwareMixerThread->sampleRate();
424}
425
426int AudioFlinger::channelCount(int output) const
427{
428#ifdef WITH_A2DP
429 if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
430 return mA2dpMixerThread->channelCount();
431 }
432#endif
433 return mHardwareMixerThread->channelCount();
434}
435
436int AudioFlinger::format(int output) const
437{
438#ifdef WITH_A2DP
439 if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
440 return mA2dpMixerThread->format();
441 }
442#endif
443 return mHardwareMixerThread->format();
444}
445
446size_t AudioFlinger::frameCount(int output) const
447{
448#ifdef WITH_A2DP
449 if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
450 return mA2dpMixerThread->frameCount();
451 }
452#endif
453 return mHardwareMixerThread->frameCount();
454}
455
456uint32_t AudioFlinger::latency(int output) const
457{
458#ifdef WITH_A2DP
459 if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
460 return mA2dpMixerThread->latency();
461 }
462#endif
463 return mHardwareMixerThread->latency();
464}
465
466status_t AudioFlinger::setMasterVolume(float value)
467{
468 // check calling permissions
469 if (!settingsAllowed()) {
470 return PERMISSION_DENIED;
471 }
472
473 // when hw supports master volume, don't scale in sw mixer
474 AutoMutex lock(mHardwareLock);
475 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
476 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
477 value = 1.0f;
478 }
479 mHardwareStatus = AUDIO_HW_IDLE;
480 mHardwareMixerThread->setMasterVolume(value);
481#ifdef WITH_A2DP
482 mA2dpMixerThread->setMasterVolume(value);
483#endif
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 return NO_ERROR;
486}
487
488status_t AudioFlinger::setRouting(int mode, uint32_t routes, uint32_t mask)
489{
490 status_t err = NO_ERROR;
491
492 // check calling permissions
493 if (!settingsAllowed()) {
494 return PERMISSION_DENIED;
495 }
496 if ((mode < AudioSystem::MODE_CURRENT) || (mode >= AudioSystem::NUM_MODES)) {
497 LOGW("Illegal value: setRouting(%d, %u, %u)", mode, routes, mask);
498 return BAD_VALUE;
499 }
500
501#ifdef WITH_A2DP
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400502 LOGV("setRouting %d %d %d, tid %d, calling tid %d\n", mode, routes, mask, gettid(),
503 IPCThreadState::self()->getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 if (mode == AudioSystem::MODE_NORMAL &&
505 (mask & AudioSystem::ROUTE_BLUETOOTH_A2DP)) {
506 AutoMutex lock(&mLock);
507
508 bool enableA2dp = false;
509 if (routes & AudioSystem::ROUTE_BLUETOOTH_A2DP) {
510 enableA2dp = true;
511 }
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700512 if (mA2dpDisableCount > 0) {
513 mA2dpSuppressed = enableA2dp;
514 } else {
515 setA2dpEnabled_l(enableA2dp);
516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 LOGV("setOutput done\n");
518 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700519 // setRouting() is always called at least for mode == AudioSystem::MODE_IN_CALL when
520 // SCO is enabled, whatever current mode is so we can safely handle A2DP disabling only
521 // in this case to avoid doing it several times.
522 if (mode == AudioSystem::MODE_IN_CALL &&
523 (mask & AudioSystem::ROUTE_BLUETOOTH_SCO)) {
524 AutoMutex lock(&mLock);
525 handleRouteDisablesA2dp_l(routes);
526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527#endif
528
529 // do nothing if only A2DP routing is affected
530 mask &= ~AudioSystem::ROUTE_BLUETOOTH_A2DP;
531 if (mask) {
532 AutoMutex lock(mHardwareLock);
533 mHardwareStatus = AUDIO_HW_GET_ROUTING;
534 uint32_t r;
535 err = mAudioHardware->getRouting(mode, &r);
536 if (err == NO_ERROR) {
537 r = (r & ~mask) | (routes & mask);
538 if (mode == AudioSystem::MODE_NORMAL ||
539 (mode == AudioSystem::MODE_CURRENT && getMode() == AudioSystem::MODE_NORMAL)) {
540 mSavedRoute = r;
541 r |= mForcedRoute;
542 LOGV("setRouting mSavedRoute %08x mForcedRoute %08x\n", mSavedRoute, mForcedRoute);
543 }
544 mHardwareStatus = AUDIO_HW_SET_ROUTING;
545 err = mAudioHardware->setRouting(mode, r);
546 }
547 mHardwareStatus = AUDIO_HW_IDLE;
548 }
549 return err;
550}
551
552uint32_t AudioFlinger::getRouting(int mode) const
553{
554 uint32_t routes = 0;
555 if ((mode >= AudioSystem::MODE_CURRENT) && (mode < AudioSystem::NUM_MODES)) {
556 if (mode == AudioSystem::MODE_NORMAL ||
557 (mode == AudioSystem::MODE_CURRENT && getMode() == AudioSystem::MODE_NORMAL)) {
558 routes = mSavedRoute;
559 } else {
560 mHardwareStatus = AUDIO_HW_GET_ROUTING;
561 mAudioHardware->getRouting(mode, &routes);
562 mHardwareStatus = AUDIO_HW_IDLE;
563 }
564 } else {
565 LOGW("Illegal value: getRouting(%d)", mode);
566 }
567 return routes;
568}
569
570status_t AudioFlinger::setMode(int mode)
571{
572 // check calling permissions
573 if (!settingsAllowed()) {
574 return PERMISSION_DENIED;
575 }
576 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
577 LOGW("Illegal value: setMode(%d)", mode);
578 return BAD_VALUE;
579 }
580
581 AutoMutex lock(mHardwareLock);
582 mHardwareStatus = AUDIO_HW_SET_MODE;
583 status_t ret = mAudioHardware->setMode(mode);
584 mHardwareStatus = AUDIO_HW_IDLE;
585 return ret;
586}
587
588int AudioFlinger::getMode() const
589{
590 int mode = AudioSystem::MODE_INVALID;
591 mHardwareStatus = AUDIO_HW_SET_MODE;
592 mAudioHardware->getMode(&mode);
593 mHardwareStatus = AUDIO_HW_IDLE;
594 return mode;
595}
596
597status_t AudioFlinger::setMicMute(bool state)
598{
599 // check calling permissions
600 if (!settingsAllowed()) {
601 return PERMISSION_DENIED;
602 }
603
604 AutoMutex lock(mHardwareLock);
605 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
606 status_t ret = mAudioHardware->setMicMute(state);
607 mHardwareStatus = AUDIO_HW_IDLE;
608 return ret;
609}
610
611bool AudioFlinger::getMicMute() const
612{
613 bool state = AudioSystem::MODE_INVALID;
614 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
615 mAudioHardware->getMicMute(&state);
616 mHardwareStatus = AUDIO_HW_IDLE;
617 return state;
618}
619
620status_t AudioFlinger::setMasterMute(bool muted)
621{
622 // check calling permissions
623 if (!settingsAllowed()) {
624 return PERMISSION_DENIED;
625 }
626 mHardwareMixerThread->setMasterMute(muted);
627#ifdef WITH_A2DP
628 mA2dpMixerThread->setMasterMute(muted);
629#endif
630 return NO_ERROR;
631}
632
633float AudioFlinger::masterVolume() const
634{
635 return mHardwareMixerThread->masterVolume();
636}
637
638bool AudioFlinger::masterMute() const
639{
640 return mHardwareMixerThread->masterMute();
641}
642
643status_t AudioFlinger::setStreamVolume(int stream, float value)
644{
645 // check calling permissions
646 if (!settingsAllowed()) {
647 return PERMISSION_DENIED;
648 }
649
Eric Laurenta7f1e5c2009-03-27 16:27:16 -0700650 if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
651 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 return BAD_VALUE;
653 }
654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 status_t ret = NO_ERROR;
656 if (stream == AudioSystem::VOICE_CALL ||
657 stream == AudioSystem::BLUETOOTH_SCO) {
Eric Laurentef028272009-04-21 07:56:33 -0700658 float hwValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 if (stream == AudioSystem::VOICE_CALL) {
Eric Laurentef028272009-04-21 07:56:33 -0700660 hwValue = (float)AudioSystem::logToLinear(value)/100.0f;
661 // offset value to reflect actual hardware volume that never reaches 0
662 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
663 value = 0.01 + 0.99 * value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 } else { // (type == AudioSystem::BLUETOOTH_SCO)
Eric Laurentef028272009-04-21 07:56:33 -0700665 hwValue = 1.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
667
668 AutoMutex lock(mHardwareLock);
669 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurentef028272009-04-21 07:56:33 -0700670 ret = mAudioHardware->setVoiceVolume(hwValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 mHardwareStatus = AUDIO_HW_IDLE;
672 }
673
Eric Laurentef028272009-04-21 07:56:33 -0700674 mHardwareMixerThread->setStreamVolume(stream, value);
675#ifdef WITH_A2DP
676 mA2dpMixerThread->setStreamVolume(stream, value);
677#endif
678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 return ret;
680}
681
682status_t AudioFlinger::setStreamMute(int stream, bool muted)
683{
684 // check calling permissions
685 if (!settingsAllowed()) {
686 return PERMISSION_DENIED;
687 }
688
Eric Laurenta7f1e5c2009-03-27 16:27:16 -0700689 if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
690 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 return BAD_VALUE;
692 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694#ifdef WITH_A2DP
695 mA2dpMixerThread->setStreamMute(stream, muted);
696#endif
697 if (stream == AudioSystem::MUSIC)
698 {
699 AutoMutex lock(&mHardwareLock);
700 if (mForcedRoute != 0)
701 mMusicMuteSaved = muted;
702 else
703 mHardwareMixerThread->setStreamMute(stream, muted);
704 } else {
705 mHardwareMixerThread->setStreamMute(stream, muted);
706 }
707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 return NO_ERROR;
709}
710
711float AudioFlinger::streamVolume(int stream) const
712{
713 if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
714 return 0.0f;
715 }
Eric Laurentef028272009-04-21 07:56:33 -0700716
717 float volume = mHardwareMixerThread->streamVolume(stream);
718 // remove correction applied by setStreamVolume()
719 if (stream == AudioSystem::VOICE_CALL) {
720 volume = (volume - 0.01) / 0.99 ;
721 }
722
723 return volume;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724}
725
726bool AudioFlinger::streamMute(int stream) const
727{
728 if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
729 return true;
730 }
731
732 if (stream == AudioSystem::MUSIC && mForcedRoute != 0)
733 {
734 return mMusicMuteSaved;
735 }
736 return mHardwareMixerThread->streamMute(stream);
737}
738
739bool AudioFlinger::isMusicActive() const
740{
Eric Laurent4e646332009-07-09 03:20:57 -0700741 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 #ifdef WITH_A2DP
743 if (isA2dpEnabled()) {
Eric Laurent4e646332009-07-09 03:20:57 -0700744 return mA2dpMixerThread->isMusicActive_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 }
746 #endif
Eric Laurent4e646332009-07-09 03:20:57 -0700747 return mHardwareMixerThread->isMusicActive_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748}
749
750status_t AudioFlinger::setParameter(const char* key, const char* value)
751{
752 status_t result, result2;
753 AutoMutex lock(mHardwareLock);
754 mHardwareStatus = AUDIO_SET_PARAMETER;
755
756 LOGV("setParameter() key %s, value %s, tid %d, calling tid %d", key, value, gettid(), IPCThreadState::self()->getCallingPid());
757 result = mAudioHardware->setParameter(key, value);
758 if (mA2dpAudioInterface) {
759 result2 = mA2dpAudioInterface->setParameter(key, value);
760 if (result2)
761 result = result2;
762 }
763 mHardwareStatus = AUDIO_HW_IDLE;
764 return result;
765}
766
767size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
768{
769 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
770}
771
772void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
773{
774
775 LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
776 Mutex::Autolock _l(mLock);
777
778 sp<IBinder> binder = client->asBinder();
779 if (mNotificationClients.indexOf(binder) < 0) {
780 LOGV("Adding notification client %p", binder.get());
781 binder->linkToDeath(this);
782 mNotificationClients.add(binder);
783 client->a2dpEnabledChanged(isA2dpEnabled());
784 }
785}
786
787void AudioFlinger::binderDied(const wp<IBinder>& who) {
788
789 LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
790 Mutex::Autolock _l(mLock);
791
792 IBinder *binder = who.unsafe_get();
793
794 if (binder != NULL) {
795 int index = mNotificationClients.indexOf(binder);
796 if (index >= 0) {
797 LOGV("Removing notification client %p", binder);
798 mNotificationClients.removeAt(index);
799 }
800 }
801}
802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803void AudioFlinger::removeClient(pid_t pid)
804{
805 LOGV("removeClient() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
806 Mutex::Autolock _l(mLock);
807 mClients.removeItem(pid);
808}
809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810bool AudioFlinger::isA2dpEnabled() const
811{
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700812 return mA2dpEnabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813}
814
815void AudioFlinger::handleForcedSpeakerRoute(int command)
816{
817 switch(command) {
818 case ACTIVE_TRACK_ADDED:
819 {
820 AutoMutex lock(mHardwareLock);
821 if (mForcedSpeakerCount++ == 0) {
Eric Laurent551603f2009-05-29 02:03:21 -0700822 if (mForcedRoute == 0) {
823 mMusicMuteSaved = mHardwareMixerThread->streamMute(AudioSystem::MUSIC);
824 LOGV("++mForcedSpeakerCount == 0, mMusicMuteSaved = %d, mRouteRestoreTime = %d", mMusicMuteSaved, mRouteRestoreTime);
825 if (!(mSavedRoute & AudioSystem::ROUTE_SPEAKER)) {
826 LOGV("Route forced to Speaker ON %08x", mSavedRoute | AudioSystem::ROUTE_SPEAKER);
827 mHardwareMixerThread->setStreamMute(AudioSystem::MUSIC, true);
828 usleep(mHardwareMixerThread->latency()*1000);
829 mHardwareStatus = AUDIO_HW_SET_ROUTING;
830 mAudioHardware->setRouting(AudioSystem::MODE_NORMAL, mSavedRoute | AudioSystem::ROUTE_SPEAKER);
831 mHardwareStatus = AUDIO_HW_IDLE;
832 // delay track start so that audio hardware has time to siwtch routes
833 usleep(kStartSleepTime);
834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 }
836 mForcedRoute = AudioSystem::ROUTE_SPEAKER;
Eric Laurent551603f2009-05-29 02:03:21 -0700837 mRouteRestoreTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 }
839 LOGV("mForcedSpeakerCount incremented to %d", mForcedSpeakerCount);
840 }
841 break;
842 case ACTIVE_TRACK_REMOVED:
843 {
844 AutoMutex lock(mHardwareLock);
845 if (mForcedSpeakerCount > 0){
846 if (--mForcedSpeakerCount == 0) {
847 mRouteRestoreTime = systemTime() + milliseconds(kStopSleepTime/1000);
848 }
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700849 LOGV("mForcedSpeakerCount decremented to %d", mForcedSpeakerCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 } else {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700851 LOGE("mForcedSpeakerCount is already zero");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 }
854 break;
855 case CHECK_ROUTE_RESTORE_TIME:
856 case FORCE_ROUTE_RESTORE:
857 if (mRouteRestoreTime) {
858 AutoMutex lock(mHardwareLock);
859 if (mRouteRestoreTime &&
860 (systemTime() > mRouteRestoreTime || command == FORCE_ROUTE_RESTORE)) {
861 mHardwareMixerThread->setStreamMute(AudioSystem::MUSIC, mMusicMuteSaved);
862 mForcedRoute = 0;
863 if (!(mSavedRoute & AudioSystem::ROUTE_SPEAKER)) {
864 mHardwareStatus = AUDIO_HW_SET_ROUTING;
865 mAudioHardware->setRouting(AudioSystem::MODE_NORMAL, mSavedRoute);
866 mHardwareStatus = AUDIO_HW_IDLE;
867 LOGV("Route forced to Speaker OFF %08x", mSavedRoute);
868 }
869 mRouteRestoreTime = 0;
870 }
871 }
872 break;
873 }
874}
875
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700876#ifdef WITH_A2DP
The Android Open Source Project10592532009-03-18 17:39:46 -0700877// handleRouteDisablesA2dp_l() must be called with AudioFlinger::mLock held
878void AudioFlinger::handleRouteDisablesA2dp_l(int routes)
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700879{
The Android Open Source Project10592532009-03-18 17:39:46 -0700880 if (routes & AudioSystem::ROUTE_BLUETOOTH_SCO) {
881 if (mA2dpDisableCount++ == 0) {
882 if (mA2dpEnabled) {
883 setA2dpEnabled_l(false);
884 mA2dpSuppressed = true;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700885 }
886 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700887 LOGV("mA2dpDisableCount incremented to %d", mA2dpDisableCount);
888 } else {
889 if (mA2dpDisableCount > 0) {
890 if (--mA2dpDisableCount == 0) {
891 if (mA2dpSuppressed) {
892 setA2dpEnabled_l(true);
893 mA2dpSuppressed = false;
894 }
895 }
896 LOGV("mA2dpDisableCount decremented to %d", mA2dpDisableCount);
897 } else {
Joe Onorato9a5e3e12009-07-01 21:04:03 -0400898 LOGV("mA2dpDisableCount is already zero");
The Android Open Source Project10592532009-03-18 17:39:46 -0700899 }
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700900 }
901}
902#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903
904// ----------------------------------------------------------------------------
905
906AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int outputType)
907 : Thread(false),
908 mAudioFlinger(audioFlinger), mAudioMixer(0), mOutput(output), mOutputType(outputType),
909 mSampleRate(0), mFrameCount(0), mChannelCount(0), mFormat(0), mMixBuffer(0),
910 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mStandby(false),
911 mInWrite(false)
912{
913 mSampleRate = output->sampleRate();
914 mChannelCount = output->channelCount();
915
916 // FIXME - Current mixer implementation only supports stereo output
917 if (mChannelCount == 1) {
918 LOGE("Invalid audio hardware channel count");
919 }
920
921 mFormat = output->format();
922 mFrameCount = output->bufferSize() / output->channelCount() / sizeof(int16_t);
923 mAudioMixer = new AudioMixer(mFrameCount, output->sampleRate());
924
925 // FIXME - Current mixer implementation only supports stereo output: Always
926 // Allocate a stereo buffer even if HW output is mono.
927 mMixBuffer = new int16_t[mFrameCount * 2];
928 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
929}
930
931AudioFlinger::MixerThread::~MixerThread()
932{
933 delete [] mMixBuffer;
934 delete mAudioMixer;
935}
936
937status_t AudioFlinger::MixerThread::dump(int fd, const Vector<String16>& args)
938{
939 dumpInternals(fd, args);
940 dumpTracks(fd, args);
941 return NO_ERROR;
942}
943
944status_t AudioFlinger::MixerThread::dumpTracks(int fd, const Vector<String16>& args)
945{
946 const size_t SIZE = 256;
947 char buffer[SIZE];
948 String8 result;
949
950 snprintf(buffer, SIZE, "Output %d mixer thread tracks\n", mOutputType);
951 result.append(buffer);
952 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
953 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentb88148e2009-03-31 14:33:34 -0700954 sp<Track> track = mTracks[i];
955 if (track != 0) {
956 track->dump(buffer, SIZE);
957 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 }
959 }
960
961 snprintf(buffer, SIZE, "Output %d mixer thread active tracks\n", mOutputType);
962 result.append(buffer);
963 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
964 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentb88148e2009-03-31 14:33:34 -0700965 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 if (wTrack != 0) {
967 sp<Track> track = wTrack.promote();
968 if (track != 0) {
969 track->dump(buffer, SIZE);
970 result.append(buffer);
971 }
972 }
973 }
974 write(fd, result.string(), result.size());
975 return NO_ERROR;
976}
977
978status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
979{
980 const size_t SIZE = 256;
981 char buffer[SIZE];
982 String8 result;
983
984 snprintf(buffer, SIZE, "Output %d mixer thread internals\n", mOutputType);
985 result.append(buffer);
986 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
987 result.append(buffer);
988 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
989 result.append(buffer);
990 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
991 result.append(buffer);
992 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
993 result.append(buffer);
994 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
995 result.append(buffer);
996 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
997 result.append(buffer);
998 write(fd, result.string(), result.size());
999 return NO_ERROR;
1000}
1001
1002// Thread virtuals
1003bool AudioFlinger::MixerThread::threadLoop()
1004{
1005 unsigned long sleepTime = kBufferRecoveryInUsecs;
1006 int16_t* curBuf = mMixBuffer;
1007 Vector< sp<Track> > tracksToRemove;
1008 size_t enabledTracks = 0;
1009 nsecs_t standbyTime = systemTime();
1010 size_t mixBufferSize = mFrameCount*mChannelCount*sizeof(int16_t);
1011 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
1012
1013#ifdef WITH_A2DP
1014 bool outputTrackActive = false;
1015#endif
1016
1017 do {
1018 enabledTracks = 0;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001019 { // scope for the AudioFlinger::mLock
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001021 Mutex::Autolock _l(mAudioFlinger->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022
1023#ifdef WITH_A2DP
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 if (mOutputTrack != NULL && !mAudioFlinger->isA2dpEnabled()) {
1025 if (outputTrackActive) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001026 mAudioFlinger->mLock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 mOutputTrack->stop();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001028 mAudioFlinger->mLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 outputTrackActive = false;
1030 }
1031 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001032 mAudioFlinger->checkA2dpEnabledChange_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033#endif
1034
1035 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1036
1037 // put audio hardware into standby after short delay
1038 if UNLIKELY(!activeTracks.size() && systemTime() > standbyTime) {
1039 // wait until we have something to do...
1040 LOGV("Audio hardware entering standby, output %d\n", mOutputType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 if (!mStandby) {
1042 mOutput->standby();
1043 mStandby = true;
1044 }
1045
1046#ifdef WITH_A2DP
1047 if (outputTrackActive) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001048 mAudioFlinger->mLock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 mOutputTrack->stop();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001050 mAudioFlinger->mLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 outputTrackActive = false;
1052 }
1053#endif
1054 if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) {
1055 mAudioFlinger->handleForcedSpeakerRoute(FORCE_ROUTE_RESTORE);
1056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 // we're about to wait, flush the binder command buffer
1058 IPCThreadState::self()->flushCommands();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001059 mAudioFlinger->mWaitWorkCV.wait(mAudioFlinger->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 LOGV("Audio hardware exiting standby, output %d\n", mOutputType);
1061
1062 if (mMasterMute == false) {
1063 char value[PROPERTY_VALUE_MAX];
1064 property_get("ro.audio.silent", value, "0");
1065 if (atoi(value)) {
1066 LOGD("Silence is golden");
1067 setMasterMute(true);
1068 }
1069 }
1070
1071 standbyTime = systemTime() + kStandbyTimeInNsecs;
1072 continue;
1073 }
1074
1075 // Forced route to speaker is handled by hardware mixer thread
1076 if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) {
1077 mAudioFlinger->handleForcedSpeakerRoute(CHECK_ROUTE_RESTORE_TIME);
1078 }
1079
1080 // find out which tracks need to be processed
1081 size_t count = activeTracks.size();
1082 for (size_t i=0 ; i<count ; i++) {
1083 sp<Track> t = activeTracks[i].promote();
1084 if (t == 0) continue;
1085
1086 Track* const track = t.get();
1087 audio_track_cblk_t* cblk = track->cblk();
1088
1089 // The first time a track is added we wait
1090 // for all its buffers to be filled before processing it
1091 mAudioMixer->setActiveTrack(track->name());
1092 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1093 !track->isPaused())
1094 {
1095 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1096
1097 // compute volume for this track
1098 int16_t left, right;
1099 if (track->isMuted() || mMasterMute || track->isPausing()) {
1100 left = right = 0;
1101 if (track->isPausing()) {
1102 LOGV("paused(%d)", track->name());
1103 track->setPaused();
1104 }
1105 } else {
1106 float typeVolume = mStreamTypes[track->type()].volume;
1107 float v = mMasterVolume * typeVolume;
1108 float v_clamped = v * cblk->volume[0];
1109 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1110 left = int16_t(v_clamped);
1111 v_clamped = v * cblk->volume[1];
1112 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1113 right = int16_t(v_clamped);
1114 }
1115
1116 // XXX: these things DON'T need to be done each time
1117 mAudioMixer->setBufferProvider(track);
1118 mAudioMixer->enable(AudioMixer::MIXING);
1119
1120 int param;
1121 if ( track->mFillingUpStatus == Track::FS_FILLED) {
1122 // no ramp for the first volume setting
1123 track->mFillingUpStatus = Track::FS_ACTIVE;
1124 if (track->mState == TrackBase::RESUMING) {
1125 track->mState = TrackBase::ACTIVE;
1126 param = AudioMixer::RAMP_VOLUME;
1127 } else {
1128 param = AudioMixer::VOLUME;
1129 }
1130 } else {
1131 param = AudioMixer::RAMP_VOLUME;
1132 }
1133 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1134 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1135 mAudioMixer->setParameter(
1136 AudioMixer::TRACK,
1137 AudioMixer::FORMAT, track->format());
1138 mAudioMixer->setParameter(
1139 AudioMixer::TRACK,
1140 AudioMixer::CHANNEL_COUNT, track->channelCount());
1141 mAudioMixer->setParameter(
1142 AudioMixer::RESAMPLE,
1143 AudioMixer::SAMPLE_RATE,
1144 int(cblk->sampleRate));
1145
1146 // reset retry count
1147 track->mRetryCount = kMaxTrackRetries;
1148 enabledTracks++;
1149 } else {
1150 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1151 if (track->isStopped()) {
1152 track->reset();
1153 }
1154 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1155 // We have consumed all the buffers of this track.
1156 // Remove it from the list of active tracks.
1157 LOGV("remove(%d) from active list", track->name());
1158 tracksToRemove.add(track);
1159 } else {
1160 // No buffers for this track. Give it a few chances to
1161 // fill a buffer, then remove it from active list.
1162 if (--(track->mRetryCount) <= 0) {
1163 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1164 tracksToRemove.add(track);
1165 }
1166 }
1167 // LOGV("disable(%d)", track->name());
1168 mAudioMixer->disable(AudioMixer::MIXING);
1169 }
1170 }
1171
1172 // remove all the tracks that need to be...
1173 count = tracksToRemove.size();
1174 if (UNLIKELY(count)) {
1175 for (size_t i=0 ; i<count ; i++) {
1176 const sp<Track>& track = tracksToRemove[i];
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001177 removeActiveTrack_l(track);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 if (track->isTerminated()) {
1179 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001180 deleteTrackName_l(track->mName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 }
1182 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
1185
1186 if (LIKELY(enabledTracks)) {
1187 // mix buffers...
1188 mAudioMixer->process(curBuf);
1189
1190#ifdef WITH_A2DP
1191 if (mOutputTrack != NULL && mAudioFlinger->isA2dpEnabled()) {
1192 if (!outputTrackActive) {
1193 LOGV("starting output track in mixer for output %d", mOutputType);
1194 mOutputTrack->start();
1195 outputTrackActive = true;
1196 }
1197 mOutputTrack->write(curBuf, mFrameCount);
1198 }
1199#endif
1200
1201 // output audio to hardware
1202 mLastWriteTime = systemTime();
1203 mInWrite = true;
1204 mOutput->write(curBuf, mixBufferSize);
1205 mNumWrites++;
1206 mInWrite = false;
1207 mStandby = false;
1208 nsecs_t temp = systemTime();
1209 standbyTime = temp + kStandbyTimeInNsecs;
1210 nsecs_t delta = temp - mLastWriteTime;
1211 if (delta > maxPeriod) {
1212 LOGW("write blocked for %llu msecs", ns2ms(delta));
1213 mNumDelayedWrites++;
1214 }
1215 sleepTime = kBufferRecoveryInUsecs;
1216 } else {
1217#ifdef WITH_A2DP
1218 if (mOutputTrack != NULL && mAudioFlinger->isA2dpEnabled()) {
1219 if (outputTrackActive) {
1220 mOutputTrack->write(curBuf, 0);
1221 if (mOutputTrack->bufferQueueEmpty()) {
1222 mOutputTrack->stop();
1223 outputTrackActive = false;
1224 } else {
1225 standbyTime = systemTime() + kStandbyTimeInNsecs;
1226 }
1227 }
1228 }
1229#endif
1230 // There was nothing to mix this round, which means all
1231 // active tracks were late. Sleep a little bit to give
1232 // them another chance. If we're too late, the audio
1233 // hardware will zero-fill for us.
1234 //LOGV("no buffers - usleep(%lu)", sleepTime);
1235 usleep(sleepTime);
1236 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1237 sleepTime += kBufferRecoveryInUsecs;
1238 }
1239 }
1240
1241 // finally let go of all our tracks, without the lock held
1242 // since we can't guarantee the destructors won't acquire that
1243 // same lock.
1244 tracksToRemove.clear();
1245 } while (true);
1246
1247 return false;
1248}
1249
1250status_t AudioFlinger::MixerThread::readyToRun()
1251{
1252 if (mSampleRate == 0) {
1253 LOGE("No working audio driver found.");
1254 return NO_INIT;
1255 }
1256 LOGI("AudioFlinger's thread ready to run for output %d", mOutputType);
1257 return NO_ERROR;
1258}
1259
1260void AudioFlinger::MixerThread::onFirstRef()
1261{
1262 const size_t SIZE = 256;
1263 char buffer[SIZE];
1264
1265 snprintf(buffer, SIZE, "Mixer Thread for output %d", mOutputType);
1266
1267 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1268}
1269
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001270// MixerThread::createTrack_l() must be called with AudioFlinger::mLock held
1271sp<AudioFlinger::MixerThread::Track> AudioFlinger::MixerThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 const sp<AudioFlinger::Client>& client,
1273 int streamType,
1274 uint32_t sampleRate,
1275 int format,
1276 int channelCount,
1277 int frameCount,
1278 const sp<IMemory>& sharedBuffer,
1279 status_t *status)
1280{
1281 sp<Track> track;
1282 status_t lStatus;
1283
1284 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
Eric Laurent88e209d2009-07-07 07:10:45 -07001285 if (sampleRate > mSampleRate*2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1287 lStatus = BAD_VALUE;
1288 goto Exit;
1289 }
1290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001292 if (mSampleRate == 0) {
1293 LOGE("Audio driver not initialized.");
1294 lStatus = NO_INIT;
1295 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 }
1297
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001298 track = new Track(this, client, streamType, sampleRate, format,
1299 channelCount, frameCount, sharedBuffer);
1300 if (track->getCblk() == NULL) {
1301 lStatus = NO_MEMORY;
1302 goto Exit;
1303 }
1304 mTracks.add(track);
1305 lStatus = NO_ERROR;
1306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307Exit:
1308 if(status) {
1309 *status = lStatus;
1310 }
1311 return track;
1312}
1313
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001314// getTracks_l() must be called with AudioFlinger::mLock held
1315void AudioFlinger::MixerThread::getTracks_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 SortedVector < sp<Track> >& tracks,
1317 SortedVector < wp<Track> >& activeTracks)
1318{
1319 size_t size = mTracks.size();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001320 LOGV ("MixerThread::getTracks_l() for output %d, mTracks.size %d, mActiveTracks.size %d", mOutputType, mTracks.size(), mActiveTracks.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 for (size_t i = 0; i < size; i++) {
1322 sp<Track> t = mTracks[i];
1323 if (AudioSystem::routedToA2dpOutput(t->mStreamType)) {
1324 tracks.add(t);
1325 int j = mActiveTracks.indexOf(t);
1326 if (j >= 0) {
1327 t = mActiveTracks[j].promote();
1328 if (t != NULL) {
1329 activeTracks.add(t);
1330 }
1331 }
1332 }
1333 }
1334
1335 size = activeTracks.size();
1336 for (size_t i = 0; i < size; i++) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001337 removeActiveTrack_l(activeTracks[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 }
1339
1340 size = tracks.size();
1341 for (size_t i = 0; i < size; i++) {
1342 sp<Track> t = tracks[i];
1343 mTracks.remove(t);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001344 deleteTrackName_l(t->name());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 }
1346}
1347
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001348// putTracks_l() must be called with AudioFlinger::mLock held
1349void AudioFlinger::MixerThread::putTracks_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 SortedVector < sp<Track> >& tracks,
1351 SortedVector < wp<Track> >& activeTracks)
1352{
1353
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001354 LOGV ("MixerThread::putTracks_l() for output %d, tracks.size %d, activeTracks.size %d", mOutputType, tracks.size(), activeTracks.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355
1356 size_t size = tracks.size();
1357 for (size_t i = 0; i < size ; i++) {
1358 sp<Track> t = tracks[i];
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001359 int name = getTrackName_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360
1361 if (name < 0) return;
1362
1363 t->mName = name;
1364 t->mMixerThread = this;
1365 mTracks.add(t);
1366
1367 int j = activeTracks.indexOf(t);
1368 if (j >= 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001369 addActiveTrack_l(t);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 }
1371 }
1372}
1373
1374uint32_t AudioFlinger::MixerThread::sampleRate() const
1375{
1376 return mSampleRate;
1377}
1378
1379int AudioFlinger::MixerThread::channelCount() const
1380{
1381 return mChannelCount;
1382}
1383
1384int AudioFlinger::MixerThread::format() const
1385{
1386 return mFormat;
1387}
1388
1389size_t AudioFlinger::MixerThread::frameCount() const
1390{
1391 return mFrameCount;
1392}
1393
1394uint32_t AudioFlinger::MixerThread::latency() const
1395{
1396 if (mOutput) {
1397 return mOutput->latency();
1398 }
1399 else {
1400 return 0;
1401 }
1402}
1403
1404status_t AudioFlinger::MixerThread::setMasterVolume(float value)
1405{
1406 mMasterVolume = value;
1407 return NO_ERROR;
1408}
1409
1410status_t AudioFlinger::MixerThread::setMasterMute(bool muted)
1411{
1412 mMasterMute = muted;
1413 return NO_ERROR;
1414}
1415
1416float AudioFlinger::MixerThread::masterVolume() const
1417{
1418 return mMasterVolume;
1419}
1420
1421bool AudioFlinger::MixerThread::masterMute() const
1422{
1423 return mMasterMute;
1424}
1425
1426status_t AudioFlinger::MixerThread::setStreamVolume(int stream, float value)
1427{
1428 mStreamTypes[stream].volume = value;
1429 return NO_ERROR;
1430}
1431
1432status_t AudioFlinger::MixerThread::setStreamMute(int stream, bool muted)
1433{
1434 mStreamTypes[stream].mute = muted;
1435 return NO_ERROR;
1436}
1437
1438float AudioFlinger::MixerThread::streamVolume(int stream) const
1439{
1440 return mStreamTypes[stream].volume;
1441}
1442
1443bool AudioFlinger::MixerThread::streamMute(int stream) const
1444{
1445 return mStreamTypes[stream].mute;
1446}
1447
Eric Laurent4e646332009-07-09 03:20:57 -07001448// isMusicActive_l() must be called with AudioFlinger::mLock held
1449bool AudioFlinger::MixerThread::isMusicActive_l() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450{
1451 size_t count = mActiveTracks.size();
1452 for (size_t i = 0 ; i < count ; ++i) {
1453 sp<Track> t = mActiveTracks[i].promote();
1454 if (t == 0) continue;
1455 Track* const track = t.get();
1456 if (t->mStreamType == AudioSystem::MUSIC)
1457 return true;
1458 }
1459 return false;
1460}
1461
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001462// addTrack_l() must be called with AudioFlinger::mLock held
1463status_t AudioFlinger::MixerThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464{
1465 status_t status = ALREADY_EXISTS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466
1467 // here the track could be either new, or restarted
1468 // in both cases "unstop" the track
1469 if (track->isPaused()) {
1470 track->mState = TrackBase::RESUMING;
1471 LOGV("PAUSED => RESUMING (%d)", track->name());
1472 } else {
1473 track->mState = TrackBase::ACTIVE;
1474 LOGV("? => ACTIVE (%d)", track->name());
1475 }
1476 // set retry count for buffer fill
1477 track->mRetryCount = kMaxTrackStartupRetries;
1478 if (mActiveTracks.indexOf(track) < 0) {
1479 // the track is newly added, make sure it fills up all its
1480 // buffers before playing. This is to ensure the client will
1481 // effectively get the latency it requested.
1482 track->mFillingUpStatus = Track::FS_FILLING;
1483 track->mResetDone = false;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001484 addActiveTrack_l(track);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 status = NO_ERROR;
1486 }
1487
1488 LOGV("mWaitWorkCV.broadcast");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001489 mAudioFlinger->mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490
1491 return status;
1492}
1493
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001494// destroyTrack_l() must be called with AudioFlinger::mLock held
1495void AudioFlinger::MixerThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 track->mState = TrackBase::TERMINATED;
1498 if (mActiveTracks.indexOf(track) < 0) {
1499 LOGV("remove track (%d) and delete from mixer", track->name());
1500 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001501 deleteTrackName_l(track->name());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
1503}
1504
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001505// addActiveTrack_l() must be called with AudioFlinger::mLock held
1506void AudioFlinger::MixerThread::addActiveTrack_l(const wp<Track>& t)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507{
1508 mActiveTracks.add(t);
1509
1510 // Force routing to speaker for certain stream types
1511 // The forced routing to speaker is managed by hardware mixer
1512 if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) {
1513 sp<Track> track = t.promote();
1514 if (track == NULL) return;
1515
1516 if (streamForcedToSpeaker(track->type())) {
1517 mAudioFlinger->handleForcedSpeakerRoute(ACTIVE_TRACK_ADDED);
1518 }
1519 }
1520}
1521
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001522// removeActiveTrack_l() must be called with AudioFlinger::mLock held
1523void AudioFlinger::MixerThread::removeActiveTrack_l(const wp<Track>& t)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524{
1525 mActiveTracks.remove(t);
1526
1527 // Force routing to speaker for certain stream types
1528 // The forced routing to speaker is managed by hardware mixer
1529 if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) {
1530 sp<Track> track = t.promote();
1531 if (track == NULL) return;
1532
1533 if (streamForcedToSpeaker(track->type())) {
1534 mAudioFlinger->handleForcedSpeakerRoute(ACTIVE_TRACK_REMOVED);
1535 }
1536 }
1537}
1538
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001539// getTrackName_l() must be called with AudioFlinger::mLock held
1540int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541{
1542 return mAudioMixer->getTrackName();
1543}
1544
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001545// deleteTrackName_l() must be called with AudioFlinger::mLock held
1546void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547{
1548 mAudioMixer->deleteTrackName(name);
1549}
1550
1551size_t AudioFlinger::MixerThread::getOutputFrameCount()
1552{
1553 return mOutput->bufferSize() / mOutput->channelCount() / sizeof(int16_t);
1554}
1555
1556// ----------------------------------------------------------------------------
1557
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001558// TrackBase constructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559AudioFlinger::MixerThread::TrackBase::TrackBase(
1560 const sp<MixerThread>& mixerThread,
1561 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 uint32_t sampleRate,
1563 int format,
1564 int channelCount,
1565 int frameCount,
1566 uint32_t flags,
1567 const sp<IMemory>& sharedBuffer)
1568 : RefBase(),
1569 mMixerThread(mixerThread),
1570 mClient(client),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 mFrameCount(0),
1572 mState(IDLE),
1573 mClientTid(-1),
1574 mFormat(format),
1575 mFlags(flags & ~SYSTEM_FLAGS_MASK)
1576{
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001577 mName = mixerThread->getTrackName_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 LOGV("TrackBase contructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
1579 if (mName < 0) {
1580 LOGE("no more track names availlable");
1581 return;
1582 }
1583
1584 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
1585
1586 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
1587 size_t size = sizeof(audio_track_cblk_t);
1588 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
1589 if (sharedBuffer == 0) {
1590 size += bufferSize;
1591 }
1592
1593 if (client != NULL) {
1594 mCblkMemory = client->heap()->allocate(size);
1595 if (mCblkMemory != 0) {
1596 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
1597 if (mCblk) { // construct the shared structure in-place.
1598 new(mCblk) audio_track_cblk_t();
1599 // clear all buffers
1600 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07001601 mCblk->sampleRate = sampleRate;
1602 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 if (sharedBuffer == 0) {
1604 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
1605 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
1606 // Force underrun condition to avoid false underrun callback until first data is
1607 // written to buffer
1608 mCblk->flowControlFlag = 1;
1609 } else {
1610 mBuffer = sharedBuffer->pointer();
1611 }
1612 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
1613 }
1614 } else {
1615 LOGE("not enough memory for AudioTrack size=%u", size);
1616 client->heap()->dump("AudioTrack");
1617 return;
1618 }
1619 } else {
1620 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
1621 if (mCblk) { // construct the shared structure in-place.
1622 new(mCblk) audio_track_cblk_t();
1623 // clear all buffers
1624 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07001625 mCblk->sampleRate = sampleRate;
1626 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
1628 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
1629 // Force underrun condition to avoid false underrun callback until first data is
1630 // written to buffer
1631 mCblk->flowControlFlag = 1;
1632 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
1633 }
1634 }
1635}
1636
1637AudioFlinger::MixerThread::TrackBase::~TrackBase()
1638{
1639 if (mCblk) {
1640 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
1641 }
1642 mCblkMemory.clear(); // and free the shared memory
1643 mClient.clear();
1644}
1645
1646void AudioFlinger::MixerThread::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1647{
1648 buffer->raw = 0;
1649 mFrameCount = buffer->frameCount;
1650 step();
1651 buffer->frameCount = 0;
1652}
1653
1654bool AudioFlinger::MixerThread::TrackBase::step() {
1655 bool result;
1656 audio_track_cblk_t* cblk = this->cblk();
1657
1658 result = cblk->stepServer(mFrameCount);
1659 if (!result) {
1660 LOGV("stepServer failed acquiring cblk mutex");
1661 mFlags |= STEPSERVER_FAILED;
1662 }
1663 return result;
1664}
1665
1666void AudioFlinger::MixerThread::TrackBase::reset() {
1667 audio_track_cblk_t* cblk = this->cblk();
1668
1669 cblk->user = 0;
1670 cblk->server = 0;
1671 cblk->userBase = 0;
1672 cblk->serverBase = 0;
1673 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
1674 LOGV("TrackBase::reset");
1675}
1676
1677sp<IMemory> AudioFlinger::MixerThread::TrackBase::getCblk() const
1678{
1679 return mCblkMemory;
1680}
1681
1682int AudioFlinger::MixerThread::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07001683 return (int)mCblk->sampleRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684}
1685
1686int AudioFlinger::MixerThread::TrackBase::channelCount() const {
Eric Laurent88e209d2009-07-07 07:10:45 -07001687 return (int)mCblk->channels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688}
1689
1690void* AudioFlinger::MixerThread::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
1691 audio_track_cblk_t* cblk = this->cblk();
1692 int16_t *bufferStart = (int16_t *)mBuffer + (offset-cblk->serverBase)*cblk->channels;
1693 int16_t *bufferEnd = bufferStart + frames * cblk->channels;
1694
1695 // Check validity of returned pointer in case the track control block would have been corrupted.
The Android Open Source Project10592532009-03-18 17:39:46 -07001696 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Eric Laurentef028272009-04-21 07:56:33 -07001697 (cblk->channels == 2 && ((unsigned long)bufferStart & 3))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001698 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
1699 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project10592532009-03-18 17:39:46 -07001701 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 return 0;
1703 }
1704
1705 return bufferStart;
1706}
1707
1708// ----------------------------------------------------------------------------
1709
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001710// Track constructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711AudioFlinger::MixerThread::Track::Track(
1712 const sp<MixerThread>& mixerThread,
1713 const sp<Client>& client,
1714 int streamType,
1715 uint32_t sampleRate,
1716 int format,
1717 int channelCount,
1718 int frameCount,
1719 const sp<IMemory>& sharedBuffer)
Eric Laurent4bc035a2009-05-22 09:18:15 -07001720 : TrackBase(mixerThread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721{
1722 mVolume[0] = 1.0f;
1723 mVolume[1] = 1.0f;
1724 mMute = false;
1725 mSharedBuffer = sharedBuffer;
Eric Laurent4bc035a2009-05-22 09:18:15 -07001726 mStreamType = streamType;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727}
1728
1729AudioFlinger::MixerThread::Track::~Track()
1730{
1731 wp<Track> weak(this); // never create a strong ref from the dtor
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001732 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 mState = TERMINATED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734}
1735
1736void AudioFlinger::MixerThread::Track::destroy()
1737{
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001738 // NOTE: destroyTrack_l() can remove a strong reference to this Track
1739 // by removing it from mTracks vector, so there is a risk that this Tracks's
1740 // desctructor is called. As the destructor needs to lock AudioFlinger::mLock,
1741 // we must acquire a strong reference on this Track before locking AudioFlinger::mLock
1742 // here so that the destructor is called only when exiting this function.
1743 // On the other hand, as long as Track::destroy() is only called by
1744 // TrackHandle destructor, the TrackHandle still holds a strong ref on
1745 // this Track with its member mTrack.
1746 sp<Track> keep(this);
1747 { // scope for AudioFlinger::mLock
1748 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
1749 mMixerThread->destroyTrack_l(this);
1750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751}
1752
1753void AudioFlinger::MixerThread::Track::dump(char* buffer, size_t size)
1754{
1755 snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
1756 mName - AudioMixer::TRACK0,
1757 (mClient == NULL) ? getpid() : mClient->pid(),
1758 mStreamType,
1759 mFormat,
1760 mCblk->channels,
1761 mFrameCount,
1762 mState,
1763 mMute,
1764 mFillingUpStatus,
1765 mCblk->sampleRate,
1766 mCblk->volume[0],
1767 mCblk->volume[1],
1768 mCblk->server,
1769 mCblk->user);
1770}
1771
1772status_t AudioFlinger::MixerThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
1773{
1774 audio_track_cblk_t* cblk = this->cblk();
1775 uint32_t framesReady;
1776 uint32_t framesReq = buffer->frameCount;
1777
1778 // Check if last stepServer failed, try to step now
1779 if (mFlags & TrackBase::STEPSERVER_FAILED) {
1780 if (!step()) goto getNextBuffer_exit;
1781 LOGV("stepServer recovered");
1782 mFlags &= ~TrackBase::STEPSERVER_FAILED;
1783 }
1784
1785 framesReady = cblk->framesReady();
1786
1787 if (LIKELY(framesReady)) {
1788 uint32_t s = cblk->server;
1789 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
1790
1791 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
1792 if (framesReq > framesReady) {
1793 framesReq = framesReady;
1794 }
1795 if (s + framesReq > bufferEnd) {
1796 framesReq = bufferEnd - s;
1797 }
1798
1799 buffer->raw = getBuffer(s, framesReq);
1800 if (buffer->raw == 0) goto getNextBuffer_exit;
1801
1802 buffer->frameCount = framesReq;
1803 return NO_ERROR;
1804 }
1805
1806getNextBuffer_exit:
1807 buffer->raw = 0;
1808 buffer->frameCount = 0;
1809 return NOT_ENOUGH_DATA;
1810}
1811
1812bool AudioFlinger::MixerThread::Track::isReady() const {
1813 if (mFillingUpStatus != FS_FILLING) return true;
1814
1815 if (mCblk->framesReady() >= mCblk->frameCount ||
1816 mCblk->forceReady) {
1817 mFillingUpStatus = FS_FILLED;
1818 mCblk->forceReady = 0;
1819 LOGV("Track::isReady() track %d for output %d", mName, mMixerThread->mOutputType);
1820 return true;
1821 }
1822 return false;
1823}
1824
1825status_t AudioFlinger::MixerThread::Track::start()
1826{
1827 LOGV("start(%d), calling thread %d for output %d", mName, IPCThreadState::self()->getCallingPid(), mMixerThread->mOutputType);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001828 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
1829 mMixerThread->addTrack_l(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 return NO_ERROR;
1831}
1832
1833void AudioFlinger::MixerThread::Track::stop()
1834{
1835 LOGV("stop(%d), calling thread %d for output %d", mName, IPCThreadState::self()->getCallingPid(), mMixerThread->mOutputType);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001836 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 if (mState > STOPPED) {
1838 mState = STOPPED;
1839 // If the track is not active (PAUSED and buffers full), flush buffers
1840 if (mMixerThread->mActiveTracks.indexOf(this) < 0) {
1841 reset();
1842 }
1843 LOGV("(> STOPPED) => STOPPED (%d)", mName);
1844 }
1845}
1846
1847void AudioFlinger::MixerThread::Track::pause()
1848{
1849 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001850 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 if (mState == ACTIVE || mState == RESUMING) {
1852 mState = PAUSING;
1853 LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
1854 }
1855}
1856
1857void AudioFlinger::MixerThread::Track::flush()
1858{
1859 LOGV("flush(%d)", mName);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001860 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
1862 return;
1863 }
1864 // No point remaining in PAUSED state after a flush => go to
1865 // STOPPED state
1866 mState = STOPPED;
1867
The Android Open Source Project10592532009-03-18 17:39:46 -07001868 mCblk->lock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 // NOTE: reset() will reset cblk->user and cblk->server with
1870 // the risk that at the same time, the AudioMixer is trying to read
1871 // data. In this case, getNextBuffer() would return a NULL pointer
1872 // as audio buffer => the AudioMixer code MUST always test that pointer
1873 // returned by getNextBuffer() is not NULL!
1874 reset();
The Android Open Source Project10592532009-03-18 17:39:46 -07001875 mCblk->lock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876}
1877
1878void AudioFlinger::MixerThread::Track::reset()
1879{
1880 // Do not reset twice to avoid discarding data written just after a flush and before
1881 // the audioflinger thread detects the track is stopped.
1882 if (!mResetDone) {
1883 TrackBase::reset();
1884 // Force underrun condition to avoid false underrun callback until first data is
1885 // written to buffer
1886 mCblk->flowControlFlag = 1;
1887 mCblk->forceReady = 0;
1888 mFillingUpStatus = FS_FILLING;
1889 mResetDone = true;
1890 }
1891}
1892
1893void AudioFlinger::MixerThread::Track::mute(bool muted)
1894{
1895 mMute = muted;
1896}
1897
1898void AudioFlinger::MixerThread::Track::setVolume(float left, float right)
1899{
1900 mVolume[0] = left;
1901 mVolume[1] = right;
1902}
1903
1904// ----------------------------------------------------------------------------
1905
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001906// RecordTrack constructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907AudioFlinger::MixerThread::RecordTrack::RecordTrack(
1908 const sp<MixerThread>& mixerThread,
1909 const sp<Client>& client,
Eric Laurent4bc035a2009-05-22 09:18:15 -07001910 int inputSource,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 uint32_t sampleRate,
1912 int format,
1913 int channelCount,
1914 int frameCount,
1915 uint32_t flags)
Eric Laurent4bc035a2009-05-22 09:18:15 -07001916 : TrackBase(mixerThread, client, sampleRate, format,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 channelCount, frameCount, flags, 0),
Eric Laurent4bc035a2009-05-22 09:18:15 -07001918 mOverflow(false), mInputSource(inputSource)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919{
1920}
1921
1922AudioFlinger::MixerThread::RecordTrack::~RecordTrack()
1923{
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001924 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
1925 mMixerThread->deleteTrackName_l(mName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926}
1927
1928status_t AudioFlinger::MixerThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
1929{
1930 audio_track_cblk_t* cblk = this->cblk();
1931 uint32_t framesAvail;
1932 uint32_t framesReq = buffer->frameCount;
1933
1934 // Check if last stepServer failed, try to step now
1935 if (mFlags & TrackBase::STEPSERVER_FAILED) {
1936 if (!step()) goto getNextBuffer_exit;
1937 LOGV("stepServer recovered");
1938 mFlags &= ~TrackBase::STEPSERVER_FAILED;
1939 }
1940
1941 framesAvail = cblk->framesAvailable_l();
1942
1943 if (LIKELY(framesAvail)) {
1944 uint32_t s = cblk->server;
1945 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
1946
1947 if (framesReq > framesAvail) {
1948 framesReq = framesAvail;
1949 }
1950 if (s + framesReq > bufferEnd) {
1951 framesReq = bufferEnd - s;
1952 }
1953
1954 buffer->raw = getBuffer(s, framesReq);
1955 if (buffer->raw == 0) goto getNextBuffer_exit;
1956
1957 buffer->frameCount = framesReq;
1958 return NO_ERROR;
1959 }
1960
1961getNextBuffer_exit:
1962 buffer->raw = 0;
1963 buffer->frameCount = 0;
1964 return NOT_ENOUGH_DATA;
1965}
1966
1967status_t AudioFlinger::MixerThread::RecordTrack::start()
1968{
1969 return mMixerThread->mAudioFlinger->startRecord(this);
1970}
1971
1972void AudioFlinger::MixerThread::RecordTrack::stop()
1973{
1974 mMixerThread->mAudioFlinger->stopRecord(this);
1975 TrackBase::reset();
1976 // Force overerrun condition to avoid false overrun callback until first data is
1977 // read from buffer
1978 mCblk->flowControlFlag = 1;
1979}
1980
1981
1982// ----------------------------------------------------------------------------
1983
1984AudioFlinger::MixerThread::OutputTrack::OutputTrack(
1985 const sp<MixerThread>& mixerThread,
1986 uint32_t sampleRate,
1987 int format,
1988 int channelCount,
1989 int frameCount)
1990 : Track(mixerThread, NULL, AudioSystem::SYSTEM, sampleRate, format, channelCount, frameCount, NULL),
1991 mOutputMixerThread(mixerThread)
1992{
1993
1994 mCblk->out = 1;
1995 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
1996 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
1997 mOutBuffer.frameCount = 0;
1998 mCblk->bufferTimeoutMs = 10;
1999
2000 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p",
2001 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd);
2002
2003}
2004
2005AudioFlinger::MixerThread::OutputTrack::~OutputTrack()
2006{
2007 stop();
2008}
2009
2010status_t AudioFlinger::MixerThread::OutputTrack::start()
2011{
2012 status_t status = Track::start();
2013
2014 mRetryCount = 127;
2015 return status;
2016}
2017
2018void AudioFlinger::MixerThread::OutputTrack::stop()
2019{
2020 Track::stop();
2021 clearBufferQueue();
2022 mOutBuffer.frameCount = 0;
2023}
2024
2025void AudioFlinger::MixerThread::OutputTrack::write(int16_t* data, uint32_t frames)
2026{
2027 Buffer *pInBuffer;
2028 Buffer inBuffer;
2029 uint32_t channels = mCblk->channels;
2030
2031 inBuffer.frameCount = frames;
2032 inBuffer.i16 = data;
2033
2034 if (mCblk->user == 0) {
Eric Laurent4e646332009-07-09 03:20:57 -07002035 mOutputMixerThread->mAudioFlinger->mLock.lock();
2036 bool isMusicActive = mOutputMixerThread->isMusicActive_l();
2037 mOutputMixerThread->mAudioFlinger->mLock.unlock();
2038 if (isMusicActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 mCblk->forceReady = 1;
2040 LOGV("OutputTrack::start() force ready");
2041 } else if (mCblk->frameCount > frames){
2042 if (mBufferQueue.size() < kMaxOutputTrackBuffers) {
2043 uint32_t startFrames = (mCblk->frameCount - frames);
2044 LOGV("OutputTrack::start() write %d frames", startFrames);
2045 pInBuffer = new Buffer;
2046 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2047 pInBuffer->frameCount = startFrames;
2048 pInBuffer->i16 = pInBuffer->mBuffer;
2049 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2050 mBufferQueue.add(pInBuffer);
2051 } else {
2052 LOGW ("OutputTrack::write() no more buffers");
2053 }
2054 }
2055 }
2056
2057 while (1) {
2058 // First write pending buffers, then new data
2059 if (mBufferQueue.size()) {
2060 pInBuffer = mBufferQueue.itemAt(0);
2061 } else {
2062 pInBuffer = &inBuffer;
2063 }
2064
2065 if (pInBuffer->frameCount == 0) {
2066 break;
2067 }
2068
2069 if (mOutBuffer.frameCount == 0) {
2070 mOutBuffer.frameCount = pInBuffer->frameCount;
2071 if (obtainBuffer(&mOutBuffer) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
2072 break;
2073 }
2074 }
2075
2076 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2077 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2078 mCblk->stepUser(outFrames);
2079 pInBuffer->frameCount -= outFrames;
2080 pInBuffer->i16 += outFrames * channels;
2081 mOutBuffer.frameCount -= outFrames;
2082 mOutBuffer.i16 += outFrames * channels;
2083
2084 if (pInBuffer->frameCount == 0) {
2085 if (mBufferQueue.size()) {
2086 mBufferQueue.removeAt(0);
2087 delete [] pInBuffer->mBuffer;
2088 delete pInBuffer;
2089 } else {
2090 break;
2091 }
2092 }
2093 }
2094
2095 // If we could not write all frames, allocate a buffer and queue it for next time.
2096 if (inBuffer.frameCount) {
2097 if (mBufferQueue.size() < kMaxOutputTrackBuffers) {
2098 pInBuffer = new Buffer;
2099 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2100 pInBuffer->frameCount = inBuffer.frameCount;
2101 pInBuffer->i16 = pInBuffer->mBuffer;
2102 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2103 mBufferQueue.add(pInBuffer);
2104 } else {
2105 LOGW("OutputTrack::write() no more buffers");
2106 }
2107 }
2108
2109 // Calling write() with a 0 length buffer, means that no more data will be written:
2110 // If no more buffers are pending, fill output track buffer to make sure it is started
2111 // by output mixer.
2112 if (frames == 0 && mBufferQueue.size() == 0 && mCblk->user < mCblk->frameCount) {
2113 frames = mCblk->frameCount - mCblk->user;
2114 pInBuffer = new Buffer;
2115 pInBuffer->mBuffer = new int16_t[frames * channels];
2116 pInBuffer->frameCount = frames;
2117 pInBuffer->i16 = pInBuffer->mBuffer;
2118 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2119 mBufferQueue.add(pInBuffer);
2120 }
2121
2122}
2123
2124status_t AudioFlinger::MixerThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer)
2125{
2126 int active;
2127 int timeout = 0;
2128 status_t result;
2129 audio_track_cblk_t* cblk = mCblk;
2130 uint32_t framesReq = buffer->frameCount;
2131
2132 LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
2133 buffer->frameCount = 0;
2134
2135 uint32_t framesAvail = cblk->framesAvailable();
2136
2137 if (framesAvail == 0) {
2138 return AudioTrack::NO_MORE_BUFFERS;
2139 }
2140
2141 if (framesReq > framesAvail) {
2142 framesReq = framesAvail;
2143 }
2144
2145 uint32_t u = cblk->user;
2146 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2147
2148 if (u + framesReq > bufferEnd) {
2149 framesReq = bufferEnd - u;
2150 }
2151
2152 buffer->frameCount = framesReq;
2153 buffer->raw = (void *)cblk->buffer(u);
2154 return NO_ERROR;
2155}
2156
2157
2158void AudioFlinger::MixerThread::OutputTrack::clearBufferQueue()
2159{
2160 size_t size = mBufferQueue.size();
2161 Buffer *pBuffer;
2162
2163 for (size_t i = 0; i < size; i++) {
2164 pBuffer = mBufferQueue.itemAt(i);
2165 delete [] pBuffer->mBuffer;
2166 delete pBuffer;
2167 }
2168 mBufferQueue.clear();
2169}
2170
2171// ----------------------------------------------------------------------------
2172
2173AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2174 : RefBase(),
2175 mAudioFlinger(audioFlinger),
2176 mMemoryDealer(new MemoryDealer(1024*1024)),
2177 mPid(pid)
2178{
2179 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2180}
2181
2182AudioFlinger::Client::~Client()
2183{
2184 mAudioFlinger->removeClient(mPid);
2185}
2186
2187const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2188{
2189 return mMemoryDealer;
2190}
2191
2192// ----------------------------------------------------------------------------
2193
2194AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::MixerThread::Track>& track)
2195 : BnAudioTrack(),
2196 mTrack(track)
2197{
2198}
2199
2200AudioFlinger::TrackHandle::~TrackHandle() {
2201 // just stop the track on deletion, associated resources
2202 // will be freed from the main thread once all pending buffers have
2203 // been played. Unless it's not in the active track list, in which
2204 // case we free everything now...
2205 mTrack->destroy();
2206}
2207
2208status_t AudioFlinger::TrackHandle::start() {
2209 return mTrack->start();
2210}
2211
2212void AudioFlinger::TrackHandle::stop() {
2213 mTrack->stop();
2214}
2215
2216void AudioFlinger::TrackHandle::flush() {
2217 mTrack->flush();
2218}
2219
2220void AudioFlinger::TrackHandle::mute(bool e) {
2221 mTrack->mute(e);
2222}
2223
2224void AudioFlinger::TrackHandle::pause() {
2225 mTrack->pause();
2226}
2227
2228void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2229 mTrack->setVolume(left, right);
2230}
2231
2232sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2233 return mTrack->getCblk();
2234}
2235
2236status_t AudioFlinger::TrackHandle::onTransact(
2237 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2238{
2239 return BnAudioTrack::onTransact(code, data, reply, flags);
2240}
2241
2242// ----------------------------------------------------------------------------
2243
2244sp<IAudioRecord> AudioFlinger::openRecord(
2245 pid_t pid,
Eric Laurent4bc035a2009-05-22 09:18:15 -07002246 int inputSource,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 uint32_t sampleRate,
2248 int format,
2249 int channelCount,
2250 int frameCount,
2251 uint32_t flags,
2252 status_t *status)
2253{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 sp<MixerThread::RecordTrack> recordTrack;
2255 sp<RecordHandle> recordHandle;
2256 sp<Client> client;
2257 wp<Client> wclient;
2258 AudioStreamIn* input = 0;
2259 int inFrameCount;
2260 size_t inputBufferSize;
2261 status_t lStatus;
2262
2263 // check calling permissions
2264 if (!recordingAllowed()) {
2265 lStatus = PERMISSION_DENIED;
2266 goto Exit;
2267 }
2268
Eric Laurent4bc035a2009-05-22 09:18:15 -07002269 if (uint32_t(inputSource) >= AudioRecord::NUM_INPUT_SOURCES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 LOGE("invalid stream type");
2271 lStatus = BAD_VALUE;
2272 goto Exit;
2273 }
2274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 if (mAudioRecordThread == 0) {
2276 LOGE("Audio record thread not started");
2277 lStatus = NO_INIT;
2278 goto Exit;
2279 }
2280
2281
2282 // Check that audio input stream accepts requested audio parameters
2283 inputBufferSize = mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
2284 if (inputBufferSize == 0) {
2285 lStatus = BAD_VALUE;
2286 LOGE("Bad audio input parameters: sampling rate %u, format %d, channels %d", sampleRate, format, channelCount);
2287 goto Exit;
2288 }
2289
2290 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002291 { // scope for mLock
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 Mutex::Autolock _l(mLock);
2293 wclient = mClients.valueFor(pid);
2294 if (wclient != NULL) {
2295 client = wclient.promote();
2296 } else {
2297 client = new Client(this, pid);
2298 mClients.add(pid, client);
2299 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002300
2301 // frameCount must be a multiple of input buffer size
2302 inFrameCount = inputBufferSize/channelCount/sizeof(short);
2303 frameCount = ((frameCount - 1)/inFrameCount + 1) * inFrameCount;
2304
2305 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent4bc035a2009-05-22 09:18:15 -07002306 recordTrack = new MixerThread::RecordTrack(mHardwareMixerThread, client, inputSource, sampleRate,
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002307 format, channelCount, frameCount, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 if (recordTrack->getCblk() == NULL) {
2310 recordTrack.clear();
2311 lStatus = NO_MEMORY;
2312 goto Exit;
2313 }
2314
2315 // return to handle to client
2316 recordHandle = new RecordHandle(recordTrack);
2317 lStatus = NO_ERROR;
2318
2319Exit:
2320 if (status) {
2321 *status = lStatus;
2322 }
2323 return recordHandle;
2324}
2325
2326status_t AudioFlinger::startRecord(MixerThread::RecordTrack* recordTrack) {
2327 if (mAudioRecordThread != 0) {
2328 return mAudioRecordThread->start(recordTrack);
2329 }
2330 return NO_INIT;
2331}
2332
2333void AudioFlinger::stopRecord(MixerThread::RecordTrack* recordTrack) {
2334 if (mAudioRecordThread != 0) {
2335 mAudioRecordThread->stop(recordTrack);
2336 }
2337}
2338
2339// ----------------------------------------------------------------------------
2340
2341AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::MixerThread::RecordTrack>& recordTrack)
2342 : BnAudioRecord(),
2343 mRecordTrack(recordTrack)
2344{
2345}
2346
2347AudioFlinger::RecordHandle::~RecordHandle() {
2348 stop();
2349}
2350
2351status_t AudioFlinger::RecordHandle::start() {
2352 LOGV("RecordHandle::start()");
2353 return mRecordTrack->start();
2354}
2355
2356void AudioFlinger::RecordHandle::stop() {
2357 LOGV("RecordHandle::stop()");
2358 mRecordTrack->stop();
2359}
2360
2361sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
2362 return mRecordTrack->getCblk();
2363}
2364
2365status_t AudioFlinger::RecordHandle::onTransact(
2366 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2367{
2368 return BnAudioRecord::onTransact(code, data, reply, flags);
2369}
2370
2371// ----------------------------------------------------------------------------
2372
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002373AudioFlinger::AudioRecordThread::AudioRecordThread(AudioHardwareInterface* audioHardware,
2374 const sp<AudioFlinger>& audioFlinger) :
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 mAudioHardware(audioHardware),
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002376 mAudioFlinger(audioFlinger),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 mActive(false)
2378{
2379}
2380
2381AudioFlinger::AudioRecordThread::~AudioRecordThread()
2382{
2383}
2384
2385bool AudioFlinger::AudioRecordThread::threadLoop()
2386{
2387 LOGV("AudioRecordThread: start record loop");
2388 AudioBufferProvider::Buffer buffer;
2389 int inBufferSize = 0;
2390 int inFrameCount = 0;
2391 AudioStreamIn* input = 0;
2392
2393 mActive = 0;
2394
2395 // start recording
2396 while (!exitPending()) {
2397 if (!mActive) {
2398 mLock.lock();
2399 if (!mActive && !exitPending()) {
2400 LOGV("AudioRecordThread: loop stopping");
2401 if (input) {
2402 delete input;
2403 input = 0;
2404 }
2405 mRecordTrack.clear();
2406 mStopped.signal();
2407
2408 mWaitWorkCV.wait(mLock);
2409
2410 LOGV("AudioRecordThread: loop starting");
2411 if (mRecordTrack != 0) {
Dave Sparks356d8a32009-05-19 16:41:29 -07002412 input = mAudioHardware->openInputStream(
Eric Laurent4bc035a2009-05-22 09:18:15 -07002413 mRecordTrack->inputSource(),
Dave Sparks356d8a32009-05-19 16:41:29 -07002414 mRecordTrack->format(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 mRecordTrack->channelCount(),
2416 mRecordTrack->sampleRate(),
2417 &mStartStatus,
2418 (AudioSystem::audio_in_acoustics)(mRecordTrack->mFlags >> 16));
2419 if (input != 0) {
2420 inBufferSize = input->bufferSize();
2421 inFrameCount = inBufferSize/input->frameSize();
2422 }
2423 } else {
2424 mStartStatus = NO_INIT;
2425 }
2426 if (mStartStatus !=NO_ERROR) {
2427 LOGW("record start failed, status %d", mStartStatus);
2428 mActive = false;
2429 mRecordTrack.clear();
2430 }
2431 mWaitWorkCV.signal();
2432 }
2433 mLock.unlock();
2434 } else if (mRecordTrack != 0) {
2435
2436 buffer.frameCount = inFrameCount;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002437 if (LIKELY(mRecordTrack->getNextBuffer(&buffer) == NO_ERROR &&
2438 (int)buffer.frameCount == inFrameCount)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 LOGV("AudioRecordThread read: %d frames", buffer.frameCount);
2440 ssize_t bytesRead = input->read(buffer.raw, inBufferSize);
2441 if (bytesRead < 0) {
2442 LOGE("Error reading audio input");
2443 sleep(1);
2444 }
2445 mRecordTrack->releaseBuffer(&buffer);
2446 mRecordTrack->overflow();
2447 }
2448
2449 // client isn't retrieving buffers fast enough
2450 else {
2451 if (!mRecordTrack->setOverflow())
2452 LOGW("AudioRecordThread: buffer overflow");
2453 // Release the processor for a while before asking for a new buffer.
2454 // This will give the application more chance to read from the buffer and
2455 // clear the overflow.
2456 usleep(5000);
2457 }
2458 }
2459 }
2460
2461
2462 if (input) {
2463 delete input;
2464 }
2465 mRecordTrack.clear();
2466
2467 return false;
2468}
2469
2470status_t AudioFlinger::AudioRecordThread::start(MixerThread::RecordTrack* recordTrack)
2471{
2472 LOGV("AudioRecordThread::start");
2473 AutoMutex lock(&mLock);
2474 mActive = true;
2475 // If starting the active track, just reset mActive in case a stop
2476 // was pending and exit
2477 if (recordTrack == mRecordTrack.get()) return NO_ERROR;
2478
2479 if (mRecordTrack != 0) return -EBUSY;
2480
2481 mRecordTrack = recordTrack;
2482
2483 // signal thread to start
2484 LOGV("Signal record thread");
2485 mWaitWorkCV.signal();
2486 mWaitWorkCV.wait(mLock);
2487 LOGV("Record started, status %d", mStartStatus);
2488 return mStartStatus;
2489}
2490
2491void AudioFlinger::AudioRecordThread::stop(MixerThread::RecordTrack* recordTrack) {
2492 LOGV("AudioRecordThread::stop");
2493 AutoMutex lock(&mLock);
2494 if (mActive && (recordTrack == mRecordTrack.get())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 mActive = false;
2496 mStopped.wait(mLock);
2497 }
2498}
2499
2500void AudioFlinger::AudioRecordThread::exit()
2501{
2502 LOGV("AudioRecordThread::exit");
2503 {
2504 AutoMutex lock(&mLock);
2505 requestExit();
2506 mWaitWorkCV.signal();
2507 }
2508 requestExitAndWait();
2509}
2510
2511status_t AudioFlinger::AudioRecordThread::dump(int fd, const Vector<String16>& args)
2512{
2513 const size_t SIZE = 256;
2514 char buffer[SIZE];
2515 String8 result;
2516 pid_t pid = 0;
2517
2518 if (mRecordTrack != 0 && mRecordTrack->mClient != 0) {
2519 snprintf(buffer, SIZE, "Record client pid: %d\n", mRecordTrack->mClient->pid());
2520 result.append(buffer);
2521 } else {
2522 result.append("No record client\n");
2523 }
2524 write(fd, result.string(), result.size());
2525 return NO_ERROR;
2526}
2527
2528status_t AudioFlinger::onTransact(
2529 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2530{
2531 return BnAudioFlinger::onTransact(code, data, reply, flags);
2532}
2533
2534// ----------------------------------------------------------------------------
2535void AudioFlinger::instantiate() {
2536 defaultServiceManager()->addService(
2537 String16("media.audio_flinger"), new AudioFlinger());
2538}
2539
2540}; // namespace android