blob: 04cfa089f8863ecee86c57d8a8a04dcabc515f4c [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"
Eric Laurent7d850f22010-07-09 13:34:17 -070020//#define LOG_NDEBUG 0
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070021
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9b3f1522011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian07952722009-05-19 19:08:10 -070028#include <binder/IServiceManager.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070029#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070030#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurentae29b762011-03-28 18:37:07 -070034#include <utils/Atomic.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080036#include <cutils/properties.h>
37
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038#include <media/AudioTrack.h>
39#include <media/AudioRecord.h>
Gloria Wang9b3f1522011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041
42#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070043#include <private/media/AudioEffectShared.h>
The Android Open Source Project9266c552009-01-15 16:12:10 -080044#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070045
46#include "AudioMixer.h"
47#include "AudioFlinger.h"
48
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080049#ifdef WITH_A2DP
50#include "A2dpAudioInterface.h"
51#endif
52
Eric Laurent53334cd2010-06-23 17:38:20 -070053#include <media/EffectsFactoryApi.h>
Eric Laurentdf9b81c2010-07-02 08:12:41 -070054#include <media/EffectVisualizerApi.h>
Eric Laurent65b65452010-06-01 23:49:17 -070055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056// ----------------------------------------------------------------------------
57// the sim build doesn't have gettid
58
59#ifndef HAVE_GETTID
60# define gettid getpid
61#endif
62
63// ----------------------------------------------------------------------------
64
Eric Laurent8ed6ed02010-07-13 04:45:46 -070065extern const char * const gEffectLibPath;
66
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070067namespace android {
68
The Android Open Source Project10592532009-03-18 17:39:46 -070069static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
70static const char* kHardwareLockedString = "Hardware lock is taken\n";
71
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080072//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070073static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070074static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070075
76// retry counts for buffer fill timeout
77// 50 * ~20msecs = 1 second
78static const int8_t kMaxTrackRetries = 50;
79static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080080// allow less retry attempts on direct output thread.
81// direct outputs can be a scarce resource in audio hardware and should
82// be released as quickly as possible.
83static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070084
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070085static const int kDumpLockRetries = 50;
86static const int kDumpLockSleep = 20000;
87
Dave Sparksd0ac8c02009-09-30 03:09:03 -070088static const nsecs_t kWarningThrottle = seconds(5);
89
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070091#define AUDIOFLINGER_SECURITY_ENABLED 1
92
93// ----------------------------------------------------------------------------
94
95static bool recordingAllowed() {
96#ifndef HAVE_ANDROID_OS
97 return true;
98#endif
99#if AUDIOFLINGER_SECURITY_ENABLED
100 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
101 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
102 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
103 return ok;
104#else
105 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
106 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
107 return true;
108#endif
109}
110
111static bool settingsAllowed() {
112#ifndef HAVE_ANDROID_OS
113 return true;
114#endif
115#if AUDIOFLINGER_SECURITY_ENABLED
116 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
117 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
118 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
119 return ok;
120#else
121 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
122 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
123 return true;
124#endif
125}
126
Gloria Wang9b3f1522011-02-24 14:51:45 -0800127// To collect the amplifier usage
128static void addBatteryData(uint32_t params) {
129 sp<IBinder> binder =
130 defaultServiceManager()->getService(String16("media.player"));
131 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
132 if (service.get() == NULL) {
133 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
134 return;
135 }
136
137 service->addBatteryData(params);
138}
139
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700140// ----------------------------------------------------------------------------
141
142AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 : BnAudioFlinger(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700144 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700145{
Eric Laurent01635942011-01-18 18:39:02 -0800146 Mutex::Autolock _l(mLock);
147
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700148 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700149
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700150 mAudioHardware = AudioHardwareInterface::create();
Eric Laurenta553c252009-07-17 12:17:14 -0700151
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700152 mHardwareStatus = AUDIO_HW_INIT;
153 if (mAudioHardware->initCheck() == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800154 AutoMutex lock(mHardwareLock);
Eric Laurent53334cd2010-06-23 17:38:20 -0700155 mMode = AudioSystem::MODE_NORMAL;
Eric Laurent01635942011-01-18 18:39:02 -0800156 mHardwareStatus = AUDIO_HW_SET_MODE;
157 mAudioHardware->setMode(mMode);
158 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
159 mAudioHardware->setMasterVolume(1.0f);
160 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700161 } else {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700162 LOGE("Couldn't even initialize the stubbed audio hardware!");
163 }
164}
165
166AudioFlinger::~AudioFlinger()
167{
Eric Laurent7954c462009-08-28 10:39:03 -0700168 while (!mRecordThreads.isEmpty()) {
169 // closeInput() will remove first entry from mRecordThreads
170 closeInput(mRecordThreads.keyAt(0));
171 }
172 while (!mPlaybackThreads.isEmpty()) {
173 // closeOutput() will remove first entry from mPlaybackThreads
174 closeOutput(mPlaybackThreads.keyAt(0));
175 }
176 if (mAudioHardware) {
177 delete mAudioHardware;
178 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800179}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800180
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700181
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700182
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700183status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
184{
185 const size_t SIZE = 256;
186 char buffer[SIZE];
187 String8 result;
188
189 result.append("Clients:\n");
190 for (size_t i = 0; i < mClients.size(); ++i) {
191 wp<Client> wClient = mClients.valueAt(i);
192 if (wClient != 0) {
193 sp<Client> client = wClient.promote();
194 if (client != 0) {
195 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
196 result.append(buffer);
197 }
198 }
199 }
200 write(fd, result.string(), result.size());
201 return NO_ERROR;
202}
203
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700204
205status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
206{
207 const size_t SIZE = 256;
208 char buffer[SIZE];
209 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700210 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700211
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700212 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700213 result.append(buffer);
214 write(fd, result.string(), result.size());
215 return NO_ERROR;
216}
217
218status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
219{
220 const size_t SIZE = 256;
221 char buffer[SIZE];
222 String8 result;
223 snprintf(buffer, SIZE, "Permission Denial: "
224 "can't dump AudioFlinger from pid=%d, uid=%d\n",
225 IPCThreadState::self()->getCallingPid(),
226 IPCThreadState::self()->getCallingUid());
227 result.append(buffer);
228 write(fd, result.string(), result.size());
229 return NO_ERROR;
230}
231
The Android Open Source Project10592532009-03-18 17:39:46 -0700232static bool tryLock(Mutex& mutex)
233{
234 bool locked = false;
235 for (int i = 0; i < kDumpLockRetries; ++i) {
236 if (mutex.tryLock() == NO_ERROR) {
237 locked = true;
238 break;
239 }
240 usleep(kDumpLockSleep);
241 }
242 return locked;
243}
244
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700245status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
246{
247 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
248 dumpPermissionDenial(fd, args);
249 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700250 // get state of hardware lock
251 bool hardwareLocked = tryLock(mHardwareLock);
252 if (!hardwareLocked) {
253 String8 result(kHardwareLockedString);
254 write(fd, result.string(), result.size());
255 } else {
256 mHardwareLock.unlock();
257 }
258
259 bool locked = tryLock(mLock);
260
261 // failed to lock - AudioFlinger is probably deadlocked
262 if (!locked) {
263 String8 result(kDeadlockedString);
264 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700265 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700266
267 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700268 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269
Eric Laurenta553c252009-07-17 12:17:14 -0700270 // dump playback threads
271 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700272 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700273 }
274
275 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700276 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700277 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700280 if (mAudioHardware) {
281 mAudioHardware->dumpState(fd, args);
282 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700283 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700284 }
285 return NO_ERROR;
286}
287
Eric Laurenta553c252009-07-17 12:17:14 -0700288
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700289// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290
291
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700292sp<IAudioTrack> AudioFlinger::createTrack(
293 pid_t pid,
294 int streamType,
295 uint32_t sampleRate,
296 int format,
297 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800298 int frameCount,
299 uint32_t flags,
300 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700301 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700302 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800303 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700304{
Eric Laurenta553c252009-07-17 12:17:14 -0700305 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700306 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700307 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800308 wp<Client> wclient;
309 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700310 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800313 LOGE("invalid stream type");
314 lStatus = BAD_VALUE;
315 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700316 }
317
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800318 {
319 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700320 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700321 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700322 if (thread == NULL) {
323 LOGE("unknown output thread");
324 lStatus = BAD_VALUE;
325 goto Exit;
326 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800327
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800328 wclient = mClients.valueFor(pid);
329
330 if (wclient != NULL) {
331 client = wclient.promote();
332 } else {
333 client = new Client(this, pid);
334 mClients.add(pid, client);
335 }
Eric Laurent65b65452010-06-01 23:49:17 -0700336
Eric Laurent65b65452010-06-01 23:49:17 -0700337 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700338 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700339 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700340 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
341 if (mPlaybackThreads.keyAt(i) != output) {
342 // prevent same audio session on different output threads
343 uint32_t sessions = t->hasAudioSession(*sessionId);
344 if (sessions & PlaybackThread::TRACK_SESSION) {
345 lStatus = BAD_VALUE;
346 goto Exit;
347 }
348 // check if an effect with same session ID is waiting for a track to be created
349 if (sessions & PlaybackThread::EFFECT_SESSION) {
350 effectThread = t.get();
351 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700352 }
353 }
Eric Laurent65b65452010-06-01 23:49:17 -0700354 lSessionId = *sessionId;
355 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700356 // if no audio session id is provided, create one here
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800357 lSessionId = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -0700358 if (sessionId != NULL) {
359 *sessionId = lSessionId;
360 }
361 }
362 LOGV("createTrack() lSessionId: %d", lSessionId);
363
Eric Laurenta553c252009-07-17 12:17:14 -0700364 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -0700365 channelCount, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700366
367 // move effect chain to this output thread if an effect on same session was waiting
368 // for a track to be created
369 if (lStatus == NO_ERROR && effectThread != NULL) {
370 Mutex::Autolock _dl(thread->mLock);
371 Mutex::Autolock _sl(effectThread->mLock);
372 moveEffectChain_l(lSessionId, effectThread, thread, true);
373 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700374 }
375 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800376 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700377 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700378 // remove local strong reference to Client before deleting the Track so that the Client
379 // destructor is called by the TrackBase destructor with mLock held
380 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700381 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800382 }
383
384Exit:
385 if(status) {
386 *status = lStatus;
387 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700388 return trackHandle;
389}
390
Eric Laurentddb78e72009-07-28 08:44:33 -0700391uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700392{
Eric Laurenta553c252009-07-17 12:17:14 -0700393 Mutex::Autolock _l(mLock);
394 PlaybackThread *thread = checkPlaybackThread_l(output);
395 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700396 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700397 return 0;
398 }
399 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700400}
401
Eric Laurentddb78e72009-07-28 08:44:33 -0700402int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700403{
Eric Laurenta553c252009-07-17 12:17:14 -0700404 Mutex::Autolock _l(mLock);
405 PlaybackThread *thread = checkPlaybackThread_l(output);
406 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700407 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700408 return 0;
409 }
410 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700411}
412
Eric Laurentddb78e72009-07-28 08:44:33 -0700413int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700414{
Eric Laurenta553c252009-07-17 12:17:14 -0700415 Mutex::Autolock _l(mLock);
416 PlaybackThread *thread = checkPlaybackThread_l(output);
417 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700418 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700419 return 0;
420 }
421 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700422}
423
Eric Laurentddb78e72009-07-28 08:44:33 -0700424size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700425{
Eric Laurenta553c252009-07-17 12:17:14 -0700426 Mutex::Autolock _l(mLock);
427 PlaybackThread *thread = checkPlaybackThread_l(output);
428 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700429 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700430 return 0;
431 }
432 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700433}
434
Eric Laurentddb78e72009-07-28 08:44:33 -0700435uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800436{
Eric Laurenta553c252009-07-17 12:17:14 -0700437 Mutex::Autolock _l(mLock);
438 PlaybackThread *thread = checkPlaybackThread_l(output);
439 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700440 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700441 return 0;
442 }
443 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800444}
445
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700446status_t AudioFlinger::setMasterVolume(float value)
447{
448 // check calling permissions
449 if (!settingsAllowed()) {
450 return PERMISSION_DENIED;
451 }
452
453 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800454 { // scope for the lock
455 AutoMutex lock(mHardwareLock);
456 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
457 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
458 value = 1.0f;
459 }
460 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700461 }
Eric Laurenta553c252009-07-17 12:17:14 -0700462
Eric Laurent01635942011-01-18 18:39:02 -0800463 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700464 mMasterVolume = value;
465 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700466 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700467
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700468 return NO_ERROR;
469}
470
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700471status_t AudioFlinger::setMode(int mode)
472{
Eric Laurent53334cd2010-06-23 17:38:20 -0700473 status_t ret;
474
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700475 // check calling permissions
476 if (!settingsAllowed()) {
477 return PERMISSION_DENIED;
478 }
479 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
480 LOGW("Illegal value: setMode(%d)", mode);
481 return BAD_VALUE;
482 }
483
Eric Laurent53334cd2010-06-23 17:38:20 -0700484 { // scope for the lock
485 AutoMutex lock(mHardwareLock);
486 mHardwareStatus = AUDIO_HW_SET_MODE;
487 ret = mAudioHardware->setMode(mode);
488 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800489 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700490
491 if (NO_ERROR == ret) {
492 Mutex::Autolock _l(mLock);
493 mMode = mode;
494 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
495 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700496 }
497
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700498 return ret;
499}
500
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700501status_t AudioFlinger::setMicMute(bool state)
502{
503 // check calling permissions
504 if (!settingsAllowed()) {
505 return PERMISSION_DENIED;
506 }
507
508 AutoMutex lock(mHardwareLock);
509 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
510 status_t ret = mAudioHardware->setMicMute(state);
511 mHardwareStatus = AUDIO_HW_IDLE;
512 return ret;
513}
514
515bool AudioFlinger::getMicMute() const
516{
517 bool state = AudioSystem::MODE_INVALID;
518 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
519 mAudioHardware->getMicMute(&state);
520 mHardwareStatus = AUDIO_HW_IDLE;
521 return state;
522}
523
524status_t AudioFlinger::setMasterMute(bool muted)
525{
526 // check calling permissions
527 if (!settingsAllowed()) {
528 return PERMISSION_DENIED;
529 }
Eric Laurenta553c252009-07-17 12:17:14 -0700530
Eric Laurent01635942011-01-18 18:39:02 -0800531 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700532 mMasterMute = muted;
533 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700534 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700535
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700536 return NO_ERROR;
537}
538
539float AudioFlinger::masterVolume() const
540{
Eric Laurenta553c252009-07-17 12:17:14 -0700541 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700542}
543
544bool AudioFlinger::masterMute() const
545{
Eric Laurenta553c252009-07-17 12:17:14 -0700546 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700547}
548
Eric Laurentddb78e72009-07-28 08:44:33 -0700549status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700550{
551 // check calling permissions
552 if (!settingsAllowed()) {
553 return PERMISSION_DENIED;
554 }
555
Eric Laurenta553c252009-07-17 12:17:14 -0700556 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700557 return BAD_VALUE;
558 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800559
Eric Laurenta553c252009-07-17 12:17:14 -0700560 AutoMutex lock(mLock);
561 PlaybackThread *thread = NULL;
562 if (output) {
563 thread = checkPlaybackThread_l(output);
564 if (thread == NULL) {
565 return BAD_VALUE;
566 }
567 }
568
Eric Laurenta553c252009-07-17 12:17:14 -0700569 mStreamTypes[stream].volume = value;
570
571 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700572 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700573 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700574 }
Eric Laurenta553c252009-07-17 12:17:14 -0700575 } else {
576 thread->setStreamVolume(stream, value);
577 }
Eric Laurentef028272009-04-21 07:56:33 -0700578
Eric Laurent415f3e22009-10-21 08:14:22 -0700579 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700580}
581
582status_t AudioFlinger::setStreamMute(int stream, bool muted)
583{
584 // check calling permissions
585 if (!settingsAllowed()) {
586 return PERMISSION_DENIED;
587 }
588
Eric Laurenta553c252009-07-17 12:17:14 -0700589 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurenteeea9222009-03-26 01:57:59 -0700590 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700591 return BAD_VALUE;
592 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700593
Eric Laurent01635942011-01-18 18:39:02 -0800594 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700595 mStreamTypes[stream].mute = muted;
596 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700597 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700599 return NO_ERROR;
600}
601
Eric Laurentddb78e72009-07-28 08:44:33 -0700602float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700603{
Eric Laurenta553c252009-07-17 12:17:14 -0700604 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700605 return 0.0f;
606 }
Eric Laurenta553c252009-07-17 12:17:14 -0700607
608 AutoMutex lock(mLock);
609 float volume;
610 if (output) {
611 PlaybackThread *thread = checkPlaybackThread_l(output);
612 if (thread == NULL) {
613 return 0.0f;
614 }
615 volume = thread->streamVolume(stream);
616 } else {
617 volume = mStreamTypes[stream].volume;
618 }
619
Eric Laurentef028272009-04-21 07:56:33 -0700620 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700621}
622
623bool AudioFlinger::streamMute(int stream) const
624{
Eric Laurenta553c252009-07-17 12:17:14 -0700625 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700626 return true;
627 }
Eric Laurenta553c252009-07-17 12:17:14 -0700628
629 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700630}
631
Eric Laurentddb78e72009-07-28 08:44:33 -0700632status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700633{
Eric Laurenta553c252009-07-17 12:17:14 -0700634 status_t result;
635
Eric Laurentddb78e72009-07-28 08:44:33 -0700636 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700637 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
638 // check calling permissions
639 if (!settingsAllowed()) {
640 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800641 }
Eric Laurenta553c252009-07-17 12:17:14 -0700642
643 // ioHandle == 0 means the parameters are global to the audio hardware interface
644 if (ioHandle == 0) {
645 AutoMutex lock(mHardwareLock);
646 mHardwareStatus = AUDIO_SET_PARAMETER;
647 result = mAudioHardware->setParameters(keyValuePairs);
648 mHardwareStatus = AUDIO_HW_IDLE;
649 return result;
650 }
651
Eric Laurentb7d94602009-09-29 11:12:57 -0700652 // hold a strong ref on thread in case closeOutput() or closeInput() is called
653 // and the thread is exited once the lock is released
654 sp<ThreadBase> thread;
655 {
656 Mutex::Autolock _l(mLock);
657 thread = checkPlaybackThread_l(ioHandle);
658 if (thread == NULL) {
659 thread = checkRecordThread_l(ioHandle);
660 }
Eric Laurenta553c252009-07-17 12:17:14 -0700661 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700662 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800663 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800664 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700665 }
Eric Laurenta553c252009-07-17 12:17:14 -0700666 return BAD_VALUE;
667}
668
Eric Laurentddb78e72009-07-28 08:44:33 -0700669String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700670{
Eric Laurentddb78e72009-07-28 08:44:33 -0700671// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700672// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
673
674 if (ioHandle == 0) {
675 return mAudioHardware->getParameters(keys);
676 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700677
678 Mutex::Autolock _l(mLock);
679
Eric Laurenta553c252009-07-17 12:17:14 -0700680 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
681 if (playbackThread != NULL) {
682 return playbackThread->getParameters(keys);
683 }
684 RecordThread *recordThread = checkRecordThread_l(ioHandle);
685 if (recordThread != NULL) {
686 return recordThread->getParameters(keys);
687 }
688 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700689}
690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
692{
693 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
694}
695
Eric Laurent47d0a922010-02-26 02:47:27 -0800696unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
697{
698 if (ioHandle == 0) {
699 return 0;
700 }
701
702 Mutex::Autolock _l(mLock);
703
704 RecordThread *recordThread = checkRecordThread_l(ioHandle);
705 if (recordThread != NULL) {
706 return recordThread->getInputFramesLost();
707 }
708 return 0;
709}
710
Eric Laurent415f3e22009-10-21 08:14:22 -0700711status_t AudioFlinger::setVoiceVolume(float value)
712{
713 // check calling permissions
714 if (!settingsAllowed()) {
715 return PERMISSION_DENIED;
716 }
717
718 AutoMutex lock(mHardwareLock);
719 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
720 status_t ret = mAudioHardware->setVoiceVolume(value);
721 mHardwareStatus = AUDIO_HW_IDLE;
722
723 return ret;
724}
725
Eric Laurent0986e792010-01-19 17:37:09 -0800726status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
727{
728 status_t status;
729
730 Mutex::Autolock _l(mLock);
731
732 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
733 if (playbackThread != NULL) {
734 return playbackThread->getRenderPosition(halFrames, dspFrames);
735 }
736
737 return BAD_VALUE;
738}
739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
741{
Eric Laurenta553c252009-07-17 12:17:14 -0700742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 Mutex::Autolock _l(mLock);
744
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700745 int pid = IPCThreadState::self()->getCallingPid();
746 if (mNotificationClients.indexOfKey(pid) < 0) {
747 sp<NotificationClient> notificationClient = new NotificationClient(this,
748 client,
749 pid);
750 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700751
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700752 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700753
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700754 sp<IBinder> binder = client->asBinder();
755 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700757 // the config change is always sent from playback or record threads to avoid deadlock
758 // with AudioSystem::gLock
759 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
760 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
761 }
Eric Laurenta553c252009-07-17 12:17:14 -0700762
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700763 for (size_t i = 0; i < mRecordThreads.size(); i++) {
764 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 }
766 }
767}
768
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700769void AudioFlinger::removeNotificationClient(pid_t pid)
770{
771 Mutex::Autolock _l(mLock);
772
773 int index = mNotificationClients.indexOfKey(pid);
774 if (index >= 0) {
775 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
776 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700777 mNotificationClients.removeItem(pid);
778 }
779}
780
Eric Laurent296a0ec2009-09-15 07:10:12 -0700781// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700782void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
783{
Eric Laurent49f02be2009-11-19 09:00:56 -0800784 size_t size = mNotificationClients.size();
785 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700786 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700787 }
788}
789
Eric Laurentb9481d82009-09-17 05:12:56 -0700790// removeClient_l() must be called with AudioFlinger::mLock held
791void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700792{
Eric Laurentb9481d82009-09-17 05:12:56 -0700793 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700794 mClients.removeItem(pid);
795}
796
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700797
Eric Laurenta553c252009-07-17 12:17:14 -0700798// ----------------------------------------------------------------------------
799
Eric Laurent49f02be2009-11-19 09:00:56 -0800800AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurenta553c252009-07-17 12:17:14 -0700801 : Thread(false),
802 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentb0a01472010-05-14 05:45:46 -0700803 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700804{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805}
806
Eric Laurenta553c252009-07-17 12:17:14 -0700807AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700809 mParamCond.broadcast();
810 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811}
812
Eric Laurenta553c252009-07-17 12:17:14 -0700813void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700814{
Eric Laurentb7d94602009-09-29 11:12:57 -0700815 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700816 // destroyed in the middle of requestExitAndWait()
817 sp <ThreadBase> strongMe = this;
818
819 LOGV("ThreadBase::exit");
820 {
821 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800822 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700823 requestExit();
824 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700825 }
Eric Laurenta553c252009-07-17 12:17:14 -0700826 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700827}
Eric Laurenta553c252009-07-17 12:17:14 -0700828
829uint32_t AudioFlinger::ThreadBase::sampleRate() const
830{
831 return mSampleRate;
832}
833
834int AudioFlinger::ThreadBase::channelCount() const
835{
Eric Laurentb0a01472010-05-14 05:45:46 -0700836 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -0700837}
838
839int AudioFlinger::ThreadBase::format() const
840{
841 return mFormat;
842}
843
844size_t AudioFlinger::ThreadBase::frameCount() const
845{
846 return mFrameCount;
847}
848
849status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
850{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700851 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700852
Eric Laurent8fce46a2009-08-04 09:45:33 -0700853 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700854 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700855
Eric Laurent8fce46a2009-08-04 09:45:33 -0700856 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700857 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700858 // wait condition with timeout in case the thread loop has exited
859 // before the request could be processed
860 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
861 status = mParamStatus;
862 mWaitWorkCV.signal();
863 } else {
864 status = TIMED_OUT;
865 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700866 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700867}
868
869void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
870{
871 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700872 sendConfigEvent_l(event, param);
873}
874
875// sendConfigEvent_l() must be called with ThreadBase::mLock held
876void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
877{
Eric Laurenta553c252009-07-17 12:17:14 -0700878 ConfigEvent *configEvent = new ConfigEvent();
879 configEvent->mEvent = event;
880 configEvent->mParam = param;
881 mConfigEvents.add(configEvent);
882 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
883 mWaitWorkCV.signal();
884}
885
886void AudioFlinger::ThreadBase::processConfigEvents()
887{
888 mLock.lock();
889 while(!mConfigEvents.isEmpty()) {
890 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
891 ConfigEvent *configEvent = mConfigEvents[0];
892 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700893 // release mLock before locking AudioFlinger mLock: lock order is always
894 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -0700895 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700896 mAudioFlinger->mLock.lock();
897 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
898 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -0700899 delete configEvent;
900 mLock.lock();
901 }
902 mLock.unlock();
903}
904
Eric Laurent3fdb1262009-11-07 00:01:32 -0800905status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
906{
907 const size_t SIZE = 256;
908 char buffer[SIZE];
909 String8 result;
910
911 bool locked = tryLock(mLock);
912 if (!locked) {
913 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
914 write(fd, buffer, strlen(buffer));
915 }
916
917 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
918 result.append(buffer);
919 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
920 result.append(buffer);
921 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
922 result.append(buffer);
923 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
924 result.append(buffer);
925 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
926 result.append(buffer);
927 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
928 result.append(buffer);
929
930 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
931 result.append(buffer);
932 result.append(" Index Command");
933 for (size_t i = 0; i < mNewParameters.size(); ++i) {
934 snprintf(buffer, SIZE, "\n %02d ", i);
935 result.append(buffer);
936 result.append(mNewParameters[i]);
937 }
938
939 snprintf(buffer, SIZE, "\n\nPending config events: \n");
940 result.append(buffer);
941 snprintf(buffer, SIZE, " Index event param\n");
942 result.append(buffer);
943 for (size_t i = 0; i < mConfigEvents.size(); i++) {
944 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
945 result.append(buffer);
946 }
947 result.append("\n");
948
949 write(fd, result.string(), result.size());
950
951 if (locked) {
952 mLock.unlock();
953 }
954 return NO_ERROR;
955}
956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957
958// ----------------------------------------------------------------------------
959
Eric Laurent65b65452010-06-01 23:49:17 -0700960AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent49f02be2009-11-19 09:00:56 -0800961 : ThreadBase(audioFlinger, id),
Eric Laurentd5603c12009-08-06 08:49:39 -0700962 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent65b65452010-06-01 23:49:17 -0700963 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
964 mDevice(device)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965{
Eric Laurenta553c252009-07-17 12:17:14 -0700966 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967
Eric Laurenta553c252009-07-17 12:17:14 -0700968 mMasterVolume = mAudioFlinger->masterVolume();
969 mMasterMute = mAudioFlinger->masterMute();
970
971 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
972 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
973 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975}
976
Eric Laurenta553c252009-07-17 12:17:14 -0700977AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978{
979 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980}
981
Eric Laurenta553c252009-07-17 12:17:14 -0700982status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983{
984 dumpInternals(fd, args);
985 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -0700986 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 return NO_ERROR;
988}
989
Eric Laurenta553c252009-07-17 12:17:14 -0700990status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991{
992 const size_t SIZE = 256;
993 char buffer[SIZE];
994 String8 result;
995
Eric Laurenta553c252009-07-17 12:17:14 -0700996 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -0700998 result.append(" Name Clien Typ Fmt Chn Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001000 sp<Track> track = mTracks[i];
1001 if (track != 0) {
1002 track->dump(buffer, SIZE);
1003 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 }
1005 }
1006
Eric Laurenta553c252009-07-17 12:17:14 -07001007 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001009 result.append(" Name Clien Typ Fmt Chn Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001011 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 if (wTrack != 0) {
1013 sp<Track> track = wTrack.promote();
1014 if (track != 0) {
1015 track->dump(buffer, SIZE);
1016 result.append(buffer);
1017 }
1018 }
1019 }
1020 write(fd, result.string(), result.size());
1021 return NO_ERROR;
1022}
1023
Eric Laurent65b65452010-06-01 23:49:17 -07001024status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1025{
1026 const size_t SIZE = 256;
1027 char buffer[SIZE];
1028 String8 result;
1029
1030 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1031 write(fd, buffer, strlen(buffer));
1032
1033 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1034 sp<EffectChain> chain = mEffectChains[i];
1035 if (chain != 0) {
1036 chain->dump(fd, args);
1037 }
1038 }
1039 return NO_ERROR;
1040}
1041
Eric Laurenta553c252009-07-17 12:17:14 -07001042status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043{
1044 const size_t SIZE = 256;
1045 char buffer[SIZE];
1046 String8 result;
1047
Eric Laurent3fdb1262009-11-07 00:01:32 -08001048 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 result.append(buffer);
1050 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1051 result.append(buffer);
1052 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1053 result.append(buffer);
1054 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1055 result.append(buffer);
1056 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1057 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001058 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1059 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001060 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1061 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001063
1064 dumpBase(fd, args);
1065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 return NO_ERROR;
1067}
1068
1069// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001070status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071{
1072 if (mSampleRate == 0) {
1073 LOGE("No working audio driver found.");
1074 return NO_INIT;
1075 }
Eric Laurenta553c252009-07-17 12:17:14 -07001076 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 return NO_ERROR;
1078}
1079
Eric Laurenta553c252009-07-17 12:17:14 -07001080void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081{
1082 const size_t SIZE = 256;
1083 char buffer[SIZE];
1084
Eric Laurenta553c252009-07-17 12:17:14 -07001085 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086
1087 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1088}
1089
Eric Laurenta553c252009-07-17 12:17:14 -07001090// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1091sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 const sp<AudioFlinger::Client>& client,
1093 int streamType,
1094 uint32_t sampleRate,
1095 int format,
1096 int channelCount,
1097 int frameCount,
1098 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001099 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 status_t *status)
1101{
1102 sp<Track> track;
1103 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001104
1105 if (mType == DIRECT) {
Eric Laurentb0a01472010-05-14 05:45:46 -07001106 if (sampleRate != mSampleRate || format != mFormat || channelCount != (int)mChannelCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001107 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1108 sampleRate, format, channelCount, mOutput);
1109 lStatus = BAD_VALUE;
1110 goto Exit;
1111 }
1112 } else {
1113 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1114 if (sampleRate > mSampleRate*2) {
1115 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1116 lStatus = BAD_VALUE;
1117 goto Exit;
1118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 }
1120
Eric Laurenta553c252009-07-17 12:17:14 -07001121 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001122 LOGE("Audio driver not initialized.");
1123 lStatus = NO_INIT;
1124 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 }
1126
Eric Laurenta553c252009-07-17 12:17:14 -07001127 { // scope for mLock
1128 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001129
1130 // all tracks in same audio session must share the same routing strategy otherwise
1131 // conflicts will happen when tracks are moved from one output to another by audio policy
1132 // manager
1133 uint32_t strategy =
1134 AudioSystem::getStrategyForStream((AudioSystem::stream_type)streamType);
1135 for (size_t i = 0; i < mTracks.size(); ++i) {
1136 sp<Track> t = mTracks[i];
1137 if (t != 0) {
1138 if (sessionId == t->sessionId() &&
1139 strategy != AudioSystem::getStrategyForStream((AudioSystem::stream_type)t->type())) {
1140 lStatus = BAD_VALUE;
1141 goto Exit;
1142 }
1143 }
1144 }
1145
Eric Laurenta553c252009-07-17 12:17:14 -07001146 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07001147 channelCount, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001148 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001149 lStatus = NO_MEMORY;
1150 goto Exit;
1151 }
1152 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001153
1154 sp<EffectChain> chain = getEffectChain_l(sessionId);
1155 if (chain != 0) {
1156 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1157 track->setMainBuffer(chain->inBuffer());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001158 chain->setStrategy(AudioSystem::getStrategyForStream((AudioSystem::stream_type)track->type()));
Eric Laurent65b65452010-06-01 23:49:17 -07001159 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001160 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001161 lStatus = NO_ERROR;
1162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163Exit:
1164 if(status) {
1165 *status = lStatus;
1166 }
1167 return track;
1168}
1169
Eric Laurenta553c252009-07-17 12:17:14 -07001170uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171{
1172 if (mOutput) {
1173 return mOutput->latency();
1174 }
1175 else {
1176 return 0;
1177 }
1178}
1179
Eric Laurenta553c252009-07-17 12:17:14 -07001180status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181{
1182 mMasterVolume = value;
1183 return NO_ERROR;
1184}
1185
Eric Laurenta553c252009-07-17 12:17:14 -07001186status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187{
1188 mMasterMute = muted;
1189 return NO_ERROR;
1190}
1191
Eric Laurenta553c252009-07-17 12:17:14 -07001192float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193{
1194 return mMasterVolume;
1195}
1196
Eric Laurenta553c252009-07-17 12:17:14 -07001197bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198{
1199 return mMasterMute;
1200}
1201
Eric Laurenta553c252009-07-17 12:17:14 -07001202status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203{
1204 mStreamTypes[stream].volume = value;
1205 return NO_ERROR;
1206}
1207
Eric Laurenta553c252009-07-17 12:17:14 -07001208status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209{
1210 mStreamTypes[stream].mute = muted;
1211 return NO_ERROR;
1212}
1213
Eric Laurenta553c252009-07-17 12:17:14 -07001214float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215{
1216 return mStreamTypes[stream].volume;
1217}
1218
Eric Laurenta553c252009-07-17 12:17:14 -07001219bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220{
1221 return mStreamTypes[stream].mute;
1222}
1223
Eric Laurenta553c252009-07-17 12:17:14 -07001224// addTrack_l() must be called with ThreadBase::mLock held
1225status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226{
1227 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001228
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001229 // set retry count for buffer fill
1230 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001231 if (mActiveTracks.indexOf(track) < 0) {
1232 // the track is newly added, make sure it fills up all its
1233 // buffers before playing. This is to ensure the client will
1234 // effectively get the latency it requested.
1235 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001236 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001237 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001238 if (track->mainBuffer() != mMixBuffer) {
1239 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1240 if (chain != 0) {
1241 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1242 chain->startTrack();
1243 }
1244 }
1245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001247 }
Eric Laurenta553c252009-07-17 12:17:14 -07001248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001250 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251
1252 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001253}
1254
Eric Laurenta553c252009-07-17 12:17:14 -07001255// destroyTrack_l() must be called with ThreadBase::mLock held
1256void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001257{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001258 track->mState = TrackBase::TERMINATED;
1259 if (mActiveTracks.indexOf(track) < 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001260 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001261 deleteTrackName_l(track->name());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001262 }
1263}
1264
Eric Laurenta553c252009-07-17 12:17:14 -07001265String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001266{
Eric Laurenta553c252009-07-17 12:17:14 -07001267 return mOutput->getParameters(keys);
1268}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001269
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001270// destroyTrack_l() must be called with AudioFlinger::mLock held
1271void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001272 AudioSystem::OutputDescriptor desc;
1273 void *param2 = 0;
1274
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001275 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001276
1277 switch (event) {
1278 case AudioSystem::OUTPUT_OPENED:
1279 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07001280 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07001281 desc.samplingRate = mSampleRate;
1282 desc.format = mFormat;
1283 desc.frameCount = mFrameCount;
1284 desc.latency = latency();
1285 param2 = &desc;
1286 break;
1287
1288 case AudioSystem::STREAM_CONFIG_CHANGED:
1289 param2 = &param;
1290 case AudioSystem::OUTPUT_CLOSED:
1291 default:
1292 break;
1293 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001294 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001295}
1296
1297void AudioFlinger::PlaybackThread::readOutputParameters()
1298{
1299 mSampleRate = mOutput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07001300 mChannels = mOutput->channels();
1301 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07001302 mFormat = mOutput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07001303 mFrameSize = (uint16_t)mOutput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07001304 mFrameCount = mOutput->bufferSize() / mFrameSize;
1305
Eric Laurenta553c252009-07-17 12:17:14 -07001306 // FIXME - Current mixer implementation only supports stereo output: Always
1307 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001308 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001309 mMixBuffer = new int16_t[mFrameCount * 2];
1310 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001311
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001312 // force reconfiguration of effect chains and engines to take new buffer size and audio
1313 // parameters into account
1314 // Note that mLock is not held when readOutputParameters() is called from the constructor
1315 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1316 // matter.
1317 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1318 Vector< sp<EffectChain> > effectChains = mEffectChains;
1319 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001320 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001321 }
Eric Laurenta553c252009-07-17 12:17:14 -07001322}
1323
Eric Laurent0986e792010-01-19 17:37:09 -08001324status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1325{
1326 if (halFrames == 0 || dspFrames == 0) {
1327 return BAD_VALUE;
1328 }
1329 if (mOutput == 0) {
1330 return INVALID_OPERATION;
1331 }
1332 *halFrames = mBytesWritten/mOutput->frameSize();
1333
1334 return mOutput->getRenderPosition(dspFrames);
1335}
1336
Eric Laurent493941b2010-07-28 01:32:47 -07001337uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001338{
1339 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001340 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001341 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001342 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001343 }
1344
1345 for (size_t i = 0; i < mTracks.size(); ++i) {
1346 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001347 if (sessionId == track->sessionId() &&
1348 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001349 result |= TRACK_SESSION;
1350 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001351 }
1352 }
1353
Eric Laurent493941b2010-07-28 01:32:47 -07001354 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001355}
1356
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001357uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1358{
1359 // session AudioSystem::SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1360 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1361 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
1362 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1363 }
1364 for (size_t i = 0; i < mTracks.size(); i++) {
1365 sp<Track> track = mTracks[i];
1366 if (sessionId == track->sessionId() &&
1367 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
1368 return AudioSystem::getStrategyForStream((AudioSystem::stream_type) track->type());
1369 }
1370 }
1371 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1372}
1373
Eric Laurent65b65452010-06-01 23:49:17 -07001374sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1375{
1376 Mutex::Autolock _l(mLock);
1377 return getEffectChain_l(sessionId);
1378}
1379
1380sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1381{
1382 sp<EffectChain> chain;
1383
1384 size_t size = mEffectChains.size();
1385 for (size_t i = 0; i < size; i++) {
1386 if (mEffectChains[i]->sessionId() == sessionId) {
1387 chain = mEffectChains[i];
1388 break;
1389 }
1390 }
1391 return chain;
1392}
1393
Eric Laurent53334cd2010-06-23 17:38:20 -07001394void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1395{
1396 Mutex::Autolock _l(mLock);
1397 size_t size = mEffectChains.size();
1398 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001399 mEffectChains[i]->setMode_l(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -07001400 }
1401}
1402
Eric Laurenta553c252009-07-17 12:17:14 -07001403// ----------------------------------------------------------------------------
1404
Eric Laurent65b65452010-06-01 23:49:17 -07001405AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1406 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001407 mAudioMixer(0)
1408{
1409 mType = PlaybackThread::MIXER;
1410 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1411
1412 // FIXME - Current mixer implementation only supports stereo output
1413 if (mChannelCount == 1) {
1414 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001416}
1417
Eric Laurenta553c252009-07-17 12:17:14 -07001418AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001419{
Eric Laurenta553c252009-07-17 12:17:14 -07001420 delete mAudioMixer;
1421}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422
Eric Laurenta553c252009-07-17 12:17:14 -07001423bool AudioFlinger::MixerThread::threadLoop()
1424{
Eric Laurenta553c252009-07-17 12:17:14 -07001425 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001426 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001427 nsecs_t standbyTime = systemTime();
1428 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001429 // FIXME: Relaxed timing because of a certain device that can't meet latency
1430 // Should be reduced to 2x after the vendor fixes the driver issue
1431 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1432 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001433 bool longStandbyExit = false;
1434 uint32_t activeSleepTime = activeSleepTimeUs();
1435 uint32_t idleSleepTime = idleSleepTimeUs();
1436 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001437 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438
Eric Laurenta553c252009-07-17 12:17:14 -07001439 while (!exitPending())
1440 {
1441 processConfigEvents();
1442
Eric Laurent059b4be2009-11-09 23:32:22 -08001443 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001444 { // scope for mLock
1445
1446 Mutex::Autolock _l(mLock);
1447
1448 if (checkForNewParameters_l()) {
1449 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001450 // FIXME: Relaxed timing because of a certain device that can't meet latency
1451 // Should be reduced to 2x after the vendor fixes the driver issue
1452 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001453 activeSleepTime = activeSleepTimeUs();
1454 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001455 }
1456
1457 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1458
1459 // put audio hardware into standby after short delay
1460 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1461 mSuspended) {
1462 if (!mStandby) {
1463 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1464 mOutput->standby();
1465 mStandby = true;
1466 mBytesWritten = 0;
1467 }
1468
1469 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1470 // we're about to wait, flush the binder command buffer
1471 IPCThreadState::self()->flushCommands();
1472
1473 if (exitPending()) break;
1474
1475 // wait until we have something to do...
1476 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1477 mWaitWorkCV.wait(mLock);
1478 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1479
1480 if (mMasterMute == false) {
1481 char value[PROPERTY_VALUE_MAX];
1482 property_get("ro.audio.silent", value, "0");
1483 if (atoi(value)) {
1484 LOGD("Silence is golden");
1485 setMasterMute(true);
1486 }
1487 }
1488
1489 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001490 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001491 continue;
1492 }
1493 }
1494
Eric Laurent059b4be2009-11-09 23:32:22 -08001495 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001496
1497 // prevent any changes in effect chain list and in each effect chain
1498 // during mixing and effect process as the audio buffers could be deleted
1499 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001500 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001501 }
1502
Eric Laurent059b4be2009-11-09 23:32:22 -08001503 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001504 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001505 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001506 sleepTime = 0;
1507 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001508 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001509 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001510 // If no tracks are ready, sleep once for the duration of an output
1511 // buffer size, then write 0s to the output
1512 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001513 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1514 sleepTime = activeSleepTime;
1515 } else {
1516 sleepTime = idleSleepTime;
1517 }
1518 } else if (mBytesWritten != 0 ||
1519 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001520 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001521 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001522 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001523 }
Eric Laurent65b65452010-06-01 23:49:17 -07001524 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001525 }
1526
1527 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07001528 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001529 }
1530 // sleepTime == 0 means we must write to audio hardware
1531 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001532 for (size_t i = 0; i < effectChains.size(); i ++) {
1533 effectChains[i]->process_l();
1534 }
1535 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001536 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07001537 mLastWriteTime = systemTime();
1538 mInWrite = true;
1539 mBytesWritten += mixBufferSize;
1540
1541 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001542 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001543 mNumWrites++;
1544 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001545 nsecs_t now = systemTime();
1546 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001547 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001548 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001549 if ((now - lastWarning) > kWarningThrottle) {
1550 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1551 ns2ms(delta), mNumDelayedWrites, this);
1552 lastWarning = now;
1553 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001554 if (mStandby) {
1555 longStandbyExit = true;
1556 }
Eric Laurenta553c252009-07-17 12:17:14 -07001557 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001558 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001559 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001560 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001561 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07001562 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001563 }
1564
1565 // finally let go of all our tracks, without the lock held
1566 // since we can't guarantee the destructors won't acquire that
1567 // same lock.
1568 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07001569
1570 // Effect chains will be actually deleted here if they were removed from
1571 // mEffectChains list during mixing or effects processing
1572 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07001573 }
1574
1575 if (!mStandby) {
1576 mOutput->standby();
1577 }
Eric Laurenta553c252009-07-17 12:17:14 -07001578
1579 LOGV("MixerThread %p exiting", this);
1580 return false;
1581}
1582
1583// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001584uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001585{
1586
Eric Laurent059b4be2009-11-09 23:32:22 -08001587 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001588 // find out which tracks need to be processed
1589 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07001590 size_t mixedTracks = 0;
1591 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001592
1593 float masterVolume = mMasterVolume;
1594 bool masterMute = mMasterMute;
1595
Eric Laurent8cc93b92010-08-11 05:20:11 -07001596 if (masterMute) {
1597 masterVolume = 0;
1598 }
Eric Laurent65b65452010-06-01 23:49:17 -07001599 // Delegate master volume control to effect in output mix effect chain if needed
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001600 sp<EffectChain> chain = getEffectChain_l(AudioSystem::SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07001601 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07001602 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07001603 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07001604 masterVolume = (float)((v + (1 << 23)) >> 24);
1605 chain.clear();
1606 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001607
Eric Laurenta553c252009-07-17 12:17:14 -07001608 for (size_t i=0 ; i<count ; i++) {
1609 sp<Track> t = activeTracks[i].promote();
1610 if (t == 0) continue;
1611
1612 Track* const track = t.get();
1613 audio_track_cblk_t* cblk = track->cblk();
1614
1615 // The first time a track is added we wait
1616 // for all its buffers to be filled before processing it
1617 mAudioMixer->setActiveTrack(track->name());
Eric Laurent9a30fc12010-10-05 14:41:42 -07001618 if (cblk->framesReady() && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07001619 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07001620 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001621 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07001622
Eric Laurent65b65452010-06-01 23:49:17 -07001623 mixedTracks++;
1624
1625 // track->mainBuffer() != mMixBuffer means there is an effect chain
1626 // connected to the track
1627 chain.clear();
1628 if (track->mainBuffer() != mMixBuffer) {
1629 chain = getEffectChain_l(track->sessionId());
1630 // Delegate volume control to effect in track effect chain if needed
1631 if (chain != 0) {
1632 tracksWithEffect++;
1633 } else {
1634 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1635 track->name(), track->sessionId());
1636 }
1637 }
1638
1639
1640 int param = AudioMixer::VOLUME;
1641 if (track->mFillingUpStatus == Track::FS_FILLED) {
1642 // no ramp for the first volume setting
1643 track->mFillingUpStatus = Track::FS_ACTIVE;
1644 if (track->mState == TrackBase::RESUMING) {
1645 track->mState = TrackBase::ACTIVE;
1646 param = AudioMixer::RAMP_VOLUME;
1647 }
Eric Laurent4bb21c42011-02-28 16:52:51 -08001648 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07001649 } else if (cblk->server != 0) {
1650 // If the track is stopped before the first frame was mixed,
1651 // do not apply ramp
1652 param = AudioMixer::RAMP_VOLUME;
1653 }
1654
Eric Laurenta553c252009-07-17 12:17:14 -07001655 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001656 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07001657 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001658 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001659 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001660 if (track->isPausing()) {
1661 track->setPaused();
1662 }
1663 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001664
Glenn Kasten871c16c2010-03-05 12:18:01 -08001665 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001666 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001667 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001668 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1669 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07001670
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001671 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07001672 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07001673 // Delegate volume control to effect in track effect chain if needed
1674 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1675 // Do not ramp volume if volume is controlled by effect
1676 param = AudioMixer::VOLUME;
1677 track->mHasVolumeController = true;
1678 } else {
1679 // force no volume ramp when volume controller was just disabled or removed
1680 // from effect chain to avoid volume spike
1681 if (track->mHasVolumeController) {
1682 param = AudioMixer::VOLUME;
1683 }
1684 track->mHasVolumeController = false;
1685 }
1686
1687 // Convert volumes from 8.24 to 4.12 format
1688 int16_t left, right, aux;
1689 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1690 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1691 left = int16_t(v_clamped);
1692 v_clamped = (vr + (1 << 11)) >> 12;
1693 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1694 right = int16_t(v_clamped);
1695
1696 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1697 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07001698
Eric Laurent65b65452010-06-01 23:49:17 -07001699 // XXX: these things DON'T need to be done each time
1700 mAudioMixer->setBufferProvider(track);
1701 mAudioMixer->enable(AudioMixer::MIXING);
1702
1703 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1704 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1705 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07001706 mAudioMixer->setParameter(
1707 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001708 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07001709 mAudioMixer->setParameter(
1710 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001711 AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
Eric Laurenta553c252009-07-17 12:17:14 -07001712 mAudioMixer->setParameter(
1713 AudioMixer::RESAMPLE,
1714 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07001715 (void *)(cblk->sampleRate));
1716 mAudioMixer->setParameter(
1717 AudioMixer::TRACK,
1718 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1719 mAudioMixer->setParameter(
1720 AudioMixer::TRACK,
1721 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07001722
1723 // reset retry count
1724 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08001725 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001726 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001727 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07001728 if (track->isStopped()) {
1729 track->reset();
1730 }
1731 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1732 // We have consumed all the buffers of this track.
1733 // Remove it from the list of active tracks.
1734 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001735 } else {
1736 // No buffers for this track. Give it a few chances to
1737 // fill a buffer, then remove it from active list.
1738 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07001739 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07001740 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07001741 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07001742 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -08001743 } else if (mixerStatus != MIXER_TRACKS_READY) {
1744 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001745 }
Eric Laurenta553c252009-07-17 12:17:14 -07001746 }
Eric Laurent65b65452010-06-01 23:49:17 -07001747 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07001748 }
1749 }
1750
1751 // remove all the tracks that need to be...
1752 count = tracksToRemove->size();
1753 if (UNLIKELY(count)) {
1754 for (size_t i=0 ; i<count ; i++) {
1755 const sp<Track>& track = tracksToRemove->itemAt(i);
1756 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001757 if (track->mainBuffer() != mMixBuffer) {
1758 chain = getEffectChain_l(track->sessionId());
1759 if (chain != 0) {
1760 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
1761 chain->stopTrack();
1762 }
1763 }
Eric Laurenta553c252009-07-17 12:17:14 -07001764 if (track->isTerminated()) {
1765 mTracks.remove(track);
1766 deleteTrackName_l(track->mName);
1767 }
1768 }
1769 }
1770
Eric Laurent65b65452010-06-01 23:49:17 -07001771 // mix buffer must be cleared if all tracks are connected to an
1772 // effect chain as in this case the mixer will not write to
1773 // mix buffer and track effects will accumulate into it
1774 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1775 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1776 }
1777
Eric Laurent059b4be2009-11-09 23:32:22 -08001778 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001779}
1780
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001781void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07001782{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001783 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1784 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001785 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001786
Eric Laurenta553c252009-07-17 12:17:14 -07001787 size_t size = mTracks.size();
1788 for (size_t i = 0; i < size; i++) {
1789 sp<Track> t = mTracks[i];
1790 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07001791 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001792 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07001793 }
Eric Laurent53334cd2010-06-23 17:38:20 -07001794 }
1795}
Eric Laurenta553c252009-07-17 12:17:14 -07001796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797
Eric Laurenta553c252009-07-17 12:17:14 -07001798// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001799int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800{
1801 return mAudioMixer->getTrackName();
1802}
1803
Eric Laurenta553c252009-07-17 12:17:14 -07001804// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001805void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806{
Eric Laurent0a080292009-12-07 10:53:10 -08001807 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 mAudioMixer->deleteTrackName(name);
1809}
1810
Eric Laurenta553c252009-07-17 12:17:14 -07001811// checkForNewParameters_l() must be called with ThreadBase::mLock held
1812bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813{
Eric Laurenta553c252009-07-17 12:17:14 -07001814 bool reconfig = false;
1815
Eric Laurent8fce46a2009-08-04 09:45:33 -07001816 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001817 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001818 String8 keyValuePair = mNewParameters[0];
1819 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001820 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001821
Eric Laurenta553c252009-07-17 12:17:14 -07001822 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1823 reconfig = true;
1824 }
1825 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1826 if (value != AudioSystem::PCM_16_BIT) {
1827 status = BAD_VALUE;
1828 } else {
1829 reconfig = true;
1830 }
1831 }
1832 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1833 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1834 status = BAD_VALUE;
1835 } else {
1836 reconfig = true;
1837 }
1838 }
1839 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1840 // do not accept frame count changes if tracks are open as the track buffer
1841 // size depends on frame count and correct behavior would not be garantied
1842 // if frame count is changed after track creation
1843 if (!mTracks.isEmpty()) {
1844 status = INVALID_OPERATION;
1845 } else {
1846 reconfig = true;
1847 }
1848 }
Eric Laurent65b65452010-06-01 23:49:17 -07001849 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08001850 // when changing the audio output device, call addBatteryData to notify
1851 // the change
1852 if (mDevice != value) {
1853 uint32_t params = 0;
1854 // check whether speaker is on
1855 if (value & AudioSystem::DEVICE_OUT_SPEAKER) {
1856 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
1857 }
1858
1859 int deviceWithoutSpeaker
1860 = AudioSystem::DEVICE_OUT_ALL & ~AudioSystem::DEVICE_OUT_SPEAKER;
1861 // check if any other device (except speaker) is on
1862 if (value & deviceWithoutSpeaker ) {
1863 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
1864 }
1865
1866 if (params != 0) {
1867 addBatteryData(params);
1868 }
1869 }
1870
Eric Laurent65b65452010-06-01 23:49:17 -07001871 // forward device change to effects that have requested to be
1872 // aware of attached audio device.
1873 mDevice = (uint32_t)value;
1874 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07001875 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07001876 }
1877 }
1878
Eric Laurenta553c252009-07-17 12:17:14 -07001879 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07001880 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001881 if (!mStandby && status == INVALID_OPERATION) {
1882 mOutput->standby();
1883 mStandby = true;
1884 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001885 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001886 }
1887 if (status == NO_ERROR && reconfig) {
1888 delete mAudioMixer;
1889 readOutputParameters();
1890 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1891 for (size_t i = 0; i < mTracks.size() ; i++) {
1892 int name = getTrackName_l();
1893 if (name < 0) break;
1894 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07001895 // limit track sample rate to 2 x new output sample rate
1896 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1897 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1898 }
Eric Laurenta553c252009-07-17 12:17:14 -07001899 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001900 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07001901 }
1902 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08001903
1904 mNewParameters.removeAt(0);
1905
Eric Laurenta553c252009-07-17 12:17:14 -07001906 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07001907 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07001908 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001909 }
1910 return reconfig;
1911}
1912
1913status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1914{
1915 const size_t SIZE = 256;
1916 char buffer[SIZE];
1917 String8 result;
1918
1919 PlaybackThread::dumpInternals(fd, args);
1920
1921 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1922 result.append(buffer);
1923 write(fd, result.string(), result.size());
1924 return NO_ERROR;
1925}
1926
Eric Laurent059b4be2009-11-09 23:32:22 -08001927uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07001928{
Eric Laurent059b4be2009-11-09 23:32:22 -08001929 return (uint32_t)(mOutput->latency() * 1000) / 2;
1930}
1931
1932uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
1933{
Eric Laurenta54d7d32010-07-29 06:50:24 -07001934 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07001935}
1936
Eric Laurent8448a792010-08-18 18:13:17 -07001937uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
1938{
1939 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
1940}
1941
Eric Laurenta553c252009-07-17 12:17:14 -07001942// ----------------------------------------------------------------------------
Eric Laurent65b65452010-06-01 23:49:17 -07001943AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1944 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07001945{
1946 mType = PlaybackThread::DIRECT;
1947}
1948
1949AudioFlinger::DirectOutputThread::~DirectOutputThread()
1950{
1951}
1952
1953
Eric Laurent65b65452010-06-01 23:49:17 -07001954static inline int16_t clamp16(int32_t sample)
1955{
1956 if ((sample>>15) ^ (sample>>31))
1957 sample = 0x7FFF ^ (sample>>31);
1958 return sample;
1959}
1960
1961static inline
1962int32_t mul(int16_t in, int16_t v)
1963{
1964#if defined(__arm__) && !defined(__thumb__)
1965 int32_t out;
1966 asm( "smulbb %[out], %[in], %[v] \n"
1967 : [out]"=r"(out)
1968 : [in]"%r"(in), [v]"r"(v)
1969 : );
1970 return out;
1971#else
1972 return in * int32_t(v);
1973#endif
1974}
1975
1976void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
1977{
1978 // Do not apply volume on compressed audio
1979 if (!AudioSystem::isLinearPCM(mFormat)) {
1980 return;
1981 }
1982
1983 // convert to signed 16 bit before volume calculation
1984 if (mFormat == AudioSystem::PCM_8_BIT) {
1985 size_t count = mFrameCount * mChannelCount;
1986 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
1987 int16_t *dst = mMixBuffer + count-1;
1988 while(count--) {
1989 *dst-- = (int16_t)(*src--^0x80) << 8;
1990 }
1991 }
1992
1993 size_t frameCount = mFrameCount;
1994 int16_t *out = mMixBuffer;
1995 if (ramp) {
1996 if (mChannelCount == 1) {
1997 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
1998 int32_t vlInc = d / (int32_t)frameCount;
1999 int32_t vl = ((int32_t)mLeftVolShort << 16);
2000 do {
2001 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2002 out++;
2003 vl += vlInc;
2004 } while (--frameCount);
2005
2006 } else {
2007 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2008 int32_t vlInc = d / (int32_t)frameCount;
2009 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2010 int32_t vrInc = d / (int32_t)frameCount;
2011 int32_t vl = ((int32_t)mLeftVolShort << 16);
2012 int32_t vr = ((int32_t)mRightVolShort << 16);
2013 do {
2014 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2015 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2016 out += 2;
2017 vl += vlInc;
2018 vr += vrInc;
2019 } while (--frameCount);
2020 }
2021 } else {
2022 if (mChannelCount == 1) {
2023 do {
2024 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2025 out++;
2026 } while (--frameCount);
2027 } else {
2028 do {
2029 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2030 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2031 out += 2;
2032 } while (--frameCount);
2033 }
2034 }
2035
2036 // convert back to unsigned 8 bit after volume calculation
2037 if (mFormat == AudioSystem::PCM_8_BIT) {
2038 size_t count = mFrameCount * mChannelCount;
2039 int16_t *src = mMixBuffer;
2040 uint8_t *dst = (uint8_t *)mMixBuffer;
2041 while(count--) {
2042 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2043 }
2044 }
2045
2046 mLeftVolShort = leftVol;
2047 mRightVolShort = rightVol;
2048}
2049
Eric Laurenta553c252009-07-17 12:17:14 -07002050bool AudioFlinger::DirectOutputThread::threadLoop()
2051{
Eric Laurent059b4be2009-11-09 23:32:22 -08002052 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002053 sp<Track> trackToRemove;
2054 sp<Track> activeTrack;
2055 nsecs_t standbyTime = systemTime();
2056 int8_t *curBuf;
2057 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002058 uint32_t activeSleepTime = activeSleepTimeUs();
2059 uint32_t idleSleepTime = idleSleepTimeUs();
2060 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002061 // use shorter standby delay as on normal output to release
2062 // hardware resources as soon as possible
2063 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002064
Eric Laurenta553c252009-07-17 12:17:14 -07002065 while (!exitPending())
2066 {
Eric Laurent65b65452010-06-01 23:49:17 -07002067 bool rampVolume;
2068 uint16_t leftVol;
2069 uint16_t rightVol;
2070 Vector< sp<EffectChain> > effectChains;
2071
Eric Laurenta553c252009-07-17 12:17:14 -07002072 processConfigEvents();
2073
Eric Laurent059b4be2009-11-09 23:32:22 -08002074 mixerStatus = MIXER_IDLE;
2075
Eric Laurenta553c252009-07-17 12:17:14 -07002076 { // scope for the mLock
2077
2078 Mutex::Autolock _l(mLock);
2079
2080 if (checkForNewParameters_l()) {
2081 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002082 activeSleepTime = activeSleepTimeUs();
2083 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002084 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002085 }
2086
2087 // put audio hardware into standby after short delay
2088 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2089 mSuspended) {
2090 // wait until we have something to do...
2091 if (!mStandby) {
2092 LOGV("Audio hardware entering standby, mixer %p\n", this);
2093 mOutput->standby();
2094 mStandby = true;
2095 mBytesWritten = 0;
2096 }
2097
2098 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2099 // we're about to wait, flush the binder command buffer
2100 IPCThreadState::self()->flushCommands();
2101
2102 if (exitPending()) break;
2103
2104 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2105 mWaitWorkCV.wait(mLock);
2106 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2107
2108 if (mMasterMute == false) {
2109 char value[PROPERTY_VALUE_MAX];
2110 property_get("ro.audio.silent", value, "0");
2111 if (atoi(value)) {
2112 LOGD("Silence is golden");
2113 setMasterMute(true);
2114 }
2115 }
2116
Eric Laurentef9500f2010-03-11 14:47:00 -08002117 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002118 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002119 continue;
2120 }
2121 }
2122
Eric Laurent65b65452010-06-01 23:49:17 -07002123 effectChains = mEffectChains;
2124
Eric Laurenta553c252009-07-17 12:17:14 -07002125 // find out which tracks need to be processed
2126 if (mActiveTracks.size() != 0) {
2127 sp<Track> t = mActiveTracks[0].promote();
2128 if (t == 0) continue;
2129
2130 Track* const track = t.get();
2131 audio_track_cblk_t* cblk = track->cblk();
2132
2133 // The first time a track is added we wait
2134 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002135 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002136 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002137 {
2138 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2139
Eric Laurent65b65452010-06-01 23:49:17 -07002140 if (track->mFillingUpStatus == Track::FS_FILLED) {
2141 track->mFillingUpStatus = Track::FS_ACTIVE;
2142 mLeftVolFloat = mRightVolFloat = 0;
2143 mLeftVolShort = mRightVolShort = 0;
2144 if (track->mState == TrackBase::RESUMING) {
2145 track->mState = TrackBase::ACTIVE;
2146 rampVolume = true;
2147 }
2148 } else if (cblk->server != 0) {
2149 // If the track is stopped before the first frame was mixed,
2150 // do not apply ramp
2151 rampVolume = true;
2152 }
Eric Laurenta553c252009-07-17 12:17:14 -07002153 // compute volume for this track
2154 float left, right;
2155 if (track->isMuted() || mMasterMute || track->isPausing() ||
2156 mStreamTypes[track->type()].mute) {
2157 left = right = 0;
2158 if (track->isPausing()) {
2159 track->setPaused();
2160 }
2161 } else {
2162 float typeVolume = mStreamTypes[track->type()].volume;
2163 float v = mMasterVolume * typeVolume;
2164 float v_clamped = v * cblk->volume[0];
2165 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2166 left = v_clamped/MAX_GAIN;
2167 v_clamped = v * cblk->volume[1];
2168 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2169 right = v_clamped/MAX_GAIN;
2170 }
2171
Eric Laurent65b65452010-06-01 23:49:17 -07002172 if (left != mLeftVolFloat || right != mRightVolFloat) {
2173 mLeftVolFloat = left;
2174 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002175
Eric Laurent65b65452010-06-01 23:49:17 -07002176 // If audio HAL implements volume control,
2177 // force software volume to nominal value
2178 if (mOutput->setVolume(left, right) == NO_ERROR) {
2179 left = 1.0f;
2180 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002181 }
Eric Laurent65b65452010-06-01 23:49:17 -07002182
2183 // Convert volumes from float to 8.24
2184 uint32_t vl = (uint32_t)(left * (1 << 24));
2185 uint32_t vr = (uint32_t)(right * (1 << 24));
2186
2187 // Delegate volume control to effect in track effect chain if needed
2188 // only one effect chain can be present on DirectOutputThread, so if
2189 // there is one, the track is connected to it
2190 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002191 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002192 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002193 rampVolume = false;
2194 }
2195 }
2196
2197 // Convert volumes from 8.24 to 4.12 format
2198 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2199 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2200 leftVol = (uint16_t)v_clamped;
2201 v_clamped = (vr + (1 << 11)) >> 12;
2202 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2203 rightVol = (uint16_t)v_clamped;
2204 } else {
2205 leftVol = mLeftVolShort;
2206 rightVol = mRightVolShort;
2207 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002208 }
2209
2210 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002211 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002212 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002213 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002214 } else {
2215 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2216 if (track->isStopped()) {
2217 track->reset();
2218 }
2219 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2220 // We have consumed all the buffers of this track.
2221 // Remove it from the list of active tracks.
2222 trackToRemove = track;
2223 } else {
2224 // No buffers for this track. Give it a few chances to
2225 // fill a buffer, then remove it from active list.
2226 if (--(track->mRetryCount) <= 0) {
2227 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2228 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002229 } else {
2230 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002231 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002232 }
Eric Laurenta553c252009-07-17 12:17:14 -07002233 }
2234 }
2235
2236 // remove all the tracks that need to be...
2237 if (UNLIKELY(trackToRemove != 0)) {
2238 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002239 if (!effectChains.isEmpty()) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002240 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2241 trackToRemove->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002242 effectChains[0]->stopTrack();
2243 }
Eric Laurenta553c252009-07-17 12:17:14 -07002244 if (trackToRemove->isTerminated()) {
2245 mTracks.remove(trackToRemove);
2246 deleteTrackName_l(trackToRemove->mName);
2247 }
2248 }
Eric Laurent65b65452010-06-01 23:49:17 -07002249
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002250 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002251 }
2252
Eric Laurent059b4be2009-11-09 23:32:22 -08002253 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002254 AudioBufferProvider::Buffer buffer;
2255 size_t frameCount = mFrameCount;
2256 curBuf = (int8_t *)mMixBuffer;
2257 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002258 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002259 buffer.frameCount = frameCount;
2260 activeTrack->getNextBuffer(&buffer);
2261 if (UNLIKELY(buffer.raw == 0)) {
2262 memset(curBuf, 0, frameCount * mFrameSize);
2263 break;
2264 }
2265 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2266 frameCount -= buffer.frameCount;
2267 curBuf += buffer.frameCount * mFrameSize;
2268 activeTrack->releaseBuffer(&buffer);
2269 }
2270 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002271 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002272 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002273 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002274 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2275 sleepTime = activeSleepTime;
2276 } else {
2277 sleepTime = idleSleepTime;
2278 }
Eric Laurent62443f52009-10-05 20:29:18 -07002279 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002280 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002281 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002282 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002283 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002284
Eric Laurentf69a3f82009-09-22 00:35:48 -07002285 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002286 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002287 }
2288 // sleepTime == 0 means we must write to audio hardware
2289 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002290 if (mixerStatus == MIXER_TRACKS_READY) {
2291 applyVolume(leftVol, rightVol, rampVolume);
2292 }
2293 for (size_t i = 0; i < effectChains.size(); i ++) {
2294 effectChains[i]->process_l();
2295 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002296 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002297
Eric Laurentf69a3f82009-09-22 00:35:48 -07002298 mLastWriteTime = systemTime();
2299 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002300 mBytesWritten += mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002301 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002302 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002303 mNumWrites++;
2304 mInWrite = false;
2305 mStandby = false;
2306 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002307 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002308 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002309 }
2310
2311 // finally let go of removed track, without the lock held
2312 // since we can't guarantee the destructors won't acquire that
2313 // same lock.
2314 trackToRemove.clear();
2315 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002316
2317 // Effect chains will be actually deleted here if they were removed from
2318 // mEffectChains list during mixing or effects processing
2319 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002320 }
2321
2322 if (!mStandby) {
2323 mOutput->standby();
2324 }
Eric Laurenta553c252009-07-17 12:17:14 -07002325
2326 LOGV("DirectOutputThread %p exiting", this);
2327 return false;
2328}
2329
2330// getTrackName_l() must be called with ThreadBase::mLock held
2331int AudioFlinger::DirectOutputThread::getTrackName_l()
2332{
2333 return 0;
2334}
2335
2336// deleteTrackName_l() must be called with ThreadBase::mLock held
2337void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2338{
2339}
2340
2341// checkForNewParameters_l() must be called with ThreadBase::mLock held
2342bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2343{
2344 bool reconfig = false;
2345
Eric Laurent8fce46a2009-08-04 09:45:33 -07002346 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002347 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002348 String8 keyValuePair = mNewParameters[0];
2349 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002350 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002351
Eric Laurenta553c252009-07-17 12:17:14 -07002352 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2353 // do not accept frame count changes if tracks are open as the track buffer
2354 // size depends on frame count and correct behavior would not be garantied
2355 // if frame count is changed after track creation
2356 if (!mTracks.isEmpty()) {
2357 status = INVALID_OPERATION;
2358 } else {
2359 reconfig = true;
2360 }
2361 }
2362 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07002363 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002364 if (!mStandby && status == INVALID_OPERATION) {
2365 mOutput->standby();
2366 mStandby = true;
2367 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002368 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002369 }
2370 if (status == NO_ERROR && reconfig) {
2371 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002372 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002373 }
2374 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002375
2376 mNewParameters.removeAt(0);
2377
Eric Laurenta553c252009-07-17 12:17:14 -07002378 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002379 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002380 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002381 }
2382 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002383}
2384
Eric Laurent059b4be2009-11-09 23:32:22 -08002385uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002386{
2387 uint32_t time;
2388 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002389 time = (uint32_t)(mOutput->latency() * 1000) / 2;
2390 } else {
2391 time = 10000;
2392 }
2393 return time;
2394}
2395
2396uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2397{
2398 uint32_t time;
2399 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002400 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002401 } else {
2402 time = 10000;
2403 }
2404 return time;
2405}
2406
Eric Laurent8448a792010-08-18 18:13:17 -07002407uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2408{
2409 uint32_t time;
2410 if (AudioSystem::isLinearPCM(mFormat)) {
2411 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2412 } else {
2413 time = 10000;
2414 }
2415 return time;
2416}
2417
2418
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002419// ----------------------------------------------------------------------------
2420
Eric Laurent49f02be2009-11-19 09:00:56 -08002421AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002422 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002423{
2424 mType = PlaybackThread::DUPLICATING;
2425 addOutputTrack(mainThread);
2426}
2427
2428AudioFlinger::DuplicatingThread::~DuplicatingThread()
2429{
Eric Laurent0a080292009-12-07 10:53:10 -08002430 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2431 mOutputTracks[i]->destroy();
2432 }
Eric Laurenta553c252009-07-17 12:17:14 -07002433 mOutputTracks.clear();
2434}
2435
2436bool AudioFlinger::DuplicatingThread::threadLoop()
2437{
Eric Laurenta553c252009-07-17 12:17:14 -07002438 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002439 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002440 nsecs_t standbyTime = systemTime();
2441 size_t mixBufferSize = mFrameCount*mFrameSize;
2442 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002443 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002444 uint32_t activeSleepTime = activeSleepTimeUs();
2445 uint32_t idleSleepTime = idleSleepTimeUs();
2446 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002447 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002448
2449 while (!exitPending())
2450 {
2451 processConfigEvents();
2452
Eric Laurent059b4be2009-11-09 23:32:22 -08002453 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002454 { // scope for the mLock
2455
2456 Mutex::Autolock _l(mLock);
2457
2458 if (checkForNewParameters_l()) {
2459 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002460 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002461 activeSleepTime = activeSleepTimeUs();
2462 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002463 }
2464
2465 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2466
2467 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2468 outputTracks.add(mOutputTracks[i]);
2469 }
2470
2471 // put audio hardware into standby after short delay
2472 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2473 mSuspended) {
2474 if (!mStandby) {
2475 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002476 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002477 }
2478 mStandby = true;
2479 mBytesWritten = 0;
2480 }
2481
2482 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2483 // we're about to wait, flush the binder command buffer
2484 IPCThreadState::self()->flushCommands();
2485 outputTracks.clear();
2486
2487 if (exitPending()) break;
2488
2489 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2490 mWaitWorkCV.wait(mLock);
2491 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2492 if (mMasterMute == false) {
2493 char value[PROPERTY_VALUE_MAX];
2494 property_get("ro.audio.silent", value, "0");
2495 if (atoi(value)) {
2496 LOGD("Silence is golden");
2497 setMasterMute(true);
2498 }
2499 }
2500
2501 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002502 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002503 continue;
2504 }
2505 }
2506
Eric Laurent059b4be2009-11-09 23:32:22 -08002507 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002508
2509 // prevent any changes in effect chain list and in each effect chain
2510 // during mixing and effect process as the audio buffers could be deleted
2511 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002512 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002513 }
Eric Laurenta553c252009-07-17 12:17:14 -07002514
Eric Laurent059b4be2009-11-09 23:32:22 -08002515 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002516 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002517 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002518 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002519 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002520 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002521 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002522 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002523 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002524 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002525 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002526 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2527 sleepTime = activeSleepTime;
2528 } else {
2529 sleepTime = idleSleepTime;
2530 }
Eric Laurent62443f52009-10-05 20:29:18 -07002531 } else if (mBytesWritten != 0) {
2532 // flush remaining overflow buffers in output tracks
2533 for (size_t i = 0; i < outputTracks.size(); i++) {
2534 if (outputTracks[i]->isActive()) {
2535 sleepTime = 0;
2536 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07002537 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07002538 break;
2539 }
2540 }
Eric Laurenta553c252009-07-17 12:17:14 -07002541 }
2542 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002543
2544 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002545 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002546 }
2547 // sleepTime == 0 means we must write to audio hardware
2548 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002549 for (size_t i = 0; i < effectChains.size(); i ++) {
2550 effectChains[i]->process_l();
2551 }
2552 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002553 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002554
Eric Laurent62443f52009-10-05 20:29:18 -07002555 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002556 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07002557 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002558 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002559 mStandby = false;
2560 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002561 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002562 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002563 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002564 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002565 }
2566
2567 // finally let go of all our tracks, without the lock held
2568 // since we can't guarantee the destructors won't acquire that
2569 // same lock.
2570 tracksToRemove.clear();
2571 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002572
2573 // Effect chains will be actually deleted here if they were removed from
2574 // mEffectChains list during mixing or effects processing
2575 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002576 }
2577
Eric Laurenta553c252009-07-17 12:17:14 -07002578 return false;
2579}
2580
2581void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2582{
2583 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2584 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002585 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002586 mSampleRate,
2587 mFormat,
2588 mChannelCount,
2589 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002590 if (outputTrack->cblk() != NULL) {
2591 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2592 mOutputTracks.add(outputTrack);
2593 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002594 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002595 }
Eric Laurenta553c252009-07-17 12:17:14 -07002596}
2597
2598void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2599{
2600 Mutex::Autolock _l(mLock);
2601 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2602 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002603 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002604 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002605 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002606 return;
2607 }
2608 }
2609 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2610}
2611
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002612void AudioFlinger::DuplicatingThread::updateWaitTime()
2613{
2614 mWaitTimeMs = UINT_MAX;
2615 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2616 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2617 if (strong != NULL) {
2618 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2619 if (waitTimeMs < mWaitTimeMs) {
2620 mWaitTimeMs = waitTimeMs;
2621 }
2622 }
2623 }
2624}
2625
2626
2627bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2628{
2629 for (size_t i = 0; i < outputTracks.size(); i++) {
2630 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2631 if (thread == 0) {
2632 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2633 return false;
2634 }
2635 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2636 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2637 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2638 return false;
2639 }
2640 }
2641 return true;
2642}
2643
2644uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2645{
2646 return (mWaitTimeMs * 1000) / 2;
2647}
2648
Eric Laurenta553c252009-07-17 12:17:14 -07002649// ----------------------------------------------------------------------------
2650
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002651// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002652AudioFlinger::ThreadBase::TrackBase::TrackBase(
2653 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002654 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002655 uint32_t sampleRate,
2656 int format,
2657 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002658 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07002660 const sp<IMemory>& sharedBuffer,
2661 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002662 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002663 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002664 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002665 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002666 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002667 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002668 mClientTid(-1),
2669 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07002670 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2671 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002672{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002673 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2674
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002675 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002676 size_t size = sizeof(audio_track_cblk_t);
2677 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2678 if (sharedBuffer == 0) {
2679 size += bufferSize;
2680 }
2681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 if (client != NULL) {
2683 mCblkMemory = client->heap()->allocate(size);
2684 if (mCblkMemory != 0) {
2685 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2686 if (mCblk) { // construct the shared structure in-place.
2687 new(mCblk) audio_track_cblk_t();
2688 // clear all buffers
2689 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002690 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002691 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 if (sharedBuffer == 0) {
2693 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2694 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2695 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002696 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002697 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 } else {
2699 mBuffer = sharedBuffer->pointer();
2700 }
2701 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 } else {
2704 LOGE("not enough memory for AudioTrack size=%u", size);
2705 client->heap()->dump("AudioTrack");
2706 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 } else {
2709 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2710 if (mCblk) { // construct the shared structure in-place.
2711 new(mCblk) audio_track_cblk_t();
2712 // clear all buffers
2713 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002714 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002715 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2717 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2718 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07002719 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002720 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2722 }
2723 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002724}
2725
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002726AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002727{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002729 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2730 if (mClient == NULL) {
2731 delete mCblk;
2732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002734 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07002735 if (mClient != NULL) {
2736 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2737 mClient.clear();
2738 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002739}
2740
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002741void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002742{
2743 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002744 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002745 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002746 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002747}
2748
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002749bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002750 bool result;
2751 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002752
2753 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002754 if (!result) {
2755 LOGV("stepServer failed acquiring cblk mutex");
2756 mFlags |= STEPSERVER_FAILED;
2757 }
2758 return result;
2759}
2760
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002761void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002762 audio_track_cblk_t* cblk = this->cblk();
2763
2764 cblk->user = 0;
2765 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002766 cblk->userBase = 0;
2767 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002769 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002770}
2771
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002772sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002773{
2774 return mCblkMemory;
2775}
2776
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002777int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002778 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002779}
2780
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002781int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurentb0a01472010-05-14 05:45:46 -07002782 return (int)mCblk->channelCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002783}
2784
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002785void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002786 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002787 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2788 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002789
2790 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002791 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2792 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002793 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Eric Laurentb0a01472010-05-14 05:45:46 -07002794 server %d, serverBase %d, user %d, userBase %d, channelCount %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002795 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Eric Laurentb0a01472010-05-14 05:45:46 -07002796 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002797 return 0;
2798 }
2799
2800 return bufferStart;
2801}
2802
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002803// ----------------------------------------------------------------------------
2804
Eric Laurenta553c252009-07-17 12:17:14 -07002805// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2806AudioFlinger::PlaybackThread::Track::Track(
2807 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002808 const sp<Client>& client,
2809 int streamType,
2810 uint32_t sampleRate,
2811 int format,
2812 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002813 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002814 const sp<IMemory>& sharedBuffer,
2815 int sessionId)
2816 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07002817 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
2818 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002819{
Eric Laurent8a77a992009-09-09 05:16:08 -07002820 if (mCblk != NULL) {
2821 sp<ThreadBase> baseThread = thread.promote();
2822 if (baseThread != 0) {
2823 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2824 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07002825 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07002826 }
2827 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2828 if (mName < 0) {
2829 LOGE("no more track names available");
2830 }
2831 mVolume[0] = 1.0f;
2832 mVolume[1] = 1.0f;
2833 mStreamType = streamType;
2834 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2835 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2836 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07002837 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002838}
2839
Eric Laurenta553c252009-07-17 12:17:14 -07002840AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002841{
Eric Laurenta553c252009-07-17 12:17:14 -07002842 LOGV("PlaybackThread::Track destructor");
2843 sp<ThreadBase> thread = mThread.promote();
2844 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002845 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002846 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002847 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002848}
2849
Eric Laurenta553c252009-07-17 12:17:14 -07002850void AudioFlinger::PlaybackThread::Track::destroy()
2851{
2852 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2853 // by removing it from mTracks vector, so there is a risk that this Tracks's
2854 // desctructor is called. As the destructor needs to lock mLock,
2855 // we must acquire a strong reference on this Track before locking mLock
2856 // here so that the destructor is called only when exiting this function.
2857 // On the other hand, as long as Track::destroy() is only called by
2858 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2859 // this Track with its member mTrack.
2860 sp<Track> keep(this);
2861 { // scope for mLock
2862 sp<ThreadBase> thread = mThread.promote();
2863 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002864 if (!isOutputTrack()) {
2865 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002866 AudioSystem::stopOutput(thread->id(),
2867 (AudioSystem::stream_type)mStreamType,
2868 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08002869
2870 // to track the speaker usage
2871 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08002872 }
2873 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08002874 }
Eric Laurenta553c252009-07-17 12:17:14 -07002875 Mutex::Autolock _l(thread->mLock);
2876 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2877 playbackThread->destroyTrack_l(this);
2878 }
2879 }
2880}
2881
2882void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002883{
Eric Laurent65b65452010-06-01 23:49:17 -07002884 snprintf(buffer, size, " %05d %05d %03u %03u %03u %05u %04u %1d %1d %1d %05u %05u %05u 0x%08x 0x%08x 0x%08x 0x%08x\n",
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002885 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002887 mStreamType,
2888 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07002889 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002890 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002891 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002892 mState,
2893 mMute,
2894 mFillingUpStatus,
2895 mCblk->sampleRate,
2896 mCblk->volume[0],
2897 mCblk->volume[1],
2898 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07002899 mCblk->user,
2900 (int)mMainBuffer,
2901 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002902}
2903
Eric Laurenta553c252009-07-17 12:17:14 -07002904status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002905{
2906 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002907 uint32_t framesReady;
2908 uint32_t framesReq = buffer->frameCount;
2909
2910 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002911 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2912 if (!step()) goto getNextBuffer_exit;
2913 LOGV("stepServer recovered");
2914 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2915 }
2916
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002917 framesReady = cblk->framesReady();
2918
2919 if (LIKELY(framesReady)) {
2920 uint32_t s = cblk->server;
2921 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2922
2923 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2924 if (framesReq > framesReady) {
2925 framesReq = framesReady;
2926 }
2927 if (s + framesReq > bufferEnd) {
2928 framesReq = bufferEnd - s;
2929 }
2930
2931 buffer->raw = getBuffer(s, framesReq);
2932 if (buffer->raw == 0) goto getNextBuffer_exit;
2933
2934 buffer->frameCount = framesReq;
2935 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002936 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002937
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002938getNextBuffer_exit:
2939 buffer->raw = 0;
2940 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002941 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002942 return NOT_ENOUGH_DATA;
2943}
2944
Eric Laurenta553c252009-07-17 12:17:14 -07002945bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07002946 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002947
2948 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002949 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002950 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07002951 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002952 return true;
2953 }
2954 return false;
2955}
2956
Eric Laurenta553c252009-07-17 12:17:14 -07002957status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002958{
Eric Laurent49f02be2009-11-19 09:00:56 -08002959 status_t status = NO_ERROR;
Eric Laurent0d7e0482010-07-19 06:24:46 -07002960 LOGV("start(%d), calling thread %d session %d",
2961 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07002962 sp<ThreadBase> thread = mThread.promote();
2963 if (thread != 0) {
2964 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08002965 int state = mState;
2966 // here the track could be either new, or restarted
2967 // in both cases "unstop" the track
2968 if (mState == PAUSED) {
2969 mState = TrackBase::RESUMING;
2970 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
2971 } else {
2972 mState = TrackBase::ACTIVE;
2973 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
2974 }
2975
2976 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
2977 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002978 status = AudioSystem::startOutput(thread->id(),
2979 (AudioSystem::stream_type)mStreamType,
2980 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08002981 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08002982
2983 // to track the speaker usage
2984 if (status == NO_ERROR) {
2985 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2986 }
Eric Laurent49f02be2009-11-19 09:00:56 -08002987 }
2988 if (status == NO_ERROR) {
2989 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2990 playbackThread->addTrack_l(this);
2991 } else {
2992 mState = state;
2993 }
2994 } else {
2995 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07002996 }
Eric Laurent49f02be2009-11-19 09:00:56 -08002997 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002998}
2999
Eric Laurenta553c252009-07-17 12:17:14 -07003000void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003001{
Eric Laurenta553c252009-07-17 12:17:14 -07003002 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3003 sp<ThreadBase> thread = mThread.promote();
3004 if (thread != 0) {
3005 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003006 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003007 if (mState > STOPPED) {
3008 mState = STOPPED;
3009 // If the track is not active (PAUSED and buffers full), flush buffers
3010 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3011 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3012 reset();
3013 }
Eric Laurent62443f52009-10-05 20:29:18 -07003014 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003015 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003016 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3017 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003018 AudioSystem::stopOutput(thread->id(),
3019 (AudioSystem::stream_type)mStreamType,
3020 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003021 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003022
3023 // to track the speaker usage
3024 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003025 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003026 }
3027}
3028
Eric Laurenta553c252009-07-17 12:17:14 -07003029void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003030{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003032 sp<ThreadBase> thread = mThread.promote();
3033 if (thread != 0) {
3034 Mutex::Autolock _l(thread->mLock);
3035 if (mState == ACTIVE || mState == RESUMING) {
3036 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07003037 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003038 if (!isOutputTrack()) {
3039 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003040 AudioSystem::stopOutput(thread->id(),
3041 (AudioSystem::stream_type)mStreamType,
3042 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003043 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003044
3045 // to track the speaker usage
3046 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003047 }
Eric Laurenta553c252009-07-17 12:17:14 -07003048 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003049 }
3050}
3051
Eric Laurenta553c252009-07-17 12:17:14 -07003052void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003053{
3054 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003055 sp<ThreadBase> thread = mThread.promote();
3056 if (thread != 0) {
3057 Mutex::Autolock _l(thread->mLock);
3058 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3059 return;
3060 }
3061 // No point remaining in PAUSED state after a flush => go to
3062 // STOPPED state
3063 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003064
Eric Laurentae29b762011-03-28 18:37:07 -07003065 // do not reset the track if it is still in the process of being stopped or paused.
3066 // this will be done by prepareTracks_l() when the track is stopped.
3067 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3068 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3069 reset();
3070 }
Eric Laurenta553c252009-07-17 12:17:14 -07003071 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003072}
3073
Eric Laurenta553c252009-07-17 12:17:14 -07003074void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003075{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003076 // Do not reset twice to avoid discarding data written just after a flush and before
3077 // the audioflinger thread detects the track is stopped.
3078 if (!mResetDone) {
3079 TrackBase::reset();
3080 // Force underrun condition to avoid false underrun callback until first data is
3081 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003082 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3083 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003084 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003085 mResetDone = true;
3086 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003087}
3088
Eric Laurenta553c252009-07-17 12:17:14 -07003089void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003090{
3091 mMute = muted;
3092}
3093
Eric Laurenta553c252009-07-17 12:17:14 -07003094void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003095{
3096 mVolume[0] = left;
3097 mVolume[1] = right;
3098}
3099
Eric Laurent65b65452010-06-01 23:49:17 -07003100status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3101{
3102 status_t status = DEAD_OBJECT;
3103 sp<ThreadBase> thread = mThread.promote();
3104 if (thread != 0) {
3105 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3106 status = playbackThread->attachAuxEffect(this, EffectId);
3107 }
3108 return status;
3109}
3110
3111void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3112{
3113 mAuxEffectId = EffectId;
3114 mAuxBuffer = buffer;
3115}
3116
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003117// ----------------------------------------------------------------------------
3118
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003119// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003120AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3121 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 uint32_t sampleRate,
3124 int format,
3125 int channelCount,
3126 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003127 uint32_t flags,
3128 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003129 : TrackBase(thread, client, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07003130 channelCount, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003131 mOverflow(false)
3132{
Eric Laurent8a77a992009-09-09 05:16:08 -07003133 if (mCblk != NULL) {
3134 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3135 if (format == AudioSystem::PCM_16_BIT) {
3136 mCblk->frameSize = channelCount * sizeof(int16_t);
3137 } else if (format == AudioSystem::PCM_8_BIT) {
3138 mCblk->frameSize = channelCount * sizeof(int8_t);
3139 } else {
3140 mCblk->frameSize = sizeof(int8_t);
3141 }
3142 }
Eric Laurenta553c252009-07-17 12:17:14 -07003143}
3144
3145AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146{
Eric Laurent49f02be2009-11-19 09:00:56 -08003147 sp<ThreadBase> thread = mThread.promote();
3148 if (thread != 0) {
3149 AudioSystem::releaseInput(thread->id());
3150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151}
3152
Eric Laurenta553c252009-07-17 12:17:14 -07003153status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154{
3155 audio_track_cblk_t* cblk = this->cblk();
3156 uint32_t framesAvail;
3157 uint32_t framesReq = buffer->frameCount;
3158
3159 // Check if last stepServer failed, try to step now
3160 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3161 if (!step()) goto getNextBuffer_exit;
3162 LOGV("stepServer recovered");
3163 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3164 }
3165
3166 framesAvail = cblk->framesAvailable_l();
3167
3168 if (LIKELY(framesAvail)) {
3169 uint32_t s = cblk->server;
3170 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3171
3172 if (framesReq > framesAvail) {
3173 framesReq = framesAvail;
3174 }
3175 if (s + framesReq > bufferEnd) {
3176 framesReq = bufferEnd - s;
3177 }
3178
3179 buffer->raw = getBuffer(s, framesReq);
3180 if (buffer->raw == 0) goto getNextBuffer_exit;
3181
3182 buffer->frameCount = framesReq;
3183 return NO_ERROR;
3184 }
3185
3186getNextBuffer_exit:
3187 buffer->raw = 0;
3188 buffer->frameCount = 0;
3189 return NOT_ENOUGH_DATA;
3190}
3191
Eric Laurenta553c252009-07-17 12:17:14 -07003192status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193{
Eric Laurenta553c252009-07-17 12:17:14 -07003194 sp<ThreadBase> thread = mThread.promote();
3195 if (thread != 0) {
3196 RecordThread *recordThread = (RecordThread *)thread.get();
3197 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003198 } else {
3199 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201}
3202
Eric Laurenta553c252009-07-17 12:17:14 -07003203void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204{
Eric Laurenta553c252009-07-17 12:17:14 -07003205 sp<ThreadBase> thread = mThread.promote();
3206 if (thread != 0) {
3207 RecordThread *recordThread = (RecordThread *)thread.get();
3208 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003209 TrackBase::reset();
3210 // Force overerrun condition to avoid false overrun callback until first data is
3211 // read from buffer
3212 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214}
3215
Eric Laurent3fdb1262009-11-07 00:01:32 -08003216void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3217{
Eric Laurent65b65452010-06-01 23:49:17 -07003218 snprintf(buffer, size, " %05d %03u %03u %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003219 (mClient == NULL) ? getpid() : mClient->pid(),
3220 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07003221 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003222 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003223 mFrameCount,
3224 mState,
3225 mCblk->sampleRate,
3226 mCblk->server,
3227 mCblk->user);
3228}
3229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230
3231// ----------------------------------------------------------------------------
3232
Eric Laurenta553c252009-07-17 12:17:14 -07003233AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3234 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003235 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 uint32_t sampleRate,
3237 int format,
3238 int channelCount,
3239 int frameCount)
Eric Laurent65b65452010-06-01 23:49:17 -07003240 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003241 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242{
Eric Laurenta553c252009-07-17 12:17:14 -07003243
3244 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003245 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003246 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003247 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3248 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3249 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003250 playbackThread->mTracks.add(this);
Eric Laurentb0a01472010-05-14 05:45:46 -07003251 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3252 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003253 } else {
3254 LOGW("Error creating output track on thread %p", playbackThread);
3255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256}
3257
Eric Laurenta553c252009-07-17 12:17:14 -07003258AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259{
Eric Laurent6c30a712009-08-10 23:22:32 -07003260 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261}
3262
Eric Laurenta553c252009-07-17 12:17:14 -07003263status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264{
3265 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003266 if (status != NO_ERROR) {
3267 return status;
3268 }
3269
3270 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 mRetryCount = 127;
3272 return status;
3273}
3274
Eric Laurenta553c252009-07-17 12:17:14 -07003275void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276{
3277 Track::stop();
3278 clearBufferQueue();
3279 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003280 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281}
3282
Eric Laurenta553c252009-07-17 12:17:14 -07003283bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284{
3285 Buffer *pInBuffer;
3286 Buffer inBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003287 uint32_t channelCount = mCblk->channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003288 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 inBuffer.frameCount = frames;
3290 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003291
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003292 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003293
Eric Laurent62443f52009-10-05 20:29:18 -07003294 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003295 start();
3296 sp<ThreadBase> thread = mThread.promote();
3297 if (thread != 0) {
3298 MixerThread *mixerThread = (MixerThread *)thread.get();
3299 if (mCblk->frameCount > frames){
3300 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3301 uint32_t startFrames = (mCblk->frameCount - frames);
3302 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003303 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003304 pInBuffer->frameCount = startFrames;
3305 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003306 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003307 mBufferQueue.add(pInBuffer);
3308 } else {
3309 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 }
Eric Laurenta553c252009-07-17 12:17:14 -07003312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 }
3314
Eric Laurenta553c252009-07-17 12:17:14 -07003315 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 // First write pending buffers, then new data
3317 if (mBufferQueue.size()) {
3318 pInBuffer = mBufferQueue.itemAt(0);
3319 } else {
3320 pInBuffer = &inBuffer;
3321 }
Eric Laurenta553c252009-07-17 12:17:14 -07003322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 if (pInBuffer->frameCount == 0) {
3324 break;
3325 }
Eric Laurenta553c252009-07-17 12:17:14 -07003326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 if (mOutBuffer.frameCount == 0) {
3328 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003329 nsecs_t startTime = systemTime();
3330 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003331 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003332 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 break;
3334 }
Eric Laurenta553c252009-07-17 12:17:14 -07003335 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003336 if (waitTimeLeftMs >= waitTimeMs) {
3337 waitTimeLeftMs -= waitTimeMs;
3338 } else {
3339 waitTimeLeftMs = 0;
3340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 }
Eric Laurenta553c252009-07-17 12:17:14 -07003342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003344 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 mCblk->stepUser(outFrames);
3346 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003347 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003349 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 if (pInBuffer->frameCount == 0) {
3352 if (mBufferQueue.size()) {
3353 mBufferQueue.removeAt(0);
3354 delete [] pInBuffer->mBuffer;
3355 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003356 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 } else {
3358 break;
3359 }
3360 }
3361 }
Eric Laurenta553c252009-07-17 12:17:14 -07003362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 // If we could not write all frames, allocate a buffer and queue it for next time.
3364 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003365 sp<ThreadBase> thread = mThread.promote();
3366 if (thread != 0 && !thread->standby()) {
3367 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3368 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003369 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003370 pInBuffer->frameCount = inBuffer.frameCount;
3371 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003372 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003373 mBufferQueue.add(pInBuffer);
3374 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3375 } else {
3376 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 }
3379 }
Eric Laurenta553c252009-07-17 12:17:14 -07003380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003382 // If no more buffers are pending, fill output track buffer to make sure it is started
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003384 if (frames == 0 && mBufferQueue.size() == 0) {
3385 if (mCblk->user < mCblk->frameCount) {
3386 frames = mCblk->frameCount - mCblk->user;
3387 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003388 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003389 pInBuffer->frameCount = frames;
3390 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003391 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003392 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003393 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003394 stop();
3395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 }
3397
Eric Laurenta553c252009-07-17 12:17:14 -07003398 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399}
3400
Eric Laurenta553c252009-07-17 12:17:14 -07003401status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402{
3403 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 status_t result;
3405 audio_track_cblk_t* cblk = mCblk;
3406 uint32_t framesReq = buffer->frameCount;
3407
Eric Laurenta553c252009-07-17 12:17:14 -07003408// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 uint32_t framesAvail = cblk->framesAvailable();
3412
Eric Laurenta553c252009-07-17 12:17:14 -07003413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003415 Mutex::Autolock _l(cblk->lock);
3416 goto start_loop_here;
3417 while (framesAvail == 0) {
3418 active = mActive;
3419 if (UNLIKELY(!active)) {
3420 LOGV("Not active and NO_MORE_BUFFERS");
3421 return AudioTrack::NO_MORE_BUFFERS;
3422 }
3423 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3424 if (result != NO_ERROR) {
3425 return AudioTrack::NO_MORE_BUFFERS;
3426 }
3427 // read the server count again
3428 start_loop_here:
3429 framesAvail = cblk->framesAvailable_l();
3430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 }
3432
Eric Laurenta553c252009-07-17 12:17:14 -07003433// if (framesAvail < framesReq) {
3434// return AudioTrack::NO_MORE_BUFFERS;
3435// }
3436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 if (framesReq > framesAvail) {
3438 framesReq = framesAvail;
3439 }
3440
3441 uint32_t u = cblk->user;
3442 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3443
3444 if (u + framesReq > bufferEnd) {
3445 framesReq = bufferEnd - u;
3446 }
3447
3448 buffer->frameCount = framesReq;
3449 buffer->raw = (void *)cblk->buffer(u);
3450 return NO_ERROR;
3451}
3452
3453
Eric Laurenta553c252009-07-17 12:17:14 -07003454void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455{
3456 size_t size = mBufferQueue.size();
3457 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 for (size_t i = 0; i < size; i++) {
3460 pBuffer = mBufferQueue.itemAt(i);
3461 delete [] pBuffer->mBuffer;
3462 delete pBuffer;
3463 }
3464 mBufferQueue.clear();
3465}
3466
3467// ----------------------------------------------------------------------------
3468
3469AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3470 : RefBase(),
3471 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003472 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 mPid(pid)
3474{
3475 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3476}
3477
Eric Laurentb9481d82009-09-17 05:12:56 -07003478// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479AudioFlinger::Client::~Client()
3480{
Eric Laurentb9481d82009-09-17 05:12:56 -07003481 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482}
3483
3484const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3485{
3486 return mMemoryDealer;
3487}
3488
3489// ----------------------------------------------------------------------------
3490
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003491AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3492 const sp<IAudioFlingerClient>& client,
3493 pid_t pid)
3494 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3495{
3496}
3497
3498AudioFlinger::NotificationClient::~NotificationClient()
3499{
3500 mClient.clear();
3501}
3502
3503void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3504{
3505 sp<NotificationClient> keep(this);
3506 {
3507 mAudioFlinger->removeNotificationClient(mPid);
3508 }
3509}
3510
3511// ----------------------------------------------------------------------------
3512
Eric Laurenta553c252009-07-17 12:17:14 -07003513AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003514 : BnAudioTrack(),
3515 mTrack(track)
3516{
3517}
3518
3519AudioFlinger::TrackHandle::~TrackHandle() {
3520 // just stop the track on deletion, associated resources
3521 // will be freed from the main thread once all pending buffers have
3522 // been played. Unless it's not in the active track list, in which
3523 // case we free everything now...
3524 mTrack->destroy();
3525}
3526
3527status_t AudioFlinger::TrackHandle::start() {
3528 return mTrack->start();
3529}
3530
3531void AudioFlinger::TrackHandle::stop() {
3532 mTrack->stop();
3533}
3534
3535void AudioFlinger::TrackHandle::flush() {
3536 mTrack->flush();
3537}
3538
3539void AudioFlinger::TrackHandle::mute(bool e) {
3540 mTrack->mute(e);
3541}
3542
3543void AudioFlinger::TrackHandle::pause() {
3544 mTrack->pause();
3545}
3546
3547void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3548 mTrack->setVolume(left, right);
3549}
3550
3551sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3552 return mTrack->getCblk();
3553}
3554
Eric Laurent65b65452010-06-01 23:49:17 -07003555status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3556{
3557 return mTrack->attachAuxEffect(EffectId);
3558}
3559
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003560status_t AudioFlinger::TrackHandle::onTransact(
3561 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3562{
3563 return BnAudioTrack::onTransact(code, data, reply, flags);
3564}
3565
3566// ----------------------------------------------------------------------------
3567
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003568sp<IAudioRecord> AudioFlinger::openRecord(
3569 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003570 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003571 uint32_t sampleRate,
3572 int format,
3573 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003574 int frameCount,
3575 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003576 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003577 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003578{
Eric Laurenta553c252009-07-17 12:17:14 -07003579 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003580 sp<RecordHandle> recordHandle;
3581 sp<Client> client;
3582 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003583 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003584 RecordThread *thread;
3585 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07003586 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003587
3588 // check calling permissions
3589 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003590 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003591 goto Exit;
3592 }
3593
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003594 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003595 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003596 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003597 thread = checkRecordThread_l(input);
3598 if (thread == NULL) {
3599 lStatus = BAD_VALUE;
3600 goto Exit;
3601 }
3602
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003603 wclient = mClients.valueFor(pid);
3604 if (wclient != NULL) {
3605 client = wclient.promote();
3606 } else {
3607 client = new Client(this, pid);
3608 mClients.add(pid, client);
3609 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003610
Eric Laurent65b65452010-06-01 23:49:17 -07003611 // If no audio session id is provided, create one here
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003612 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07003613 lSessionId = *sessionId;
3614 } else {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08003615 lSessionId = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003616 if (sessionId != NULL) {
3617 *sessionId = lSessionId;
3618 }
3619 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003620 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07003621 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Eric Laurent65b65452010-06-01 23:49:17 -07003622 format, channelCount, frameCount, flags, lSessionId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 if (recordTrack->getCblk() == NULL) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003625 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3626 // destructor is called by the TrackBase destructor with mLock held
3627 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628 recordTrack.clear();
3629 lStatus = NO_MEMORY;
3630 goto Exit;
3631 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003632
3633 // return to handle to client
3634 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003635 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003636
3637Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003638 if (status) {
3639 *status = lStatus;
3640 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003641 return recordHandle;
3642}
3643
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003644// ----------------------------------------------------------------------------
3645
Eric Laurenta553c252009-07-17 12:17:14 -07003646AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003647 : BnAudioRecord(),
3648 mRecordTrack(recordTrack)
3649{
3650}
3651
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003652AudioFlinger::RecordHandle::~RecordHandle() {
3653 stop();
3654}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003655
3656status_t AudioFlinger::RecordHandle::start() {
3657 LOGV("RecordHandle::start()");
3658 return mRecordTrack->start();
3659}
3660
3661void AudioFlinger::RecordHandle::stop() {
3662 LOGV("RecordHandle::stop()");
3663 mRecordTrack->stop();
3664}
3665
3666sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3667 return mRecordTrack->getCblk();
3668}
3669
3670status_t AudioFlinger::RecordHandle::onTransact(
3671 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3672{
3673 return BnAudioRecord::onTransact(code, data, reply, flags);
3674}
3675
3676// ----------------------------------------------------------------------------
3677
Eric Laurent49f02be2009-11-19 09:00:56 -08003678AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3679 ThreadBase(audioFlinger, id),
Eric Laurenta553c252009-07-17 12:17:14 -07003680 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003681{
Eric Laurenta553c252009-07-17 12:17:14 -07003682 mReqChannelCount = AudioSystem::popCount(channels);
3683 mReqSampleRate = sampleRate;
3684 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003685}
3686
Eric Laurenta553c252009-07-17 12:17:14 -07003687
3688AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003689{
Eric Laurenta553c252009-07-17 12:17:14 -07003690 delete[] mRsmpInBuffer;
3691 if (mResampler != 0) {
3692 delete mResampler;
3693 delete[] mRsmpOutBuffer;
3694 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003695}
3696
Eric Laurenta553c252009-07-17 12:17:14 -07003697void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003698{
Eric Laurenta553c252009-07-17 12:17:14 -07003699 const size_t SIZE = 256;
3700 char buffer[SIZE];
3701
3702 snprintf(buffer, SIZE, "Record Thread %p", this);
3703
3704 run(buffer, PRIORITY_URGENT_AUDIO);
3705}
Eric Laurent49f02be2009-11-19 09:00:56 -08003706
Eric Laurenta553c252009-07-17 12:17:14 -07003707bool AudioFlinger::RecordThread::threadLoop()
3708{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003709 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003710 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003711
Eric Laurent4712baa2010-09-30 16:12:31 -07003712 nsecs_t lastWarning = 0;
3713
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003714 // start recording
3715 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003716
Eric Laurenta553c252009-07-17 12:17:14 -07003717 processConfigEvents();
3718
3719 { // scope for mLock
3720 Mutex::Autolock _l(mLock);
3721 checkForNewParameters_l();
3722 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3723 if (!mStandby) {
3724 mInput->standby();
3725 mStandby = true;
3726 }
3727
3728 if (exitPending()) break;
3729
3730 LOGV("RecordThread: loop stopping");
3731 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003732 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003733 LOGV("RecordThread: loop starting");
3734 continue;
3735 }
3736 if (mActiveTrack != 0) {
3737 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003738 if (!mStandby) {
3739 mInput->standby();
3740 mStandby = true;
3741 }
Eric Laurenta553c252009-07-17 12:17:14 -07003742 mActiveTrack.clear();
3743 mStartStopCond.broadcast();
3744 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07003745 if (mReqChannelCount != mActiveTrack->channelCount()) {
3746 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003747 mStartStopCond.broadcast();
3748 } else if (mBytesRead != 0) {
3749 // record start succeeds only if first read from audio input
3750 // succeeds
3751 if (mBytesRead > 0) {
3752 mActiveTrack->mState = TrackBase::ACTIVE;
3753 } else {
3754 mActiveTrack.clear();
3755 }
3756 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07003757 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003758 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07003759 }
Eric Laurenta553c252009-07-17 12:17:14 -07003760 }
3761 }
3762
3763 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003764 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3765 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003766 usleep(5000);
3767 continue;
3768 }
Eric Laurenta553c252009-07-17 12:17:14 -07003769 buffer.frameCount = mFrameCount;
3770 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3771 size_t framesOut = buffer.frameCount;
3772 if (mResampler == 0) {
3773 // no resampling
3774 while (framesOut) {
3775 size_t framesIn = mFrameCount - mRsmpInIndex;
3776 if (framesIn) {
3777 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3778 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3779 if (framesIn > framesOut)
3780 framesIn = framesOut;
3781 mRsmpInIndex += framesIn;
3782 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07003783 if ((int)mChannelCount == mReqChannelCount ||
Eric Laurenta553c252009-07-17 12:17:14 -07003784 mFormat != AudioSystem::PCM_16_BIT) {
3785 memcpy(dst, src, framesIn * mFrameSize);
3786 } else {
3787 int16_t *src16 = (int16_t *)src;
3788 int16_t *dst16 = (int16_t *)dst;
3789 if (mChannelCount == 1) {
3790 while (framesIn--) {
3791 *dst16++ = *src16;
3792 *dst16++ = *src16++;
3793 }
3794 } else {
3795 while (framesIn--) {
3796 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3797 src16 += 2;
3798 }
3799 }
3800 }
3801 }
3802 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07003803 if (framesOut == mFrameCount &&
Eric Laurentb0a01472010-05-14 05:45:46 -07003804 ((int)mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003805 mBytesRead = mInput->read(buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003806 framesOut = 0;
3807 } else {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003808 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003809 mRsmpInIndex = 0;
3810 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003811 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003812 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003813 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003814 // Force input into standby so that it tries to
3815 // recover at next read attempt
3816 mInput->standby();
3817 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003818 }
Eric Laurenta553c252009-07-17 12:17:14 -07003819 mRsmpInIndex = mFrameCount;
3820 framesOut = 0;
3821 buffer.frameCount = 0;
3822 }
3823 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003824 }
3825 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07003826 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003827
Eric Laurenta553c252009-07-17 12:17:14 -07003828 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3829 // alter output frame count as if we were expecting stereo samples
3830 if (mChannelCount == 1 && mReqChannelCount == 1) {
3831 framesOut >>= 1;
3832 }
3833 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3834 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3835 // are 32 bit aligned which should be always true.
3836 if (mChannelCount == 2 && mReqChannelCount == 1) {
3837 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3838 // the resampler always outputs stereo samples: do post stereo to mono conversion
3839 int16_t *src = (int16_t *)mRsmpOutBuffer;
3840 int16_t *dst = buffer.i16;
3841 while (framesOut--) {
3842 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3843 src += 2;
3844 }
3845 } else {
3846 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3847 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003848
Eric Laurenta553c252009-07-17 12:17:14 -07003849 }
3850 mActiveTrack->releaseBuffer(&buffer);
3851 mActiveTrack->overflow();
3852 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003853 // client isn't retrieving buffers fast enough
3854 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07003855 if (!mActiveTrack->setOverflow()) {
3856 nsecs_t now = systemTime();
3857 if ((now - lastWarning) > kWarningThrottle) {
3858 LOGW("RecordThread: buffer overflow");
3859 lastWarning = now;
3860 }
3861 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003862 // Release the processor for a while before asking for a new buffer.
3863 // This will give the application more chance to read from the buffer and
3864 // clear the overflow.
3865 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003866 }
3867 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003868 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003869
Eric Laurenta553c252009-07-17 12:17:14 -07003870 if (!mStandby) {
3871 mInput->standby();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003872 }
Eric Laurenta553c252009-07-17 12:17:14 -07003873 mActiveTrack.clear();
3874
Eric Laurent49f02be2009-11-19 09:00:56 -08003875 mStartStopCond.broadcast();
3876
Eric Laurenta553c252009-07-17 12:17:14 -07003877 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003878 return false;
3879}
3880
Eric Laurenta553c252009-07-17 12:17:14 -07003881status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003882{
Eric Laurenta553c252009-07-17 12:17:14 -07003883 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08003884 sp <ThreadBase> strongMe = this;
3885 status_t status = NO_ERROR;
3886 {
3887 AutoMutex lock(&mLock);
3888 if (mActiveTrack != 0) {
3889 if (recordTrack != mActiveTrack.get()) {
3890 status = -EBUSY;
3891 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003892 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08003893 }
3894 return status;
3895 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003896
Eric Laurent49f02be2009-11-19 09:00:56 -08003897 recordTrack->mState = TrackBase::IDLE;
3898 mActiveTrack = recordTrack;
3899 mLock.unlock();
3900 status_t status = AudioSystem::startInput(mId);
3901 mLock.lock();
3902 if (status != NO_ERROR) {
3903 mActiveTrack.clear();
3904 return status;
3905 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003906 mRsmpInIndex = mFrameCount;
3907 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08003908 if (mResampler != NULL) {
3909 mResampler->reset();
3910 }
3911 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08003912 // signal thread to start
3913 LOGV("Signal record thread");
3914 mWaitWorkCV.signal();
3915 // do not wait for mStartStopCond if exiting
3916 if (mExiting) {
3917 mActiveTrack.clear();
3918 status = INVALID_OPERATION;
3919 goto startError;
3920 }
3921 mStartStopCond.wait(mLock);
3922 if (mActiveTrack == 0) {
3923 LOGV("Record failed to start");
3924 status = BAD_VALUE;
3925 goto startError;
3926 }
Eric Laurenta553c252009-07-17 12:17:14 -07003927 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003928 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07003929 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003930startError:
3931 AudioSystem::stopInput(mId);
3932 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003933}
3934
Eric Laurenta553c252009-07-17 12:17:14 -07003935void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3936 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08003937 sp <ThreadBase> strongMe = this;
3938 {
3939 AutoMutex lock(&mLock);
3940 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3941 mActiveTrack->mState = TrackBase::PAUSING;
3942 // do not wait for mStartStopCond if exiting
3943 if (mExiting) {
3944 return;
3945 }
3946 mStartStopCond.wait(mLock);
3947 // if we have been restarted, recordTrack == mActiveTrack.get() here
3948 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
3949 mLock.unlock();
3950 AudioSystem::stopInput(mId);
3951 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003952 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003953 }
3954 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003955 }
3956}
3957
Eric Laurenta553c252009-07-17 12:17:14 -07003958status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959{
3960 const size_t SIZE = 256;
3961 char buffer[SIZE];
3962 String8 result;
3963 pid_t pid = 0;
3964
Eric Laurent3fdb1262009-11-07 00:01:32 -08003965 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
3966 result.append(buffer);
3967
3968 if (mActiveTrack != 0) {
3969 result.append("Active Track:\n");
Eric Laurent65b65452010-06-01 23:49:17 -07003970 result.append(" Clien Fmt Chn Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08003971 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08003973
3974 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
3975 result.append(buffer);
3976 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
3977 result.append(buffer);
3978 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
3979 result.append(buffer);
3980 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
3981 result.append(buffer);
3982 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
3983 result.append(buffer);
3984
3985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 } else {
3987 result.append("No record client\n");
3988 }
3989 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08003990
3991 dumpBase(fd, args);
3992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 return NO_ERROR;
3994}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003995
Eric Laurenta553c252009-07-17 12:17:14 -07003996status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3997{
3998 size_t framesReq = buffer->frameCount;
3999 size_t framesReady = mFrameCount - mRsmpInIndex;
4000 int channelCount;
4001
4002 if (framesReady == 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004003 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
4004 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004005 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004006 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004007 // Force input into standby so that it tries to
4008 // recover at next read attempt
4009 mInput->standby();
4010 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004011 }
Eric Laurenta553c252009-07-17 12:17:14 -07004012 buffer->raw = 0;
4013 buffer->frameCount = 0;
4014 return NOT_ENOUGH_DATA;
4015 }
4016 mRsmpInIndex = 0;
4017 framesReady = mFrameCount;
4018 }
4019
4020 if (framesReq > framesReady) {
4021 framesReq = framesReady;
4022 }
4023
4024 if (mChannelCount == 1 && mReqChannelCount == 2) {
4025 channelCount = 1;
4026 } else {
4027 channelCount = 2;
4028 }
4029 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4030 buffer->frameCount = framesReq;
4031 return NO_ERROR;
4032}
4033
4034void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4035{
4036 mRsmpInIndex += buffer->frameCount;
4037 buffer->frameCount = 0;
4038}
4039
4040bool AudioFlinger::RecordThread::checkForNewParameters_l()
4041{
4042 bool reconfig = false;
4043
Eric Laurent8fce46a2009-08-04 09:45:33 -07004044 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004045 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004046 String8 keyValuePair = mNewParameters[0];
4047 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004048 int value;
4049 int reqFormat = mFormat;
4050 int reqSamplingRate = mReqSampleRate;
4051 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004052
Eric Laurenta553c252009-07-17 12:17:14 -07004053 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4054 reqSamplingRate = value;
4055 reconfig = true;
4056 }
4057 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4058 reqFormat = value;
4059 reconfig = true;
4060 }
4061 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4062 reqChannelCount = AudioSystem::popCount(value);
4063 reconfig = true;
4064 }
4065 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4066 // do not accept frame count changes if tracks are open as the track buffer
4067 // size depends on frame count and correct behavior would not be garantied
4068 // if frame count is changed after track creation
4069 if (mActiveTrack != 0) {
4070 status = INVALID_OPERATION;
4071 } else {
4072 reconfig = true;
4073 }
4074 }
4075 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07004076 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004077 if (status == INVALID_OPERATION) {
4078 mInput->standby();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004079 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004080 }
4081 if (reconfig) {
4082 if (status == BAD_VALUE &&
4083 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
4084 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
4085 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
4086 status = NO_ERROR;
4087 }
4088 if (status == NO_ERROR) {
4089 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004090 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004091 }
4092 }
4093 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004094
4095 mNewParameters.removeAt(0);
4096
Eric Laurenta553c252009-07-17 12:17:14 -07004097 mParamStatus = status;
4098 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004099 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004100 }
4101 return reconfig;
4102}
4103
4104String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4105{
4106 return mInput->getParameters(keys);
4107}
4108
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004109void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004110 AudioSystem::OutputDescriptor desc;
4111 void *param2 = 0;
4112
4113 switch (event) {
4114 case AudioSystem::INPUT_OPENED:
4115 case AudioSystem::INPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07004116 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07004117 desc.samplingRate = mSampleRate;
4118 desc.format = mFormat;
4119 desc.frameCount = mFrameCount;
4120 desc.latency = 0;
4121 param2 = &desc;
4122 break;
4123
4124 case AudioSystem::INPUT_CLOSED:
4125 default:
4126 break;
4127 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004128 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004129}
4130
4131void AudioFlinger::RecordThread::readInputParameters()
4132{
4133 if (mRsmpInBuffer) delete mRsmpInBuffer;
4134 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4135 if (mResampler) delete mResampler;
4136 mResampler = 0;
4137
4138 mSampleRate = mInput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07004139 mChannels = mInput->channels();
4140 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07004141 mFormat = mInput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07004142 mFrameSize = (uint16_t)mInput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07004143 mInputBytes = mInput->bufferSize();
4144 mFrameCount = mInputBytes / mFrameSize;
4145 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4146
4147 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4148 {
4149 int channelCount;
4150 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4151 // stereo to mono post process as the resampler always outputs stereo.
4152 if (mChannelCount == 1 && mReqChannelCount == 2) {
4153 channelCount = 1;
4154 } else {
4155 channelCount = 2;
4156 }
4157 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4158 mResampler->setSampleRate(mSampleRate);
4159 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4160 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4161
4162 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4163 if (mChannelCount == 1 && mReqChannelCount == 1) {
4164 mFrameCount >>= 1;
4165 }
4166
4167 }
4168 mRsmpInIndex = mFrameCount;
4169}
4170
Eric Laurent47d0a922010-02-26 02:47:27 -08004171unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4172{
4173 return mInput->getInputFramesLost();
4174}
4175
Eric Laurenta553c252009-07-17 12:17:14 -07004176// ----------------------------------------------------------------------------
4177
Eric Laurentddb78e72009-07-28 08:44:33 -07004178int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004179 uint32_t *pSamplingRate,
4180 uint32_t *pFormat,
4181 uint32_t *pChannels,
4182 uint32_t *pLatencyMs,
4183 uint32_t flags)
4184{
4185 status_t status;
4186 PlaybackThread *thread = NULL;
4187 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4188 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4189 uint32_t format = pFormat ? *pFormat : 0;
4190 uint32_t channels = pChannels ? *pChannels : 0;
4191 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4192
4193 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4194 pDevices ? *pDevices : 0,
4195 samplingRate,
4196 format,
4197 channels,
4198 flags);
4199
4200 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004201 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004202 }
4203 Mutex::Autolock _l(mLock);
4204
4205 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
4206 (int *)&format,
4207 &channels,
4208 &samplingRate,
4209 &status);
4210 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4211 output,
4212 samplingRate,
4213 format,
4214 channels,
4215 status);
4216
4217 mHardwareStatus = AUDIO_HW_IDLE;
4218 if (output != 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004219 int id = nextUniqueId_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004220 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
4221 (format != AudioSystem::PCM_16_BIT) ||
4222 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004223 thread = new DirectOutputThread(this, output, id, *pDevices);
4224 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004225 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004226 thread = new MixerThread(this, output, id, *pDevices);
4227 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004228 }
Eric Laurent65b65452010-06-01 23:49:17 -07004229 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004230
4231 if (pSamplingRate) *pSamplingRate = samplingRate;
4232 if (pFormat) *pFormat = format;
4233 if (pChannels) *pChannels = channels;
4234 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004235
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004236 // notify client processes of the new output creation
4237 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004238 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004239 }
4240
Eric Laurent9cc489a22009-12-05 05:20:01 -08004241 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004242}
4243
Eric Laurentddb78e72009-07-28 08:44:33 -07004244int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004245{
4246 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004247 MixerThread *thread1 = checkMixerThread_l(output1);
4248 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004249
Eric Laurentddb78e72009-07-28 08:44:33 -07004250 if (thread1 == NULL || thread2 == NULL) {
4251 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4252 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004253 }
4254
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004255 int id = nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07004256 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004257 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004258 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004259 // notify client processes of the new output creation
4260 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004261 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004262}
4263
Eric Laurentddb78e72009-07-28 08:44:33 -07004264status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004265{
Eric Laurent49018a52009-08-04 08:37:05 -07004266 // keep strong reference on the playback thread so that
4267 // it is not destroyed while exit() is executed
4268 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004269 {
4270 Mutex::Autolock _l(mLock);
4271 thread = checkPlaybackThread_l(output);
4272 if (thread == NULL) {
4273 return BAD_VALUE;
4274 }
4275
Eric Laurentddb78e72009-07-28 08:44:33 -07004276 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004277
4278 if (thread->type() == PlaybackThread::MIXER) {
4279 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004280 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4281 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004282 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004283 }
4284 }
4285 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004286 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004287 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004288 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004289 }
4290 thread->exit();
4291
Eric Laurent49018a52009-08-04 08:37:05 -07004292 if (thread->type() != PlaybackThread::DUPLICATING) {
4293 mAudioHardware->closeOutputStream(thread->getOutput());
4294 }
Eric Laurenta553c252009-07-17 12:17:14 -07004295 return NO_ERROR;
4296}
4297
Eric Laurentddb78e72009-07-28 08:44:33 -07004298status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004299{
4300 Mutex::Autolock _l(mLock);
4301 PlaybackThread *thread = checkPlaybackThread_l(output);
4302
4303 if (thread == NULL) {
4304 return BAD_VALUE;
4305 }
4306
Eric Laurentddb78e72009-07-28 08:44:33 -07004307 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004308 thread->suspend();
4309
4310 return NO_ERROR;
4311}
4312
Eric Laurentddb78e72009-07-28 08:44:33 -07004313status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004314{
4315 Mutex::Autolock _l(mLock);
4316 PlaybackThread *thread = checkPlaybackThread_l(output);
4317
4318 if (thread == NULL) {
4319 return BAD_VALUE;
4320 }
4321
Eric Laurentddb78e72009-07-28 08:44:33 -07004322 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004323
4324 thread->restore();
4325
4326 return NO_ERROR;
4327}
4328
Eric Laurentddb78e72009-07-28 08:44:33 -07004329int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004330 uint32_t *pSamplingRate,
4331 uint32_t *pFormat,
4332 uint32_t *pChannels,
4333 uint32_t acoustics)
4334{
4335 status_t status;
4336 RecordThread *thread = NULL;
4337 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4338 uint32_t format = pFormat ? *pFormat : 0;
4339 uint32_t channels = pChannels ? *pChannels : 0;
4340 uint32_t reqSamplingRate = samplingRate;
4341 uint32_t reqFormat = format;
4342 uint32_t reqChannels = channels;
4343
4344 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004345 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004346 }
4347 Mutex::Autolock _l(mLock);
4348
4349 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
4350 (int *)&format,
4351 &channels,
4352 &samplingRate,
4353 &status,
4354 (AudioSystem::audio_in_acoustics)acoustics);
4355 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
4356 input,
4357 samplingRate,
4358 format,
4359 channels,
4360 acoustics,
4361 status);
4362
4363 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4364 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4365 // or stereo to mono conversions on 16 bit PCM inputs.
4366 if (input == 0 && status == BAD_VALUE &&
4367 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
4368 (samplingRate <= 2 * reqSamplingRate) &&
4369 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
4370 LOGV("openInput() reopening with proposed sampling rate and channels");
4371 input = mAudioHardware->openInputStream(*pDevices,
4372 (int *)&format,
4373 &channels,
4374 &samplingRate,
4375 &status,
4376 (AudioSystem::audio_in_acoustics)acoustics);
4377 }
4378
4379 if (input != 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004380 int id = nextUniqueId_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004381 // Start record thread
Eric Laurent65b65452010-06-01 23:49:17 -07004382 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4383 mRecordThreads.add(id, thread);
4384 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004385 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4386 if (pFormat) *pFormat = format;
4387 if (pChannels) *pChannels = reqChannels;
4388
4389 input->standby();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004390
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004391 // notify client processes of the new input creation
4392 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004393 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004394 }
4395
Eric Laurent9cc489a22009-12-05 05:20:01 -08004396 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004397}
4398
Eric Laurentddb78e72009-07-28 08:44:33 -07004399status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07004400{
Eric Laurent49018a52009-08-04 08:37:05 -07004401 // keep strong reference on the record thread so that
4402 // it is not destroyed while exit() is executed
4403 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004404 {
4405 Mutex::Autolock _l(mLock);
4406 thread = checkRecordThread_l(input);
4407 if (thread == NULL) {
4408 return BAD_VALUE;
4409 }
4410
Eric Laurentddb78e72009-07-28 08:44:33 -07004411 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07004412 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004413 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004414 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07004415 }
4416 thread->exit();
4417
Eric Laurent49018a52009-08-04 08:37:05 -07004418 mAudioHardware->closeInputStream(thread->getInput());
4419
Eric Laurenta553c252009-07-17 12:17:14 -07004420 return NO_ERROR;
4421}
4422
Eric Laurentddb78e72009-07-28 08:44:33 -07004423status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004424{
4425 Mutex::Autolock _l(mLock);
4426 MixerThread *dstThread = checkMixerThread_l(output);
4427 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004428 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004429 return BAD_VALUE;
4430 }
4431
Eric Laurentddb78e72009-07-28 08:44:33 -07004432 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004433 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004434
4435 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004436 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004437 if (thread != dstThread &&
4438 thread->type() != PlaybackThread::DIRECT) {
4439 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004440 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004441 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004442 }
Eric Laurentd069f322009-09-01 05:56:26 -07004443
Eric Laurenta553c252009-07-17 12:17:14 -07004444 return NO_ERROR;
4445}
4446
Eric Laurent65b65452010-06-01 23:49:17 -07004447
4448int AudioFlinger::newAudioSessionId()
4449{
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004450 AutoMutex _l(mLock);
4451 return nextUniqueId_l();
Eric Laurent65b65452010-06-01 23:49:17 -07004452}
4453
Eric Laurenta553c252009-07-17 12:17:14 -07004454// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004455AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004456{
4457 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004458 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4459 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004460 }
Eric Laurenta553c252009-07-17 12:17:14 -07004461 return thread;
4462}
4463
4464// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004465AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004466{
4467 PlaybackThread *thread = checkPlaybackThread_l(output);
4468 if (thread != NULL) {
4469 if (thread->type() == PlaybackThread::DIRECT) {
4470 thread = NULL;
4471 }
4472 }
4473 return (MixerThread *)thread;
4474}
4475
4476// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004477AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004478{
4479 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004480 if (mRecordThreads.indexOfKey(input) >= 0) {
4481 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004482 }
Eric Laurenta553c252009-07-17 12:17:14 -07004483 return thread;
4484}
4485
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004486// nextUniqueId_l() must be called with AudioFlinger::mLock held
4487int AudioFlinger::nextUniqueId_l()
Eric Laurent65b65452010-06-01 23:49:17 -07004488{
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004489 return mNextUniqueId++;
Eric Laurent65b65452010-06-01 23:49:17 -07004490}
4491
4492// ----------------------------------------------------------------------------
4493// Effect management
4494// ----------------------------------------------------------------------------
4495
4496
4497status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4498{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004499 // check calling permissions
4500 if (!settingsAllowed()) {
4501 return PERMISSION_DENIED;
4502 }
4503 // only allow libraries loaded from /system/lib/soundfx for now
4504 if (strncmp(gEffectLibPath, libPath, strlen(gEffectLibPath)) != 0) {
4505 return PERMISSION_DENIED;
4506 }
4507
Eric Laurent65b65452010-06-01 23:49:17 -07004508 Mutex::Autolock _l(mLock);
4509 return EffectLoadLibrary(libPath, handle);
4510}
4511
4512status_t AudioFlinger::unloadEffectLibrary(int handle)
4513{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004514 // check calling permissions
4515 if (!settingsAllowed()) {
4516 return PERMISSION_DENIED;
4517 }
4518
Eric Laurent65b65452010-06-01 23:49:17 -07004519 Mutex::Autolock _l(mLock);
4520 return EffectUnloadLibrary(handle);
4521}
4522
4523status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4524{
4525 Mutex::Autolock _l(mLock);
4526 return EffectQueryNumberEffects(numEffects);
4527}
4528
Eric Laurent53334cd2010-06-23 17:38:20 -07004529status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07004530{
4531 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004532 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07004533}
4534
4535status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4536{
4537 Mutex::Autolock _l(mLock);
4538 return EffectGetDescriptor(pUuid, descriptor);
4539}
4540
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004541
4542// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4543static const effect_uuid_t VISUALIZATION_UUID_ =
4544 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4545
Eric Laurent65b65452010-06-01 23:49:17 -07004546sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4547 effect_descriptor_t *pDesc,
4548 const sp<IEffectClient>& effectClient,
4549 int32_t priority,
4550 int output,
4551 int sessionId,
4552 status_t *status,
4553 int *id,
4554 int *enabled)
4555{
4556 status_t lStatus = NO_ERROR;
4557 sp<EffectHandle> handle;
4558 effect_interface_t itfe;
4559 effect_descriptor_t desc;
4560 sp<Client> client;
4561 wp<Client> wclient;
4562
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004563 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4564 pid, effectClient.get(), priority, sessionId, output);
Eric Laurent65b65452010-06-01 23:49:17 -07004565
4566 if (pDesc == NULL) {
4567 lStatus = BAD_VALUE;
4568 goto Exit;
4569 }
4570
Eric Laurent98c92592010-09-23 16:10:16 -07004571 // check audio settings permission for global effects
4572 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && !settingsAllowed()) {
4573 lStatus = PERMISSION_DENIED;
4574 goto Exit;
4575 }
4576
4577 // Session AudioSystem::SESSION_OUTPUT_STAGE is reserved for output stage effects
4578 // that can only be created by audio policy manager (running in same process)
4579 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE && getpid() != pid) {
4580 lStatus = PERMISSION_DENIED;
4581 goto Exit;
4582 }
4583
4584 // check recording permission for visualizer
4585 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4586 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4587 !recordingAllowed()) {
4588 lStatus = PERMISSION_DENIED;
4589 goto Exit;
4590 }
4591
4592 if (output == 0) {
4593 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE) {
4594 // output must be specified by AudioPolicyManager when using session
4595 // AudioSystem::SESSION_OUTPUT_STAGE
4596 lStatus = BAD_VALUE;
4597 goto Exit;
4598 } else if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
4599 // if the output returned by getOutputForEffect() is removed before we lock the
4600 // mutex below, the call to checkPlaybackThread_l(output) below will detect it
4601 // and we will exit safely
4602 output = AudioSystem::getOutputForEffect(&desc);
4603 }
4604 }
4605
Eric Laurent65b65452010-06-01 23:49:17 -07004606 {
4607 Mutex::Autolock _l(mLock);
4608
Eric Laurentdf9b81c2010-07-02 08:12:41 -07004609
Eric Laurent65b65452010-06-01 23:49:17 -07004610 if (!EffectIsNullUuid(&pDesc->uuid)) {
4611 // if uuid is specified, request effect descriptor
4612 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4613 if (lStatus < 0) {
4614 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4615 goto Exit;
4616 }
4617 } else {
4618 // if uuid is not specified, look for an available implementation
4619 // of the required type in effect factory
4620 if (EffectIsNullUuid(&pDesc->type)) {
4621 LOGW("createEffect() no effect type");
4622 lStatus = BAD_VALUE;
4623 goto Exit;
4624 }
4625 uint32_t numEffects = 0;
4626 effect_descriptor_t d;
4627 bool found = false;
4628
4629 lStatus = EffectQueryNumberEffects(&numEffects);
4630 if (lStatus < 0) {
4631 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4632 goto Exit;
4633 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004634 for (uint32_t i = 0; i < numEffects; i++) {
4635 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004636 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004637 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004638 continue;
4639 }
4640 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4641 // If matching type found save effect descriptor. If the session is
4642 // 0 and the effect is not auxiliary, continue enumeration in case
4643 // an auxiliary version of this effect type is available
4644 found = true;
4645 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004646 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07004647 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4648 break;
4649 }
4650 }
4651 }
4652 if (!found) {
4653 lStatus = BAD_VALUE;
4654 LOGW("createEffect() effect not found");
4655 goto Exit;
4656 }
4657 // For same effect type, chose auxiliary version over insert version if
4658 // connect to output mix (Compliance to OpenSL ES)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004659 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004660 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4661 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4662 }
4663 }
4664
4665 // Do not allow auxiliary effects on a session different from 0 (output mix)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004666 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07004667 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4668 lStatus = INVALID_OPERATION;
4669 goto Exit;
4670 }
4671
4672 // return effect descriptor
4673 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4674
4675 // If output is not specified try to find a matching audio session ID in one of the
4676 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07004677 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4678 // because of code checking output when entering the function.
Eric Laurent65b65452010-06-01 23:49:17 -07004679 if (output == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07004680 // look for the thread where the specified audio session is present
4681 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4682 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4683 output = mPlaybackThreads.keyAt(i);
4684 break;
Eric Laurent493941b2010-07-28 01:32:47 -07004685 }
Eric Laurent65b65452010-06-01 23:49:17 -07004686 }
Eric Laurent98c92592010-09-23 16:10:16 -07004687 // If no output thread contains the requested session ID, default to
4688 // first output. The effect chain will be moved to the correct output
4689 // thread when a track with the same session ID is created
4690 if (output == 0 && mPlaybackThreads.size()) {
4691 output = mPlaybackThreads.keyAt(0);
4692 }
Eric Laurent65b65452010-06-01 23:49:17 -07004693 }
Eric Laurent98c92592010-09-23 16:10:16 -07004694 LOGV("createEffect() got output %d for effect %s", output, desc.name);
Eric Laurent65b65452010-06-01 23:49:17 -07004695 PlaybackThread *thread = checkPlaybackThread_l(output);
4696 if (thread == NULL) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004697 LOGE("createEffect() unknown output thread");
Eric Laurent65b65452010-06-01 23:49:17 -07004698 lStatus = BAD_VALUE;
4699 goto Exit;
4700 }
4701
Eric Laurent98c92592010-09-23 16:10:16 -07004702 // TODO: allow attachment of effect to inputs
4703
Eric Laurent65b65452010-06-01 23:49:17 -07004704 wclient = mClients.valueFor(pid);
4705
4706 if (wclient != NULL) {
4707 client = wclient.promote();
4708 } else {
4709 client = new Client(this, pid);
4710 mClients.add(pid, client);
4711 }
4712
4713 // create effect on selected output trhead
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004714 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4715 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07004716 if (handle != 0 && id != NULL) {
4717 *id = handle->id();
4718 }
4719 }
4720
4721Exit:
4722 if(status) {
4723 *status = lStatus;
4724 }
4725 return handle;
4726}
4727
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004728status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4729{
4730 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4731 session, srcOutput, dstOutput);
4732 Mutex::Autolock _l(mLock);
4733 if (srcOutput == dstOutput) {
4734 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4735 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004736 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004737 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4738 if (srcThread == NULL) {
4739 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4740 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07004741 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004742 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4743 if (dstThread == NULL) {
4744 LOGW("moveEffects() bad dstOutput %d", dstOutput);
4745 return BAD_VALUE;
4746 }
4747
4748 Mutex::Autolock _dl(dstThread->mLock);
4749 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07004750 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004751
Eric Laurent53334cd2010-06-23 17:38:20 -07004752 return NO_ERROR;
4753}
4754
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004755// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4756status_t AudioFlinger::moveEffectChain_l(int session,
4757 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07004758 AudioFlinger::PlaybackThread *dstThread,
4759 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004760{
4761 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4762 session, srcThread, dstThread);
4763
4764 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4765 if (chain == 0) {
4766 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4767 session, srcThread);
4768 return INVALID_OPERATION;
4769 }
4770
Eric Laurent493941b2010-07-28 01:32:47 -07004771 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004772 // so that a new chain is created with correct parameters when first effect is added. This is
4773 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4774 // removed.
4775 srcThread->removeEffectChain_l(chain);
4776
4777 // transfer all effects one by one so that new effect chain is created on new thread with
4778 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07004779 int dstOutput = dstThread->id();
4780 sp<EffectChain> dstChain;
4781 uint32_t strategy;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004782 sp<EffectModule> effect = chain->getEffectFromId_l(0);
4783 while (effect != 0) {
4784 srcThread->removeEffect_l(effect);
4785 dstThread->addEffect_l(effect);
Eric Laurent493941b2010-07-28 01:32:47 -07004786 // if the move request is not received from audio policy manager, the effect must be
4787 // re-registered with the new strategy and output
4788 if (dstChain == 0) {
4789 dstChain = effect->chain().promote();
4790 if (dstChain == 0) {
4791 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
4792 srcThread->addEffect_l(effect);
4793 return NO_INIT;
4794 }
4795 strategy = dstChain->strategy();
4796 }
4797 if (reRegister) {
4798 AudioSystem::unregisterEffect(effect->id());
4799 AudioSystem::registerEffect(&effect->desc(),
4800 dstOutput,
4801 strategy,
4802 session,
4803 effect->id());
4804 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004805 effect = chain->getEffectFromId_l(0);
4806 }
4807
4808 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07004809}
4810
Eric Laurent65b65452010-06-01 23:49:17 -07004811// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4812sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4813 const sp<AudioFlinger::Client>& client,
4814 const sp<IEffectClient>& effectClient,
4815 int32_t priority,
4816 int sessionId,
4817 effect_descriptor_t *desc,
4818 int *enabled,
4819 status_t *status
4820 )
4821{
4822 sp<EffectModule> effect;
4823 sp<EffectHandle> handle;
4824 status_t lStatus;
4825 sp<Track> track;
4826 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004827 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004828 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07004829 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07004830
4831 if (mOutput == 0) {
4832 LOGW("createEffect_l() Audio driver not initialized.");
4833 lStatus = NO_INIT;
4834 goto Exit;
4835 }
4836
4837 // Do not allow auxiliary effect on session other than 0
4838 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004839 sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
4840 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4841 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004842 lStatus = BAD_VALUE;
4843 goto Exit;
4844 }
4845
4846 // Do not allow effects with session ID 0 on direct output or duplicating threads
4847 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004848 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && mType != MIXER) {
4849 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4850 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004851 lStatus = BAD_VALUE;
4852 goto Exit;
4853 }
4854
4855 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4856
4857 { // scope for mLock
4858 Mutex::Autolock _l(mLock);
4859
4860 // check for existing effect chain with the requested audio session
4861 chain = getEffectChain_l(sessionId);
4862 if (chain == 0) {
4863 // create a new chain for this session
4864 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4865 chain = new EffectChain(this, sessionId);
4866 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004867 chain->setStrategy(getStrategyForSession_l(sessionId));
4868 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004869 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07004870 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07004871 }
4872
4873 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4874
4875 if (effect == 0) {
Eric Laurentf3d6dd02010-11-18 08:40:16 -08004876 int id = mAudioFlinger->nextUniqueId_l();
Eric Laurent53334cd2010-06-23 17:38:20 -07004877 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004878 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07004879 if (lStatus != NO_ERROR) {
4880 goto Exit;
4881 }
4882 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004883 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004884 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07004885 lStatus = effect->status();
4886 if (lStatus != NO_ERROR) {
4887 goto Exit;
4888 }
Eric Laurent76c40f72010-07-15 12:50:15 -07004889 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07004890 if (lStatus != NO_ERROR) {
4891 goto Exit;
4892 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004893 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07004894
4895 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07004896 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07004897 }
4898 // create effect handle and connect it to effect module
4899 handle = new EffectHandle(effect, client, effectClient, priority);
4900 lStatus = effect->addHandle(handle);
4901 if (enabled) {
4902 *enabled = (int)effect->isEnabled();
4903 }
4904 }
4905
4906Exit:
4907 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004908 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07004909 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004910 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07004911 }
Eric Laurent53334cd2010-06-23 17:38:20 -07004912 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004913 AudioSystem::unregisterEffect(effect->id());
4914 }
4915 if (chainCreated) {
4916 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07004917 }
Eric Laurent65b65452010-06-01 23:49:17 -07004918 handle.clear();
4919 }
4920
4921 if(status) {
4922 *status = lStatus;
4923 }
4924 return handle;
4925}
4926
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004927// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
4928// PlaybackThread::mLock held
4929status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
4930{
4931 // check for existing effect chain with the requested audio session
4932 int sessionId = effect->sessionId();
4933 sp<EffectChain> chain = getEffectChain_l(sessionId);
4934 bool chainCreated = false;
4935
4936 if (chain == 0) {
4937 // create a new chain for this session
4938 LOGV("addEffect_l() new effect chain for session %d", sessionId);
4939 chain = new EffectChain(this, sessionId);
4940 addEffectChain_l(chain);
4941 chain->setStrategy(getStrategyForSession_l(sessionId));
4942 chainCreated = true;
4943 }
4944 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
4945
4946 if (chain->getEffectFromId_l(effect->id()) != 0) {
4947 LOGW("addEffect_l() %p effect %s already present in chain %p",
4948 this, effect->desc().name, chain.get());
4949 return BAD_VALUE;
4950 }
4951
4952 status_t status = chain->addEffect_l(effect);
4953 if (status != NO_ERROR) {
4954 if (chainCreated) {
4955 removeEffectChain_l(chain);
4956 }
4957 return status;
4958 }
4959
4960 effect->setDevice(mDevice);
4961 effect->setMode(mAudioFlinger->getMode());
4962 return NO_ERROR;
4963}
4964
4965void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
4966
4967 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07004968 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004969 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4970 detachAuxEffect_l(effect->id());
4971 }
4972
4973 sp<EffectChain> chain = effect->chain().promote();
4974 if (chain != 0) {
4975 // remove effect chain if removing last effect
4976 if (chain->removeEffect_l(effect) == 0) {
4977 removeEffectChain_l(chain);
4978 }
4979 } else {
4980 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
4981 }
4982}
4983
4984void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
4985 const wp<EffectHandle>& handle) {
Eric Laurent53334cd2010-06-23 17:38:20 -07004986 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004987 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07004988 // delete the effect module if removing last handle on it
4989 if (effect->removeHandle(handle) == 0) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07004990 removeEffect_l(effect);
4991 AudioSystem::unregisterEffect(effect->id());
Eric Laurent53334cd2010-06-23 17:38:20 -07004992 }
4993}
4994
Eric Laurent65b65452010-06-01 23:49:17 -07004995status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
4996{
4997 int session = chain->sessionId();
4998 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07004999 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005000
5001 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005002 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005003 // Only one effect chain can be present in direct output thread and it uses
5004 // the mix buffer as input
5005 if (mType != DIRECT) {
5006 size_t numSamples = mFrameCount * mChannelCount;
5007 buffer = new int16_t[numSamples];
5008 memset(buffer, 0, numSamples * sizeof(int16_t));
5009 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5010 ownsBuffer = true;
5011 }
Eric Laurent65b65452010-06-01 23:49:17 -07005012
Eric Laurent53334cd2010-06-23 17:38:20 -07005013 // Attach all tracks with same session ID to this chain.
5014 for (size_t i = 0; i < mTracks.size(); ++i) {
5015 sp<Track> track = mTracks[i];
5016 if (session == track->sessionId()) {
5017 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5018 track->setMainBuffer(buffer);
5019 }
5020 }
5021
5022 // indicate all active tracks in the chain
5023 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5024 sp<Track> track = mActiveTracks[i].promote();
5025 if (track == 0) continue;
5026 if (session == track->sessionId()) {
5027 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
5028 chain->startTrack();
5029 }
Eric Laurent65b65452010-06-01 23:49:17 -07005030 }
5031 }
5032
Eric Laurent53334cd2010-06-23 17:38:20 -07005033 chain->setInBuffer(buffer, ownsBuffer);
5034 chain->setOutBuffer(mMixBuffer);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005035 // Effect chain for session AudioSystem::SESSION_OUTPUT_STAGE is inserted at end of effect
5036 // chains list in order to be processed last as it contains output stage effects
5037 // Effect chain for session AudioSystem::SESSION_OUTPUT_MIX is inserted before
5038 // session AudioSystem::SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005039 // after track specific effects and before output stage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005040 // It is therefore mandatory that AudioSystem::SESSION_OUTPUT_MIX == 0 and
5041 // that AudioSystem::SESSION_OUTPUT_STAGE < AudioSystem::SESSION_OUTPUT_MIX
5042 // Effect chain for other sessions are inserted at beginning of effect
5043 // chains list to be processed before output mix effects. Relative order between other
5044 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005045 size_t size = mEffectChains.size();
5046 size_t i = 0;
5047 for (i = 0; i < size; i++) {
5048 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005049 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005050 mEffectChains.insertAt(chain, i);
Eric Laurent65b65452010-06-01 23:49:17 -07005051
5052 return NO_ERROR;
5053}
5054
5055size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5056{
5057 int session = chain->sessionId();
5058
5059 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5060
5061 for (size_t i = 0; i < mEffectChains.size(); i++) {
5062 if (chain == mEffectChains[i]) {
5063 mEffectChains.removeAt(i);
5064 // detach all tracks with same session ID from this chain
5065 for (size_t i = 0; i < mTracks.size(); ++i) {
5066 sp<Track> track = mTracks[i];
5067 if (session == track->sessionId()) {
5068 track->setMainBuffer(mMixBuffer);
5069 }
5070 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005071 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005072 }
5073 }
5074 return mEffectChains.size();
5075}
5076
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005077void AudioFlinger::PlaybackThread::lockEffectChains_l(
5078 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005079{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005080 effectChains = mEffectChains;
Eric Laurent65b65452010-06-01 23:49:17 -07005081 for (size_t i = 0; i < mEffectChains.size(); i++) {
5082 mEffectChains[i]->lock();
5083 }
5084}
5085
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005086void AudioFlinger::PlaybackThread::unlockEffectChains(
5087 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Eric Laurent65b65452010-06-01 23:49:17 -07005088{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005089 for (size_t i = 0; i < effectChains.size(); i++) {
5090 effectChains[i]->unlock();
Eric Laurent65b65452010-06-01 23:49:17 -07005091 }
5092}
5093
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005094
Eric Laurent65b65452010-06-01 23:49:17 -07005095sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5096{
5097 sp<EffectModule> effect;
5098
5099 sp<EffectChain> chain = getEffectChain_l(sessionId);
5100 if (chain != 0) {
Eric Laurent76c40f72010-07-15 12:50:15 -07005101 effect = chain->getEffectFromId_l(effectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005102 }
5103 return effect;
5104}
5105
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005106status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5107 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005108{
5109 Mutex::Autolock _l(mLock);
5110 return attachAuxEffect_l(track, EffectId);
5111}
5112
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005113status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5114 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005115{
5116 status_t status = NO_ERROR;
5117
5118 if (EffectId == 0) {
5119 track->setAuxBuffer(0, NULL);
5120 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005121 // Auxiliary effects are always in audio session AudioSystem::SESSION_OUTPUT_MIX
5122 sp<EffectModule> effect = getEffect_l(AudioSystem::SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07005123 if (effect != 0) {
5124 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5125 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5126 } else {
5127 status = INVALID_OPERATION;
5128 }
5129 } else {
5130 status = BAD_VALUE;
5131 }
5132 }
5133 return status;
5134}
5135
5136void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5137{
5138 for (size_t i = 0; i < mTracks.size(); ++i) {
5139 sp<Track> track = mTracks[i];
5140 if (track->auxEffectId() == effectId) {
5141 attachAuxEffect_l(track, 0);
5142 }
5143 }
5144}
5145
5146// ----------------------------------------------------------------------------
5147// EffectModule implementation
5148// ----------------------------------------------------------------------------
5149
5150#undef LOG_TAG
5151#define LOG_TAG "AudioFlinger::EffectModule"
5152
5153AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5154 const wp<AudioFlinger::EffectChain>& chain,
5155 effect_descriptor_t *desc,
5156 int id,
5157 int sessionId)
5158 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5159 mStatus(NO_INIT), mState(IDLE)
5160{
5161 LOGV("Constructor %p", this);
5162 int lStatus;
5163 sp<ThreadBase> thread = mThread.promote();
5164 if (thread == 0) {
5165 return;
5166 }
5167 PlaybackThread *p = (PlaybackThread *)thread.get();
5168
5169 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5170
5171 // create effect engine from effect factory
Eric Laurent53334cd2010-06-23 17:38:20 -07005172 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5173
Eric Laurent65b65452010-06-01 23:49:17 -07005174 if (mStatus != NO_ERROR) {
5175 return;
5176 }
5177 lStatus = init();
5178 if (lStatus < 0) {
5179 mStatus = lStatus;
5180 goto Error;
5181 }
5182
5183 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5184 return;
5185Error:
5186 EffectRelease(mEffectInterface);
5187 mEffectInterface = NULL;
5188 LOGV("Constructor Error %d", mStatus);
5189}
5190
5191AudioFlinger::EffectModule::~EffectModule()
5192{
5193 LOGV("Destructor %p", this);
5194 if (mEffectInterface != NULL) {
5195 // release effect engine
5196 EffectRelease(mEffectInterface);
5197 }
5198}
5199
5200status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5201{
5202 status_t status;
5203
5204 Mutex::Autolock _l(mLock);
5205 // First handle in mHandles has highest priority and controls the effect module
5206 int priority = handle->priority();
5207 size_t size = mHandles.size();
5208 sp<EffectHandle> h;
5209 size_t i;
5210 for (i = 0; i < size; i++) {
5211 h = mHandles[i].promote();
5212 if (h == 0) continue;
5213 if (h->priority() <= priority) break;
5214 }
5215 // if inserted in first place, move effect control from previous owner to this handle
5216 if (i == 0) {
5217 if (h != 0) {
5218 h->setControl(false, true);
5219 }
5220 handle->setControl(true, false);
5221 status = NO_ERROR;
5222 } else {
5223 status = ALREADY_EXISTS;
5224 }
5225 mHandles.insertAt(handle, i);
5226 return status;
5227}
5228
5229size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5230{
5231 Mutex::Autolock _l(mLock);
5232 size_t size = mHandles.size();
5233 size_t i;
5234 for (i = 0; i < size; i++) {
5235 if (mHandles[i] == handle) break;
5236 }
5237 if (i == size) {
5238 return size;
5239 }
5240 mHandles.removeAt(i);
5241 size = mHandles.size();
5242 // if removed from first place, move effect control from this handle to next in line
5243 if (i == 0 && size != 0) {
5244 sp<EffectHandle> h = mHandles[0].promote();
5245 if (h != 0) {
5246 h->setControl(true, true);
5247 }
5248 }
5249
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07005250 // Release effect engine here so that it is done immediately. Otherwise it will be released
5251 // by the destructor when the last strong reference on the this object is released which can
5252 // happen after next process is called on this effect.
5253 if (size == 0 && mEffectInterface != NULL) {
5254 // release effect engine
5255 EffectRelease(mEffectInterface);
5256 mEffectInterface = NULL;
5257 }
5258
Eric Laurent65b65452010-06-01 23:49:17 -07005259 return size;
5260}
5261
5262void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5263{
5264 // keep a strong reference on this EffectModule to avoid calling the
5265 // destructor before we exit
5266 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07005267 {
5268 sp<ThreadBase> thread = mThread.promote();
5269 if (thread != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005270 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent53334cd2010-06-23 17:38:20 -07005271 playbackThread->disconnectEffect(keep, handle);
Eric Laurent65b65452010-06-01 23:49:17 -07005272 }
5273 }
5274}
5275
Eric Laurent7d850f22010-07-09 13:34:17 -07005276void AudioFlinger::EffectModule::updateState() {
5277 Mutex::Autolock _l(mLock);
5278
5279 switch (mState) {
5280 case RESTART:
5281 reset_l();
5282 // FALL THROUGH
5283
5284 case STARTING:
5285 // clear auxiliary effect input buffer for next accumulation
5286 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5287 memset(mConfig.inputCfg.buffer.raw,
5288 0,
5289 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5290 }
5291 start_l();
5292 mState = ACTIVE;
5293 break;
5294 case STOPPING:
5295 stop_l();
5296 mDisableWaitCnt = mMaxDisableWaitCnt;
5297 mState = STOPPED;
5298 break;
5299 case STOPPED:
5300 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5301 // turn off sequence.
5302 if (--mDisableWaitCnt == 0) {
5303 reset_l();
5304 mState = IDLE;
5305 }
5306 break;
5307 default: //IDLE , ACTIVE
5308 break;
5309 }
5310}
5311
Eric Laurent65b65452010-06-01 23:49:17 -07005312void AudioFlinger::EffectModule::process()
5313{
5314 Mutex::Autolock _l(mLock);
5315
Eric Laurent7d850f22010-07-09 13:34:17 -07005316 if (mEffectInterface == NULL ||
5317 mConfig.inputCfg.buffer.raw == NULL ||
5318 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005319 return;
5320 }
5321
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005322 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07005323 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5324 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5325 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5326 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005327 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07005328 }
5329
Eric Laurent65b65452010-06-01 23:49:17 -07005330 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07005331 int ret = (*mEffectInterface)->process(mEffectInterface,
5332 &mConfig.inputCfg.buffer,
5333 &mConfig.outputCfg.buffer);
5334
5335 // force transition to IDLE state when engine is ready
5336 if (mState == STOPPED && ret == -ENODATA) {
5337 mDisableWaitCnt = 1;
5338 }
Eric Laurent65b65452010-06-01 23:49:17 -07005339
5340 // clear auxiliary effect input buffer for next accumulation
5341 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005342 memset(mConfig.inputCfg.buffer.raw, 0,
5343 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07005344 }
5345 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08005346 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5347 // If an insert effect is idle and input buffer is different from output buffer,
5348 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07005349 sp<EffectChain> chain = mChain.promote();
5350 if (chain != 0 && chain->activeTracks() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08005351 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5352 int16_t *in = mConfig.inputCfg.buffer.s16;
5353 int16_t *out = mConfig.outputCfg.buffer.s16;
5354 for (size_t i = 0; i < frameCnt; i++) {
5355 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07005356 }
Eric Laurent65b65452010-06-01 23:49:17 -07005357 }
5358 }
5359}
5360
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005361void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005362{
5363 if (mEffectInterface == NULL) {
5364 return;
5365 }
5366 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5367}
5368
5369status_t AudioFlinger::EffectModule::configure()
5370{
5371 uint32_t channels;
5372 if (mEffectInterface == NULL) {
5373 return NO_INIT;
5374 }
5375
5376 sp<ThreadBase> thread = mThread.promote();
5377 if (thread == 0) {
5378 return DEAD_OBJECT;
5379 }
5380
5381 // TODO: handle configuration of effects replacing track process
5382 if (thread->channelCount() == 1) {
5383 channels = CHANNEL_MONO;
5384 } else {
5385 channels = CHANNEL_STEREO;
5386 }
5387
5388 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5389 mConfig.inputCfg.channels = CHANNEL_MONO;
5390 } else {
5391 mConfig.inputCfg.channels = channels;
5392 }
5393 mConfig.outputCfg.channels = channels;
Eric Laurent53334cd2010-06-23 17:38:20 -07005394 mConfig.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
5395 mConfig.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
Eric Laurent65b65452010-06-01 23:49:17 -07005396 mConfig.inputCfg.samplingRate = thread->sampleRate();
5397 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5398 mConfig.inputCfg.bufferProvider.cookie = NULL;
5399 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5400 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5401 mConfig.outputCfg.bufferProvider.cookie = NULL;
5402 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5403 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5404 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5405 // Insert effect:
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005406 // - in session AudioSystem::SESSION_OUTPUT_MIX or AudioSystem::SESSION_OUTPUT_STAGE,
5407 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07005408 // - in other sessions:
5409 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5410 // other effect: overwrites output buffer: input buffer == output buffer
5411 // Auxiliary effect:
5412 // accumulates in output buffer: input buffer != output buffer
5413 // Therefore: accumulate <=> input buffer != output buffer
5414 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5415 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5416 } else {
5417 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5418 }
5419 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5420 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5421 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5422 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5423
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005424 LOGV("configure() %p thread %p buffer %p framecount %d",
5425 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5426
Eric Laurent65b65452010-06-01 23:49:17 -07005427 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005428 uint32_t size = sizeof(int);
5429 status_t status = (*mEffectInterface)->command(mEffectInterface,
5430 EFFECT_CMD_CONFIGURE,
5431 sizeof(effect_config_t),
5432 &mConfig,
5433 &size,
5434 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005435 if (status == 0) {
5436 status = cmdStatus;
5437 }
Eric Laurent7d850f22010-07-09 13:34:17 -07005438
5439 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5440 (1000 * mConfig.outputCfg.buffer.frameCount);
5441
Eric Laurent65b65452010-06-01 23:49:17 -07005442 return status;
5443}
5444
5445status_t AudioFlinger::EffectModule::init()
5446{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005447 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005448 if (mEffectInterface == NULL) {
5449 return NO_INIT;
5450 }
5451 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005452 uint32_t size = sizeof(status_t);
5453 status_t status = (*mEffectInterface)->command(mEffectInterface,
5454 EFFECT_CMD_INIT,
5455 0,
5456 NULL,
5457 &size,
5458 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005459 if (status == 0) {
5460 status = cmdStatus;
5461 }
5462 return status;
5463}
5464
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005465status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005466{
5467 if (mEffectInterface == NULL) {
5468 return NO_INIT;
5469 }
5470 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005471 uint32_t size = sizeof(status_t);
5472 status_t status = (*mEffectInterface)->command(mEffectInterface,
5473 EFFECT_CMD_ENABLE,
5474 0,
5475 NULL,
5476 &size,
5477 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005478 if (status == 0) {
5479 status = cmdStatus;
5480 }
5481 return status;
5482}
5483
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005484status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07005485{
5486 if (mEffectInterface == NULL) {
5487 return NO_INIT;
5488 }
5489 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005490 uint32_t size = sizeof(status_t);
5491 status_t status = (*mEffectInterface)->command(mEffectInterface,
5492 EFFECT_CMD_DISABLE,
5493 0,
5494 NULL,
5495 &size,
5496 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005497 if (status == 0) {
5498 status = cmdStatus;
5499 }
5500 return status;
5501}
5502
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005503status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5504 uint32_t cmdSize,
5505 void *pCmdData,
5506 uint32_t *replySize,
5507 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005508{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005509 Mutex::Autolock _l(mLock);
5510// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07005511
5512 if (mEffectInterface == NULL) {
5513 return NO_INIT;
5514 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005515 status_t status = (*mEffectInterface)->command(mEffectInterface,
5516 cmdCode,
5517 cmdSize,
5518 pCmdData,
5519 replySize,
5520 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07005521 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005522 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07005523 for (size_t i = 1; i < mHandles.size(); i++) {
5524 sp<EffectHandle> h = mHandles[i].promote();
5525 if (h != 0) {
5526 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5527 }
5528 }
5529 }
5530 return status;
5531}
5532
5533status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5534{
5535 Mutex::Autolock _l(mLock);
5536 LOGV("setEnabled %p enabled %d", this, enabled);
5537
5538 if (enabled != isEnabled()) {
5539 switch (mState) {
5540 // going from disabled to enabled
5541 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07005542 mState = STARTING;
5543 break;
5544 case STOPPED:
5545 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07005546 break;
5547 case STOPPING:
5548 mState = ACTIVE;
5549 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005550
5551 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07005552 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005553 mState = STOPPED;
5554 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005555 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07005556 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07005557 break;
5558 case ACTIVE:
5559 mState = STOPPING;
5560 break;
5561 }
5562 for (size_t i = 1; i < mHandles.size(); i++) {
5563 sp<EffectHandle> h = mHandles[i].promote();
5564 if (h != 0) {
5565 h->setEnabled(enabled);
5566 }
5567 }
5568 }
5569 return NO_ERROR;
5570}
5571
5572bool AudioFlinger::EffectModule::isEnabled()
5573{
5574 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07005575 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07005576 case STARTING:
5577 case ACTIVE:
5578 return true;
5579 case IDLE:
5580 case STOPPING:
5581 case STOPPED:
5582 default:
5583 return false;
5584 }
5585}
5586
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005587bool AudioFlinger::EffectModule::isProcessEnabled()
5588{
5589 switch (mState) {
5590 case RESTART:
5591 case ACTIVE:
5592 case STOPPING:
5593 case STOPPED:
5594 return true;
5595 case IDLE:
5596 case STARTING:
5597 default:
5598 return false;
5599 }
5600}
5601
Eric Laurent65b65452010-06-01 23:49:17 -07005602status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5603{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005604 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005605 status_t status = NO_ERROR;
5606
5607 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5608 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07005609 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07005610 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5611 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07005612 status_t cmdStatus;
5613 uint32_t volume[2];
5614 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005615 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07005616 volume[0] = *left;
5617 volume[1] = *right;
5618 if (controller) {
5619 pVolume = volume;
5620 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005621 status = (*mEffectInterface)->command(mEffectInterface,
5622 EFFECT_CMD_SET_VOLUME,
5623 size,
5624 volume,
5625 &size,
5626 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07005627 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5628 *left = volume[0];
5629 *right = volume[1];
5630 }
5631 }
5632 return status;
5633}
5634
5635status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5636{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005637 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07005638 status_t status = NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005639 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5640 // convert device bit field from AudioSystem to EffectApi format.
5641 device = deviceAudioSystemToEffectApi(device);
5642 if (device == 0) {
5643 return BAD_VALUE;
5644 }
Eric Laurent65b65452010-06-01 23:49:17 -07005645 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005646 uint32_t size = sizeof(status_t);
5647 status = (*mEffectInterface)->command(mEffectInterface,
5648 EFFECT_CMD_SET_DEVICE,
5649 sizeof(uint32_t),
5650 &device,
5651 &size,
5652 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005653 if (status == NO_ERROR) {
5654 status = cmdStatus;
5655 }
5656 }
5657 return status;
5658}
5659
Eric Laurent53334cd2010-06-23 17:38:20 -07005660status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5661{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005662 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005663 status_t status = NO_ERROR;
5664 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
5665 // convert audio mode from AudioSystem to EffectApi format.
5666 int effectMode = modeAudioSystemToEffectApi(mode);
5667 if (effectMode < 0) {
5668 return BAD_VALUE;
5669 }
5670 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005671 uint32_t size = sizeof(status_t);
5672 status = (*mEffectInterface)->command(mEffectInterface,
5673 EFFECT_CMD_SET_AUDIO_MODE,
5674 sizeof(int),
5675 &effectMode,
5676 &size,
5677 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07005678 if (status == NO_ERROR) {
5679 status = cmdStatus;
5680 }
5681 }
5682 return status;
5683}
5684
5685// update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
5686const uint32_t AudioFlinger::EffectModule::sDeviceConvTable[] = {
5687 DEVICE_EARPIECE, // AudioSystem::DEVICE_OUT_EARPIECE
5688 DEVICE_SPEAKER, // AudioSystem::DEVICE_OUT_SPEAKER
5689 DEVICE_WIRED_HEADSET, // case AudioSystem::DEVICE_OUT_WIRED_HEADSET
5690 DEVICE_WIRED_HEADPHONE, // AudioSystem::DEVICE_OUT_WIRED_HEADPHONE
5691 DEVICE_BLUETOOTH_SCO, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO
5692 DEVICE_BLUETOOTH_SCO_HEADSET, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET
5693 DEVICE_BLUETOOTH_SCO_CARKIT, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT
5694 DEVICE_BLUETOOTH_A2DP, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP
5695 DEVICE_BLUETOOTH_A2DP_HEADPHONES, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES
5696 DEVICE_BLUETOOTH_A2DP_SPEAKER, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER
5697 DEVICE_AUX_DIGITAL // AudioSystem::DEVICE_OUT_AUX_DIGITAL
5698};
5699
5700uint32_t AudioFlinger::EffectModule::deviceAudioSystemToEffectApi(uint32_t device)
5701{
5702 uint32_t deviceOut = 0;
5703 while (device) {
5704 const uint32_t i = 31 - __builtin_clz(device);
5705 device &= ~(1 << i);
5706 if (i >= sizeof(sDeviceConvTable)/sizeof(uint32_t)) {
Glenn Kastened0079d2011-04-04 10:50:50 -07005707 LOGE("device conversion error for AudioSystem device 0x%08x", device);
Eric Laurent53334cd2010-06-23 17:38:20 -07005708 return 0;
5709 }
5710 deviceOut |= (uint32_t)sDeviceConvTable[i];
5711 }
5712 return deviceOut;
5713}
5714
5715// update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
5716const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
5717 AUDIO_MODE_NORMAL, // AudioSystem::MODE_NORMAL
5718 AUDIO_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08005719 AUDIO_MODE_IN_CALL, // AudioSystem::MODE_IN_CALL
5720 AUDIO_MODE_IN_CALL // AudioSystem::MODE_IN_COMMUNICATION, same conversion as for MODE_IN_CALL
Eric Laurent53334cd2010-06-23 17:38:20 -07005721};
5722
5723int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
5724{
5725 int modeOut = -1;
5726 if (mode < sizeof(sModeConvTable) / sizeof(uint32_t)) {
5727 modeOut = (int)sModeConvTable[mode];
5728 }
5729 return modeOut;
5730}
Eric Laurent65b65452010-06-01 23:49:17 -07005731
5732status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5733{
5734 const size_t SIZE = 256;
5735 char buffer[SIZE];
5736 String8 result;
5737
5738 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5739 result.append(buffer);
5740
5741 bool locked = tryLock(mLock);
5742 // failed to lock - AudioFlinger is probably deadlocked
5743 if (!locked) {
5744 result.append("\t\tCould not lock Fx mutex:\n");
5745 }
5746
5747 result.append("\t\tSession Status State Engine:\n");
5748 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5749 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5750 result.append(buffer);
5751
5752 result.append("\t\tDescriptor:\n");
5753 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5754 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5755 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5756 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5757 result.append(buffer);
5758 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5759 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5760 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5761 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5762 result.append(buffer);
5763 snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5764 mDescriptor.apiVersion,
5765 mDescriptor.flags);
5766 result.append(buffer);
5767 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5768 mDescriptor.name);
5769 result.append(buffer);
5770 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5771 mDescriptor.implementor);
5772 result.append(buffer);
5773
5774 result.append("\t\t- Input configuration:\n");
5775 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5776 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5777 (uint32_t)mConfig.inputCfg.buffer.raw,
5778 mConfig.inputCfg.buffer.frameCount,
5779 mConfig.inputCfg.samplingRate,
5780 mConfig.inputCfg.channels,
5781 mConfig.inputCfg.format);
5782 result.append(buffer);
5783
5784 result.append("\t\t- Output configuration:\n");
5785 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5786 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5787 (uint32_t)mConfig.outputCfg.buffer.raw,
5788 mConfig.outputCfg.buffer.frameCount,
5789 mConfig.outputCfg.samplingRate,
5790 mConfig.outputCfg.channels,
5791 mConfig.outputCfg.format);
5792 result.append(buffer);
5793
5794 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5795 result.append(buffer);
5796 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5797 for (size_t i = 0; i < mHandles.size(); ++i) {
5798 sp<EffectHandle> handle = mHandles[i].promote();
5799 if (handle != 0) {
5800 handle->dump(buffer, SIZE);
5801 result.append(buffer);
5802 }
5803 }
5804
5805 result.append("\n");
5806
5807 write(fd, result.string(), result.length());
5808
5809 if (locked) {
5810 mLock.unlock();
5811 }
5812
5813 return NO_ERROR;
5814}
5815
5816// ----------------------------------------------------------------------------
5817// EffectHandle implementation
5818// ----------------------------------------------------------------------------
5819
5820#undef LOG_TAG
5821#define LOG_TAG "AudioFlinger::EffectHandle"
5822
5823AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5824 const sp<AudioFlinger::Client>& client,
5825 const sp<IEffectClient>& effectClient,
5826 int32_t priority)
5827 : BnEffect(),
5828 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5829{
5830 LOGV("constructor %p", this);
5831
5832 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5833 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5834 if (mCblkMemory != 0) {
5835 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5836
5837 if (mCblk) {
5838 new(mCblk) effect_param_cblk_t();
5839 mBuffer = (uint8_t *)mCblk + bufOffset;
5840 }
5841 } else {
5842 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5843 return;
5844 }
5845}
5846
5847AudioFlinger::EffectHandle::~EffectHandle()
5848{
5849 LOGV("Destructor %p", this);
5850 disconnect();
5851}
5852
5853status_t AudioFlinger::EffectHandle::enable()
5854{
5855 if (!mHasControl) return INVALID_OPERATION;
5856 if (mEffect == 0) return DEAD_OBJECT;
5857
5858 return mEffect->setEnabled(true);
5859}
5860
5861status_t AudioFlinger::EffectHandle::disable()
5862{
5863 if (!mHasControl) return INVALID_OPERATION;
5864 if (mEffect == NULL) return DEAD_OBJECT;
5865
5866 return mEffect->setEnabled(false);
5867}
5868
5869void AudioFlinger::EffectHandle::disconnect()
5870{
5871 if (mEffect == 0) {
5872 return;
5873 }
5874 mEffect->disconnect(this);
5875 // release sp on module => module destructor can be called now
5876 mEffect.clear();
5877 if (mCblk) {
5878 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5879 }
5880 mCblkMemory.clear(); // and free the shared memory
5881 if (mClient != 0) {
5882 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5883 mClient.clear();
5884 }
5885}
5886
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005887status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
5888 uint32_t cmdSize,
5889 void *pCmdData,
5890 uint32_t *replySize,
5891 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005892{
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005893// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
5894// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005895
5896 // only get parameter command is permitted for applications not controlling the effect
5897 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5898 return INVALID_OPERATION;
5899 }
5900 if (mEffect == 0) return DEAD_OBJECT;
5901
5902 // handle commands that are not forwarded transparently to effect engine
5903 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5904 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5905 // no risk to block the whole media server process or mixer threads is we are stuck here
5906 Mutex::Autolock _l(mCblk->lock);
5907 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5908 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
5909 mCblk->serverIndex = 0;
5910 mCblk->clientIndex = 0;
5911 return BAD_VALUE;
5912 }
5913 status_t status = NO_ERROR;
5914 while (mCblk->serverIndex < mCblk->clientIndex) {
5915 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005916 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07005917 int *p = (int *)(mBuffer + mCblk->serverIndex);
5918 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07005919 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
5920 LOGW("command(): invalid parameter block size");
5921 break;
5922 }
Eric Laurent65b65452010-06-01 23:49:17 -07005923 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07005924 if (param->psize == 0 || param->vsize == 0) {
5925 LOGW("command(): null parameter or value size");
5926 mCblk->serverIndex += size;
5927 continue;
5928 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005929 uint32_t psize = sizeof(effect_param_t) +
5930 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
5931 param->vsize;
5932 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
5933 psize,
5934 p,
5935 &rsize,
5936 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07005937 // stop at first error encountered
5938 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07005939 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07005940 *(int *)pReplyData = reply;
5941 break;
5942 } else if (reply != NO_ERROR) {
5943 *(int *)pReplyData = reply;
5944 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005945 }
5946 mCblk->serverIndex += size;
5947 }
5948 mCblk->serverIndex = 0;
5949 mCblk->clientIndex = 0;
5950 return status;
5951 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07005952 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07005953 return enable();
5954 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07005955 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07005956 return disable();
5957 }
5958
5959 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5960}
5961
5962sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
5963 return mCblkMemory;
5964}
5965
5966void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
5967{
5968 LOGV("setControl %p control %d", this, hasControl);
5969
5970 mHasControl = hasControl;
5971 if (signal && mEffectClient != 0) {
5972 mEffectClient->controlStatusChanged(hasControl);
5973 }
5974}
5975
Eric Laurenta4c72ac2010-07-28 05:40:18 -07005976void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
5977 uint32_t cmdSize,
5978 void *pCmdData,
5979 uint32_t replySize,
5980 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07005981{
5982 if (mEffectClient != 0) {
5983 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5984 }
5985}
5986
5987
5988
5989void AudioFlinger::EffectHandle::setEnabled(bool enabled)
5990{
5991 if (mEffectClient != 0) {
5992 mEffectClient->enableStatusChanged(enabled);
5993 }
5994}
5995
5996status_t AudioFlinger::EffectHandle::onTransact(
5997 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5998{
5999 return BnEffect::onTransact(code, data, reply, flags);
6000}
6001
6002
6003void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6004{
6005 bool locked = tryLock(mCblk->lock);
6006
6007 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6008 (mClient == NULL) ? getpid() : mClient->pid(),
6009 mPriority,
6010 mHasControl,
6011 !locked,
6012 mCblk->clientIndex,
6013 mCblk->serverIndex
6014 );
6015
6016 if (locked) {
6017 mCblk->lock.unlock();
6018 }
6019}
6020
6021#undef LOG_TAG
6022#define LOG_TAG "AudioFlinger::EffectChain"
6023
6024AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6025 int sessionId)
Eric Laurent76c40f72010-07-15 12:50:15 -07006026 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mOwnInBuffer(false),
Eric Laurent2a6b80b2010-07-29 23:43:43 -07006027 mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6028 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07006029{
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006030 mStrategy = AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
Eric Laurent65b65452010-06-01 23:49:17 -07006031}
6032
6033AudioFlinger::EffectChain::~EffectChain()
6034{
6035 if (mOwnInBuffer) {
6036 delete mInBuffer;
6037 }
6038
6039}
6040
Eric Laurent76c40f72010-07-15 12:50:15 -07006041// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6042sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07006043{
6044 sp<EffectModule> effect;
6045 size_t size = mEffects.size();
6046
6047 for (size_t i = 0; i < size; i++) {
6048 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6049 effect = mEffects[i];
6050 break;
6051 }
6052 }
6053 return effect;
6054}
6055
Eric Laurent76c40f72010-07-15 12:50:15 -07006056// getEffectFromId_l() must be called with PlaybackThread::mLock held
6057sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07006058{
6059 sp<EffectModule> effect;
6060 size_t size = mEffects.size();
6061
6062 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006063 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6064 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07006065 effect = mEffects[i];
6066 break;
6067 }
6068 }
6069 return effect;
6070}
6071
6072// Must be called with EffectChain::mLock locked
6073void AudioFlinger::EffectChain::process_l()
6074{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006075 sp<ThreadBase> thread = mThread.promote();
6076 if (thread == 0) {
6077 LOGW("process_l(): cannot promote mixer thread");
6078 return;
6079 }
6080 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6081 bool isGlobalSession = (mSessionId == AudioSystem::SESSION_OUTPUT_MIX) ||
6082 (mSessionId == AudioSystem::SESSION_OUTPUT_STAGE);
6083 bool tracksOnSession = false;
6084 if (!isGlobalSession) {
6085 tracksOnSession =
6086 playbackThread->hasAudioSession(mSessionId) & PlaybackThread::TRACK_SESSION;
6087 }
6088
Eric Laurent65b65452010-06-01 23:49:17 -07006089 size_t size = mEffects.size();
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006090 // do not process effect if no track is present in same audio session
6091 if (isGlobalSession || tracksOnSession) {
6092 for (size_t i = 0; i < size; i++) {
6093 mEffects[i]->process();
6094 }
Eric Laurent65b65452010-06-01 23:49:17 -07006095 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006096 for (size_t i = 0; i < size; i++) {
6097 mEffects[i]->updateState();
6098 }
Eric Laurent65b65452010-06-01 23:49:17 -07006099 // if no track is active, input buffer must be cleared here as the mixer process
6100 // will not do it
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006101 if (tracksOnSession &&
6102 activeTracks() == 0) {
6103 size_t numSamples = playbackThread->frameCount() * playbackThread->channelCount();
6104 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006105 }
6106}
6107
Eric Laurent76c40f72010-07-15 12:50:15 -07006108// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006109status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006110{
6111 effect_descriptor_t desc = effect->desc();
6112 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6113
6114 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006115 effect->setChain(this);
6116 sp<ThreadBase> thread = mThread.promote();
6117 if (thread == 0) {
6118 return NO_INIT;
6119 }
6120 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07006121
6122 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6123 // Auxiliary effects are inserted at the beginning of mEffects vector as
6124 // they are processed first and accumulated in chain input buffer
6125 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006126
Eric Laurent65b65452010-06-01 23:49:17 -07006127 // the input buffer for auxiliary effect contains mono samples in
6128 // 32 bit format. This is to avoid saturation in AudoMixer
6129 // accumulation stage. Saturation is done in EffectModule::process() before
6130 // calling the process in effect engine
6131 size_t numSamples = thread->frameCount();
6132 int32_t *buffer = new int32_t[numSamples];
6133 memset(buffer, 0, numSamples * sizeof(int32_t));
6134 effect->setInBuffer((int16_t *)buffer);
6135 // auxiliary effects output samples to chain input buffer for further processing
6136 // by insert effects
6137 effect->setOutBuffer(mInBuffer);
6138 } else {
6139 // Insert effects are inserted at the end of mEffects vector as they are processed
6140 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07006141 // Insert effect order as a function of indicated preference:
6142 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6143 // another effect is present
6144 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6145 // last effect claiming first position
6146 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6147 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07006148 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07006149 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6150 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07006151
6152 int size = (int)mEffects.size();
6153 int idx_insert = size;
6154 int idx_insert_first = -1;
6155 int idx_insert_last = -1;
6156
6157 for (int i = 0; i < size; i++) {
6158 effect_descriptor_t d = mEffects[i]->desc();
6159 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6160 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6161 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6162 // check invalid effect chaining combinations
6163 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07006164 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006165 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07006166 return INVALID_OPERATION;
6167 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006168 // remember position of first insert effect and by default
6169 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07006170 if (idx_insert == size) {
6171 idx_insert = i;
6172 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006173 // remember position of last insert effect claiming
6174 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07006175 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6176 idx_insert_first = i;
6177 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006178 // remember position of first insert effect claiming
6179 // last position
6180 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6181 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07006182 idx_insert_last = i;
6183 }
6184 }
6185 }
6186
Eric Laurent53334cd2010-06-23 17:38:20 -07006187 // modify idx_insert from first position if needed
6188 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6189 if (idx_insert_last != -1) {
6190 idx_insert = idx_insert_last;
6191 } else {
6192 idx_insert = size;
6193 }
6194 } else {
6195 if (idx_insert_first != -1) {
6196 idx_insert = idx_insert_first + 1;
6197 }
Eric Laurent65b65452010-06-01 23:49:17 -07006198 }
6199
6200 // always read samples from chain input buffer
6201 effect->setInBuffer(mInBuffer);
6202
6203 // if last effect in the chain, output samples to chain
6204 // output buffer, otherwise to chain input buffer
6205 if (idx_insert == size) {
6206 if (idx_insert != 0) {
6207 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6208 mEffects[idx_insert-1]->configure();
6209 }
6210 effect->setOutBuffer(mOutBuffer);
6211 } else {
6212 effect->setOutBuffer(mInBuffer);
6213 }
Eric Laurent53334cd2010-06-23 17:38:20 -07006214 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006215
Eric Laurent76c40f72010-07-15 12:50:15 -07006216 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07006217 }
6218 effect->configure();
6219 return NO_ERROR;
6220}
6221
Eric Laurent76c40f72010-07-15 12:50:15 -07006222// removeEffect_l() must be called with PlaybackThread::mLock held
6223size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07006224{
6225 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006226 int size = (int)mEffects.size();
6227 int i;
6228 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6229
6230 for (i = 0; i < size; i++) {
6231 if (effect == mEffects[i]) {
6232 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6233 delete[] effect->inBuffer();
6234 } else {
6235 if (i == size - 1 && i != 0) {
6236 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6237 mEffects[i - 1]->configure();
6238 }
6239 }
6240 mEffects.removeAt(i);
Eric Laurent76c40f72010-07-15 12:50:15 -07006241 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07006242 break;
6243 }
6244 }
Eric Laurent65b65452010-06-01 23:49:17 -07006245
6246 return mEffects.size();
6247}
6248
Eric Laurent76c40f72010-07-15 12:50:15 -07006249// setDevice_l() must be called with PlaybackThread::mLock held
6250void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07006251{
6252 size_t size = mEffects.size();
6253 for (size_t i = 0; i < size; i++) {
6254 mEffects[i]->setDevice(device);
6255 }
6256}
6257
Eric Laurent76c40f72010-07-15 12:50:15 -07006258// setMode_l() must be called with PlaybackThread::mLock held
6259void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006260{
6261 size_t size = mEffects.size();
6262 for (size_t i = 0; i < size; i++) {
6263 mEffects[i]->setMode(mode);
6264 }
6265}
6266
Eric Laurent76c40f72010-07-15 12:50:15 -07006267// setVolume_l() must be called with PlaybackThread::mLock held
6268bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07006269{
6270 uint32_t newLeft = *left;
6271 uint32_t newRight = *right;
6272 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07006273 int ctrlIdx = -1;
6274 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07006275
Eric Laurent76c40f72010-07-15 12:50:15 -07006276 // first update volume controller
6277 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006278 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07006279 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6280 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006281 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07006282 break;
6283 }
6284 }
6285
6286 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07006287 if (hasControl) {
6288 *left = mNewLeftVolume;
6289 *right = mNewRightVolume;
6290 }
6291 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07006292 }
6293
6294 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07006295 mLeftVolume = newLeft;
6296 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006297
6298 // second get volume update from volume controller
6299 if (ctrlIdx >= 0) {
6300 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07006301 mNewLeftVolume = newLeft;
6302 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07006303 }
6304 // then indicate volume to all other effects in chain.
6305 // Pass altered volume to effects before volume controller
6306 // and requested volume to effects after controller
6307 uint32_t lVol = newLeft;
6308 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07006309
Eric Laurent65b65452010-06-01 23:49:17 -07006310 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07006311 if ((int)i == ctrlIdx) continue;
6312 // this also works for ctrlIdx == -1 when there is no volume controller
6313 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07006314 lVol = *left;
6315 rVol = *right;
6316 }
6317 mEffects[i]->setVolume(&lVol, &rVol, false);
6318 }
6319 *left = newLeft;
6320 *right = newRight;
6321
6322 return hasControl;
6323}
6324
Eric Laurent65b65452010-06-01 23:49:17 -07006325status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6326{
6327 const size_t SIZE = 256;
6328 char buffer[SIZE];
6329 String8 result;
6330
6331 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6332 result.append(buffer);
6333
6334 bool locked = tryLock(mLock);
6335 // failed to lock - AudioFlinger is probably deadlocked
6336 if (!locked) {
6337 result.append("\tCould not lock mutex:\n");
6338 }
6339
Eric Laurent76c40f72010-07-15 12:50:15 -07006340 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6341 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006342 mEffects.size(),
6343 (uint32_t)mInBuffer,
6344 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07006345 mActiveTrackCnt);
6346 result.append(buffer);
6347 write(fd, result.string(), result.size());
6348
6349 for (size_t i = 0; i < mEffects.size(); ++i) {
6350 sp<EffectModule> effect = mEffects[i];
6351 if (effect != 0) {
6352 effect->dump(fd, args);
6353 }
6354 }
6355
6356 if (locked) {
6357 mLock.unlock();
6358 }
6359
6360 return NO_ERROR;
6361}
6362
6363#undef LOG_TAG
6364#define LOG_TAG "AudioFlinger"
6365
Eric Laurenta553c252009-07-17 12:17:14 -07006366// ----------------------------------------------------------------------------
6367
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006368status_t AudioFlinger::onTransact(
6369 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6370{
6371 return BnAudioFlinger::onTransact(code, data, reply, flags);
6372}
6373
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07006374}; // namespace android