blob: a4050b30e20a8f1d6c5a73e19e36b8550de620ad [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/* //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
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080034#include <cutils/properties.h>
35
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036#include <media/AudioTrack.h>
37#include <media/AudioRecord.h>
38
39#include <private/media/AudioTrackShared.h>
40
The Android Open Source Project9266c552009-01-15 16:12:10 -080041#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include "AudioMixer.h"
44#include "AudioFlinger.h"
45
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080046#ifdef WITH_A2DP
47#include "A2dpAudioInterface.h"
48#endif
49
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050// ----------------------------------------------------------------------------
51// the sim build doesn't have gettid
52
53#ifndef HAVE_GETTID
54# define gettid getpid
55#endif
56
57// ----------------------------------------------------------------------------
58
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070059namespace 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 Projectf013e1a2008-12-17 18:05:43 -080064//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070065static 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074static 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
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070084#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()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 : 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 Project54b6cfa2008-10-21 07:00:00 -0700127{
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;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800134 status_t status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 AudioStreamOut *hwOutput = mAudioHardware->openOutputStream(AudioSystem::PCM_16_BIT, 0, 0, &status);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700136 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 if (hwOutput) {
138 mHardwareMixerThread = new MixerThread(this, hwOutput, AudioSystem::AUDIO_OUTPUT_HARDWARE);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700139 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 LOGE("Failed to initialize hardware output stream, status: %d", status);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700141 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800142
143#ifdef WITH_A2DP
144 // Create A2DP interface
145 mA2dpAudioInterface = new A2dpAudioInterface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 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 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800161#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
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
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800172 // Start record thread
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700173 mAudioRecordThread = new AudioRecordThread(mAudioHardware, this);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800174 if (mAudioRecordThread != 0) {
175 mAudioRecordThread->run("AudioRecordThread", PRIORITY_URGENT_AUDIO);
176 }
177 } else {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700178 LOGE("Couldn't even initialize the stubbed audio hardware!");
179 }
180}
181
182AudioFlinger::~AudioFlinger()
183{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800184 if (mAudioRecordThread != 0) {
185 mAudioRecordThread->exit();
186 mAudioRecordThread.clear();
187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 mHardwareMixerThread.clear();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700189 delete mAudioHardware;
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800190 // deleting mA2dpAudioInterface also deletes mA2dpOutput;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191#ifdef WITH_A2DP
192 mA2dpMixerThread.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800193 delete mA2dpAudioInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194#endif
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800195}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800196
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700197
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -0800198#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();
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -0800219}
220
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700221// checkA2dpEnabledChange_l() must be called with AudioFlinger::mLock held
222void AudioFlinger::checkA2dpEnabledChange_l()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -0800223{
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700224 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;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -0800236 }
237}
238#endif // WITH_A2DP
239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240bool 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 Laurenteeea9222009-03-26 01:57:59 -0700246 streamType == AudioSystem::NOTIFICATION ||
247 streamType == AudioSystem::ENFORCED_AUDIBLE);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700248}
249
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700250status_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
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700271
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 Project54b6cfa2008-10-21 07:00:00 -0700283 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 Project54b6cfa2008-10-21 07:00:00 -0700315status_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 Project54b6cfa2008-10-21 07:00:00 -0700336
337 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700338 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 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
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700347 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 Project54b6cfa2008-10-21 07:00:00 -0700351 }
352 return NO_ERROR;
353}
354
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700355// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356
357
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700358sp<IAudioTrack> AudioFlinger::createTrack(
359 pid_t pid,
360 int streamType,
361 uint32_t sampleRate,
362 int format,
363 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800364 int frameCount,
365 uint32_t flags,
366 const sp<IMemory>& sharedBuffer,
367 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700368{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 sp<MixerThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700370 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700371 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800372 wp<Client> wclient;
373 status_t lStatus;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800376 LOGE("invalid stream type");
377 lStatus = BAD_VALUE;
378 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700379 }
380
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800381 {
382 Mutex::Autolock _l(mLock);
383
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800384 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 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392#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) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800404 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700405 } else {
406 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800407 }
408
409Exit:
410 if(status) {
411 *status = lStatus;
412 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700413 return trackHandle;
414}
415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700417{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418#ifdef WITH_A2DP
419 if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
420 return mA2dpMixerThread->sampleRate();
421 }
422#endif
423 return mHardwareMixerThread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700424}
425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700427{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428#ifdef WITH_A2DP
429 if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
430 return mA2dpMixerThread->channelCount();
431 }
432#endif
433 return mHardwareMixerThread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700434}
435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700437{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438#ifdef WITH_A2DP
439 if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
440 return mA2dpMixerThread->format();
441 }
442#endif
443 return mHardwareMixerThread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700444}
445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700447{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448#ifdef WITH_A2DP
449 if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
450 return mA2dpMixerThread->frameCount();
451 }
452#endif
453 return mHardwareMixerThread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700454}
455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800457{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458#ifdef WITH_A2DP
459 if (output == AudioSystem::AUDIO_OUTPUT_A2DP) {
460 return mA2dpMixerThread->latency();
461 }
462#endif
463 return mHardwareMixerThread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800464}
465
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700466status_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) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 value = 1.0f;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700478 }
479 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 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 Project54b6cfa2008-10-21 07:00:00 -0700485 return NO_ERROR;
486}
487
488status_t AudioFlinger::setRouting(int mode, uint32_t routes, uint32_t mask)
489{
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800490 status_t err = NO_ERROR;
491
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700492 // 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
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800501#ifdef WITH_A2DP
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 LOGD("setRouting %d %d %d, tid %d, calling tid %d\n", mode, routes, mask, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800503 if (mode == AudioSystem::MODE_NORMAL &&
504 (mask & AudioSystem::ROUTE_BLUETOOTH_A2DP)) {
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -0800505 AutoMutex lock(&mLock);
506
507 bool enableA2dp = false;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800508 if (routes & AudioSystem::ROUTE_BLUETOOTH_A2DP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 enableA2dp = true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800510 }
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700511 if (mA2dpDisableCount > 0) {
512 mA2dpSuppressed = enableA2dp;
513 } else {
514 setA2dpEnabled_l(enableA2dp);
515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 LOGV("setOutput done\n");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800517 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700518 // setRouting() is always called at least for mode == AudioSystem::MODE_IN_CALL when
519 // SCO is enabled, whatever current mode is so we can safely handle A2DP disabling only
520 // in this case to avoid doing it several times.
521 if (mode == AudioSystem::MODE_IN_CALL &&
522 (mask & AudioSystem::ROUTE_BLUETOOTH_SCO)) {
523 AutoMutex lock(&mLock);
524 handleRouteDisablesA2dp_l(routes);
525 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800526#endif
527
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800528 // do nothing if only A2DP routing is affected
529 mask &= ~AudioSystem::ROUTE_BLUETOOTH_A2DP;
530 if (mask) {
531 AutoMutex lock(mHardwareLock);
532 mHardwareStatus = AUDIO_HW_GET_ROUTING;
533 uint32_t r;
534 err = mAudioHardware->getRouting(mode, &r);
535 if (err == NO_ERROR) {
536 r = (r & ~mask) | (routes & mask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 if (mode == AudioSystem::MODE_NORMAL ||
538 (mode == AudioSystem::MODE_CURRENT && getMode() == AudioSystem::MODE_NORMAL)) {
539 mSavedRoute = r;
540 r |= mForcedRoute;
541 LOGV("setRouting mSavedRoute %08x mForcedRoute %08x\n", mSavedRoute, mForcedRoute);
542 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800543 mHardwareStatus = AUDIO_HW_SET_ROUTING;
544 err = mAudioHardware->setRouting(mode, r);
545 }
546 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700547 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700548 return err;
549}
550
551uint32_t AudioFlinger::getRouting(int mode) const
552{
553 uint32_t routes = 0;
554 if ((mode >= AudioSystem::MODE_CURRENT) && (mode < AudioSystem::NUM_MODES)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 if (mode == AudioSystem::MODE_NORMAL ||
556 (mode == AudioSystem::MODE_CURRENT && getMode() == AudioSystem::MODE_NORMAL)) {
557 routes = mSavedRoute;
558 } else {
559 mHardwareStatus = AUDIO_HW_GET_ROUTING;
560 mAudioHardware->getRouting(mode, &routes);
561 mHardwareStatus = AUDIO_HW_IDLE;
562 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700563 } else {
564 LOGW("Illegal value: getRouting(%d)", mode);
565 }
566 return routes;
567}
568
569status_t AudioFlinger::setMode(int mode)
570{
571 // check calling permissions
572 if (!settingsAllowed()) {
573 return PERMISSION_DENIED;
574 }
575 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
576 LOGW("Illegal value: setMode(%d)", mode);
577 return BAD_VALUE;
578 }
579
580 AutoMutex lock(mHardwareLock);
581 mHardwareStatus = AUDIO_HW_SET_MODE;
582 status_t ret = mAudioHardware->setMode(mode);
583 mHardwareStatus = AUDIO_HW_IDLE;
584 return ret;
585}
586
587int AudioFlinger::getMode() const
588{
589 int mode = AudioSystem::MODE_INVALID;
590 mHardwareStatus = AUDIO_HW_SET_MODE;
591 mAudioHardware->getMode(&mode);
592 mHardwareStatus = AUDIO_HW_IDLE;
593 return mode;
594}
595
596status_t AudioFlinger::setMicMute(bool state)
597{
598 // check calling permissions
599 if (!settingsAllowed()) {
600 return PERMISSION_DENIED;
601 }
602
603 AutoMutex lock(mHardwareLock);
604 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
605 status_t ret = mAudioHardware->setMicMute(state);
606 mHardwareStatus = AUDIO_HW_IDLE;
607 return ret;
608}
609
610bool AudioFlinger::getMicMute() const
611{
612 bool state = AudioSystem::MODE_INVALID;
613 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
614 mAudioHardware->getMicMute(&state);
615 mHardwareStatus = AUDIO_HW_IDLE;
616 return state;
617}
618
619status_t AudioFlinger::setMasterMute(bool muted)
620{
621 // check calling permissions
622 if (!settingsAllowed()) {
623 return PERMISSION_DENIED;
624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 mHardwareMixerThread->setMasterMute(muted);
626#ifdef WITH_A2DP
627 mA2dpMixerThread->setMasterMute(muted);
628#endif
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700629 return NO_ERROR;
630}
631
632float AudioFlinger::masterVolume() const
633{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 return mHardwareMixerThread->masterVolume();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700635}
636
637bool AudioFlinger::masterMute() const
638{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 return mHardwareMixerThread->masterMute();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700640}
641
642status_t AudioFlinger::setStreamVolume(int stream, float value)
643{
644 // check calling permissions
645 if (!settingsAllowed()) {
646 return PERMISSION_DENIED;
647 }
648
Eric Laurenteeea9222009-03-26 01:57:59 -0700649 if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
650 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700651 return BAD_VALUE;
652 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800653
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700654 status_t ret = NO_ERROR;
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 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) {
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700660 hwValue = (float)AudioSystem::logToLinear(value)/100.0f;
Eric Laurentef028272009-04-21 07:56:33 -0700661 // 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)
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700665 hwValue = 1.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
667
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700668 AutoMutex lock(mHardwareLock);
669 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700670 ret = mAudioHardware->setVoiceVolume(hwValue);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700671 mHardwareStatus = AUDIO_HW_IDLE;
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700672
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700673 }
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700674
675 mHardwareMixerThread->setStreamVolume(stream, value);
676#ifdef WITH_A2DP
677 mA2dpMixerThread->setStreamVolume(stream, value);
678#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679
Eric Laurentef028272009-04-21 07:56:33 -0700680 mHardwareMixerThread->setStreamVolume(stream, value);
681#ifdef WITH_A2DP
682 mA2dpMixerThread->setStreamVolume(stream, value);
683#endif
684
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700685 return ret;
686}
687
688status_t AudioFlinger::setStreamMute(int stream, bool muted)
689{
690 // check calling permissions
691 if (!settingsAllowed()) {
692 return PERMISSION_DENIED;
693 }
694
Eric Laurenteeea9222009-03-26 01:57:59 -0700695 if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
696 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700697 return BAD_VALUE;
698 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700#ifdef WITH_A2DP
701 mA2dpMixerThread->setStreamMute(stream, muted);
702#endif
703 if (stream == AudioSystem::MUSIC)
704 {
705 AutoMutex lock(&mHardwareLock);
706 if (mForcedRoute != 0)
707 mMusicMuteSaved = muted;
708 else
709 mHardwareMixerThread->setStreamMute(stream, muted);
710 } else {
711 mHardwareMixerThread->setStreamMute(stream, muted);
712 }
713
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700714 return NO_ERROR;
715}
716
717float AudioFlinger::streamVolume(int stream) const
718{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700720 return 0.0f;
721 }
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700722
Eric Laurentef028272009-04-21 07:56:33 -0700723 float volume = mHardwareMixerThread->streamVolume(stream);
724 // remove correction applied by setStreamVolume()
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700725 if (stream == AudioSystem::VOICE_CALL) {
Eric Laurentef028272009-04-21 07:56:33 -0700726 volume = (volume - 0.01) / 0.99 ;
James E. Blair90329a62009-01-17 13:30:20 -0800727 }
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700728
Eric Laurentef028272009-04-21 07:56:33 -0700729 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700730}
731
732bool AudioFlinger::streamMute(int stream) const
733{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 if (uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700735 return true;
736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737
738 if (stream == AudioSystem::MUSIC && mForcedRoute != 0)
739 {
740 return mMusicMuteSaved;
741 }
742 return mHardwareMixerThread->streamMute(stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700743}
744
745bool AudioFlinger::isMusicActive() const
746{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 #ifdef WITH_A2DP
748 if (isA2dpEnabled()) {
749 return mA2dpMixerThread->isMusicActive();
750 }
751 #endif
752 return mHardwareMixerThread->isMusicActive();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700753}
754
755status_t AudioFlinger::setParameter(const char* key, const char* value)
756{
The Android Open Source Project9266c552009-01-15 16:12:10 -0800757 status_t result, result2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700758 AutoMutex lock(mHardwareLock);
759 mHardwareStatus = AUDIO_SET_PARAMETER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760
761 LOGV("setParameter() key %s, value %s, tid %d, calling tid %d", key, value, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700762 result = mAudioHardware->setParameter(key, value);
The Android Open Source Project9266c552009-01-15 16:12:10 -0800763 if (mA2dpAudioInterface) {
764 result2 = mA2dpAudioInterface->setParameter(key, value);
765 if (result2)
766 result = result2;
767 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700768 mHardwareStatus = AUDIO_HW_IDLE;
769 return result;
770}
771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
773{
774 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
775}
776
777void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
778{
779
780 LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
781 Mutex::Autolock _l(mLock);
782
783 sp<IBinder> binder = client->asBinder();
784 if (mNotificationClients.indexOf(binder) < 0) {
785 LOGV("Adding notification client %p", binder.get());
786 binder->linkToDeath(this);
787 mNotificationClients.add(binder);
788 client->a2dpEnabledChanged(isA2dpEnabled());
789 }
790}
791
792void AudioFlinger::binderDied(const wp<IBinder>& who) {
793
794 LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
795 Mutex::Autolock _l(mLock);
796
797 IBinder *binder = who.unsafe_get();
798
799 if (binder != NULL) {
800 int index = mNotificationClients.indexOf(binder);
801 if (index >= 0) {
802 LOGV("Removing notification client %p", binder);
803 mNotificationClients.removeAt(index);
804 }
805 }
806}
807
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700808void AudioFlinger::removeClient(pid_t pid)
809{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 LOGV("removeClient() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700811 Mutex::Autolock _l(mLock);
812 mClients.removeItem(pid);
813}
814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815bool AudioFlinger::isA2dpEnabled() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700816{
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700817 return mA2dpEnabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818}
819
820void AudioFlinger::handleForcedSpeakerRoute(int command)
821{
822 switch(command) {
823 case ACTIVE_TRACK_ADDED:
824 {
825 AutoMutex lock(mHardwareLock);
826 if (mForcedSpeakerCount++ == 0) {
827 mRouteRestoreTime = 0;
828 mMusicMuteSaved = mHardwareMixerThread->streamMute(AudioSystem::MUSIC);
829 if (mForcedRoute == 0 && !(mSavedRoute & AudioSystem::ROUTE_SPEAKER)) {
830 LOGV("Route forced to Speaker ON %08x", mSavedRoute | AudioSystem::ROUTE_SPEAKER);
831 mHardwareMixerThread->setStreamMute(AudioSystem::MUSIC, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 usleep(mHardwareMixerThread->latency()*1000);
833 mHardwareStatus = AUDIO_HW_SET_ROUTING;
834 mAudioHardware->setRouting(AudioSystem::MODE_NORMAL, mSavedRoute | AudioSystem::ROUTE_SPEAKER);
835 mHardwareStatus = AUDIO_HW_IDLE;
836 // delay track start so that audio hardware has time to siwtch routes
837 usleep(kStartSleepTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 }
839 mForcedRoute = AudioSystem::ROUTE_SPEAKER;
840 }
841 LOGV("mForcedSpeakerCount incremented to %d", mForcedSpeakerCount);
842 }
843 break;
844 case ACTIVE_TRACK_REMOVED:
845 {
846 AutoMutex lock(mHardwareLock);
847 if (mForcedSpeakerCount > 0){
848 if (--mForcedSpeakerCount == 0) {
849 mRouteRestoreTime = systemTime() + milliseconds(kStopSleepTime/1000);
850 }
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700851 LOGV("mForcedSpeakerCount decremented to %d", mForcedSpeakerCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 } else {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700853 LOGE("mForcedSpeakerCount is already zero");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856 break;
857 case CHECK_ROUTE_RESTORE_TIME:
858 case FORCE_ROUTE_RESTORE:
859 if (mRouteRestoreTime) {
860 AutoMutex lock(mHardwareLock);
861 if (mRouteRestoreTime &&
862 (systemTime() > mRouteRestoreTime || command == FORCE_ROUTE_RESTORE)) {
863 mHardwareMixerThread->setStreamMute(AudioSystem::MUSIC, mMusicMuteSaved);
864 mForcedRoute = 0;
865 if (!(mSavedRoute & AudioSystem::ROUTE_SPEAKER)) {
866 mHardwareStatus = AUDIO_HW_SET_ROUTING;
867 mAudioHardware->setRouting(AudioSystem::MODE_NORMAL, mSavedRoute);
868 mHardwareStatus = AUDIO_HW_IDLE;
869 LOGV("Route forced to Speaker OFF %08x", mSavedRoute);
870 }
871 mRouteRestoreTime = 0;
872 }
873 }
874 break;
875 }
876}
877
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700878#ifdef WITH_A2DP
The Android Open Source Project10592532009-03-18 17:39:46 -0700879// handleRouteDisablesA2dp_l() must be called with AudioFlinger::mLock held
880void AudioFlinger::handleRouteDisablesA2dp_l(int routes)
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700881{
The Android Open Source Project10592532009-03-18 17:39:46 -0700882 if (routes & AudioSystem::ROUTE_BLUETOOTH_SCO) {
883 if (mA2dpDisableCount++ == 0) {
884 if (mA2dpEnabled) {
885 setA2dpEnabled_l(false);
886 mA2dpSuppressed = true;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700887 }
888 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700889 LOGV("mA2dpDisableCount incremented to %d", mA2dpDisableCount);
890 } else {
891 if (mA2dpDisableCount > 0) {
892 if (--mA2dpDisableCount == 0) {
893 if (mA2dpSuppressed) {
894 setA2dpEnabled_l(true);
895 mA2dpSuppressed = false;
896 }
897 }
898 LOGV("mA2dpDisableCount decremented to %d", mA2dpDisableCount);
899 } else {
900 LOGE("mA2dpDisableCount is already zero");
901 }
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700902 }
903}
904#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905
906// ----------------------------------------------------------------------------
907
908AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int outputType)
909 : Thread(false),
910 mAudioFlinger(audioFlinger), mAudioMixer(0), mOutput(output), mOutputType(outputType),
911 mSampleRate(0), mFrameCount(0), mChannelCount(0), mFormat(0), mMixBuffer(0),
912 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mStandby(false),
913 mInWrite(false)
914{
915 mSampleRate = output->sampleRate();
916 mChannelCount = output->channelCount();
917
918 // FIXME - Current mixer implementation only supports stereo output
919 if (mChannelCount == 1) {
920 LOGE("Invalid audio hardware channel count");
921 }
922
923 mFormat = output->format();
924 mFrameCount = output->bufferSize() / output->channelCount() / sizeof(int16_t);
925 mAudioMixer = new AudioMixer(mFrameCount, output->sampleRate());
926
927 // FIXME - Current mixer implementation only supports stereo output: Always
928 // Allocate a stereo buffer even if HW output is mono.
929 mMixBuffer = new int16_t[mFrameCount * 2];
930 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
931}
932
933AudioFlinger::MixerThread::~MixerThread()
934{
935 delete [] mMixBuffer;
936 delete mAudioMixer;
937}
938
939status_t AudioFlinger::MixerThread::dump(int fd, const Vector<String16>& args)
940{
941 dumpInternals(fd, args);
942 dumpTracks(fd, args);
943 return NO_ERROR;
944}
945
946status_t AudioFlinger::MixerThread::dumpTracks(int fd, const Vector<String16>& args)
947{
948 const size_t SIZE = 256;
949 char buffer[SIZE];
950 String8 result;
951
952 snprintf(buffer, SIZE, "Output %d mixer thread tracks\n", mOutputType);
953 result.append(buffer);
954 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
955 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -0700956 sp<Track> track = mTracks[i];
957 if (track != 0) {
958 track->dump(buffer, SIZE);
959 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 }
961 }
962
963 snprintf(buffer, SIZE, "Output %d mixer thread active tracks\n", mOutputType);
964 result.append(buffer);
965 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
966 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -0700967 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 if (wTrack != 0) {
969 sp<Track> track = wTrack.promote();
970 if (track != 0) {
971 track->dump(buffer, SIZE);
972 result.append(buffer);
973 }
974 }
975 }
976 write(fd, result.string(), result.size());
977 return NO_ERROR;
978}
979
980status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
981{
982 const size_t SIZE = 256;
983 char buffer[SIZE];
984 String8 result;
985
986 snprintf(buffer, SIZE, "Output %d mixer thread internals\n", mOutputType);
987 result.append(buffer);
988 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
989 result.append(buffer);
990 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
991 result.append(buffer);
992 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
993 result.append(buffer);
994 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
995 result.append(buffer);
996 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
997 result.append(buffer);
998 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
999 result.append(buffer);
1000 write(fd, result.string(), result.size());
1001 return NO_ERROR;
1002}
1003
1004// Thread virtuals
1005bool AudioFlinger::MixerThread::threadLoop()
1006{
1007 unsigned long sleepTime = kBufferRecoveryInUsecs;
1008 int16_t* curBuf = mMixBuffer;
1009 Vector< sp<Track> > tracksToRemove;
1010 size_t enabledTracks = 0;
1011 nsecs_t standbyTime = systemTime();
1012 size_t mixBufferSize = mFrameCount*mChannelCount*sizeof(int16_t);
1013 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
1014
1015#ifdef WITH_A2DP
1016 bool outputTrackActive = false;
1017#endif
1018
1019 do {
1020 enabledTracks = 0;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001021 { // scope for the AudioFlinger::mLock
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001023 Mutex::Autolock _l(mAudioFlinger->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024
1025#ifdef WITH_A2DP
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 if (mOutputTrack != NULL && !mAudioFlinger->isA2dpEnabled()) {
1027 if (outputTrackActive) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001028 mAudioFlinger->mLock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 mOutputTrack->stop();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001030 mAudioFlinger->mLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 outputTrackActive = false;
1032 }
1033 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001034 mAudioFlinger->checkA2dpEnabledChange_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035#endif
1036
1037 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1038
1039 // put audio hardware into standby after short delay
1040 if UNLIKELY(!activeTracks.size() && systemTime() > standbyTime) {
1041 // wait until we have something to do...
1042 LOGV("Audio hardware entering standby, output %d\n", mOutputType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 if (!mStandby) {
1044 mOutput->standby();
1045 mStandby = true;
1046 }
1047
1048#ifdef WITH_A2DP
1049 if (outputTrackActive) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001050 mAudioFlinger->mLock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 mOutputTrack->stop();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001052 mAudioFlinger->mLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 outputTrackActive = false;
1054 }
1055#endif
1056 if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) {
1057 mAudioFlinger->handleForcedSpeakerRoute(FORCE_ROUTE_RESTORE);
1058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 // we're about to wait, flush the binder command buffer
1060 IPCThreadState::self()->flushCommands();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001061 mAudioFlinger->mWaitWorkCV.wait(mAudioFlinger->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 LOGV("Audio hardware exiting standby, output %d\n", mOutputType);
1063
1064 if (mMasterMute == false) {
1065 char value[PROPERTY_VALUE_MAX];
1066 property_get("ro.audio.silent", value, "0");
1067 if (atoi(value)) {
1068 LOGD("Silence is golden");
1069 setMasterMute(true);
1070 }
1071 }
1072
1073 standbyTime = systemTime() + kStandbyTimeInNsecs;
1074 continue;
1075 }
1076
1077 // Forced route to speaker is handled by hardware mixer thread
1078 if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) {
1079 mAudioFlinger->handleForcedSpeakerRoute(CHECK_ROUTE_RESTORE_TIME);
1080 }
1081
1082 // find out which tracks need to be processed
1083 size_t count = activeTracks.size();
1084 for (size_t i=0 ; i<count ; i++) {
1085 sp<Track> t = activeTracks[i].promote();
1086 if (t == 0) continue;
1087
1088 Track* const track = t.get();
1089 audio_track_cblk_t* cblk = track->cblk();
1090
1091 // The first time a track is added we wait
1092 // for all its buffers to be filled before processing it
1093 mAudioMixer->setActiveTrack(track->name());
1094 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1095 !track->isPaused())
1096 {
1097 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1098
1099 // compute volume for this track
1100 int16_t left, right;
1101 if (track->isMuted() || mMasterMute || track->isPausing()) {
1102 left = right = 0;
1103 if (track->isPausing()) {
1104 LOGV("paused(%d)", track->name());
1105 track->setPaused();
1106 }
1107 } else {
1108 float typeVolume = mStreamTypes[track->type()].volume;
1109 float v = mMasterVolume * typeVolume;
1110 float v_clamped = v * cblk->volume[0];
1111 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1112 left = int16_t(v_clamped);
1113 v_clamped = v * cblk->volume[1];
1114 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1115 right = int16_t(v_clamped);
1116 }
1117
1118 // XXX: these things DON'T need to be done each time
1119 mAudioMixer->setBufferProvider(track);
1120 mAudioMixer->enable(AudioMixer::MIXING);
1121
1122 int param;
1123 if ( track->mFillingUpStatus == Track::FS_FILLED) {
1124 // no ramp for the first volume setting
1125 track->mFillingUpStatus = Track::FS_ACTIVE;
1126 if (track->mState == TrackBase::RESUMING) {
1127 track->mState = TrackBase::ACTIVE;
1128 param = AudioMixer::RAMP_VOLUME;
1129 } else {
1130 param = AudioMixer::VOLUME;
1131 }
1132 } else {
1133 param = AudioMixer::RAMP_VOLUME;
1134 }
1135 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1136 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1137 mAudioMixer->setParameter(
1138 AudioMixer::TRACK,
1139 AudioMixer::FORMAT, track->format());
1140 mAudioMixer->setParameter(
1141 AudioMixer::TRACK,
1142 AudioMixer::CHANNEL_COUNT, track->channelCount());
1143 mAudioMixer->setParameter(
1144 AudioMixer::RESAMPLE,
1145 AudioMixer::SAMPLE_RATE,
1146 int(cblk->sampleRate));
1147
1148 // reset retry count
1149 track->mRetryCount = kMaxTrackRetries;
1150 enabledTracks++;
1151 } else {
1152 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1153 if (track->isStopped()) {
1154 track->reset();
1155 }
1156 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1157 // We have consumed all the buffers of this track.
1158 // Remove it from the list of active tracks.
1159 LOGV("remove(%d) from active list", track->name());
1160 tracksToRemove.add(track);
1161 } else {
1162 // No buffers for this track. Give it a few chances to
1163 // fill a buffer, then remove it from active list.
1164 if (--(track->mRetryCount) <= 0) {
1165 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1166 tracksToRemove.add(track);
1167 }
1168 }
1169 // LOGV("disable(%d)", track->name());
1170 mAudioMixer->disable(AudioMixer::MIXING);
1171 }
1172 }
1173
1174 // remove all the tracks that need to be...
1175 count = tracksToRemove.size();
1176 if (UNLIKELY(count)) {
1177 for (size_t i=0 ; i<count ; i++) {
1178 const sp<Track>& track = tracksToRemove[i];
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001179 removeActiveTrack_l(track);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 if (track->isTerminated()) {
1181 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001182 deleteTrackName_l(track->mName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
1184 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
1187
1188 if (LIKELY(enabledTracks)) {
1189 // mix buffers...
1190 mAudioMixer->process(curBuf);
1191
1192#ifdef WITH_A2DP
1193 if (mOutputTrack != NULL && mAudioFlinger->isA2dpEnabled()) {
1194 if (!outputTrackActive) {
1195 LOGV("starting output track in mixer for output %d", mOutputType);
1196 mOutputTrack->start();
1197 outputTrackActive = true;
1198 }
1199 mOutputTrack->write(curBuf, mFrameCount);
1200 }
1201#endif
1202
1203 // output audio to hardware
1204 mLastWriteTime = systemTime();
1205 mInWrite = true;
1206 mOutput->write(curBuf, mixBufferSize);
1207 mNumWrites++;
1208 mInWrite = false;
1209 mStandby = false;
1210 nsecs_t temp = systemTime();
1211 standbyTime = temp + kStandbyTimeInNsecs;
1212 nsecs_t delta = temp - mLastWriteTime;
1213 if (delta > maxPeriod) {
1214 LOGW("write blocked for %llu msecs", ns2ms(delta));
1215 mNumDelayedWrites++;
1216 }
1217 sleepTime = kBufferRecoveryInUsecs;
1218 } else {
1219#ifdef WITH_A2DP
1220 if (mOutputTrack != NULL && mAudioFlinger->isA2dpEnabled()) {
1221 if (outputTrackActive) {
1222 mOutputTrack->write(curBuf, 0);
1223 if (mOutputTrack->bufferQueueEmpty()) {
1224 mOutputTrack->stop();
1225 outputTrackActive = false;
1226 } else {
1227 standbyTime = systemTime() + kStandbyTimeInNsecs;
1228 }
1229 }
1230 }
1231#endif
1232 // There was nothing to mix this round, which means all
1233 // active tracks were late. Sleep a little bit to give
1234 // them another chance. If we're too late, the audio
1235 // hardware will zero-fill for us.
1236 //LOGV("no buffers - usleep(%lu)", sleepTime);
1237 usleep(sleepTime);
1238 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1239 sleepTime += kBufferRecoveryInUsecs;
1240 }
1241 }
1242
1243 // finally let go of all our tracks, without the lock held
1244 // since we can't guarantee the destructors won't acquire that
1245 // same lock.
1246 tracksToRemove.clear();
1247 } while (true);
1248
1249 return false;
1250}
1251
1252status_t AudioFlinger::MixerThread::readyToRun()
1253{
1254 if (mSampleRate == 0) {
1255 LOGE("No working audio driver found.");
1256 return NO_INIT;
1257 }
1258 LOGI("AudioFlinger's thread ready to run for output %d", mOutputType);
1259 return NO_ERROR;
1260}
1261
1262void AudioFlinger::MixerThread::onFirstRef()
1263{
1264 const size_t SIZE = 256;
1265 char buffer[SIZE];
1266
1267 snprintf(buffer, SIZE, "Mixer Thread for output %d", mOutputType);
1268
1269 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1270}
1271
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001272// MixerThread::createTrack_l() must be called with AudioFlinger::mLock held
1273sp<AudioFlinger::MixerThread::Track> AudioFlinger::MixerThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 const sp<AudioFlinger::Client>& client,
1275 int streamType,
1276 uint32_t sampleRate,
1277 int format,
1278 int channelCount,
1279 int frameCount,
1280 const sp<IMemory>& sharedBuffer,
1281 status_t *status)
1282{
1283 sp<Track> track;
1284 status_t lStatus;
1285
1286 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1287 if (sampleRate > MAX_SAMPLE_RATE || sampleRate > mSampleRate*2) {
1288 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1289 lStatus = BAD_VALUE;
1290 goto Exit;
1291 }
1292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001294 if (mSampleRate == 0) {
1295 LOGE("Audio driver not initialized.");
1296 lStatus = NO_INIT;
1297 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 }
1299
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001300 track = new Track(this, client, streamType, sampleRate, format,
1301 channelCount, frameCount, sharedBuffer);
1302 if (track->getCblk() == NULL) {
1303 lStatus = NO_MEMORY;
1304 goto Exit;
1305 }
1306 mTracks.add(track);
1307 lStatus = NO_ERROR;
1308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309Exit:
1310 if(status) {
1311 *status = lStatus;
1312 }
1313 return track;
1314}
1315
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001316// getTracks_l() must be called with AudioFlinger::mLock held
1317void AudioFlinger::MixerThread::getTracks_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 SortedVector < sp<Track> >& tracks,
1319 SortedVector < wp<Track> >& activeTracks)
1320{
1321 size_t size = mTracks.size();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001322 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 -08001323 for (size_t i = 0; i < size; i++) {
1324 sp<Track> t = mTracks[i];
1325 if (AudioSystem::routedToA2dpOutput(t->mStreamType)) {
1326 tracks.add(t);
1327 int j = mActiveTracks.indexOf(t);
1328 if (j >= 0) {
1329 t = mActiveTracks[j].promote();
1330 if (t != NULL) {
1331 activeTracks.add(t);
1332 }
1333 }
1334 }
1335 }
1336
1337 size = activeTracks.size();
1338 for (size_t i = 0; i < size; i++) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001339 removeActiveTrack_l(activeTracks[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 }
1341
1342 size = tracks.size();
1343 for (size_t i = 0; i < size; i++) {
1344 sp<Track> t = tracks[i];
1345 mTracks.remove(t);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001346 deleteTrackName_l(t->name());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 }
1348}
1349
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001350// putTracks_l() must be called with AudioFlinger::mLock held
1351void AudioFlinger::MixerThread::putTracks_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 SortedVector < sp<Track> >& tracks,
1353 SortedVector < wp<Track> >& activeTracks)
1354{
1355
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001356 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 -08001357
1358 size_t size = tracks.size();
1359 for (size_t i = 0; i < size ; i++) {
1360 sp<Track> t = tracks[i];
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001361 int name = getTrackName_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362
1363 if (name < 0) return;
1364
1365 t->mName = name;
1366 t->mMixerThread = this;
1367 mTracks.add(t);
1368
1369 int j = activeTracks.indexOf(t);
1370 if (j >= 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001371 addActiveTrack_l(t);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 }
1373 }
1374}
1375
1376uint32_t AudioFlinger::MixerThread::sampleRate() const
1377{
1378 return mSampleRate;
1379}
1380
1381int AudioFlinger::MixerThread::channelCount() const
1382{
1383 return mChannelCount;
1384}
1385
1386int AudioFlinger::MixerThread::format() const
1387{
1388 return mFormat;
1389}
1390
1391size_t AudioFlinger::MixerThread::frameCount() const
1392{
1393 return mFrameCount;
1394}
1395
1396uint32_t AudioFlinger::MixerThread::latency() const
1397{
1398 if (mOutput) {
1399 return mOutput->latency();
1400 }
1401 else {
1402 return 0;
1403 }
1404}
1405
1406status_t AudioFlinger::MixerThread::setMasterVolume(float value)
1407{
1408 mMasterVolume = value;
1409 return NO_ERROR;
1410}
1411
1412status_t AudioFlinger::MixerThread::setMasterMute(bool muted)
1413{
1414 mMasterMute = muted;
1415 return NO_ERROR;
1416}
1417
1418float AudioFlinger::MixerThread::masterVolume() const
1419{
1420 return mMasterVolume;
1421}
1422
1423bool AudioFlinger::MixerThread::masterMute() const
1424{
1425 return mMasterMute;
1426}
1427
1428status_t AudioFlinger::MixerThread::setStreamVolume(int stream, float value)
1429{
1430 mStreamTypes[stream].volume = value;
1431 return NO_ERROR;
1432}
1433
1434status_t AudioFlinger::MixerThread::setStreamMute(int stream, bool muted)
1435{
1436 mStreamTypes[stream].mute = muted;
1437 return NO_ERROR;
1438}
1439
1440float AudioFlinger::MixerThread::streamVolume(int stream) const
1441{
1442 return mStreamTypes[stream].volume;
1443}
1444
1445bool AudioFlinger::MixerThread::streamMute(int stream) const
1446{
1447 return mStreamTypes[stream].mute;
1448}
1449
1450bool AudioFlinger::MixerThread::isMusicActive() const
1451{
1452 size_t count = mActiveTracks.size();
1453 for (size_t i = 0 ; i < count ; ++i) {
1454 sp<Track> t = mActiveTracks[i].promote();
1455 if (t == 0) continue;
1456 Track* const track = t.get();
1457 if (t->mStreamType == AudioSystem::MUSIC)
1458 return true;
1459 }
1460 return false;
1461}
1462
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001463// addTrack_l() must be called with AudioFlinger::mLock held
1464status_t AudioFlinger::MixerThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465{
1466 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001467
1468 // here the track could be either new, or restarted
1469 // in both cases "unstop" the track
1470 if (track->isPaused()) {
1471 track->mState = TrackBase::RESUMING;
1472 LOGV("PAUSED => RESUMING (%d)", track->name());
1473 } else {
1474 track->mState = TrackBase::ACTIVE;
1475 LOGV("? => ACTIVE (%d)", track->name());
1476 }
1477 // set retry count for buffer fill
1478 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001479 if (mActiveTracks.indexOf(track) < 0) {
1480 // the track is newly added, make sure it fills up all its
1481 // buffers before playing. This is to ensure the client will
1482 // effectively get the latency it requested.
1483 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001484 track->mResetDone = false;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001485 addActiveTrack_l(track);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488
1489 LOGV("mWaitWorkCV.broadcast");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001490 mAudioFlinger->mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491
1492 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001493}
1494
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001495// destroyTrack_l() must be called with AudioFlinger::mLock held
1496void AudioFlinger::MixerThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001497{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001498 track->mState = TrackBase::TERMINATED;
1499 if (mActiveTracks.indexOf(track) < 0) {
1500 LOGV("remove track (%d) and delete from mixer", track->name());
1501 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001502 deleteTrackName_l(track->name());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001503 }
1504}
1505
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001506// addActiveTrack_l() must be called with AudioFlinger::mLock held
1507void AudioFlinger::MixerThread::addActiveTrack_l(const wp<Track>& t)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001508{
1509 mActiveTracks.add(t);
1510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 // Force routing to speaker for certain stream types
1512 // The forced routing to speaker is managed by hardware mixer
1513 if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) {
1514 sp<Track> track = t.promote();
1515 if (track == NULL) return;
1516
1517 if (streamForcedToSpeaker(track->type())) {
1518 mAudioFlinger->handleForcedSpeakerRoute(ACTIVE_TRACK_ADDED);
1519 }
1520 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001521}
1522
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001523// removeActiveTrack_l() must be called with AudioFlinger::mLock held
1524void AudioFlinger::MixerThread::removeActiveTrack_l(const wp<Track>& t)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001525{
1526 mActiveTracks.remove(t);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527
1528 // Force routing to speaker for certain stream types
1529 // The forced routing to speaker is managed by hardware mixer
1530 if (mOutputType == AudioSystem::AUDIO_OUTPUT_HARDWARE) {
1531 sp<Track> track = t.promote();
1532 if (track == NULL) return;
1533
1534 if (streamForcedToSpeaker(track->type())) {
1535 mAudioFlinger->handleForcedSpeakerRoute(ACTIVE_TRACK_REMOVED);
1536 }
1537 }
1538}
1539
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001540// getTrackName_l() must be called with AudioFlinger::mLock held
1541int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542{
1543 return mAudioMixer->getTrackName();
1544}
1545
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001546// deleteTrackName_l() must be called with AudioFlinger::mLock held
1547void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548{
1549 mAudioMixer->deleteTrackName(name);
1550}
1551
1552size_t AudioFlinger::MixerThread::getOutputFrameCount()
1553{
1554 return mOutput->bufferSize() / mOutput->channelCount() / sizeof(int16_t);
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001555}
1556
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001557// ----------------------------------------------------------------------------
1558
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001559// TrackBase constructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560AudioFlinger::MixerThread::TrackBase::TrackBase(
1561 const sp<MixerThread>& mixerThread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001562 const sp<Client>& client,
1563 int streamType,
1564 uint32_t sampleRate,
1565 int format,
1566 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001567 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 uint32_t flags,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001569 const sp<IMemory>& sharedBuffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001570 : RefBase(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 mMixerThread(mixerThread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001572 mClient(client),
1573 mStreamType(streamType),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001574 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001575 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001576 mClientTid(-1),
1577 mFormat(format),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001579{
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001580 mName = mixerThread->getTrackName_l();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 LOGV("TrackBase contructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001582 if (mName < 0) {
1583 LOGE("no more track names availlable");
1584 return;
1585 }
1586
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001587 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
1588
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001589 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001590 size_t size = sizeof(audio_track_cblk_t);
1591 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
1592 if (sharedBuffer == 0) {
1593 size += bufferSize;
1594 }
1595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 if (client != NULL) {
1597 mCblkMemory = client->heap()->allocate(size);
1598 if (mCblkMemory != 0) {
1599 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
1600 if (mCblk) { // construct the shared structure in-place.
1601 new(mCblk) audio_track_cblk_t();
1602 // clear all buffers
1603 mCblk->frameCount = frameCount;
The Android Open Source Project10592532009-03-18 17:39:46 -07001604 mCblk->sampleRate = (uint16_t)sampleRate;
1605 mCblk->channels = (uint16_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 if (sharedBuffer == 0) {
1607 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
1608 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
1609 // Force underrun condition to avoid false underrun callback until first data is
1610 // written to buffer
1611 mCblk->flowControlFlag = 1;
1612 } else {
1613 mBuffer = sharedBuffer->pointer();
1614 }
1615 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 } else {
1618 LOGE("not enough memory for AudioTrack size=%u", size);
1619 client->heap()->dump("AudioTrack");
1620 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 } else {
1623 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
1624 if (mCblk) { // construct the shared structure in-place.
1625 new(mCblk) audio_track_cblk_t();
1626 // clear all buffers
1627 mCblk->frameCount = frameCount;
The Android Open Source Project10592532009-03-18 17:39:46 -07001628 mCblk->sampleRate = (uint16_t)sampleRate;
1629 mCblk->channels = (uint16_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
1631 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
1632 // Force underrun condition to avoid false underrun callback until first data is
1633 // written to buffer
1634 mCblk->flowControlFlag = 1;
1635 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
1636 }
1637 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001638}
1639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640AudioFlinger::MixerThread::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001641{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 if (mCblk) {
1643 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
1644 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001645 mCblkMemory.clear(); // and free the shared memory
1646 mClient.clear();
1647}
1648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649void AudioFlinger::MixerThread::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001650{
1651 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001652 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001653 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001654 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001655}
1656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657bool AudioFlinger::MixerThread::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001658 bool result;
1659 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001660
1661 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001662 if (!result) {
1663 LOGV("stepServer failed acquiring cblk mutex");
1664 mFlags |= STEPSERVER_FAILED;
1665 }
1666 return result;
1667}
1668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669void AudioFlinger::MixerThread::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001670 audio_track_cblk_t* cblk = this->cblk();
1671
1672 cblk->user = 0;
1673 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001674 cblk->userBase = 0;
1675 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001677 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001678}
1679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680sp<IMemory> AudioFlinger::MixerThread::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001681{
1682 return mCblkMemory;
1683}
1684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685int AudioFlinger::MixerThread::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07001686 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001687}
1688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689int AudioFlinger::MixerThread::TrackBase::channelCount() const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001690 return mCblk->channels;
1691}
1692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693void* AudioFlinger::MixerThread::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001694 audio_track_cblk_t* cblk = this->cblk();
1695 int16_t *bufferStart = (int16_t *)mBuffer + (offset-cblk->serverBase)*cblk->channels;
1696 int16_t *bufferEnd = bufferStart + frames * cblk->channels;
1697
1698 // 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 -07001699 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Eric Laurentef028272009-04-21 07:56:33 -07001700 (cblk->channels == 2 && ((unsigned long)bufferStart & 3))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001701 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
1702 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001703 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project10592532009-03-18 17:39:46 -07001704 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001705 return 0;
1706 }
1707
1708 return bufferStart;
1709}
1710
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001711// ----------------------------------------------------------------------------
1712
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001713// Track constructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714AudioFlinger::MixerThread::Track::Track(
1715 const sp<MixerThread>& mixerThread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001716 const sp<Client>& client,
1717 int streamType,
1718 uint32_t sampleRate,
1719 int format,
1720 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001721 int frameCount,
1722 const sp<IMemory>& sharedBuffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 : TrackBase(mixerThread, client, streamType, sampleRate, format, channelCount, frameCount, 0, sharedBuffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001724{
1725 mVolume[0] = 1.0f;
1726 mVolume[1] = 1.0f;
1727 mMute = false;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001728 mSharedBuffer = sharedBuffer;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001729}
1730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731AudioFlinger::MixerThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001732{
1733 wp<Track> weak(this); // never create a strong ref from the dtor
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001734 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001735 mState = TERMINATED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001736}
1737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738void AudioFlinger::MixerThread::Track::destroy()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001739{
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001740 // NOTE: destroyTrack_l() can remove a strong reference to this Track
1741 // by removing it from mTracks vector, so there is a risk that this Tracks's
1742 // desctructor is called. As the destructor needs to lock AudioFlinger::mLock,
1743 // we must acquire a strong reference on this Track before locking AudioFlinger::mLock
1744 // here so that the destructor is called only when exiting this function.
1745 // On the other hand, as long as Track::destroy() is only called by
1746 // TrackHandle destructor, the TrackHandle still holds a strong ref on
1747 // this Track with its member mTrack.
1748 sp<Track> keep(this);
1749 { // scope for AudioFlinger::mLock
1750 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
1751 mMixerThread->destroyTrack_l(this);
1752 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001753}
1754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755void AudioFlinger::MixerThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001756{
1757 snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
1758 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001760 mStreamType,
1761 mFormat,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001762 mCblk->channels,
1763 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001764 mState,
1765 mMute,
1766 mFillingUpStatus,
1767 mCblk->sampleRate,
1768 mCblk->volume[0],
1769 mCblk->volume[1],
1770 mCblk->server,
1771 mCblk->user);
1772}
1773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774status_t AudioFlinger::MixerThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001775{
1776 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001777 uint32_t framesReady;
1778 uint32_t framesReq = buffer->frameCount;
1779
1780 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001781 if (mFlags & TrackBase::STEPSERVER_FAILED) {
1782 if (!step()) goto getNextBuffer_exit;
1783 LOGV("stepServer recovered");
1784 mFlags &= ~TrackBase::STEPSERVER_FAILED;
1785 }
1786
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001787 framesReady = cblk->framesReady();
1788
1789 if (LIKELY(framesReady)) {
1790 uint32_t s = cblk->server;
1791 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
1792
1793 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
1794 if (framesReq > framesReady) {
1795 framesReq = framesReady;
1796 }
1797 if (s + framesReq > bufferEnd) {
1798 framesReq = bufferEnd - s;
1799 }
1800
1801 buffer->raw = getBuffer(s, framesReq);
1802 if (buffer->raw == 0) goto getNextBuffer_exit;
1803
1804 buffer->frameCount = framesReq;
1805 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001806 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001807
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001808getNextBuffer_exit:
1809 buffer->raw = 0;
1810 buffer->frameCount = 0;
1811 return NOT_ENOUGH_DATA;
1812}
1813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814bool AudioFlinger::MixerThread::Track::isReady() const {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001815 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001816
1817 if (mCblk->framesReady() >= mCblk->frameCount ||
1818 mCblk->forceReady) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001819 mFillingUpStatus = FS_FILLED;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001820 mCblk->forceReady = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 LOGV("Track::isReady() track %d for output %d", mName, mMixerThread->mOutputType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001822 return true;
1823 }
1824 return false;
1825}
1826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827status_t AudioFlinger::MixerThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001828{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 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 -07001830 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
1831 mMixerThread->addTrack_l(this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001832 return NO_ERROR;
1833}
1834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835void AudioFlinger::MixerThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001836{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 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 -07001838 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001839 if (mState > STOPPED) {
1840 mState = STOPPED;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001841 // If the track is not active (PAUSED and buffers full), flush buffers
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 if (mMixerThread->mActiveTracks.indexOf(this) < 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001843 reset();
1844 }
1845 LOGV("(> STOPPED) => STOPPED (%d)", mName);
1846 }
1847}
1848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849void AudioFlinger::MixerThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001850{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001852 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001853 if (mState == ACTIVE || mState == RESUMING) {
1854 mState = PAUSING;
1855 LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
1856 }
1857}
1858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859void AudioFlinger::MixerThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001860{
1861 LOGV("flush(%d)", mName);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001862 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001863 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
1864 return;
1865 }
1866 // No point remaining in PAUSED state after a flush => go to
1867 // STOPPED state
1868 mState = STOPPED;
1869
The Android Open Source Project10592532009-03-18 17:39:46 -07001870 mCblk->lock.lock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001871 // NOTE: reset() will reset cblk->user and cblk->server with
1872 // the risk that at the same time, the AudioMixer is trying to read
1873 // data. In this case, getNextBuffer() would return a NULL pointer
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001874 // as audio buffer => the AudioMixer code MUST always test that pointer
1875 // returned by getNextBuffer() is not NULL!
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001876 reset();
The Android Open Source Project10592532009-03-18 17:39:46 -07001877 mCblk->lock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001878}
1879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880void AudioFlinger::MixerThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001881{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001882 // Do not reset twice to avoid discarding data written just after a flush and before
1883 // the audioflinger thread detects the track is stopped.
1884 if (!mResetDone) {
1885 TrackBase::reset();
1886 // Force underrun condition to avoid false underrun callback until first data is
1887 // written to buffer
1888 mCblk->flowControlFlag = 1;
1889 mCblk->forceReady = 0;
1890 mFillingUpStatus = FS_FILLING;
1891 mResetDone = true;
1892 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001893}
1894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895void AudioFlinger::MixerThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001896{
1897 mMute = muted;
1898}
1899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900void AudioFlinger::MixerThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001901{
1902 mVolume[0] = left;
1903 mVolume[1] = right;
1904}
1905
1906// ----------------------------------------------------------------------------
1907
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001908// RecordTrack constructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909AudioFlinger::MixerThread::RecordTrack::RecordTrack(
1910 const sp<MixerThread>& mixerThread,
1911 const sp<Client>& client,
1912 int streamType,
1913 uint32_t sampleRate,
1914 int format,
1915 int channelCount,
1916 int frameCount,
1917 uint32_t flags)
1918 : TrackBase(mixerThread, client, streamType, sampleRate, format,
1919 channelCount, frameCount, flags, 0),
1920 mOverflow(false)
1921{
1922}
1923
1924AudioFlinger::MixerThread::RecordTrack::~RecordTrack()
1925{
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001926 Mutex::Autolock _l(mMixerThread->mAudioFlinger->mLock);
1927 mMixerThread->deleteTrackName_l(mName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928}
1929
1930status_t AudioFlinger::MixerThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
1931{
1932 audio_track_cblk_t* cblk = this->cblk();
1933 uint32_t framesAvail;
1934 uint32_t framesReq = buffer->frameCount;
1935
1936 // Check if last stepServer failed, try to step now
1937 if (mFlags & TrackBase::STEPSERVER_FAILED) {
1938 if (!step()) goto getNextBuffer_exit;
1939 LOGV("stepServer recovered");
1940 mFlags &= ~TrackBase::STEPSERVER_FAILED;
1941 }
1942
1943 framesAvail = cblk->framesAvailable_l();
1944
1945 if (LIKELY(framesAvail)) {
1946 uint32_t s = cblk->server;
1947 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
1948
1949 if (framesReq > framesAvail) {
1950 framesReq = framesAvail;
1951 }
1952 if (s + framesReq > bufferEnd) {
1953 framesReq = bufferEnd - s;
1954 }
1955
1956 buffer->raw = getBuffer(s, framesReq);
1957 if (buffer->raw == 0) goto getNextBuffer_exit;
1958
1959 buffer->frameCount = framesReq;
1960 return NO_ERROR;
1961 }
1962
1963getNextBuffer_exit:
1964 buffer->raw = 0;
1965 buffer->frameCount = 0;
1966 return NOT_ENOUGH_DATA;
1967}
1968
1969status_t AudioFlinger::MixerThread::RecordTrack::start()
1970{
1971 return mMixerThread->mAudioFlinger->startRecord(this);
1972}
1973
1974void AudioFlinger::MixerThread::RecordTrack::stop()
1975{
1976 mMixerThread->mAudioFlinger->stopRecord(this);
1977 TrackBase::reset();
1978 // Force overerrun condition to avoid false overrun callback until first data is
1979 // read from buffer
1980 mCblk->flowControlFlag = 1;
1981}
1982
1983
1984// ----------------------------------------------------------------------------
1985
1986AudioFlinger::MixerThread::OutputTrack::OutputTrack(
1987 const sp<MixerThread>& mixerThread,
1988 uint32_t sampleRate,
1989 int format,
1990 int channelCount,
1991 int frameCount)
1992 : Track(mixerThread, NULL, AudioSystem::SYSTEM, sampleRate, format, channelCount, frameCount, NULL),
1993 mOutputMixerThread(mixerThread)
1994{
1995
1996 mCblk->out = 1;
1997 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
1998 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
1999 mOutBuffer.frameCount = 0;
2000 mCblk->bufferTimeoutMs = 10;
2001
2002 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p",
2003 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd);
2004
2005}
2006
2007AudioFlinger::MixerThread::OutputTrack::~OutputTrack()
2008{
2009 stop();
2010}
2011
2012status_t AudioFlinger::MixerThread::OutputTrack::start()
2013{
2014 status_t status = Track::start();
2015
2016 mRetryCount = 127;
2017 return status;
2018}
2019
2020void AudioFlinger::MixerThread::OutputTrack::stop()
2021{
2022 Track::stop();
2023 clearBufferQueue();
2024 mOutBuffer.frameCount = 0;
2025}
2026
2027void AudioFlinger::MixerThread::OutputTrack::write(int16_t* data, uint32_t frames)
2028{
2029 Buffer *pInBuffer;
2030 Buffer inBuffer;
2031 uint32_t channels = mCblk->channels;
2032
2033 inBuffer.frameCount = frames;
2034 inBuffer.i16 = data;
2035
2036 if (mCblk->user == 0) {
2037 if (mOutputMixerThread->isMusicActive()) {
2038 mCblk->forceReady = 1;
2039 LOGV("OutputTrack::start() force ready");
2040 } else if (mCblk->frameCount > frames){
2041 if (mBufferQueue.size() < kMaxOutputTrackBuffers) {
2042 uint32_t startFrames = (mCblk->frameCount - frames);
2043 LOGV("OutputTrack::start() write %d frames", startFrames);
2044 pInBuffer = new Buffer;
2045 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2046 pInBuffer->frameCount = startFrames;
2047 pInBuffer->i16 = pInBuffer->mBuffer;
2048 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2049 mBufferQueue.add(pInBuffer);
2050 } else {
2051 LOGW ("OutputTrack::write() no more buffers");
2052 }
2053 }
2054 }
2055
2056 while (1) {
2057 // First write pending buffers, then new data
2058 if (mBufferQueue.size()) {
2059 pInBuffer = mBufferQueue.itemAt(0);
2060 } else {
2061 pInBuffer = &inBuffer;
2062 }
2063
2064 if (pInBuffer->frameCount == 0) {
2065 break;
2066 }
2067
2068 if (mOutBuffer.frameCount == 0) {
2069 mOutBuffer.frameCount = pInBuffer->frameCount;
2070 if (obtainBuffer(&mOutBuffer) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
2071 break;
2072 }
2073 }
2074
2075 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2076 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2077 mCblk->stepUser(outFrames);
2078 pInBuffer->frameCount -= outFrames;
2079 pInBuffer->i16 += outFrames * channels;
2080 mOutBuffer.frameCount -= outFrames;
2081 mOutBuffer.i16 += outFrames * channels;
2082
2083 if (pInBuffer->frameCount == 0) {
2084 if (mBufferQueue.size()) {
2085 mBufferQueue.removeAt(0);
2086 delete [] pInBuffer->mBuffer;
2087 delete pInBuffer;
2088 } else {
2089 break;
2090 }
2091 }
2092 }
2093
2094 // If we could not write all frames, allocate a buffer and queue it for next time.
2095 if (inBuffer.frameCount) {
2096 if (mBufferQueue.size() < kMaxOutputTrackBuffers) {
2097 pInBuffer = new Buffer;
2098 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2099 pInBuffer->frameCount = inBuffer.frameCount;
2100 pInBuffer->i16 = pInBuffer->mBuffer;
2101 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2102 mBufferQueue.add(pInBuffer);
2103 } else {
2104 LOGW("OutputTrack::write() no more buffers");
2105 }
2106 }
2107
2108 // Calling write() with a 0 length buffer, means that no more data will be written:
2109 // If no more buffers are pending, fill output track buffer to make sure it is started
2110 // by output mixer.
2111 if (frames == 0 && mBufferQueue.size() == 0 && mCblk->user < mCblk->frameCount) {
2112 frames = mCblk->frameCount - mCblk->user;
2113 pInBuffer = new Buffer;
2114 pInBuffer->mBuffer = new int16_t[frames * channels];
2115 pInBuffer->frameCount = frames;
2116 pInBuffer->i16 = pInBuffer->mBuffer;
2117 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2118 mBufferQueue.add(pInBuffer);
2119 }
2120
2121}
2122
2123status_t AudioFlinger::MixerThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer)
2124{
2125 int active;
2126 int timeout = 0;
2127 status_t result;
2128 audio_track_cblk_t* cblk = mCblk;
2129 uint32_t framesReq = buffer->frameCount;
2130
2131 LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
2132 buffer->frameCount = 0;
2133
2134 uint32_t framesAvail = cblk->framesAvailable();
2135
2136 if (framesAvail == 0) {
2137 return AudioTrack::NO_MORE_BUFFERS;
2138 }
2139
2140 if (framesReq > framesAvail) {
2141 framesReq = framesAvail;
2142 }
2143
2144 uint32_t u = cblk->user;
2145 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2146
2147 if (u + framesReq > bufferEnd) {
2148 framesReq = bufferEnd - u;
2149 }
2150
2151 buffer->frameCount = framesReq;
2152 buffer->raw = (void *)cblk->buffer(u);
2153 return NO_ERROR;
2154}
2155
2156
2157void AudioFlinger::MixerThread::OutputTrack::clearBufferQueue()
2158{
2159 size_t size = mBufferQueue.size();
2160 Buffer *pBuffer;
2161
2162 for (size_t i = 0; i < size; i++) {
2163 pBuffer = mBufferQueue.itemAt(i);
2164 delete [] pBuffer->mBuffer;
2165 delete pBuffer;
2166 }
2167 mBufferQueue.clear();
2168}
2169
2170// ----------------------------------------------------------------------------
2171
2172AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2173 : RefBase(),
2174 mAudioFlinger(audioFlinger),
2175 mMemoryDealer(new MemoryDealer(1024*1024)),
2176 mPid(pid)
2177{
2178 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2179}
2180
2181AudioFlinger::Client::~Client()
2182{
2183 mAudioFlinger->removeClient(mPid);
2184}
2185
2186const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2187{
2188 return mMemoryDealer;
2189}
2190
2191// ----------------------------------------------------------------------------
2192
2193AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::MixerThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002194 : BnAudioTrack(),
2195 mTrack(track)
2196{
2197}
2198
2199AudioFlinger::TrackHandle::~TrackHandle() {
2200 // just stop the track on deletion, associated resources
2201 // will be freed from the main thread once all pending buffers have
2202 // been played. Unless it's not in the active track list, in which
2203 // case we free everything now...
2204 mTrack->destroy();
2205}
2206
2207status_t AudioFlinger::TrackHandle::start() {
2208 return mTrack->start();
2209}
2210
2211void AudioFlinger::TrackHandle::stop() {
2212 mTrack->stop();
2213}
2214
2215void AudioFlinger::TrackHandle::flush() {
2216 mTrack->flush();
2217}
2218
2219void AudioFlinger::TrackHandle::mute(bool e) {
2220 mTrack->mute(e);
2221}
2222
2223void AudioFlinger::TrackHandle::pause() {
2224 mTrack->pause();
2225}
2226
2227void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2228 mTrack->setVolume(left, right);
2229}
2230
2231sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2232 return mTrack->getCblk();
2233}
2234
2235status_t AudioFlinger::TrackHandle::onTransact(
2236 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2237{
2238 return BnAudioTrack::onTransact(code, data, reply, flags);
2239}
2240
2241// ----------------------------------------------------------------------------
2242
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002243sp<IAudioRecord> AudioFlinger::openRecord(
2244 pid_t pid,
2245 int streamType,
2246 uint32_t sampleRate,
2247 int format,
2248 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002249 int frameCount,
2250 uint32_t flags,
2251 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002252{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253 sp<MixerThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002254 sp<RecordHandle> recordHandle;
2255 sp<Client> client;
2256 wp<Client> wclient;
2257 AudioStreamIn* input = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002258 int inFrameCount;
2259 size_t inputBufferSize;
2260 status_t lStatus;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002261
2262 // check calling permissions
2263 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002264 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002265 goto Exit;
2266 }
2267
2268 if (uint32_t(streamType) >= AudioRecord::NUM_STREAM_TYPES) {
2269 LOGE("invalid stream type");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002270 lStatus = BAD_VALUE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002271 goto Exit;
2272 }
2273
2274 if (sampleRate > MAX_SAMPLE_RATE) {
2275 LOGE("Sample rate out of range");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002276 lStatus = BAD_VALUE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002277 goto Exit;
2278 }
2279
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002280 if (mAudioRecordThread == 0) {
2281 LOGE("Audio record thread not started");
2282 lStatus = NO_INIT;
2283 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002284 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002285
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002286
2287 // Check that audio input stream accepts requested audio parameters
2288 inputBufferSize = mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
2289 if (inputBufferSize == 0) {
2290 lStatus = BAD_VALUE;
2291 LOGE("Bad audio input parameters: sampling rate %u, format %d, channels %d", sampleRate, format, channelCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002292 goto Exit;
2293 }
2294
2295 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002296 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002297 Mutex::Autolock _l(mLock);
2298 wclient = mClients.valueFor(pid);
2299 if (wclient != NULL) {
2300 client = wclient.promote();
2301 } else {
2302 client = new Client(this, pid);
2303 mClients.add(pid, client);
2304 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002305
2306 // frameCount must be a multiple of input buffer size
2307 inFrameCount = inputBufferSize/channelCount/sizeof(short);
2308 frameCount = ((frameCount - 1)/inFrameCount + 1) * inFrameCount;
2309
2310 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
2311 recordTrack = new MixerThread::RecordTrack(mHardwareMixerThread, client, streamType, sampleRate,
2312 format, channelCount, frameCount, flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 if (recordTrack->getCblk() == NULL) {
2315 recordTrack.clear();
2316 lStatus = NO_MEMORY;
2317 goto Exit;
2318 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002319
2320 // return to handle to client
2321 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002322 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002323
2324Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002325 if (status) {
2326 *status = lStatus;
2327 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002328 return recordHandle;
2329}
2330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331status_t AudioFlinger::startRecord(MixerThread::RecordTrack* recordTrack) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002332 if (mAudioRecordThread != 0) {
2333 return mAudioRecordThread->start(recordTrack);
2334 }
2335 return NO_INIT;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002336}
2337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338void AudioFlinger::stopRecord(MixerThread::RecordTrack* recordTrack) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002339 if (mAudioRecordThread != 0) {
2340 mAudioRecordThread->stop(recordTrack);
2341 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002342}
2343
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002344// ----------------------------------------------------------------------------
2345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::MixerThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002347 : BnAudioRecord(),
2348 mRecordTrack(recordTrack)
2349{
2350}
2351
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002352AudioFlinger::RecordHandle::~RecordHandle() {
2353 stop();
2354}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002355
2356status_t AudioFlinger::RecordHandle::start() {
2357 LOGV("RecordHandle::start()");
2358 return mRecordTrack->start();
2359}
2360
2361void AudioFlinger::RecordHandle::stop() {
2362 LOGV("RecordHandle::stop()");
2363 mRecordTrack->stop();
2364}
2365
2366sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
2367 return mRecordTrack->getCblk();
2368}
2369
2370status_t AudioFlinger::RecordHandle::onTransact(
2371 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2372{
2373 return BnAudioRecord::onTransact(code, data, reply, flags);
2374}
2375
2376// ----------------------------------------------------------------------------
2377
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002378AudioFlinger::AudioRecordThread::AudioRecordThread(AudioHardwareInterface* audioHardware,
2379 const sp<AudioFlinger>& audioFlinger) :
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002380 mAudioHardware(audioHardware),
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002381 mAudioFlinger(audioFlinger),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002382 mActive(false)
2383{
2384}
2385
2386AudioFlinger::AudioRecordThread::~AudioRecordThread()
2387{
2388}
2389
2390bool AudioFlinger::AudioRecordThread::threadLoop()
2391{
2392 LOGV("AudioRecordThread: start record loop");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002393 AudioBufferProvider::Buffer buffer;
2394 int inBufferSize = 0;
2395 int inFrameCount = 0;
2396 AudioStreamIn* input = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002397
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002398 mActive = 0;
2399
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002400 // start recording
2401 while (!exitPending()) {
2402 if (!mActive) {
2403 mLock.lock();
2404 if (!mActive && !exitPending()) {
2405 LOGV("AudioRecordThread: loop stopping");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002406 if (input) {
2407 delete input;
2408 input = 0;
2409 }
2410 mRecordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 mStopped.signal();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002412
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002413 mWaitWorkCV.wait(mLock);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002414
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002415 LOGV("AudioRecordThread: loop starting");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002416 if (mRecordTrack != 0) {
2417 input = mAudioHardware->openInputStream(mRecordTrack->format(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 mRecordTrack->channelCount(),
2419 mRecordTrack->sampleRate(),
2420 &mStartStatus,
2421 (AudioSystem::audio_in_acoustics)(mRecordTrack->mFlags >> 16));
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002422 if (input != 0) {
2423 inBufferSize = input->bufferSize();
2424 inFrameCount = inBufferSize/input->frameSize();
2425 }
2426 } else {
2427 mStartStatus = NO_INIT;
2428 }
2429 if (mStartStatus !=NO_ERROR) {
2430 LOGW("record start failed, status %d", mStartStatus);
2431 mActive = false;
2432 mRecordTrack.clear();
2433 }
2434 mWaitWorkCV.signal();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002435 }
2436 mLock.unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 } else if (mRecordTrack != 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002438
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002439 buffer.frameCount = inFrameCount;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002440 if (LIKELY(mRecordTrack->getNextBuffer(&buffer) == NO_ERROR &&
2441 (int)buffer.frameCount == inFrameCount)) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002442 LOGV("AudioRecordThread read: %d frames", buffer.frameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 ssize_t bytesRead = input->read(buffer.raw, inBufferSize);
2444 if (bytesRead < 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002445 LOGE("Error reading audio input");
2446 sleep(1);
2447 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002448 mRecordTrack->releaseBuffer(&buffer);
2449 mRecordTrack->overflow();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002450 }
2451
2452 // client isn't retrieving buffers fast enough
2453 else {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002454 if (!mRecordTrack->setOverflow())
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002455 LOGW("AudioRecordThread: buffer overflow");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002456 // Release the processor for a while before asking for a new buffer.
2457 // This will give the application more chance to read from the buffer and
2458 // clear the overflow.
2459 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002460 }
2461 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002462 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002463
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002464
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002465 if (input) {
2466 delete input;
2467 }
2468 mRecordTrack.clear();
2469
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002470 return false;
2471}
2472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473status_t AudioFlinger::AudioRecordThread::start(MixerThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002474{
2475 LOGV("AudioRecordThread::start");
2476 AutoMutex lock(&mLock);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002477 mActive = true;
2478 // If starting the active track, just reset mActive in case a stop
2479 // was pending and exit
2480 if (recordTrack == mRecordTrack.get()) return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002481
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002482 if (mRecordTrack != 0) return -EBUSY;
2483
2484 mRecordTrack = recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002485
2486 // signal thread to start
2487 LOGV("Signal record thread");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002488 mWaitWorkCV.signal();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002489 mWaitWorkCV.wait(mLock);
2490 LOGV("Record started, status %d", mStartStatus);
2491 return mStartStatus;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002492}
2493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494void AudioFlinger::AudioRecordThread::stop(MixerThread::RecordTrack* recordTrack) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002495 LOGV("AudioRecordThread::stop");
2496 AutoMutex lock(&mLock);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002497 if (mActive && (recordTrack == mRecordTrack.get())) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002498 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 mStopped.wait(mLock);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002500 }
2501}
2502
2503void AudioFlinger::AudioRecordThread::exit()
2504{
2505 LOGV("AudioRecordThread::exit");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002506 {
2507 AutoMutex lock(&mLock);
2508 requestExit();
2509 mWaitWorkCV.signal();
2510 }
2511 requestExitAndWait();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002512}
2513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514status_t AudioFlinger::AudioRecordThread::dump(int fd, const Vector<String16>& args)
2515{
2516 const size_t SIZE = 256;
2517 char buffer[SIZE];
2518 String8 result;
2519 pid_t pid = 0;
2520
2521 if (mRecordTrack != 0 && mRecordTrack->mClient != 0) {
2522 snprintf(buffer, SIZE, "Record client pid: %d\n", mRecordTrack->mClient->pid());
2523 result.append(buffer);
2524 } else {
2525 result.append("No record client\n");
2526 }
2527 write(fd, result.string(), result.size());
2528 return NO_ERROR;
2529}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002530
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002531status_t AudioFlinger::onTransact(
2532 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2533{
2534 return BnAudioFlinger::onTransact(code, data, reply, flags);
2535}
2536
2537// ----------------------------------------------------------------------------
2538void AudioFlinger::instantiate() {
2539 defaultServiceManager()->addService(
2540 String16("media.audio_flinger"), new AudioFlinger());
2541}
2542
2543}; // namespace android