blob: 60d27731f1d4f397dc79c769960e01be0f309e06 [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
Dima Zavin24fc2fb2011-04-19 22:30:36 -070036#include <cutils/bitops.h>
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080037#include <cutils/properties.h>
38
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039#include <media/AudioTrack.h>
40#include <media/AudioRecord.h>
Gloria Wang9b3f1522011-02-24 14:51:45 -080041#include <media/IMediaPlayerService.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070044#include <private/media/AudioEffectShared.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070045
Dima Zavin34bb4192011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070047#include <hardware/audio.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Eric Laurent53334cd2010-06-23 17:38:20 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent5cc05262011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent6639b552011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Eric Laurent65b65452010-06-01 23:49:17 -070056
Glenn Kastenda494f92011-07-08 15:26:12 -070057#include <cpustats/ThreadCpuUsage.h>
Eric Laurent6dbdc402011-07-22 09:04:31 -070058#include <powermanager/PowerManager.h>
Glenn Kastenda494f92011-07-08 15:26:12 -070059// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
60
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061// ----------------------------------------------------------------------------
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062
Eric Laurent8ed6ed02010-07-13 04:45:46 -070063
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070064namespace android {
65
The Android Open Source Project10592532009-03-18 17:39:46 -070066static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
67static const char* kHardwareLockedString = "Hardware lock is taken\n";
68
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080069//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070070static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070071static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070072
73// retry counts for buffer fill timeout
74// 50 * ~20msecs = 1 second
75static const int8_t kMaxTrackRetries = 50;
76static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080077// allow less retry attempts on direct output thread.
78// direct outputs can be a scarce resource in audio hardware and should
79// be released as quickly as possible.
80static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070081
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070082static const int kDumpLockRetries = 50;
Glenn Kastencbfe2e12011-12-13 11:04:14 -080083static const int kDumpLockSleepUs = 20000;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070084
Glenn Kastencbfe2e12011-12-13 11:04:14 -080085// don't warn about blocked writes or record buffer overflows more often than this
86static const nsecs_t kWarningThrottleNs = seconds(5);
Dave Sparksd0ac8c02009-09-30 03:09:03 -070087
Eric Laurent464d5b32011-06-17 21:29:58 -070088// RecordThread loop sleep time upon application overrun or audio HAL read error
89static const int kRecordThreadSleepUs = 5000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
Glenn Kastencbfe2e12011-12-13 11:04:14 -080091// maximum time to wait for setParameters to complete
92static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent5f37be32011-09-13 11:40:21 -070093
Eric Laurentf1f5fc82011-11-22 18:50:29 -080094// minimum sleep time for the mixer thread loop when tracks are active but in underrun
95static const uint32_t kMinThreadSleepTimeUs = 5000;
96// maximum divider applied to the active sleep time in the mixer thread loop
97static const uint32_t kMaxThreadSleepTimeShift = 2;
98
99
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700100// ----------------------------------------------------------------------------
101
102static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700103 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
104 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
105 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
106 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700107}
108
109static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700110 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
111 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
112 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
113 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700114}
115
Gloria Wang9b3f1522011-02-24 14:51:45 -0800116// To collect the amplifier usage
117static void addBatteryData(uint32_t params) {
118 sp<IBinder> binder =
119 defaultServiceManager()->getService(String16("media.player"));
120 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
121 if (service.get() == NULL) {
122 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
123 return;
124 }
125
126 service->addBatteryData(params);
127}
128
Dima Zavin31f188892011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
139 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
152static const char *audio_interfaces[] = {
153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 : BnAudioFlinger(),
Eric Laurent6639b552011-08-01 09:52:20 -0700163 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700164 mBtNrecIsOff(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700165{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700166}
167
168void AudioFlinger::onFirstRef()
169{
Dima Zavin31f188892011-04-18 16:57:27 -0700170 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700171
Eric Laurent01635942011-01-18 18:39:02 -0800172 Mutex::Autolock _l(mLock);
173
Dima Zavin31f188892011-04-18 16:57:27 -0700174 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700175 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700176
Dima Zavin31f188892011-04-18 16:57:27 -0700177 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
178 const hw_module_t *mod;
179 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700180
Dima Zavin31f188892011-04-18 16:57:27 -0700181 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
182 if (rc)
183 continue;
184
185 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
186 mod->name, mod->id);
187 mAudioHwDevs.push(dev);
188
189 if (!mPrimaryHardwareDev) {
190 mPrimaryHardwareDev = dev;
191 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700192 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700193 }
194 }
Eric Laurenta553c252009-07-17 12:17:14 -0700195
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700196 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700197
Dima Zavin31f188892011-04-18 16:57:27 -0700198 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
199 LOGE("Primary audio interface not found");
200 return;
201 }
202
203 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
204 audio_hw_device_t *dev = mAudioHwDevs[i];
205
206 mHardwareStatus = AUDIO_HW_INIT;
207 rc = dev->init_check(dev);
208 if (rc == 0) {
209 AutoMutex lock(mHardwareLock);
210
211 mMode = AUDIO_MODE_NORMAL;
212 mHardwareStatus = AUDIO_HW_SET_MODE;
213 dev->set_mode(dev, mMode);
214 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
215 dev->set_master_volume(dev, 1.0f);
216 mHardwareStatus = AUDIO_HW_IDLE;
217 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700218 }
219}
220
Dima Zavin2986f5b2011-04-19 19:04:32 -0700221status_t AudioFlinger::initCheck() const
222{
223 Mutex::Autolock _l(mLock);
224 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
225 return NO_INIT;
226 return NO_ERROR;
227}
228
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700229AudioFlinger::~AudioFlinger()
230{
Dima Zavin31f188892011-04-18 16:57:27 -0700231 int num_devs = mAudioHwDevs.size();
232
Eric Laurent7954c462009-08-28 10:39:03 -0700233 while (!mRecordThreads.isEmpty()) {
234 // closeInput() will remove first entry from mRecordThreads
235 closeInput(mRecordThreads.keyAt(0));
236 }
237 while (!mPlaybackThreads.isEmpty()) {
238 // closeOutput() will remove first entry from mPlaybackThreads
239 closeOutput(mPlaybackThreads.keyAt(0));
240 }
Dima Zavin31f188892011-04-18 16:57:27 -0700241
242 for (int i = 0; i < num_devs; i++) {
243 audio_hw_device_t *dev = mAudioHwDevs[i];
244 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700245 }
Dima Zavin31f188892011-04-18 16:57:27 -0700246 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800247}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800248
Dima Zavin31f188892011-04-18 16:57:27 -0700249audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
250{
251 /* first matching HW device is returned */
252 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
253 audio_hw_device_t *dev = mAudioHwDevs[i];
254 if ((dev->get_supported_devices(dev) & devices) == devices)
255 return dev;
256 }
257 return NULL;
258}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700259
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700260status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
261{
262 const size_t SIZE = 256;
263 char buffer[SIZE];
264 String8 result;
265
266 result.append("Clients:\n");
267 for (size_t i = 0; i < mClients.size(); ++i) {
268 wp<Client> wClient = mClients.valueAt(i);
269 if (wClient != 0) {
270 sp<Client> client = wClient.promote();
271 if (client != 0) {
272 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
273 result.append(buffer);
274 }
275 }
276 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700277
278 result.append("Global session refs:\n");
279 result.append(" session pid cnt\n");
280 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
281 AudioSessionRef *r = mAudioSessionRefs[i];
282 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
283 result.append(buffer);
284 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700285 write(fd, result.string(), result.size());
286 return NO_ERROR;
287}
288
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700289
290status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
291{
292 const size_t SIZE = 256;
293 char buffer[SIZE];
294 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700295 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700296
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700297 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700298 result.append(buffer);
299 write(fd, result.string(), result.size());
300 return NO_ERROR;
301}
302
303status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
304{
305 const size_t SIZE = 256;
306 char buffer[SIZE];
307 String8 result;
308 snprintf(buffer, SIZE, "Permission Denial: "
309 "can't dump AudioFlinger from pid=%d, uid=%d\n",
310 IPCThreadState::self()->getCallingPid(),
311 IPCThreadState::self()->getCallingUid());
312 result.append(buffer);
313 write(fd, result.string(), result.size());
314 return NO_ERROR;
315}
316
The Android Open Source Project10592532009-03-18 17:39:46 -0700317static bool tryLock(Mutex& mutex)
318{
319 bool locked = false;
320 for (int i = 0; i < kDumpLockRetries; ++i) {
321 if (mutex.tryLock() == NO_ERROR) {
322 locked = true;
323 break;
324 }
Glenn Kastencbfe2e12011-12-13 11:04:14 -0800325 usleep(kDumpLockSleepUs);
The Android Open Source Project10592532009-03-18 17:39:46 -0700326 }
327 return locked;
328}
329
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700330status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
331{
332 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
333 dumpPermissionDenial(fd, args);
334 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700335 // get state of hardware lock
336 bool hardwareLocked = tryLock(mHardwareLock);
337 if (!hardwareLocked) {
338 String8 result(kHardwareLockedString);
339 write(fd, result.string(), result.size());
340 } else {
341 mHardwareLock.unlock();
342 }
343
344 bool locked = tryLock(mLock);
345
346 // failed to lock - AudioFlinger is probably deadlocked
347 if (!locked) {
348 String8 result(kDeadlockedString);
349 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700350 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700351
352 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700353 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354
Eric Laurenta553c252009-07-17 12:17:14 -0700355 // dump playback threads
356 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700357 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700358 }
359
360 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700361 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700362 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364
Dima Zavin31f188892011-04-18 16:57:27 -0700365 // dump all hardware devs
366 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
367 audio_hw_device_t *dev = mAudioHwDevs[i];
368 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700369 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700370 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700371 }
372 return NO_ERROR;
373}
374
Eric Laurenta553c252009-07-17 12:17:14 -0700375
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700376// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377
378
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700379sp<IAudioTrack> AudioFlinger::createTrack(
380 pid_t pid,
381 int streamType,
382 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700383 uint32_t format,
384 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800385 int frameCount,
386 uint32_t flags,
387 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700388 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700389 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800390 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700391{
Eric Laurenta553c252009-07-17 12:17:14 -0700392 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700393 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700394 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800395 wp<Client> wclient;
396 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700397 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700398
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700399 if (streamType >= AUDIO_STREAM_CNT) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800400 LOGE("invalid stream type");
401 lStatus = BAD_VALUE;
402 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700403 }
404
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800405 {
406 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700407 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700408 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700409 if (thread == NULL) {
410 LOGE("unknown output thread");
411 lStatus = BAD_VALUE;
412 goto Exit;
413 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800414
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800415 wclient = mClients.valueFor(pid);
416
417 if (wclient != NULL) {
418 client = wclient.promote();
419 } else {
420 client = new Client(this, pid);
421 mClients.add(pid, client);
422 }
Eric Laurent65b65452010-06-01 23:49:17 -0700423
Steve Block71f2cf12011-10-20 11:56:00 +0100424 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700425 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700426 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700427 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
428 if (mPlaybackThreads.keyAt(i) != output) {
429 // prevent same audio session on different output threads
430 uint32_t sessions = t->hasAudioSession(*sessionId);
431 if (sessions & PlaybackThread::TRACK_SESSION) {
432 lStatus = BAD_VALUE;
433 goto Exit;
434 }
435 // check if an effect with same session ID is waiting for a track to be created
436 if (sessions & PlaybackThread::EFFECT_SESSION) {
437 effectThread = t.get();
438 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700439 }
440 }
Eric Laurent65b65452010-06-01 23:49:17 -0700441 lSessionId = *sessionId;
442 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700443 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700444 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700445 if (sessionId != NULL) {
446 *sessionId = lSessionId;
447 }
448 }
Steve Block71f2cf12011-10-20 11:56:00 +0100449 ALOGV("createTrack() lSessionId: %d", lSessionId);
Eric Laurent65b65452010-06-01 23:49:17 -0700450
Eric Laurenta553c252009-07-17 12:17:14 -0700451 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700452 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700453
454 // move effect chain to this output thread if an effect on same session was waiting
455 // for a track to be created
456 if (lStatus == NO_ERROR && effectThread != NULL) {
457 Mutex::Autolock _dl(thread->mLock);
458 Mutex::Autolock _sl(effectThread->mLock);
459 moveEffectChain_l(lSessionId, effectThread, thread, true);
460 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700461 }
462 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800463 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700464 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700465 // remove local strong reference to Client before deleting the Track so that the Client
466 // destructor is called by the TrackBase destructor with mLock held
467 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700468 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800469 }
470
471Exit:
472 if(status) {
473 *status = lStatus;
474 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700475 return trackHandle;
476}
477
Eric Laurentddb78e72009-07-28 08:44:33 -0700478uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700479{
Eric Laurenta553c252009-07-17 12:17:14 -0700480 Mutex::Autolock _l(mLock);
481 PlaybackThread *thread = checkPlaybackThread_l(output);
482 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700483 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700484 return 0;
485 }
486 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700487}
488
Eric Laurentddb78e72009-07-28 08:44:33 -0700489int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700490{
Eric Laurenta553c252009-07-17 12:17:14 -0700491 Mutex::Autolock _l(mLock);
492 PlaybackThread *thread = checkPlaybackThread_l(output);
493 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700494 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700495 return 0;
496 }
497 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700498}
499
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700500uint32_t AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700501{
Eric Laurenta553c252009-07-17 12:17:14 -0700502 Mutex::Autolock _l(mLock);
503 PlaybackThread *thread = checkPlaybackThread_l(output);
504 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700505 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700506 return 0;
507 }
508 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700509}
510
Eric Laurentddb78e72009-07-28 08:44:33 -0700511size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700512{
Eric Laurenta553c252009-07-17 12:17:14 -0700513 Mutex::Autolock _l(mLock);
514 PlaybackThread *thread = checkPlaybackThread_l(output);
515 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700516 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700517 return 0;
518 }
519 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700520}
521
Eric Laurentddb78e72009-07-28 08:44:33 -0700522uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800523{
Eric Laurenta553c252009-07-17 12:17:14 -0700524 Mutex::Autolock _l(mLock);
525 PlaybackThread *thread = checkPlaybackThread_l(output);
526 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700527 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700528 return 0;
529 }
530 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800531}
532
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700533status_t AudioFlinger::setMasterVolume(float value)
534{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700535 status_t ret = initCheck();
536 if (ret != NO_ERROR) {
537 return ret;
538 }
539
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700540 // check calling permissions
541 if (!settingsAllowed()) {
542 return PERMISSION_DENIED;
543 }
544
545 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800546 { // scope for the lock
547 AutoMutex lock(mHardwareLock);
548 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700549 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800550 value = 1.0f;
551 }
552 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700553 }
Eric Laurenta553c252009-07-17 12:17:14 -0700554
Eric Laurent01635942011-01-18 18:39:02 -0800555 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700556 mMasterVolume = value;
557 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700558 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700559
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700560 return NO_ERROR;
561}
562
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700563status_t AudioFlinger::setMode(int mode)
564{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700565 status_t ret = initCheck();
566 if (ret != NO_ERROR) {
567 return ret;
568 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700569
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700570 // check calling permissions
571 if (!settingsAllowed()) {
572 return PERMISSION_DENIED;
573 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700574 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700575 LOGW("Illegal value: setMode(%d)", mode);
576 return BAD_VALUE;
577 }
578
Eric Laurent53334cd2010-06-23 17:38:20 -0700579 { // scope for the lock
580 AutoMutex lock(mHardwareLock);
581 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700582 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700583 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800584 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700585
586 if (NO_ERROR == ret) {
587 Mutex::Autolock _l(mLock);
588 mMode = mode;
589 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
590 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700591 }
592
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700593 return ret;
594}
595
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700596status_t AudioFlinger::setMicMute(bool state)
597{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700598 status_t ret = initCheck();
599 if (ret != NO_ERROR) {
600 return ret;
601 }
602
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700603 // check calling permissions
604 if (!settingsAllowed()) {
605 return PERMISSION_DENIED;
606 }
607
608 AutoMutex lock(mHardwareLock);
609 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700610 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700611 mHardwareStatus = AUDIO_HW_IDLE;
612 return ret;
613}
614
615bool AudioFlinger::getMicMute() const
616{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700617 status_t ret = initCheck();
618 if (ret != NO_ERROR) {
619 return false;
620 }
621
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700622 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700623 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700624 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700625 mHardwareStatus = AUDIO_HW_IDLE;
626 return state;
627}
628
629status_t AudioFlinger::setMasterMute(bool muted)
630{
631 // check calling permissions
632 if (!settingsAllowed()) {
633 return PERMISSION_DENIED;
634 }
Eric Laurenta553c252009-07-17 12:17:14 -0700635
Eric Laurent01635942011-01-18 18:39:02 -0800636 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700637 mMasterMute = muted;
638 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700639 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700640
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700641 return NO_ERROR;
642}
643
644float AudioFlinger::masterVolume() const
645{
Eric Laurenta553c252009-07-17 12:17:14 -0700646 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700647}
648
649bool AudioFlinger::masterMute() const
650{
Eric Laurenta553c252009-07-17 12:17:14 -0700651 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700652}
653
Eric Laurentddb78e72009-07-28 08:44:33 -0700654status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700655{
656 // check calling permissions
657 if (!settingsAllowed()) {
658 return PERMISSION_DENIED;
659 }
660
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700661 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700662 return BAD_VALUE;
663 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800664
Eric Laurenta553c252009-07-17 12:17:14 -0700665 AutoMutex lock(mLock);
666 PlaybackThread *thread = NULL;
667 if (output) {
668 thread = checkPlaybackThread_l(output);
669 if (thread == NULL) {
670 return BAD_VALUE;
671 }
672 }
673
Eric Laurenta553c252009-07-17 12:17:14 -0700674 mStreamTypes[stream].volume = value;
675
676 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700677 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700678 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700679 }
Eric Laurenta553c252009-07-17 12:17:14 -0700680 } else {
681 thread->setStreamVolume(stream, value);
682 }
Eric Laurentef028272009-04-21 07:56:33 -0700683
Eric Laurent415f3e22009-10-21 08:14:22 -0700684 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700685}
686
687status_t AudioFlinger::setStreamMute(int stream, bool muted)
688{
689 // check calling permissions
690 if (!settingsAllowed()) {
691 return PERMISSION_DENIED;
692 }
693
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700694 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
695 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700696 return BAD_VALUE;
697 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700698
Eric Laurent01635942011-01-18 18:39:02 -0800699 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700700 mStreamTypes[stream].mute = muted;
701 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700702 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700704 return NO_ERROR;
705}
706
Eric Laurentddb78e72009-07-28 08:44:33 -0700707float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700708{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700709 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700710 return 0.0f;
711 }
Eric Laurenta553c252009-07-17 12:17:14 -0700712
713 AutoMutex lock(mLock);
714 float volume;
715 if (output) {
716 PlaybackThread *thread = checkPlaybackThread_l(output);
717 if (thread == NULL) {
718 return 0.0f;
719 }
720 volume = thread->streamVolume(stream);
721 } else {
722 volume = mStreamTypes[stream].volume;
723 }
724
Eric Laurentef028272009-04-21 07:56:33 -0700725 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700726}
727
728bool AudioFlinger::streamMute(int stream) const
729{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700730 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700731 return true;
732 }
Eric Laurenta553c252009-07-17 12:17:14 -0700733
734 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700735}
736
Eric Laurentddb78e72009-07-28 08:44:33 -0700737status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700738{
Eric Laurenta553c252009-07-17 12:17:14 -0700739 status_t result;
740
Steve Block71f2cf12011-10-20 11:56:00 +0100741 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700742 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
743 // check calling permissions
744 if (!settingsAllowed()) {
745 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800746 }
Eric Laurenta553c252009-07-17 12:17:14 -0700747
748 // ioHandle == 0 means the parameters are global to the audio hardware interface
749 if (ioHandle == 0) {
750 AutoMutex lock(mHardwareLock);
751 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700752 status_t final_result = NO_ERROR;
753 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
754 audio_hw_device_t *dev = mAudioHwDevs[i];
755 result = dev->set_parameters(dev, keyValuePairs.string());
756 final_result = result ?: final_result;
757 }
Eric Laurenta553c252009-07-17 12:17:14 -0700758 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent6639b552011-08-01 09:52:20 -0700759 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
760 AudioParameter param = AudioParameter(keyValuePairs);
761 String8 value;
762 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
763 Mutex::Autolock _l(mLock);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700764 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
765 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent6639b552011-08-01 09:52:20 -0700766 for (size_t i = 0; i < mRecordThreads.size(); i++) {
767 sp<RecordThread> thread = mRecordThreads.valueAt(i);
768 RecordThread::RecordTrack *track = thread->track();
769 if (track != NULL) {
770 audio_devices_t device = (audio_devices_t)(
771 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700772 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700773 thread->setEffectSuspended(FX_IID_AEC,
774 suspend,
775 track->sessionId());
776 thread->setEffectSuspended(FX_IID_NS,
777 suspend,
778 track->sessionId());
779 }
780 }
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700781 mBtNrecIsOff = btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700782 }
783 }
Dima Zavin31f188892011-04-18 16:57:27 -0700784 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700785 }
786
Eric Laurentb7d94602009-09-29 11:12:57 -0700787 // hold a strong ref on thread in case closeOutput() or closeInput() is called
788 // and the thread is exited once the lock is released
789 sp<ThreadBase> thread;
790 {
791 Mutex::Autolock _l(mLock);
792 thread = checkPlaybackThread_l(ioHandle);
793 if (thread == NULL) {
794 thread = checkRecordThread_l(ioHandle);
Eric Laurent464d5b32011-06-17 21:29:58 -0700795 } else if (thread.get() == primaryPlaybackThread_l()) {
796 // indicate output device change to all input threads for pre processing
797 AudioParameter param = AudioParameter(keyValuePairs);
798 int value;
799 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
800 for (size_t i = 0; i < mRecordThreads.size(); i++) {
801 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
802 }
803 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700804 }
Eric Laurenta553c252009-07-17 12:17:14 -0700805 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700806 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800807 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800808 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700809 }
Eric Laurenta553c252009-07-17 12:17:14 -0700810 return BAD_VALUE;
811}
812
Eric Laurentddb78e72009-07-28 08:44:33 -0700813String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700814{
Steve Block71f2cf12011-10-20 11:56:00 +0100815// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700816// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
817
818 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700819 String8 out_s8;
820
Dima Zavin31f188892011-04-18 16:57:27 -0700821 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
822 audio_hw_device_t *dev = mAudioHwDevs[i];
823 char *s = dev->get_parameters(dev, keys.string());
824 out_s8 += String8(s);
825 free(s);
826 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700827 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700828 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700829
830 Mutex::Autolock _l(mLock);
831
Eric Laurenta553c252009-07-17 12:17:14 -0700832 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
833 if (playbackThread != NULL) {
834 return playbackThread->getParameters(keys);
835 }
836 RecordThread *recordThread = checkRecordThread_l(ioHandle);
837 if (recordThread != NULL) {
838 return recordThread->getParameters(keys);
839 }
840 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700841}
842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
844{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700845 status_t ret = initCheck();
846 if (ret != NO_ERROR) {
847 return 0;
848 }
849
Dima Zavin31f188892011-04-18 16:57:27 -0700850 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851}
852
Eric Laurent47d0a922010-02-26 02:47:27 -0800853unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
854{
855 if (ioHandle == 0) {
856 return 0;
857 }
858
859 Mutex::Autolock _l(mLock);
860
861 RecordThread *recordThread = checkRecordThread_l(ioHandle);
862 if (recordThread != NULL) {
863 return recordThread->getInputFramesLost();
864 }
865 return 0;
866}
867
Eric Laurent415f3e22009-10-21 08:14:22 -0700868status_t AudioFlinger::setVoiceVolume(float value)
869{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700870 status_t ret = initCheck();
871 if (ret != NO_ERROR) {
872 return ret;
873 }
874
Eric Laurent415f3e22009-10-21 08:14:22 -0700875 // check calling permissions
876 if (!settingsAllowed()) {
877 return PERMISSION_DENIED;
878 }
879
880 AutoMutex lock(mHardwareLock);
881 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700882 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700883 mHardwareStatus = AUDIO_HW_IDLE;
884
885 return ret;
886}
887
Eric Laurent0986e792010-01-19 17:37:09 -0800888status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
889{
890 status_t status;
891
892 Mutex::Autolock _l(mLock);
893
894 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
895 if (playbackThread != NULL) {
896 return playbackThread->getRenderPosition(halFrames, dspFrames);
897 }
898
899 return BAD_VALUE;
900}
901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
903{
Eric Laurenta553c252009-07-17 12:17:14 -0700904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 Mutex::Autolock _l(mLock);
906
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700907 int pid = IPCThreadState::self()->getCallingPid();
908 if (mNotificationClients.indexOfKey(pid) < 0) {
909 sp<NotificationClient> notificationClient = new NotificationClient(this,
910 client,
911 pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100912 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700913
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700914 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700915
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700916 sp<IBinder> binder = client->asBinder();
917 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700919 // the config change is always sent from playback or record threads to avoid deadlock
920 // with AudioSystem::gLock
921 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
922 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
923 }
Eric Laurenta553c252009-07-17 12:17:14 -0700924
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700925 for (size_t i = 0; i < mRecordThreads.size(); i++) {
926 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 }
928 }
929}
930
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700931void AudioFlinger::removeNotificationClient(pid_t pid)
932{
933 Mutex::Autolock _l(mLock);
934
935 int index = mNotificationClients.indexOfKey(pid);
936 if (index >= 0) {
937 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100938 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700939 mNotificationClients.removeItem(pid);
940 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700941
Steve Block71f2cf12011-10-20 11:56:00 +0100942 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700943 int num = mAudioSessionRefs.size();
944 bool removed = false;
945 for (int i = 0; i< num; i++) {
946 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +0100947 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700948 if (ref->pid == pid) {
Steve Block71f2cf12011-10-20 11:56:00 +0100949 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700950 mAudioSessionRefs.removeAt(i);
951 delete ref;
952 removed = true;
953 i--;
954 num--;
955 }
956 }
957 if (removed) {
958 purgeStaleEffects_l();
959 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700960}
961
Eric Laurent296a0ec2009-09-15 07:10:12 -0700962// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700963void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
964{
Eric Laurent49f02be2009-11-19 09:00:56 -0800965 size_t size = mNotificationClients.size();
966 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700967 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700968 }
969}
970
Eric Laurentb9481d82009-09-17 05:12:56 -0700971// removeClient_l() must be called with AudioFlinger::mLock held
972void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700973{
Steve Block71f2cf12011-10-20 11:56:00 +0100974 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700975 mClients.removeItem(pid);
976}
977
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700978
Eric Laurenta553c252009-07-17 12:17:14 -0700979// ----------------------------------------------------------------------------
980
Eric Laurent464d5b32011-06-17 21:29:58 -0700981AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Eric Laurenta553c252009-07-17 12:17:14 -0700982 : Thread(false),
983 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent6dbdc402011-07-22 09:04:31 -0700984 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
985 mDevice(device)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700986{
Eric Laurent6dbdc402011-07-22 09:04:31 -0700987 mDeathRecipient = new PMDeathRecipient(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988}
989
Eric Laurenta553c252009-07-17 12:17:14 -0700990AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700992 mParamCond.broadcast();
993 mNewParameters.clear();
Eric Laurent6dbdc402011-07-22 09:04:31 -0700994 // do not lock the mutex in destructor
995 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -0700996 if (mPowerManager != 0) {
997 sp<IBinder> binder = mPowerManager->asBinder();
998 binder->unlinkToDeath(mDeathRecipient);
999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000}
1001
Eric Laurenta553c252009-07-17 12:17:14 -07001002void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001003{
Eric Laurentb7d94602009-09-29 11:12:57 -07001004 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -07001005 // destroyed in the middle of requestExitAndWait()
1006 sp <ThreadBase> strongMe = this;
1007
Steve Block71f2cf12011-10-20 11:56:00 +01001008 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001009 {
1010 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001011 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001012 requestExit();
1013 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001014 }
Eric Laurenta553c252009-07-17 12:17:14 -07001015 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001016}
Eric Laurenta553c252009-07-17 12:17:14 -07001017
1018uint32_t AudioFlinger::ThreadBase::sampleRate() const
1019{
1020 return mSampleRate;
1021}
1022
1023int AudioFlinger::ThreadBase::channelCount() const
1024{
Eric Laurentb0a01472010-05-14 05:45:46 -07001025 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07001026}
1027
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001028uint32_t AudioFlinger::ThreadBase::format() const
Eric Laurenta553c252009-07-17 12:17:14 -07001029{
1030 return mFormat;
1031}
1032
1033size_t AudioFlinger::ThreadBase::frameCount() const
1034{
1035 return mFrameCount;
1036}
1037
1038status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1039{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001040 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001041
Steve Block71f2cf12011-10-20 11:56:00 +01001042 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001043 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001044
Eric Laurent8fce46a2009-08-04 09:45:33 -07001045 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001046 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001047 // wait condition with timeout in case the thread loop has exited
1048 // before the request could be processed
Glenn Kastencbfe2e12011-12-13 11:04:14 -08001049 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001050 status = mParamStatus;
1051 mWaitWorkCV.signal();
1052 } else {
1053 status = TIMED_OUT;
1054 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001055 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001056}
1057
1058void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1059{
1060 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001061 sendConfigEvent_l(event, param);
1062}
1063
1064// sendConfigEvent_l() must be called with ThreadBase::mLock held
1065void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1066{
Eric Laurenta553c252009-07-17 12:17:14 -07001067 ConfigEvent *configEvent = new ConfigEvent();
1068 configEvent->mEvent = event;
1069 configEvent->mParam = param;
1070 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001071 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001072 mWaitWorkCV.signal();
1073}
1074
1075void AudioFlinger::ThreadBase::processConfigEvents()
1076{
1077 mLock.lock();
1078 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001079 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001080 ConfigEvent *configEvent = mConfigEvents[0];
1081 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001082 // release mLock before locking AudioFlinger mLock: lock order is always
1083 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001084 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001085 mAudioFlinger->mLock.lock();
1086 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1087 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001088 delete configEvent;
1089 mLock.lock();
1090 }
1091 mLock.unlock();
1092}
1093
Eric Laurent3fdb1262009-11-07 00:01:32 -08001094status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1095{
1096 const size_t SIZE = 256;
1097 char buffer[SIZE];
1098 String8 result;
1099
1100 bool locked = tryLock(mLock);
1101 if (!locked) {
1102 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1103 write(fd, buffer, strlen(buffer));
1104 }
1105
1106 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1107 result.append(buffer);
1108 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1109 result.append(buffer);
1110 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1111 result.append(buffer);
1112 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1113 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001114 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1115 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001116 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1117 result.append(buffer);
1118 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1119 result.append(buffer);
1120
1121 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1122 result.append(buffer);
1123 result.append(" Index Command");
1124 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1125 snprintf(buffer, SIZE, "\n %02d ", i);
1126 result.append(buffer);
1127 result.append(mNewParameters[i]);
1128 }
1129
1130 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1131 result.append(buffer);
1132 snprintf(buffer, SIZE, " Index event param\n");
1133 result.append(buffer);
1134 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1135 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1136 result.append(buffer);
1137 }
1138 result.append("\n");
1139
1140 write(fd, result.string(), result.size());
1141
1142 if (locked) {
1143 mLock.unlock();
1144 }
1145 return NO_ERROR;
1146}
1147
Eric Laurent1345d332011-07-24 17:49:51 -07001148status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1149{
1150 const size_t SIZE = 256;
1151 char buffer[SIZE];
1152 String8 result;
1153
1154 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1155 write(fd, buffer, strlen(buffer));
1156
1157 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1158 sp<EffectChain> chain = mEffectChains[i];
1159 if (chain != 0) {
1160 chain->dump(fd, args);
1161 }
1162 }
1163 return NO_ERROR;
1164}
1165
Eric Laurent6dbdc402011-07-22 09:04:31 -07001166void AudioFlinger::ThreadBase::acquireWakeLock()
1167{
1168 Mutex::Autolock _l(mLock);
1169 acquireWakeLock_l();
1170}
1171
1172void AudioFlinger::ThreadBase::acquireWakeLock_l()
1173{
1174 if (mPowerManager == 0) {
1175 // use checkService() to avoid blocking if power service is not up yet
1176 sp<IBinder> binder =
1177 defaultServiceManager()->checkService(String16("power"));
1178 if (binder == 0) {
1179 LOGW("Thread %s cannot connect to the power manager service", mName);
1180 } else {
1181 mPowerManager = interface_cast<IPowerManager>(binder);
1182 binder->linkToDeath(mDeathRecipient);
1183 }
1184 }
1185 if (mPowerManager != 0) {
1186 sp<IBinder> binder = new BBinder();
1187 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1188 binder,
1189 String16(mName));
1190 if (status == NO_ERROR) {
1191 mWakeLockToken = binder;
1192 }
Steve Block71f2cf12011-10-20 11:56:00 +01001193 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001194 }
1195}
1196
1197void AudioFlinger::ThreadBase::releaseWakeLock()
1198{
1199 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001200 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001201}
1202
1203void AudioFlinger::ThreadBase::releaseWakeLock_l()
1204{
1205 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001206 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001207 if (mPowerManager != 0) {
1208 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1209 }
1210 mWakeLockToken.clear();
1211 }
1212}
1213
1214void AudioFlinger::ThreadBase::clearPowerManager()
1215{
1216 Mutex::Autolock _l(mLock);
1217 releaseWakeLock_l();
1218 mPowerManager.clear();
1219}
1220
1221void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1222{
1223 sp<ThreadBase> thread = mThread.promote();
1224 if (thread != 0) {
1225 thread->clearPowerManager();
1226 }
1227 LOGW("power manager service died !!!");
1228}
Eric Laurent1345d332011-07-24 17:49:51 -07001229
Eric Laurentf82fccd2011-07-27 19:49:51 -07001230void AudioFlinger::ThreadBase::setEffectSuspended(
1231 const effect_uuid_t *type, bool suspend, int sessionId)
1232{
1233 Mutex::Autolock _l(mLock);
1234 setEffectSuspended_l(type, suspend, sessionId);
1235}
1236
1237void AudioFlinger::ThreadBase::setEffectSuspended_l(
1238 const effect_uuid_t *type, bool suspend, int sessionId)
1239{
1240 sp<EffectChain> chain;
1241 chain = getEffectChain_l(sessionId);
1242 if (chain != 0) {
1243 if (type != NULL) {
1244 chain->setEffectSuspended_l(type, suspend);
1245 } else {
1246 chain->setEffectSuspendedAll_l(suspend);
1247 }
1248 }
1249
1250 updateSuspendedSessions_l(type, suspend, sessionId);
1251}
1252
1253void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1254{
1255 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1256 if (index < 0) {
1257 return;
1258 }
1259
1260 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1261 mSuspendedSessions.editValueAt(index);
1262
1263 for (size_t i = 0; i < sessionEffects.size(); i++) {
1264 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1265 for (int j = 0; j < desc->mRefCount; j++) {
1266 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1267 chain->setEffectSuspendedAll_l(true);
1268 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001269 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001270 desc->mType.timeLow);
1271 chain->setEffectSuspended_l(&desc->mType, true);
1272 }
1273 }
1274 }
1275}
1276
Eric Laurentf82fccd2011-07-27 19:49:51 -07001277void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1278 bool suspend,
1279 int sessionId)
1280{
1281 int index = mSuspendedSessions.indexOfKey(sessionId);
1282
1283 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1284
1285 if (suspend) {
1286 if (index >= 0) {
1287 sessionEffects = mSuspendedSessions.editValueAt(index);
1288 } else {
1289 mSuspendedSessions.add(sessionId, sessionEffects);
1290 }
1291 } else {
1292 if (index < 0) {
1293 return;
1294 }
1295 sessionEffects = mSuspendedSessions.editValueAt(index);
1296 }
1297
1298
1299 int key = EffectChain::kKeyForSuspendAll;
1300 if (type != NULL) {
1301 key = type->timeLow;
1302 }
1303 index = sessionEffects.indexOfKey(key);
1304
1305 sp <SuspendedSessionDesc> desc;
1306 if (suspend) {
1307 if (index >= 0) {
1308 desc = sessionEffects.valueAt(index);
1309 } else {
1310 desc = new SuspendedSessionDesc();
1311 if (type != NULL) {
1312 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1313 }
1314 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001315 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001316 }
1317 desc->mRefCount++;
1318 } else {
1319 if (index < 0) {
1320 return;
1321 }
1322 desc = sessionEffects.valueAt(index);
1323 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001324 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001325 sessionEffects.removeItemsAt(index);
1326 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001327 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001328 sessionId);
1329 mSuspendedSessions.removeItem(sessionId);
1330 }
1331 }
1332 }
1333 if (!sessionEffects.isEmpty()) {
1334 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1335 }
1336}
1337
1338void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1339 bool enabled,
1340 int sessionId)
1341{
1342 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001343 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1344}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001345
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001346void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1347 bool enabled,
1348 int sessionId)
1349{
Eric Laurent6752ec82011-08-10 10:37:50 -07001350 if (mType != RECORD) {
1351 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1352 // another session. This gives the priority to well behaved effect control panels
1353 // and applications not using global effects.
1354 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1355 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1356 }
1357 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001358
1359 sp<EffectChain> chain = getEffectChain_l(sessionId);
1360 if (chain != 0) {
1361 chain->checkSuspendOnEffectEnabled(effect, enabled);
1362 }
1363}
1364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365// ----------------------------------------------------------------------------
1366
Eric Laurent464d5b32011-06-17 21:29:58 -07001367AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1368 AudioStreamOut* output,
1369 int id,
1370 uint32_t device)
1371 : ThreadBase(audioFlinger, id, device),
Eric Laurentd5603c12009-08-06 08:49:39 -07001372 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent464d5b32011-06-17 21:29:58 -07001373 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001375 snprintf(mName, kNameLength, "AudioOut_%d", id);
1376
Eric Laurenta553c252009-07-17 12:17:14 -07001377 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378
Eric Laurenta553c252009-07-17 12:17:14 -07001379 mMasterVolume = mAudioFlinger->masterVolume();
1380 mMasterMute = mAudioFlinger->masterMute();
1381
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001382 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurenta553c252009-07-17 12:17:14 -07001383 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1384 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent05ce0942011-08-30 10:18:54 -07001385 mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387}
1388
Eric Laurenta553c252009-07-17 12:17:14 -07001389AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390{
1391 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392}
1393
Eric Laurenta553c252009-07-17 12:17:14 -07001394status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395{
1396 dumpInternals(fd, args);
1397 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001398 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 return NO_ERROR;
1400}
1401
Eric Laurenta553c252009-07-17 12:17:14 -07001402status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403{
1404 const size_t SIZE = 256;
1405 char buffer[SIZE];
1406 String8 result;
1407
Eric Laurenta553c252009-07-17 12:17:14 -07001408 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001410 result.append(" Name Clien Typ Fmt Chn mask 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 -08001411 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001412 sp<Track> track = mTracks[i];
1413 if (track != 0) {
1414 track->dump(buffer, SIZE);
1415 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417 }
1418
Eric Laurenta553c252009-07-17 12:17:14 -07001419 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001421 result.append(" Name Clien Typ Fmt Chn mask 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 -08001422 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001423 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 if (wTrack != 0) {
1425 sp<Track> track = wTrack.promote();
1426 if (track != 0) {
1427 track->dump(buffer, SIZE);
1428 result.append(buffer);
1429 }
1430 }
1431 }
1432 write(fd, result.string(), result.size());
1433 return NO_ERROR;
1434}
1435
Eric Laurenta553c252009-07-17 12:17:14 -07001436status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437{
1438 const size_t SIZE = 256;
1439 char buffer[SIZE];
1440 String8 result;
1441
Eric Laurent3fdb1262009-11-07 00:01:32 -08001442 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 result.append(buffer);
1444 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1445 result.append(buffer);
1446 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1447 result.append(buffer);
1448 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1449 result.append(buffer);
1450 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1451 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001452 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1453 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001454 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1455 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001457
1458 dumpBase(fd, args);
1459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 return NO_ERROR;
1461}
1462
1463// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001464status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465{
Eric Laurent828b9772011-08-07 16:32:26 -07001466 status_t status = initCheck();
1467 if (status == NO_ERROR) {
1468 LOGI("AudioFlinger's thread %p ready to run", this);
1469 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 LOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 }
Eric Laurent828b9772011-08-07 16:32:26 -07001472 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473}
1474
Eric Laurenta553c252009-07-17 12:17:14 -07001475void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001477 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478}
1479
Eric Laurenta553c252009-07-17 12:17:14 -07001480// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1481sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 const sp<AudioFlinger::Client>& client,
1483 int streamType,
1484 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001485 uint32_t format,
1486 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 int frameCount,
1488 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001489 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 status_t *status)
1491{
1492 sp<Track> track;
1493 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001494
1495 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001496 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1497 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1498 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1499 "for output %p with format %d",
1500 sampleRate, format, channelMask, mOutput, mFormat);
1501 lStatus = BAD_VALUE;
1502 goto Exit;
1503 }
Eric Laurenta553c252009-07-17 12:17:14 -07001504 }
1505 } else {
1506 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1507 if (sampleRate > mSampleRate*2) {
1508 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1509 lStatus = BAD_VALUE;
1510 goto Exit;
1511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513
Eric Laurent464d5b32011-06-17 21:29:58 -07001514 lStatus = initCheck();
1515 if (lStatus != NO_ERROR) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001516 LOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001517 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 }
1519
Eric Laurenta553c252009-07-17 12:17:14 -07001520 { // scope for mLock
1521 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001522
1523 // all tracks in same audio session must share the same routing strategy otherwise
1524 // conflicts will happen when tracks are moved from one output to another by audio policy
1525 // manager
1526 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001527 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001528 for (size_t i = 0; i < mTracks.size(); ++i) {
1529 sp<Track> t = mTracks[i];
1530 if (t != 0) {
1531 if (sessionId == t->sessionId() &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001532 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001533 lStatus = BAD_VALUE;
1534 goto Exit;
1535 }
1536 }
1537 }
1538
Eric Laurenta553c252009-07-17 12:17:14 -07001539 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001540 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001541 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001542 lStatus = NO_MEMORY;
1543 goto Exit;
1544 }
1545 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001546
1547 sp<EffectChain> chain = getEffectChain_l(sessionId);
1548 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001549 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001550 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001551 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001552 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001553 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001554
1555 // invalidate track immediately if the stream type was moved to another thread since
1556 // createTrack() was called by the client process.
1557 if (!mStreamTypes[streamType].valid) {
1558 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1559 this, streamType);
1560 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1561 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001562 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001563 lStatus = NO_ERROR;
1564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565Exit:
1566 if(status) {
1567 *status = lStatus;
1568 }
1569 return track;
1570}
1571
Eric Laurenta553c252009-07-17 12:17:14 -07001572uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573{
Eric Laurent828b9772011-08-07 16:32:26 -07001574 Mutex::Autolock _l(mLock);
1575 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001576 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001577 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 return 0;
1579 }
1580}
1581
Eric Laurenta553c252009-07-17 12:17:14 -07001582status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583{
1584 mMasterVolume = value;
1585 return NO_ERROR;
1586}
1587
Eric Laurenta553c252009-07-17 12:17:14 -07001588status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589{
1590 mMasterMute = muted;
1591 return NO_ERROR;
1592}
1593
Eric Laurenta553c252009-07-17 12:17:14 -07001594float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595{
1596 return mMasterVolume;
1597}
1598
Eric Laurenta553c252009-07-17 12:17:14 -07001599bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600{
1601 return mMasterMute;
1602}
1603
Eric Laurenta553c252009-07-17 12:17:14 -07001604status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605{
1606 mStreamTypes[stream].volume = value;
1607 return NO_ERROR;
1608}
1609
Eric Laurenta553c252009-07-17 12:17:14 -07001610status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611{
1612 mStreamTypes[stream].mute = muted;
1613 return NO_ERROR;
1614}
1615
Eric Laurenta553c252009-07-17 12:17:14 -07001616float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617{
1618 return mStreamTypes[stream].volume;
1619}
1620
Eric Laurenta553c252009-07-17 12:17:14 -07001621bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622{
1623 return mStreamTypes[stream].mute;
1624}
1625
Eric Laurenta553c252009-07-17 12:17:14 -07001626// addTrack_l() must be called with ThreadBase::mLock held
1627status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628{
1629 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001630
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001631 // set retry count for buffer fill
1632 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001633 if (mActiveTracks.indexOf(track) < 0) {
1634 // the track is newly added, make sure it fills up all its
1635 // buffers before playing. This is to ensure the client will
1636 // effectively get the latency it requested.
1637 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001638 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001639 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001640 if (track->mainBuffer() != mMixBuffer) {
1641 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1642 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001643 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001644 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001645 }
1646 }
1647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001649 }
Eric Laurenta553c252009-07-17 12:17:14 -07001650
Steve Block71f2cf12011-10-20 11:56:00 +01001651 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001652 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653
1654 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001655}
1656
Eric Laurenta553c252009-07-17 12:17:14 -07001657// destroyTrack_l() must be called with ThreadBase::mLock held
1658void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001659{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001660 track->mState = TrackBase::TERMINATED;
1661 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001662 removeTrack_l(track);
1663 }
1664}
1665
1666void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1667{
1668 mTracks.remove(track);
1669 deleteTrackName_l(track->name());
1670 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1671 if (chain != 0) {
1672 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001673 }
1674}
1675
Eric Laurenta553c252009-07-17 12:17:14 -07001676String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001677{
Eric Laurent828b9772011-08-07 16:32:26 -07001678 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001679 char *s;
1680
Eric Laurent828b9772011-08-07 16:32:26 -07001681 Mutex::Autolock _l(mLock);
1682 if (initCheck() != NO_ERROR) {
1683 return out_s8;
1684 }
1685
Dima Zavin31f188892011-04-18 16:57:27 -07001686 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001687 out_s8 = String8(s);
1688 free(s);
1689 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001690}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001691
Eric Laurent828b9772011-08-07 16:32:26 -07001692// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001693void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001694 AudioSystem::OutputDescriptor desc;
1695 void *param2 = 0;
1696
Steve Block71f2cf12011-10-20 11:56:00 +01001697 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001698
1699 switch (event) {
1700 case AudioSystem::OUTPUT_OPENED:
1701 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001702 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001703 desc.samplingRate = mSampleRate;
1704 desc.format = mFormat;
1705 desc.frameCount = mFrameCount;
1706 desc.latency = latency();
1707 param2 = &desc;
1708 break;
1709
1710 case AudioSystem::STREAM_CONFIG_CHANGED:
1711 param2 = &param;
1712 case AudioSystem::OUTPUT_CLOSED:
1713 default:
1714 break;
1715 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001716 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001717}
1718
1719void AudioFlinger::PlaybackThread::readOutputParameters()
1720{
Dima Zavin31f188892011-04-18 16:57:27 -07001721 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001722 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1723 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001724 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1725 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1726 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001727
Eric Laurenta553c252009-07-17 12:17:14 -07001728 // FIXME - Current mixer implementation only supports stereo output: Always
1729 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001730 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001731 mMixBuffer = new int16_t[mFrameCount * 2];
1732 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001733
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001734 // force reconfiguration of effect chains and engines to take new buffer size and audio
1735 // parameters into account
1736 // Note that mLock is not held when readOutputParameters() is called from the constructor
1737 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1738 // matter.
1739 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1740 Vector< sp<EffectChain> > effectChains = mEffectChains;
1741 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001742 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001743 }
Eric Laurenta553c252009-07-17 12:17:14 -07001744}
1745
Eric Laurent0986e792010-01-19 17:37:09 -08001746status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1747{
1748 if (halFrames == 0 || dspFrames == 0) {
1749 return BAD_VALUE;
1750 }
Eric Laurent828b9772011-08-07 16:32:26 -07001751 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001752 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001753 return INVALID_OPERATION;
1754 }
Dima Zavin31f188892011-04-18 16:57:27 -07001755 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001756
Dima Zavin31f188892011-04-18 16:57:27 -07001757 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001758}
1759
Eric Laurent493941b2010-07-28 01:32:47 -07001760uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001761{
1762 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001763 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001764 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001765 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001766 }
1767
1768 for (size_t i = 0; i < mTracks.size(); ++i) {
1769 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001770 if (sessionId == track->sessionId() &&
1771 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001772 result |= TRACK_SESSION;
1773 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001774 }
1775 }
1776
Eric Laurent493941b2010-07-28 01:32:47 -07001777 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001778}
1779
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001780uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1781{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001782 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001783 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001784 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1785 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001786 }
1787 for (size_t i = 0; i < mTracks.size(); i++) {
1788 sp<Track> track = mTracks[i];
1789 if (sessionId == track->sessionId() &&
1790 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001791 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001792 }
1793 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001794 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001795}
1796
Eric Laurent53334cd2010-06-23 17:38:20 -07001797
Eric Laurent828b9772011-08-07 16:32:26 -07001798AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1799{
1800 Mutex::Autolock _l(mLock);
1801 return mOutput;
1802}
1803
1804AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1805{
1806 Mutex::Autolock _l(mLock);
1807 AudioStreamOut *output = mOutput;
1808 mOutput = NULL;
1809 return output;
1810}
1811
1812// this method must always be called either with ThreadBase mLock held or inside the thread loop
1813audio_stream_t* AudioFlinger::PlaybackThread::stream()
1814{
1815 if (mOutput == NULL) {
1816 return NULL;
1817 }
1818 return &mOutput->stream->common;
1819}
1820
Eric Laurent44331692011-12-05 09:47:19 -08001821uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1822{
1823 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1824 // decoding and transfer time. So sleeping for half of the latency would likely cause
1825 // underruns
1826 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1827 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1828 } else {
1829 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1830 }
1831}
1832
Eric Laurenta553c252009-07-17 12:17:14 -07001833// ----------------------------------------------------------------------------
1834
Dima Zavin31f188892011-04-18 16:57:27 -07001835AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001836 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001837 mAudioMixer(0)
1838{
Eric Laurent464d5b32011-06-17 21:29:58 -07001839 mType = ThreadBase::MIXER;
Eric Laurenta553c252009-07-17 12:17:14 -07001840 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1841
1842 // FIXME - Current mixer implementation only supports stereo output
1843 if (mChannelCount == 1) {
1844 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001846}
1847
Eric Laurenta553c252009-07-17 12:17:14 -07001848AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001849{
Eric Laurenta553c252009-07-17 12:17:14 -07001850 delete mAudioMixer;
1851}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852
Eric Laurenta553c252009-07-17 12:17:14 -07001853bool AudioFlinger::MixerThread::threadLoop()
1854{
Eric Laurenta553c252009-07-17 12:17:14 -07001855 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001856 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001857 nsecs_t standbyTime = systemTime();
1858 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001859 // FIXME: Relaxed timing because of a certain device that can't meet latency
1860 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001861 // increase threshold again due to low power audio mode. The way this warning threshold is
1862 // calculated and its usefulness should be reconsidered anyway.
1863 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001864 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001865 bool longStandbyExit = false;
1866 uint32_t activeSleepTime = activeSleepTimeUs();
1867 uint32_t idleSleepTime = idleSleepTimeUs();
1868 uint32_t sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001869 uint32_t sleepTimeShift = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001870 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001871#ifdef DEBUG_CPU_USAGE
1872 ThreadCpuUsage cpu;
1873 const CentralTendencyStatistics& stats = cpu.statistics();
1874#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875
Eric Laurent6dbdc402011-07-22 09:04:31 -07001876 acquireWakeLock();
1877
Eric Laurenta553c252009-07-17 12:17:14 -07001878 while (!exitPending())
1879 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001880#ifdef DEBUG_CPU_USAGE
1881 cpu.sampleAndEnable();
1882 unsigned n = stats.n();
1883 // cpu.elapsed() is expensive, so don't call it every loop
1884 if ((n & 127) == 1) {
1885 long long elapsed = cpu.elapsed();
1886 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1887 double perLoop = elapsed / (double) n;
1888 double perLoop100 = perLoop * 0.01;
1889 double mean = stats.mean();
1890 double stddev = stats.stddev();
1891 double minimum = stats.minimum();
1892 double maximum = stats.maximum();
1893 cpu.resetStatistics();
1894 LOGI("CPU usage over past %.1f secs (%u mixer loops at %.1f mean ms per loop):\n us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f",
1895 elapsed * .000000001, n, perLoop * .000001,
1896 mean * .001,
1897 stddev * .001,
1898 minimum * .001,
1899 maximum * .001,
1900 mean / perLoop100,
1901 stddev / perLoop100,
1902 minimum / perLoop100,
1903 maximum / perLoop100);
1904 }
1905 }
1906#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001907 processConfigEvents();
1908
Eric Laurent059b4be2009-11-09 23:32:22 -08001909 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001910 { // scope for mLock
1911
1912 Mutex::Autolock _l(mLock);
1913
1914 if (checkForNewParameters_l()) {
1915 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001916 // FIXME: Relaxed timing because of a certain device that can't meet latency
1917 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001918 // increase threshold again due to low power audio mode. The way this warning
1919 // threshold is calculated and its usefulness should be reconsidered anyway.
1920 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001921 activeSleepTime = activeSleepTimeUs();
1922 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001923 }
1924
1925 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1926
1927 // put audio hardware into standby after short delay
1928 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1929 mSuspended) {
1930 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01001931 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001932 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001933 mStandby = true;
1934 mBytesWritten = 0;
1935 }
1936
1937 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1938 // we're about to wait, flush the binder command buffer
1939 IPCThreadState::self()->flushCommands();
1940
1941 if (exitPending()) break;
1942
Eric Laurent6dbdc402011-07-22 09:04:31 -07001943 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001944 // wait until we have something to do...
Steve Block71f2cf12011-10-20 11:56:00 +01001945 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07001946 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01001947 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001948 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001949
1950 if (mMasterMute == false) {
1951 char value[PROPERTY_VALUE_MAX];
1952 property_get("ro.audio.silent", value, "0");
1953 if (atoi(value)) {
1954 LOGD("Silence is golden");
1955 setMasterMute(true);
1956 }
1957 }
1958
1959 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001960 sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001961 sleepTimeShift = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001962 continue;
1963 }
1964 }
1965
Eric Laurent059b4be2009-11-09 23:32:22 -08001966 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001967
1968 // prevent any changes in effect chain list and in each effect chain
1969 // during mixing and effect process as the audio buffers could be deleted
1970 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001971 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07001972 }
1973
Eric Laurent059b4be2009-11-09 23:32:22 -08001974 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001975 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001976 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001977 sleepTime = 0;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001978 // increase sleep time progressively when application underrun condition clears
1979 if (sleepTimeShift > 0) {
1980 sleepTimeShift--;
1981 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07001982 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001983 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001984 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001985 // If no tracks are ready, sleep once for the duration of an output
1986 // buffer size, then write 0s to the output
1987 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001988 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001989 sleepTime = activeSleepTime >> sleepTimeShift;
1990 if (sleepTime < kMinThreadSleepTimeUs) {
1991 sleepTime = kMinThreadSleepTimeUs;
1992 }
1993 // reduce sleep time in case of consecutive application underruns to avoid
1994 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1995 // duration we would end up writing less data than needed by the audio HAL if
1996 // the condition persists.
1997 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1998 sleepTimeShift++;
1999 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002000 } else {
2001 sleepTime = idleSleepTime;
2002 }
2003 } else if (mBytesWritten != 0 ||
2004 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002005 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002006 sleepTime = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01002007 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07002008 }
Eric Laurent65b65452010-06-01 23:49:17 -07002009 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07002010 }
2011
2012 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002013 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002014 }
2015 // sleepTime == 0 means we must write to audio hardware
2016 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002017 for (size_t i = 0; i < effectChains.size(); i ++) {
2018 effectChains[i]->process_l();
2019 }
2020 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002021 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002022 mLastWriteTime = systemTime();
2023 mInWrite = true;
2024 mBytesWritten += mixBufferSize;
2025
Dima Zavin31f188892011-04-18 16:57:27 -07002026 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002027 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002028 mNumWrites++;
2029 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002030 nsecs_t now = systemTime();
2031 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07002032 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002033 mNumDelayedWrites++;
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002034 if ((now - lastWarning) > kWarningThrottleNs) {
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002035 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2036 ns2ms(delta), mNumDelayedWrites, this);
2037 lastWarning = now;
2038 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002039 if (mStandby) {
2040 longStandbyExit = true;
2041 }
Eric Laurenta553c252009-07-17 12:17:14 -07002042 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002043 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002044 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002045 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002046 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002047 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002048 }
2049
2050 // finally let go of all our tracks, without the lock held
2051 // since we can't guarantee the destructors won't acquire that
2052 // same lock.
2053 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002054
2055 // Effect chains will be actually deleted here if they were removed from
2056 // mEffectChains list during mixing or effects processing
2057 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002058 }
2059
2060 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002061 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002062 }
Eric Laurenta553c252009-07-17 12:17:14 -07002063
Eric Laurent6dbdc402011-07-22 09:04:31 -07002064 releaseWakeLock();
2065
Steve Block71f2cf12011-10-20 11:56:00 +01002066 ALOGV("MixerThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002067 return false;
2068}
2069
2070// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08002071uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002072{
2073
Eric Laurent059b4be2009-11-09 23:32:22 -08002074 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002075 // find out which tracks need to be processed
2076 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002077 size_t mixedTracks = 0;
2078 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002079
2080 float masterVolume = mMasterVolume;
2081 bool masterMute = mMasterMute;
2082
Eric Laurent8cc93b92010-08-11 05:20:11 -07002083 if (masterMute) {
2084 masterVolume = 0;
2085 }
Eric Laurent65b65452010-06-01 23:49:17 -07002086 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002087 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002088 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002089 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002090 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002091 masterVolume = (float)((v + (1 << 23)) >> 24);
2092 chain.clear();
2093 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002094
Eric Laurenta553c252009-07-17 12:17:14 -07002095 for (size_t i=0 ; i<count ; i++) {
2096 sp<Track> t = activeTracks[i].promote();
2097 if (t == 0) continue;
2098
2099 Track* const track = t.get();
2100 audio_track_cblk_t* cblk = track->cblk();
2101
2102 // The first time a track is added we wait
2103 // for all its buffers to be filled before processing it
2104 mAudioMixer->setActiveTrack(track->name());
Eric Laurent8a04fe02011-11-08 18:10:16 -08002105 // make sure that we have enough frames to mix one full buffer.
2106 // enforce this condition only once to enable draining the buffer in case the client
2107 // app does not call stop() and relies on underrun to stop:
2108 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2109 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002110 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002111 if (!track->isStopped() && !track->isPausing() &&
2112 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002113 if (t->sampleRate() == (int)mSampleRate) {
2114 minFrames = mFrameCount;
2115 } else {
2116 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1;
2117 }
2118 }
2119 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002120 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002121 {
Steve Block71f2cf12011-10-20 11:56:00 +01002122 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002123
Eric Laurent65b65452010-06-01 23:49:17 -07002124 mixedTracks++;
2125
2126 // track->mainBuffer() != mMixBuffer means there is an effect chain
2127 // connected to the track
2128 chain.clear();
2129 if (track->mainBuffer() != mMixBuffer) {
2130 chain = getEffectChain_l(track->sessionId());
2131 // Delegate volume control to effect in track effect chain if needed
2132 if (chain != 0) {
2133 tracksWithEffect++;
2134 } else {
2135 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2136 track->name(), track->sessionId());
2137 }
2138 }
2139
2140
2141 int param = AudioMixer::VOLUME;
2142 if (track->mFillingUpStatus == Track::FS_FILLED) {
2143 // no ramp for the first volume setting
2144 track->mFillingUpStatus = Track::FS_ACTIVE;
2145 if (track->mState == TrackBase::RESUMING) {
2146 track->mState = TrackBase::ACTIVE;
2147 param = AudioMixer::RAMP_VOLUME;
2148 }
Eric Laurent4bb21c42011-02-28 16:52:51 -08002149 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002150 } else if (cblk->server != 0) {
2151 // If the track is stopped before the first frame was mixed,
2152 // do not apply ramp
2153 param = AudioMixer::RAMP_VOLUME;
2154 }
2155
Eric Laurenta553c252009-07-17 12:17:14 -07002156 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002157 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002158 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002159 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002160 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002161 if (track->isPausing()) {
2162 track->setPaused();
2163 }
2164 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002165
Glenn Kasten871c16c2010-03-05 12:18:01 -08002166 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002167 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002168 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002169 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2170 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07002171
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002172 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002173 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002174 // Delegate volume control to effect in track effect chain if needed
2175 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2176 // Do not ramp volume if volume is controlled by effect
2177 param = AudioMixer::VOLUME;
2178 track->mHasVolumeController = true;
2179 } else {
2180 // force no volume ramp when volume controller was just disabled or removed
2181 // from effect chain to avoid volume spike
2182 if (track->mHasVolumeController) {
2183 param = AudioMixer::VOLUME;
2184 }
2185 track->mHasVolumeController = false;
2186 }
2187
2188 // Convert volumes from 8.24 to 4.12 format
2189 int16_t left, right, aux;
2190 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2191 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2192 left = int16_t(v_clamped);
2193 v_clamped = (vr + (1 << 11)) >> 12;
2194 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2195 right = int16_t(v_clamped);
2196
2197 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2198 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002199
Eric Laurent65b65452010-06-01 23:49:17 -07002200 // XXX: these things DON'T need to be done each time
2201 mAudioMixer->setBufferProvider(track);
2202 mAudioMixer->enable(AudioMixer::MIXING);
2203
2204 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2205 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2206 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002207 mAudioMixer->setParameter(
2208 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002209 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002210 mAudioMixer->setParameter(
2211 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002212 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002213 mAudioMixer->setParameter(
2214 AudioMixer::RESAMPLE,
2215 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002216 (void *)(cblk->sampleRate));
2217 mAudioMixer->setParameter(
2218 AudioMixer::TRACK,
2219 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2220 mAudioMixer->setParameter(
2221 AudioMixer::TRACK,
2222 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002223
2224 // reset retry count
2225 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08002226 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002227 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002228 //ALOGV("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 -07002229 if (track->isStopped()) {
2230 track->reset();
2231 }
2232 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2233 // We have consumed all the buffers of this track.
2234 // Remove it from the list of active tracks.
2235 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002236 } else {
2237 // No buffers for this track. Give it a few chances to
2238 // fill a buffer, then remove it from active list.
2239 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002240 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07002241 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002242 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002243 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -08002244 } else if (mixerStatus != MIXER_TRACKS_READY) {
2245 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002246 }
Eric Laurenta553c252009-07-17 12:17:14 -07002247 }
Eric Laurent65b65452010-06-01 23:49:17 -07002248 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07002249 }
2250 }
2251
2252 // remove all the tracks that need to be...
2253 count = tracksToRemove->size();
2254 if (UNLIKELY(count)) {
2255 for (size_t i=0 ; i<count ; i++) {
2256 const sp<Track>& track = tracksToRemove->itemAt(i);
2257 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002258 if (track->mainBuffer() != mMixBuffer) {
2259 chain = getEffectChain_l(track->sessionId());
2260 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002261 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002262 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002263 }
2264 }
Eric Laurenta553c252009-07-17 12:17:14 -07002265 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002266 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002267 }
2268 }
2269 }
2270
Eric Laurent65b65452010-06-01 23:49:17 -07002271 // mix buffer must be cleared if all tracks are connected to an
2272 // effect chain as in this case the mixer will not write to
2273 // mix buffer and track effects will accumulate into it
2274 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2275 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2276 }
2277
Eric Laurent059b4be2009-11-09 23:32:22 -08002278 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002279}
2280
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002281void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002282{
Steve Block71f2cf12011-10-20 11:56:00 +01002283 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002284 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002285 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002286
Eric Laurenta553c252009-07-17 12:17:14 -07002287 size_t size = mTracks.size();
2288 for (size_t i = 0; i < size; i++) {
2289 sp<Track> t = mTracks[i];
2290 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002291 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002292 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002293 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002294 }
2295}
Eric Laurenta553c252009-07-17 12:17:14 -07002296
Eric Laurent05ce0942011-08-30 10:18:54 -07002297void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2298{
Steve Block71f2cf12011-10-20 11:56:00 +01002299 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002300 this, streamType, valid);
2301 Mutex::Autolock _l(mLock);
2302
2303 mStreamTypes[streamType].valid = valid;
2304}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305
Eric Laurenta553c252009-07-17 12:17:14 -07002306// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002307int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308{
2309 return mAudioMixer->getTrackName();
2310}
2311
Eric Laurenta553c252009-07-17 12:17:14 -07002312// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002313void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314{
Steve Block71f2cf12011-10-20 11:56:00 +01002315 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 mAudioMixer->deleteTrackName(name);
2317}
2318
Eric Laurenta553c252009-07-17 12:17:14 -07002319// checkForNewParameters_l() must be called with ThreadBase::mLock held
2320bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321{
Eric Laurenta553c252009-07-17 12:17:14 -07002322 bool reconfig = false;
2323
Eric Laurent8fce46a2009-08-04 09:45:33 -07002324 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002325 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002326 String8 keyValuePair = mNewParameters[0];
2327 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002328 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002329
Eric Laurenta553c252009-07-17 12:17:14 -07002330 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2331 reconfig = true;
2332 }
2333 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002334 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002335 status = BAD_VALUE;
2336 } else {
2337 reconfig = true;
2338 }
2339 }
2340 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002341 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002342 status = BAD_VALUE;
2343 } else {
2344 reconfig = true;
2345 }
2346 }
2347 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2348 // do not accept frame count changes if tracks are open as the track buffer
2349 // size depends on frame count and correct behavior would not be garantied
2350 // if frame count is changed after track creation
2351 if (!mTracks.isEmpty()) {
2352 status = INVALID_OPERATION;
2353 } else {
2354 reconfig = true;
2355 }
2356 }
Eric Laurent65b65452010-06-01 23:49:17 -07002357 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002358 // when changing the audio output device, call addBatteryData to notify
2359 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002360 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002361 uint32_t params = 0;
2362 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002363 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002364 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2365 }
2366
2367 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002368 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002369 // check if any other device (except speaker) is on
2370 if (value & deviceWithoutSpeaker ) {
2371 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2372 }
2373
2374 if (params != 0) {
2375 addBatteryData(params);
2376 }
2377 }
2378
Eric Laurent65b65452010-06-01 23:49:17 -07002379 // forward device change to effects that have requested to be
2380 // aware of attached audio device.
2381 mDevice = (uint32_t)value;
2382 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002383 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002384 }
2385 }
2386
Eric Laurenta553c252009-07-17 12:17:14 -07002387 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002388 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002389 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002390 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002391 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002392 mStandby = true;
2393 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002394 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002395 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002396 }
2397 if (status == NO_ERROR && reconfig) {
2398 delete mAudioMixer;
2399 readOutputParameters();
2400 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2401 for (size_t i = 0; i < mTracks.size() ; i++) {
2402 int name = getTrackName_l();
2403 if (name < 0) break;
2404 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002405 // limit track sample rate to 2 x new output sample rate
2406 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2407 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2408 }
Eric Laurenta553c252009-07-17 12:17:14 -07002409 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002410 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002411 }
2412 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002413
2414 mNewParameters.removeAt(0);
2415
Eric Laurenta553c252009-07-17 12:17:14 -07002416 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002417 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002418 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2419 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002420 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002421 }
2422 return reconfig;
2423}
2424
2425status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2426{
2427 const size_t SIZE = 256;
2428 char buffer[SIZE];
2429 String8 result;
2430
2431 PlaybackThread::dumpInternals(fd, args);
2432
2433 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2434 result.append(buffer);
2435 write(fd, result.string(), result.size());
2436 return NO_ERROR;
2437}
2438
Eric Laurent059b4be2009-11-09 23:32:22 -08002439uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2440{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002441 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002442}
2443
Eric Laurent8448a792010-08-18 18:13:17 -07002444uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2445{
2446 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2447}
2448
Eric Laurenta553c252009-07-17 12:17:14 -07002449// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002450AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002451 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002452{
Eric Laurent464d5b32011-06-17 21:29:58 -07002453 mType = ThreadBase::DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -07002454}
2455
2456AudioFlinger::DirectOutputThread::~DirectOutputThread()
2457{
2458}
2459
2460
Eric Laurent65b65452010-06-01 23:49:17 -07002461static inline int16_t clamp16(int32_t sample)
2462{
2463 if ((sample>>15) ^ (sample>>31))
2464 sample = 0x7FFF ^ (sample>>31);
2465 return sample;
2466}
2467
2468static inline
2469int32_t mul(int16_t in, int16_t v)
2470{
2471#if defined(__arm__) && !defined(__thumb__)
2472 int32_t out;
2473 asm( "smulbb %[out], %[in], %[v] \n"
2474 : [out]"=r"(out)
2475 : [in]"%r"(in), [v]"r"(v)
2476 : );
2477 return out;
2478#else
2479 return in * int32_t(v);
2480#endif
2481}
2482
2483void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2484{
2485 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002486 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002487 return;
2488 }
2489
2490 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002491 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002492 size_t count = mFrameCount * mChannelCount;
2493 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2494 int16_t *dst = mMixBuffer + count-1;
2495 while(count--) {
2496 *dst-- = (int16_t)(*src--^0x80) << 8;
2497 }
2498 }
2499
2500 size_t frameCount = mFrameCount;
2501 int16_t *out = mMixBuffer;
2502 if (ramp) {
2503 if (mChannelCount == 1) {
2504 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2505 int32_t vlInc = d / (int32_t)frameCount;
2506 int32_t vl = ((int32_t)mLeftVolShort << 16);
2507 do {
2508 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2509 out++;
2510 vl += vlInc;
2511 } while (--frameCount);
2512
2513 } else {
2514 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2515 int32_t vlInc = d / (int32_t)frameCount;
2516 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2517 int32_t vrInc = d / (int32_t)frameCount;
2518 int32_t vl = ((int32_t)mLeftVolShort << 16);
2519 int32_t vr = ((int32_t)mRightVolShort << 16);
2520 do {
2521 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2522 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2523 out += 2;
2524 vl += vlInc;
2525 vr += vrInc;
2526 } while (--frameCount);
2527 }
2528 } else {
2529 if (mChannelCount == 1) {
2530 do {
2531 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2532 out++;
2533 } while (--frameCount);
2534 } else {
2535 do {
2536 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2537 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2538 out += 2;
2539 } while (--frameCount);
2540 }
2541 }
2542
2543 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002544 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002545 size_t count = mFrameCount * mChannelCount;
2546 int16_t *src = mMixBuffer;
2547 uint8_t *dst = (uint8_t *)mMixBuffer;
2548 while(count--) {
2549 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2550 }
2551 }
2552
2553 mLeftVolShort = leftVol;
2554 mRightVolShort = rightVol;
2555}
2556
Eric Laurenta553c252009-07-17 12:17:14 -07002557bool AudioFlinger::DirectOutputThread::threadLoop()
2558{
Eric Laurent059b4be2009-11-09 23:32:22 -08002559 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002560 sp<Track> trackToRemove;
2561 sp<Track> activeTrack;
2562 nsecs_t standbyTime = systemTime();
2563 int8_t *curBuf;
2564 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002565 uint32_t activeSleepTime = activeSleepTimeUs();
2566 uint32_t idleSleepTime = idleSleepTimeUs();
2567 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002568 // use shorter standby delay as on normal output to release
2569 // hardware resources as soon as possible
2570 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002571
Eric Laurent6dbdc402011-07-22 09:04:31 -07002572 acquireWakeLock();
2573
Eric Laurenta553c252009-07-17 12:17:14 -07002574 while (!exitPending())
2575 {
Eric Laurent65b65452010-06-01 23:49:17 -07002576 bool rampVolume;
2577 uint16_t leftVol;
2578 uint16_t rightVol;
2579 Vector< sp<EffectChain> > effectChains;
2580
Eric Laurenta553c252009-07-17 12:17:14 -07002581 processConfigEvents();
2582
Eric Laurent059b4be2009-11-09 23:32:22 -08002583 mixerStatus = MIXER_IDLE;
2584
Eric Laurenta553c252009-07-17 12:17:14 -07002585 { // scope for the mLock
2586
2587 Mutex::Autolock _l(mLock);
2588
2589 if (checkForNewParameters_l()) {
2590 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002591 activeSleepTime = activeSleepTimeUs();
2592 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002593 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002594 }
2595
2596 // put audio hardware into standby after short delay
2597 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2598 mSuspended) {
2599 // wait until we have something to do...
2600 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01002601 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002602 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002603 mStandby = true;
2604 mBytesWritten = 0;
2605 }
2606
2607 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2608 // we're about to wait, flush the binder command buffer
2609 IPCThreadState::self()->flushCommands();
2610
2611 if (exitPending()) break;
2612
Eric Laurent6dbdc402011-07-22 09:04:31 -07002613 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002614 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002615 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002616 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002617 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002618
2619 if (mMasterMute == false) {
2620 char value[PROPERTY_VALUE_MAX];
2621 property_get("ro.audio.silent", value, "0");
2622 if (atoi(value)) {
2623 LOGD("Silence is golden");
2624 setMasterMute(true);
2625 }
2626 }
2627
Eric Laurentef9500f2010-03-11 14:47:00 -08002628 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002629 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002630 continue;
2631 }
2632 }
2633
Eric Laurent65b65452010-06-01 23:49:17 -07002634 effectChains = mEffectChains;
2635
Eric Laurenta553c252009-07-17 12:17:14 -07002636 // find out which tracks need to be processed
2637 if (mActiveTracks.size() != 0) {
2638 sp<Track> t = mActiveTracks[0].promote();
2639 if (t == 0) continue;
2640
2641 Track* const track = t.get();
2642 audio_track_cblk_t* cblk = track->cblk();
2643
2644 // The first time a track is added we wait
2645 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002646 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002647 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002648 {
Steve Block71f2cf12011-10-20 11:56:00 +01002649 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002650
Eric Laurent65b65452010-06-01 23:49:17 -07002651 if (track->mFillingUpStatus == Track::FS_FILLED) {
2652 track->mFillingUpStatus = Track::FS_ACTIVE;
2653 mLeftVolFloat = mRightVolFloat = 0;
2654 mLeftVolShort = mRightVolShort = 0;
2655 if (track->mState == TrackBase::RESUMING) {
2656 track->mState = TrackBase::ACTIVE;
2657 rampVolume = true;
2658 }
2659 } else if (cblk->server != 0) {
2660 // If the track is stopped before the first frame was mixed,
2661 // do not apply ramp
2662 rampVolume = true;
2663 }
Eric Laurenta553c252009-07-17 12:17:14 -07002664 // compute volume for this track
2665 float left, right;
2666 if (track->isMuted() || mMasterMute || track->isPausing() ||
2667 mStreamTypes[track->type()].mute) {
2668 left = right = 0;
2669 if (track->isPausing()) {
2670 track->setPaused();
2671 }
2672 } else {
2673 float typeVolume = mStreamTypes[track->type()].volume;
2674 float v = mMasterVolume * typeVolume;
2675 float v_clamped = v * cblk->volume[0];
2676 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2677 left = v_clamped/MAX_GAIN;
2678 v_clamped = v * cblk->volume[1];
2679 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2680 right = v_clamped/MAX_GAIN;
2681 }
2682
Eric Laurent65b65452010-06-01 23:49:17 -07002683 if (left != mLeftVolFloat || right != mRightVolFloat) {
2684 mLeftVolFloat = left;
2685 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002686
Eric Laurent65b65452010-06-01 23:49:17 -07002687 // If audio HAL implements volume control,
2688 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002689 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002690 left = 1.0f;
2691 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002692 }
Eric Laurent65b65452010-06-01 23:49:17 -07002693
2694 // Convert volumes from float to 8.24
2695 uint32_t vl = (uint32_t)(left * (1 << 24));
2696 uint32_t vr = (uint32_t)(right * (1 << 24));
2697
2698 // Delegate volume control to effect in track effect chain if needed
2699 // only one effect chain can be present on DirectOutputThread, so if
2700 // there is one, the track is connected to it
2701 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002702 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002703 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002704 rampVolume = false;
2705 }
2706 }
2707
2708 // Convert volumes from 8.24 to 4.12 format
2709 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2710 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2711 leftVol = (uint16_t)v_clamped;
2712 v_clamped = (vr + (1 << 11)) >> 12;
2713 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2714 rightVol = (uint16_t)v_clamped;
2715 } else {
2716 leftVol = mLeftVolShort;
2717 rightVol = mRightVolShort;
2718 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002719 }
2720
2721 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002722 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002723 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002724 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002725 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002726 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002727 if (track->isStopped()) {
2728 track->reset();
2729 }
2730 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2731 // We have consumed all the buffers of this track.
2732 // Remove it from the list of active tracks.
2733 trackToRemove = track;
2734 } else {
2735 // No buffers for this track. Give it a few chances to
2736 // fill a buffer, then remove it from active list.
2737 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002738 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurenta553c252009-07-17 12:17:14 -07002739 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002740 } else {
2741 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002742 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002743 }
Eric Laurenta553c252009-07-17 12:17:14 -07002744 }
2745 }
2746
2747 // remove all the tracks that need to be...
2748 if (UNLIKELY(trackToRemove != 0)) {
2749 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002750 if (!effectChains.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01002751 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002752 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002753 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002754 }
Eric Laurenta553c252009-07-17 12:17:14 -07002755 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002756 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002757 }
2758 }
Eric Laurent65b65452010-06-01 23:49:17 -07002759
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002760 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002761 }
2762
Eric Laurent059b4be2009-11-09 23:32:22 -08002763 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002764 AudioBufferProvider::Buffer buffer;
2765 size_t frameCount = mFrameCount;
2766 curBuf = (int8_t *)mMixBuffer;
2767 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002768 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002769 buffer.frameCount = frameCount;
2770 activeTrack->getNextBuffer(&buffer);
2771 if (UNLIKELY(buffer.raw == 0)) {
2772 memset(curBuf, 0, frameCount * mFrameSize);
2773 break;
2774 }
2775 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2776 frameCount -= buffer.frameCount;
2777 curBuf += buffer.frameCount * mFrameSize;
2778 activeTrack->releaseBuffer(&buffer);
2779 }
2780 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002781 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002782 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002783 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002784 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2785 sleepTime = activeSleepTime;
2786 } else {
2787 sleepTime = idleSleepTime;
2788 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002789 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002790 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002791 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002792 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002793 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002794
Eric Laurentf69a3f82009-09-22 00:35:48 -07002795 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002796 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002797 }
2798 // sleepTime == 0 means we must write to audio hardware
2799 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002800 if (mixerStatus == MIXER_TRACKS_READY) {
2801 applyVolume(leftVol, rightVol, rampVolume);
2802 }
2803 for (size_t i = 0; i < effectChains.size(); i ++) {
2804 effectChains[i]->process_l();
2805 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002806 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002807
Eric Laurentf69a3f82009-09-22 00:35:48 -07002808 mLastWriteTime = systemTime();
2809 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002810 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002811 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002812 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002813 mNumWrites++;
2814 mInWrite = false;
2815 mStandby = false;
2816 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002817 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002818 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002819 }
2820
2821 // finally let go of removed track, without the lock held
2822 // since we can't guarantee the destructors won't acquire that
2823 // same lock.
2824 trackToRemove.clear();
2825 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002826
2827 // Effect chains will be actually deleted here if they were removed from
2828 // mEffectChains list during mixing or effects processing
2829 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002830 }
2831
2832 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002833 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002834 }
Eric Laurenta553c252009-07-17 12:17:14 -07002835
Eric Laurent6dbdc402011-07-22 09:04:31 -07002836 releaseWakeLock();
2837
Steve Block71f2cf12011-10-20 11:56:00 +01002838 ALOGV("DirectOutputThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002839 return false;
2840}
2841
2842// getTrackName_l() must be called with ThreadBase::mLock held
2843int AudioFlinger::DirectOutputThread::getTrackName_l()
2844{
2845 return 0;
2846}
2847
2848// deleteTrackName_l() must be called with ThreadBase::mLock held
2849void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2850{
2851}
2852
2853// checkForNewParameters_l() must be called with ThreadBase::mLock held
2854bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2855{
2856 bool reconfig = false;
2857
Eric Laurent8fce46a2009-08-04 09:45:33 -07002858 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002859 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002860 String8 keyValuePair = mNewParameters[0];
2861 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002862 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002863
Eric Laurenta553c252009-07-17 12:17:14 -07002864 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2865 // do not accept frame count changes if tracks are open as the track buffer
2866 // size depends on frame count and correct behavior would not be garantied
2867 // if frame count is changed after track creation
2868 if (!mTracks.isEmpty()) {
2869 status = INVALID_OPERATION;
2870 } else {
2871 reconfig = true;
2872 }
2873 }
2874 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002875 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002876 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002877 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002878 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002879 mStandby = true;
2880 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002881 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002882 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002883 }
2884 if (status == NO_ERROR && reconfig) {
2885 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002886 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002887 }
2888 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002889
2890 mNewParameters.removeAt(0);
2891
Eric Laurenta553c252009-07-17 12:17:14 -07002892 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002893 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002894 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2895 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002896 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002897 }
2898 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002899}
2900
Eric Laurent059b4be2009-11-09 23:32:22 -08002901uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002902{
2903 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002904 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08002905 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08002906 } else {
2907 time = 10000;
2908 }
2909 return time;
2910}
2911
2912uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2913{
2914 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002915 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002916 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002917 } else {
2918 time = 10000;
2919 }
2920 return time;
2921}
2922
Eric Laurent8448a792010-08-18 18:13:17 -07002923uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2924{
2925 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002926 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002927 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2928 } else {
2929 time = 10000;
2930 }
2931 return time;
2932}
2933
2934
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002935// ----------------------------------------------------------------------------
2936
Eric Laurent49f02be2009-11-19 09:00:56 -08002937AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002938 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002939{
Eric Laurent464d5b32011-06-17 21:29:58 -07002940 mType = ThreadBase::DUPLICATING;
Eric Laurenta553c252009-07-17 12:17:14 -07002941 addOutputTrack(mainThread);
2942}
2943
2944AudioFlinger::DuplicatingThread::~DuplicatingThread()
2945{
Eric Laurent0a080292009-12-07 10:53:10 -08002946 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2947 mOutputTracks[i]->destroy();
2948 }
Eric Laurenta553c252009-07-17 12:17:14 -07002949 mOutputTracks.clear();
2950}
2951
2952bool AudioFlinger::DuplicatingThread::threadLoop()
2953{
Eric Laurenta553c252009-07-17 12:17:14 -07002954 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002955 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002956 nsecs_t standbyTime = systemTime();
2957 size_t mixBufferSize = mFrameCount*mFrameSize;
2958 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002959 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002960 uint32_t activeSleepTime = activeSleepTimeUs();
2961 uint32_t idleSleepTime = idleSleepTimeUs();
2962 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002963 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002964
Eric Laurent6dbdc402011-07-22 09:04:31 -07002965 acquireWakeLock();
2966
Eric Laurenta553c252009-07-17 12:17:14 -07002967 while (!exitPending())
2968 {
2969 processConfigEvents();
2970
Eric Laurent059b4be2009-11-09 23:32:22 -08002971 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002972 { // scope for the mLock
2973
2974 Mutex::Autolock _l(mLock);
2975
2976 if (checkForNewParameters_l()) {
2977 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002978 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002979 activeSleepTime = activeSleepTimeUs();
2980 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002981 }
2982
2983 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2984
2985 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2986 outputTracks.add(mOutputTracks[i]);
2987 }
2988
2989 // put audio hardware into standby after short delay
2990 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2991 mSuspended) {
2992 if (!mStandby) {
2993 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002994 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002995 }
2996 mStandby = true;
2997 mBytesWritten = 0;
2998 }
2999
3000 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3001 // we're about to wait, flush the binder command buffer
3002 IPCThreadState::self()->flushCommands();
3003 outputTracks.clear();
3004
3005 if (exitPending()) break;
3006
Eric Laurent6dbdc402011-07-22 09:04:31 -07003007 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01003008 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07003009 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01003010 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07003011 acquireWakeLock_l();
3012
Eric Laurenta553c252009-07-17 12:17:14 -07003013 if (mMasterMute == false) {
3014 char value[PROPERTY_VALUE_MAX];
3015 property_get("ro.audio.silent", value, "0");
3016 if (atoi(value)) {
3017 LOGD("Silence is golden");
3018 setMasterMute(true);
3019 }
3020 }
3021
3022 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08003023 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07003024 continue;
3025 }
3026 }
3027
Eric Laurent059b4be2009-11-09 23:32:22 -08003028 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07003029
3030 // prevent any changes in effect chain list and in each effect chain
3031 // during mixing and effect process as the audio buffers could be deleted
3032 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003033 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003034 }
Eric Laurenta553c252009-07-17 12:17:14 -07003035
Eric Laurent059b4be2009-11-09 23:32:22 -08003036 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003037 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003038 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003039 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003040 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003041 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003042 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003043 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003044 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003045 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003046 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003047 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3048 sleepTime = activeSleepTime;
3049 } else {
3050 sleepTime = idleSleepTime;
3051 }
Eric Laurent62443f52009-10-05 20:29:18 -07003052 } else if (mBytesWritten != 0) {
3053 // flush remaining overflow buffers in output tracks
3054 for (size_t i = 0; i < outputTracks.size(); i++) {
3055 if (outputTracks[i]->isActive()) {
3056 sleepTime = 0;
3057 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003058 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003059 break;
3060 }
3061 }
Eric Laurenta553c252009-07-17 12:17:14 -07003062 }
3063 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003064
3065 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003066 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003067 }
3068 // sleepTime == 0 means we must write to audio hardware
3069 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003070 for (size_t i = 0; i < effectChains.size(); i ++) {
3071 effectChains[i]->process_l();
3072 }
3073 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003074 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003075
Eric Laurent62443f52009-10-05 20:29:18 -07003076 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003077 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003078 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003079 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003080 mStandby = false;
3081 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003082 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003083 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003084 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003085 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003086 }
3087
3088 // finally let go of all our tracks, without the lock held
3089 // since we can't guarantee the destructors won't acquire that
3090 // same lock.
3091 tracksToRemove.clear();
3092 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003093
3094 // Effect chains will be actually deleted here if they were removed from
3095 // mEffectChains list during mixing or effects processing
3096 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003097 }
3098
Eric Laurent6dbdc402011-07-22 09:04:31 -07003099 releaseWakeLock();
3100
Eric Laurenta553c252009-07-17 12:17:14 -07003101 return false;
3102}
3103
3104void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3105{
3106 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3107 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003108 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003109 mSampleRate,
3110 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003111 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003112 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003113 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003114 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003115 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003116 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003117 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003118 }
Eric Laurenta553c252009-07-17 12:17:14 -07003119}
3120
3121void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3122{
3123 Mutex::Autolock _l(mLock);
3124 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3125 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003126 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003127 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003128 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003129 return;
3130 }
3131 }
Steve Block71f2cf12011-10-20 11:56:00 +01003132 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003133}
3134
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003135void AudioFlinger::DuplicatingThread::updateWaitTime()
3136{
3137 mWaitTimeMs = UINT_MAX;
3138 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3139 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3140 if (strong != NULL) {
3141 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3142 if (waitTimeMs < mWaitTimeMs) {
3143 mWaitTimeMs = waitTimeMs;
3144 }
3145 }
3146 }
3147}
3148
3149
3150bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3151{
3152 for (size_t i = 0; i < outputTracks.size(); i++) {
3153 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3154 if (thread == 0) {
3155 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3156 return false;
3157 }
3158 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3159 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003160 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003161 return false;
3162 }
3163 }
3164 return true;
3165}
3166
3167uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3168{
3169 return (mWaitTimeMs * 1000) / 2;
3170}
3171
Eric Laurenta553c252009-07-17 12:17:14 -07003172// ----------------------------------------------------------------------------
3173
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003174// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003175AudioFlinger::ThreadBase::TrackBase::TrackBase(
3176 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003177 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003178 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003179 uint32_t format,
3180 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003181 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003183 const sp<IMemory>& sharedBuffer,
3184 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003185 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003186 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003187 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07003188 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003189 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003190 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003191 mClientTid(-1),
3192 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003193 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3194 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003195{
Steve Block71f2cf12011-10-20 11:56:00 +01003196 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003197
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003198 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003199 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003200 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003201 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3202 if (sharedBuffer == 0) {
3203 size += bufferSize;
3204 }
3205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 if (client != NULL) {
3207 mCblkMemory = client->heap()->allocate(size);
3208 if (mCblkMemory != 0) {
3209 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3210 if (mCblk) { // construct the shared structure in-place.
3211 new(mCblk) audio_track_cblk_t();
3212 // clear all buffers
3213 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003214 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003215 mChannelCount = channelCount;
3216 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 if (sharedBuffer == 0) {
3218 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3219 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3220 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003221 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003222 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 } else {
3224 mBuffer = sharedBuffer->pointer();
3225 }
3226 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 } else {
3229 LOGE("not enough memory for AudioTrack size=%u", size);
3230 client->heap()->dump("AudioTrack");
3231 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 } else {
3234 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3235 if (mCblk) { // construct the shared structure in-place.
3236 new(mCblk) audio_track_cblk_t();
3237 // clear all buffers
3238 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003239 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003240 mChannelCount = channelCount;
3241 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3243 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3244 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003245 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003246 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3248 }
3249 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003250}
3251
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003252AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003253{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07003255 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3256 if (mClient == NULL) {
3257 delete mCblk;
3258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003260 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07003261 if (mClient != NULL) {
3262 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3263 mClient.clear();
3264 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003265}
3266
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003267void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003268{
3269 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003270 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003271 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003272 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003273}
3274
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003275bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003276 bool result;
3277 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003278
3279 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003280 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003281 ALOGV("stepServer failed acquiring cblk mutex");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003282 mFlags |= STEPSERVER_FAILED;
3283 }
3284 return result;
3285}
3286
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003287void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003288 audio_track_cblk_t* cblk = this->cblk();
3289
3290 cblk->user = 0;
3291 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003292 cblk->userBase = 0;
3293 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block71f2cf12011-10-20 11:56:00 +01003295 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003296}
3297
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003298sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003299{
3300 return mCblkMemory;
3301}
3302
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003303int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003304 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003305}
3306
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003307int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003308 return (const int)mChannelCount;
3309}
3310
3311uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3312 return mChannelMask;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003313}
3314
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003315void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003316 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07003317 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3318 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003319
3320 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003321 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3322 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07003323 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003324 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003325 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003326 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003327 return 0;
3328 }
3329
3330 return bufferStart;
3331}
3332
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003333// ----------------------------------------------------------------------------
3334
Eric Laurenta553c252009-07-17 12:17:14 -07003335// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3336AudioFlinger::PlaybackThread::Track::Track(
3337 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003338 const sp<Client>& client,
3339 int streamType,
3340 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003341 uint32_t format,
3342 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003343 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003344 const sp<IMemory>& sharedBuffer,
3345 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003346 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003347 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3348 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003349{
Eric Laurent8a77a992009-09-09 05:16:08 -07003350 if (mCblk != NULL) {
3351 sp<ThreadBase> baseThread = thread.promote();
3352 if (baseThread != 0) {
3353 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3354 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003355 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003356 }
Steve Block71f2cf12011-10-20 11:56:00 +01003357 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003358 if (mName < 0) {
3359 LOGE("no more track names available");
3360 }
3361 mVolume[0] = 1.0f;
3362 mVolume[1] = 1.0f;
3363 mStreamType = streamType;
3364 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3365 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003366 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003367 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003368}
3369
Eric Laurenta553c252009-07-17 12:17:14 -07003370AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003371{
Steve Block71f2cf12011-10-20 11:56:00 +01003372 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003373 sp<ThreadBase> thread = mThread.promote();
3374 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003375 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003376 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003377 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003378}
3379
Eric Laurenta553c252009-07-17 12:17:14 -07003380void AudioFlinger::PlaybackThread::Track::destroy()
3381{
3382 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3383 // by removing it from mTracks vector, so there is a risk that this Tracks's
3384 // desctructor is called. As the destructor needs to lock mLock,
3385 // we must acquire a strong reference on this Track before locking mLock
3386 // here so that the destructor is called only when exiting this function.
3387 // On the other hand, as long as Track::destroy() is only called by
3388 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3389 // this Track with its member mTrack.
3390 sp<Track> keep(this);
3391 { // scope for mLock
3392 sp<ThreadBase> thread = mThread.promote();
3393 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003394 if (!isOutputTrack()) {
3395 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003396 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003397 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003398 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003399
3400 // to track the speaker usage
3401 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003402 }
3403 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003404 }
Eric Laurenta553c252009-07-17 12:17:14 -07003405 Mutex::Autolock _l(thread->mLock);
3406 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3407 playbackThread->destroyTrack_l(this);
3408 }
3409 }
3410}
3411
3412void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003413{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003414 snprintf(buffer, size, " %05d %05d %03u %03u 0x%08x %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 -07003415 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003417 mStreamType,
3418 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003419 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003420 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003421 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003422 mState,
3423 mMute,
3424 mFillingUpStatus,
3425 mCblk->sampleRate,
3426 mCblk->volume[0],
3427 mCblk->volume[1],
3428 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003429 mCblk->user,
3430 (int)mMainBuffer,
3431 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003432}
3433
Eric Laurenta553c252009-07-17 12:17:14 -07003434status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003435{
3436 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003437 uint32_t framesReady;
3438 uint32_t framesReq = buffer->frameCount;
3439
3440 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003441 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3442 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003443 ALOGV("stepServer recovered");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003444 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3445 }
3446
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003447 framesReady = cblk->framesReady();
3448
3449 if (LIKELY(framesReady)) {
3450 uint32_t s = cblk->server;
3451 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3452
3453 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3454 if (framesReq > framesReady) {
3455 framesReq = framesReady;
3456 }
3457 if (s + framesReq > bufferEnd) {
3458 framesReq = bufferEnd - s;
3459 }
3460
3461 buffer->raw = getBuffer(s, framesReq);
3462 if (buffer->raw == 0) goto getNextBuffer_exit;
3463
3464 buffer->frameCount = framesReq;
3465 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003466 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003467
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003468getNextBuffer_exit:
3469 buffer->raw = 0;
3470 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003471 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003472 return NOT_ENOUGH_DATA;
3473}
3474
Eric Laurenta553c252009-07-17 12:17:14 -07003475bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003476 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003477
3478 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003479 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003480 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003481 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003482 return true;
3483 }
3484 return false;
3485}
3486
Eric Laurenta553c252009-07-17 12:17:14 -07003487status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003488{
Eric Laurent49f02be2009-11-19 09:00:56 -08003489 status_t status = NO_ERROR;
Steve Block71f2cf12011-10-20 11:56:00 +01003490 ALOGV("start(%d), calling thread %d session %d",
Eric Laurent0d7e0482010-07-19 06:24:46 -07003491 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003492 sp<ThreadBase> thread = mThread.promote();
3493 if (thread != 0) {
3494 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003495 int state = mState;
3496 // here the track could be either new, or restarted
3497 // in both cases "unstop" the track
3498 if (mState == PAUSED) {
3499 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003500 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003501 } else {
3502 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003503 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003504 }
3505
3506 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3507 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003508 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003509 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003510 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003511 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003512
3513 // to track the speaker usage
3514 if (status == NO_ERROR) {
3515 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3516 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003517 }
3518 if (status == NO_ERROR) {
3519 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3520 playbackThread->addTrack_l(this);
3521 } else {
3522 mState = state;
3523 }
3524 } else {
3525 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003526 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003527 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003528}
3529
Eric Laurenta553c252009-07-17 12:17:14 -07003530void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003531{
Steve Block71f2cf12011-10-20 11:56:00 +01003532 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003533 sp<ThreadBase> thread = mThread.promote();
3534 if (thread != 0) {
3535 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003536 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003537 if (mState > STOPPED) {
3538 mState = STOPPED;
3539 // If the track is not active (PAUSED and buffers full), flush buffers
3540 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3541 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3542 reset();
3543 }
Steve Block71f2cf12011-10-20 11:56:00 +01003544 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003545 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003546 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3547 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003548 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003549 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003550 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003551 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003552
3553 // to track the speaker usage
3554 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003555 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003556 }
3557}
3558
Eric Laurenta553c252009-07-17 12:17:14 -07003559void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003560{
Steve Block71f2cf12011-10-20 11:56:00 +01003561 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003562 sp<ThreadBase> thread = mThread.promote();
3563 if (thread != 0) {
3564 Mutex::Autolock _l(thread->mLock);
3565 if (mState == ACTIVE || mState == RESUMING) {
3566 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003567 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003568 if (!isOutputTrack()) {
3569 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003570 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003571 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003572 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003573 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003574
3575 // to track the speaker usage
3576 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003577 }
Eric Laurenta553c252009-07-17 12:17:14 -07003578 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003579 }
3580}
3581
Eric Laurenta553c252009-07-17 12:17:14 -07003582void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003583{
Steve Block71f2cf12011-10-20 11:56:00 +01003584 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003585 sp<ThreadBase> thread = mThread.promote();
3586 if (thread != 0) {
3587 Mutex::Autolock _l(thread->mLock);
3588 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3589 return;
3590 }
3591 // No point remaining in PAUSED state after a flush => go to
3592 // STOPPED state
3593 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003594
Eric Laurentae29b762011-03-28 18:37:07 -07003595 // do not reset the track if it is still in the process of being stopped or paused.
3596 // this will be done by prepareTracks_l() when the track is stopped.
3597 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3598 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3599 reset();
3600 }
Eric Laurenta553c252009-07-17 12:17:14 -07003601 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003602}
3603
Eric Laurenta553c252009-07-17 12:17:14 -07003604void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003605{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003606 // Do not reset twice to avoid discarding data written just after a flush and before
3607 // the audioflinger thread detects the track is stopped.
3608 if (!mResetDone) {
3609 TrackBase::reset();
3610 // Force underrun condition to avoid false underrun callback until first data is
3611 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003612 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3613 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003614 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003615 mResetDone = true;
3616 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003617}
3618
Eric Laurenta553c252009-07-17 12:17:14 -07003619void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003620{
3621 mMute = muted;
3622}
3623
Eric Laurenta553c252009-07-17 12:17:14 -07003624void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003625{
3626 mVolume[0] = left;
3627 mVolume[1] = right;
3628}
3629
Eric Laurent65b65452010-06-01 23:49:17 -07003630status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3631{
3632 status_t status = DEAD_OBJECT;
3633 sp<ThreadBase> thread = mThread.promote();
3634 if (thread != 0) {
3635 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3636 status = playbackThread->attachAuxEffect(this, EffectId);
3637 }
3638 return status;
3639}
3640
3641void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3642{
3643 mAuxEffectId = EffectId;
3644 mAuxBuffer = buffer;
3645}
3646
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003647// ----------------------------------------------------------------------------
3648
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003649// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003650AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3651 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003654 uint32_t format,
3655 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003657 uint32_t flags,
3658 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003659 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003660 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003661 mOverflow(false)
3662{
Eric Laurent8a77a992009-09-09 05:16:08 -07003663 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003664 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003665 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003666 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003667 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003668 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003669 } else {
3670 mCblk->frameSize = sizeof(int8_t);
3671 }
3672 }
Eric Laurenta553c252009-07-17 12:17:14 -07003673}
3674
3675AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676{
Eric Laurent49f02be2009-11-19 09:00:56 -08003677 sp<ThreadBase> thread = mThread.promote();
3678 if (thread != 0) {
3679 AudioSystem::releaseInput(thread->id());
3680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681}
3682
Eric Laurenta553c252009-07-17 12:17:14 -07003683status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684{
3685 audio_track_cblk_t* cblk = this->cblk();
3686 uint32_t framesAvail;
3687 uint32_t framesReq = buffer->frameCount;
3688
3689 // Check if last stepServer failed, try to step now
3690 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3691 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003692 ALOGV("stepServer recovered");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3694 }
3695
3696 framesAvail = cblk->framesAvailable_l();
3697
3698 if (LIKELY(framesAvail)) {
3699 uint32_t s = cblk->server;
3700 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3701
3702 if (framesReq > framesAvail) {
3703 framesReq = framesAvail;
3704 }
3705 if (s + framesReq > bufferEnd) {
3706 framesReq = bufferEnd - s;
3707 }
3708
3709 buffer->raw = getBuffer(s, framesReq);
3710 if (buffer->raw == 0) goto getNextBuffer_exit;
3711
3712 buffer->frameCount = framesReq;
3713 return NO_ERROR;
3714 }
3715
3716getNextBuffer_exit:
3717 buffer->raw = 0;
3718 buffer->frameCount = 0;
3719 return NOT_ENOUGH_DATA;
3720}
3721
Eric Laurenta553c252009-07-17 12:17:14 -07003722status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723{
Eric Laurenta553c252009-07-17 12:17:14 -07003724 sp<ThreadBase> thread = mThread.promote();
3725 if (thread != 0) {
3726 RecordThread *recordThread = (RecordThread *)thread.get();
3727 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003728 } else {
3729 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731}
3732
Eric Laurenta553c252009-07-17 12:17:14 -07003733void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734{
Eric Laurenta553c252009-07-17 12:17:14 -07003735 sp<ThreadBase> thread = mThread.promote();
3736 if (thread != 0) {
3737 RecordThread *recordThread = (RecordThread *)thread.get();
3738 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003739 TrackBase::reset();
3740 // Force overerrun condition to avoid false overrun callback until first data is
3741 // read from buffer
3742 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744}
3745
Eric Laurent3fdb1262009-11-07 00:01:32 -08003746void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3747{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003748 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003749 (mClient == NULL) ? getpid() : mClient->pid(),
3750 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003751 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003752 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003753 mFrameCount,
3754 mState,
3755 mCblk->sampleRate,
3756 mCblk->server,
3757 mCblk->user);
3758}
3759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760
3761// ----------------------------------------------------------------------------
3762
Eric Laurenta553c252009-07-17 12:17:14 -07003763AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3764 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003765 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003767 uint32_t format,
3768 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003770 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003771 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772{
Eric Laurenta553c252009-07-17 12:17:14 -07003773
3774 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003775 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003776 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003777 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3778 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3779 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003780 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01003781 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003782 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3783 mCblk, mBuffer, mCblk->buffers,
3784 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003785 } else {
3786 LOGW("Error creating output track on thread %p", playbackThread);
3787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788}
3789
Eric Laurenta553c252009-07-17 12:17:14 -07003790AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791{
Eric Laurent6c30a712009-08-10 23:22:32 -07003792 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793}
3794
Eric Laurenta553c252009-07-17 12:17:14 -07003795status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796{
3797 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003798 if (status != NO_ERROR) {
3799 return status;
3800 }
3801
3802 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003803 mRetryCount = 127;
3804 return status;
3805}
3806
Eric Laurenta553c252009-07-17 12:17:14 -07003807void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808{
3809 Track::stop();
3810 clearBufferQueue();
3811 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003812 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813}
3814
Eric Laurenta553c252009-07-17 12:17:14 -07003815bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816{
3817 Buffer *pInBuffer;
3818 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003819 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003820 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 inBuffer.frameCount = frames;
3822 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003823
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003824 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003825
Eric Laurent62443f52009-10-05 20:29:18 -07003826 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003827 start();
3828 sp<ThreadBase> thread = mThread.promote();
3829 if (thread != 0) {
3830 MixerThread *mixerThread = (MixerThread *)thread.get();
3831 if (mCblk->frameCount > frames){
3832 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3833 uint32_t startFrames = (mCblk->frameCount - frames);
3834 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003835 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003836 pInBuffer->frameCount = startFrames;
3837 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003838 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003839 mBufferQueue.add(pInBuffer);
3840 } else {
3841 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 }
Eric Laurenta553c252009-07-17 12:17:14 -07003844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003845 }
3846
Eric Laurenta553c252009-07-17 12:17:14 -07003847 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003848 // First write pending buffers, then new data
3849 if (mBufferQueue.size()) {
3850 pInBuffer = mBufferQueue.itemAt(0);
3851 } else {
3852 pInBuffer = &inBuffer;
3853 }
Eric Laurenta553c252009-07-17 12:17:14 -07003854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 if (pInBuffer->frameCount == 0) {
3856 break;
3857 }
Eric Laurenta553c252009-07-17 12:17:14 -07003858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 if (mOutBuffer.frameCount == 0) {
3860 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003861 nsecs_t startTime = systemTime();
3862 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01003863 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003864 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 break;
3866 }
Eric Laurenta553c252009-07-17 12:17:14 -07003867 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003868 if (waitTimeLeftMs >= waitTimeMs) {
3869 waitTimeLeftMs -= waitTimeMs;
3870 } else {
3871 waitTimeLeftMs = 0;
3872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 }
Eric Laurenta553c252009-07-17 12:17:14 -07003874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003876 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 mCblk->stepUser(outFrames);
3878 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003879 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003881 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 if (pInBuffer->frameCount == 0) {
3884 if (mBufferQueue.size()) {
3885 mBufferQueue.removeAt(0);
3886 delete [] pInBuffer->mBuffer;
3887 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01003888 ALOGV("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 -08003889 } else {
3890 break;
3891 }
3892 }
3893 }
Eric Laurenta553c252009-07-17 12:17:14 -07003894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 // If we could not write all frames, allocate a buffer and queue it for next time.
3896 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003897 sp<ThreadBase> thread = mThread.promote();
3898 if (thread != 0 && !thread->standby()) {
3899 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3900 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003901 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003902 pInBuffer->frameCount = inBuffer.frameCount;
3903 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003904 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003905 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01003906 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003907 } else {
3908 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 }
3911 }
Eric Laurenta553c252009-07-17 12:17:14 -07003912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003914 // 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 -08003915 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003916 if (frames == 0 && mBufferQueue.size() == 0) {
3917 if (mCblk->user < mCblk->frameCount) {
3918 frames = mCblk->frameCount - mCblk->user;
3919 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003920 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003921 pInBuffer->frameCount = frames;
3922 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003923 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003924 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003925 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003926 stop();
3927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 }
3929
Eric Laurenta553c252009-07-17 12:17:14 -07003930 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931}
3932
Eric Laurenta553c252009-07-17 12:17:14 -07003933status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934{
3935 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 status_t result;
3937 audio_track_cblk_t* cblk = mCblk;
3938 uint32_t framesReq = buffer->frameCount;
3939
Steve Block71f2cf12011-10-20 11:56:00 +01003940// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 uint32_t framesAvail = cblk->framesAvailable();
3944
Eric Laurenta553c252009-07-17 12:17:14 -07003945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003947 Mutex::Autolock _l(cblk->lock);
3948 goto start_loop_here;
3949 while (framesAvail == 0) {
3950 active = mActive;
3951 if (UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01003952 ALOGV("Not active and NO_MORE_BUFFERS");
Eric Laurenta553c252009-07-17 12:17:14 -07003953 return AudioTrack::NO_MORE_BUFFERS;
3954 }
3955 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3956 if (result != NO_ERROR) {
3957 return AudioTrack::NO_MORE_BUFFERS;
3958 }
3959 // read the server count again
3960 start_loop_here:
3961 framesAvail = cblk->framesAvailable_l();
3962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 }
3964
Eric Laurenta553c252009-07-17 12:17:14 -07003965// if (framesAvail < framesReq) {
3966// return AudioTrack::NO_MORE_BUFFERS;
3967// }
3968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 if (framesReq > framesAvail) {
3970 framesReq = framesAvail;
3971 }
3972
3973 uint32_t u = cblk->user;
3974 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3975
3976 if (u + framesReq > bufferEnd) {
3977 framesReq = bufferEnd - u;
3978 }
3979
3980 buffer->frameCount = framesReq;
3981 buffer->raw = (void *)cblk->buffer(u);
3982 return NO_ERROR;
3983}
3984
3985
Eric Laurenta553c252009-07-17 12:17:14 -07003986void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987{
3988 size_t size = mBufferQueue.size();
3989 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 for (size_t i = 0; i < size; i++) {
3992 pBuffer = mBufferQueue.itemAt(i);
3993 delete [] pBuffer->mBuffer;
3994 delete pBuffer;
3995 }
3996 mBufferQueue.clear();
3997}
3998
3999// ----------------------------------------------------------------------------
4000
4001AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4002 : RefBase(),
4003 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08004004 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 mPid(pid)
4006{
4007 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4008}
4009
Eric Laurentb9481d82009-09-17 05:12:56 -07004010// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011AudioFlinger::Client::~Client()
4012{
Eric Laurentb9481d82009-09-17 05:12:56 -07004013 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014}
4015
4016const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4017{
4018 return mMemoryDealer;
4019}
4020
4021// ----------------------------------------------------------------------------
4022
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004023AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4024 const sp<IAudioFlingerClient>& client,
4025 pid_t pid)
4026 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4027{
4028}
4029
4030AudioFlinger::NotificationClient::~NotificationClient()
4031{
4032 mClient.clear();
4033}
4034
4035void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4036{
4037 sp<NotificationClient> keep(this);
4038 {
4039 mAudioFlinger->removeNotificationClient(mPid);
4040 }
4041}
4042
4043// ----------------------------------------------------------------------------
4044
Eric Laurenta553c252009-07-17 12:17:14 -07004045AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004046 : BnAudioTrack(),
4047 mTrack(track)
4048{
4049}
4050
4051AudioFlinger::TrackHandle::~TrackHandle() {
4052 // just stop the track on deletion, associated resources
4053 // will be freed from the main thread once all pending buffers have
4054 // been played. Unless it's not in the active track list, in which
4055 // case we free everything now...
4056 mTrack->destroy();
4057}
4058
4059status_t AudioFlinger::TrackHandle::start() {
4060 return mTrack->start();
4061}
4062
4063void AudioFlinger::TrackHandle::stop() {
4064 mTrack->stop();
4065}
4066
4067void AudioFlinger::TrackHandle::flush() {
4068 mTrack->flush();
4069}
4070
4071void AudioFlinger::TrackHandle::mute(bool e) {
4072 mTrack->mute(e);
4073}
4074
4075void AudioFlinger::TrackHandle::pause() {
4076 mTrack->pause();
4077}
4078
4079void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4080 mTrack->setVolume(left, right);
4081}
4082
4083sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4084 return mTrack->getCblk();
4085}
4086
Eric Laurent65b65452010-06-01 23:49:17 -07004087status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4088{
4089 return mTrack->attachAuxEffect(EffectId);
4090}
4091
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004092status_t AudioFlinger::TrackHandle::onTransact(
4093 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4094{
4095 return BnAudioTrack::onTransact(code, data, reply, flags);
4096}
4097
4098// ----------------------------------------------------------------------------
4099
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004100sp<IAudioRecord> AudioFlinger::openRecord(
4101 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07004102 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004103 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004104 uint32_t format,
4105 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004106 int frameCount,
4107 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004108 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004109 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004110{
Eric Laurenta553c252009-07-17 12:17:14 -07004111 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004112 sp<RecordHandle> recordHandle;
4113 sp<Client> client;
4114 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004115 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004116 RecordThread *thread;
4117 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004118 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004119
4120 // check calling permissions
4121 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004122 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004123 goto Exit;
4124 }
4125
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004126 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004127 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004128 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004129 thread = checkRecordThread_l(input);
4130 if (thread == NULL) {
4131 lStatus = BAD_VALUE;
4132 goto Exit;
4133 }
4134
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004135 wclient = mClients.valueFor(pid);
4136 if (wclient != NULL) {
4137 client = wclient.promote();
4138 } else {
4139 client = new Client(this, pid);
4140 mClients.add(pid, client);
4141 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004142
Eric Laurent65b65452010-06-01 23:49:17 -07004143 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004144 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004145 lSessionId = *sessionId;
4146 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004147 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004148 if (sessionId != NULL) {
4149 *sessionId = lSessionId;
4150 }
4151 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004152 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004153 recordTrack = thread->createRecordTrack_l(client,
4154 sampleRate,
4155 format,
4156 channelMask,
4157 frameCount,
4158 flags,
4159 lSessionId,
4160 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004161 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004162 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004163 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4164 // destructor is called by the TrackBase destructor with mLock held
4165 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 goto Exit;
4168 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004169
4170 // return to handle to client
4171 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004172 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004173
4174Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004175 if (status) {
4176 *status = lStatus;
4177 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004178 return recordHandle;
4179}
4180
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004181// ----------------------------------------------------------------------------
4182
Eric Laurenta553c252009-07-17 12:17:14 -07004183AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004184 : BnAudioRecord(),
4185 mRecordTrack(recordTrack)
4186{
4187}
4188
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004189AudioFlinger::RecordHandle::~RecordHandle() {
4190 stop();
4191}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004192
4193status_t AudioFlinger::RecordHandle::start() {
Steve Block71f2cf12011-10-20 11:56:00 +01004194 ALOGV("RecordHandle::start()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004195 return mRecordTrack->start();
4196}
4197
4198void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004199 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004200 mRecordTrack->stop();
4201}
4202
4203sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4204 return mRecordTrack->getCblk();
4205}
4206
4207status_t AudioFlinger::RecordHandle::onTransact(
4208 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4209{
4210 return BnAudioRecord::onTransact(code, data, reply, flags);
4211}
4212
4213// ----------------------------------------------------------------------------
4214
Eric Laurent464d5b32011-06-17 21:29:58 -07004215AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4216 AudioStreamIn *input,
4217 uint32_t sampleRate,
4218 uint32_t channels,
4219 int id,
4220 uint32_t device) :
4221 ThreadBase(audioFlinger, id, device),
4222 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004223{
Eric Laurent464d5b32011-06-17 21:29:58 -07004224 mType = ThreadBase::RECORD;
Eric Laurent6dbdc402011-07-22 09:04:31 -07004225
4226 snprintf(mName, kNameLength, "AudioIn_%d", id);
4227
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004228 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07004229 mReqSampleRate = sampleRate;
4230 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004231}
4232
Eric Laurenta553c252009-07-17 12:17:14 -07004233
4234AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004235{
Eric Laurenta553c252009-07-17 12:17:14 -07004236 delete[] mRsmpInBuffer;
4237 if (mResampler != 0) {
4238 delete mResampler;
4239 delete[] mRsmpOutBuffer;
4240 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004241}
4242
Eric Laurenta553c252009-07-17 12:17:14 -07004243void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004244{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004245 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004246}
Eric Laurent49f02be2009-11-19 09:00:56 -08004247
Eric Laurent828b9772011-08-07 16:32:26 -07004248status_t AudioFlinger::RecordThread::readyToRun()
4249{
4250 status_t status = initCheck();
4251 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4252 return status;
4253}
4254
Eric Laurenta553c252009-07-17 12:17:14 -07004255bool AudioFlinger::RecordThread::threadLoop()
4256{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004257 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004258 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004259 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004260
Eric Laurent4712baa2010-09-30 16:12:31 -07004261 nsecs_t lastWarning = 0;
4262
Eric Laurent6dbdc402011-07-22 09:04:31 -07004263 acquireWakeLock();
4264
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004265 // start recording
4266 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004267
Eric Laurenta553c252009-07-17 12:17:14 -07004268 processConfigEvents();
4269
4270 { // scope for mLock
4271 Mutex::Autolock _l(mLock);
4272 checkForNewParameters_l();
4273 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4274 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004275 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004276 mStandby = true;
4277 }
4278
4279 if (exitPending()) break;
4280
Eric Laurent6dbdc402011-07-22 09:04:31 -07004281 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004282 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004283 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004284 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004285 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004286 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004287 continue;
4288 }
4289 if (mActiveTrack != 0) {
4290 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004291 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004292 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004293 mStandby = true;
4294 }
Eric Laurenta553c252009-07-17 12:17:14 -07004295 mActiveTrack.clear();
4296 mStartStopCond.broadcast();
4297 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004298 if (mReqChannelCount != mActiveTrack->channelCount()) {
4299 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004300 mStartStopCond.broadcast();
4301 } else if (mBytesRead != 0) {
4302 // record start succeeds only if first read from audio input
4303 // succeeds
4304 if (mBytesRead > 0) {
4305 mActiveTrack->mState = TrackBase::ACTIVE;
4306 } else {
4307 mActiveTrack.clear();
4308 }
4309 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004310 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004311 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004312 }
Eric Laurenta553c252009-07-17 12:17:14 -07004313 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004314 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004315 }
4316
4317 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004318 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4319 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004320 unlockEffectChains(effectChains);
4321 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004322 continue;
4323 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004324 for (size_t i = 0; i < effectChains.size(); i ++) {
4325 effectChains[i]->process_l();
4326 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004327
Eric Laurenta553c252009-07-17 12:17:14 -07004328 buffer.frameCount = mFrameCount;
4329 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4330 size_t framesOut = buffer.frameCount;
4331 if (mResampler == 0) {
4332 // no resampling
4333 while (framesOut) {
4334 size_t framesIn = mFrameCount - mRsmpInIndex;
4335 if (framesIn) {
4336 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4337 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4338 if (framesIn > framesOut)
4339 framesIn = framesOut;
4340 mRsmpInIndex += framesIn;
4341 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004342 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004343 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004344 memcpy(dst, src, framesIn * mFrameSize);
4345 } else {
4346 int16_t *src16 = (int16_t *)src;
4347 int16_t *dst16 = (int16_t *)dst;
4348 if (mChannelCount == 1) {
4349 while (framesIn--) {
4350 *dst16++ = *src16;
4351 *dst16++ = *src16++;
4352 }
4353 } else {
4354 while (framesIn--) {
4355 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4356 src16 += 2;
4357 }
4358 }
4359 }
4360 }
4361 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004362 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004363 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004364 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004365 framesOut = 0;
4366 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004367 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004368 mRsmpInIndex = 0;
4369 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004370 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004371 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004372 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004373 // Force input into standby so that it tries to
4374 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004375 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004376 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004377 }
Eric Laurenta553c252009-07-17 12:17:14 -07004378 mRsmpInIndex = mFrameCount;
4379 framesOut = 0;
4380 buffer.frameCount = 0;
4381 }
4382 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004383 }
4384 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004385 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004386
Eric Laurenta553c252009-07-17 12:17:14 -07004387 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4388 // alter output frame count as if we were expecting stereo samples
4389 if (mChannelCount == 1 && mReqChannelCount == 1) {
4390 framesOut >>= 1;
4391 }
4392 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4393 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4394 // are 32 bit aligned which should be always true.
4395 if (mChannelCount == 2 && mReqChannelCount == 1) {
4396 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4397 // the resampler always outputs stereo samples: do post stereo to mono conversion
4398 int16_t *src = (int16_t *)mRsmpOutBuffer;
4399 int16_t *dst = buffer.i16;
4400 while (framesOut--) {
4401 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4402 src += 2;
4403 }
4404 } else {
4405 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4406 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004407
Eric Laurenta553c252009-07-17 12:17:14 -07004408 }
4409 mActiveTrack->releaseBuffer(&buffer);
4410 mActiveTrack->overflow();
4411 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004412 // client isn't retrieving buffers fast enough
4413 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004414 if (!mActiveTrack->setOverflow()) {
4415 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004416 if ((now - lastWarning) > kWarningThrottleNs) {
Eric Laurent4712baa2010-09-30 16:12:31 -07004417 LOGW("RecordThread: buffer overflow");
4418 lastWarning = now;
4419 }
4420 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004421 // Release the processor for a while before asking for a new buffer.
4422 // This will give the application more chance to read from the buffer and
4423 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004424 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004425 }
4426 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004427 // enable changes in effect chain
4428 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004429 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004430 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004431
Eric Laurenta553c252009-07-17 12:17:14 -07004432 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004433 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004434 }
Eric Laurenta553c252009-07-17 12:17:14 -07004435 mActiveTrack.clear();
4436
Eric Laurent49f02be2009-11-19 09:00:56 -08004437 mStartStopCond.broadcast();
4438
Eric Laurent6dbdc402011-07-22 09:04:31 -07004439 releaseWakeLock();
4440
Steve Block71f2cf12011-10-20 11:56:00 +01004441 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004442 return false;
4443}
4444
Eric Laurent464d5b32011-06-17 21:29:58 -07004445
4446sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4447 const sp<AudioFlinger::Client>& client,
4448 uint32_t sampleRate,
4449 int format,
4450 int channelMask,
4451 int frameCount,
4452 uint32_t flags,
4453 int sessionId,
4454 status_t *status)
4455{
4456 sp<RecordTrack> track;
4457 status_t lStatus;
4458
4459 lStatus = initCheck();
4460 if (lStatus != NO_ERROR) {
4461 LOGE("Audio driver not initialized.");
4462 goto Exit;
4463 }
4464
4465 { // scope for mLock
4466 Mutex::Autolock _l(mLock);
4467
4468 track = new RecordTrack(this, client, sampleRate,
4469 format, channelMask, frameCount, flags, sessionId);
4470
4471 if (track->getCblk() == NULL) {
4472 lStatus = NO_MEMORY;
4473 goto Exit;
4474 }
4475
4476 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004477 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4478 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004479 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004480 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4481 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004482 }
4483 lStatus = NO_ERROR;
4484
4485Exit:
4486 if (status) {
4487 *status = lStatus;
4488 }
4489 return track;
4490}
4491
Eric Laurenta553c252009-07-17 12:17:14 -07004492status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004493{
Steve Block71f2cf12011-10-20 11:56:00 +01004494 ALOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004495 sp <ThreadBase> strongMe = this;
4496 status_t status = NO_ERROR;
4497 {
4498 AutoMutex lock(&mLock);
4499 if (mActiveTrack != 0) {
4500 if (recordTrack != mActiveTrack.get()) {
4501 status = -EBUSY;
4502 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004503 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004504 }
4505 return status;
4506 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004507
Eric Laurent49f02be2009-11-19 09:00:56 -08004508 recordTrack->mState = TrackBase::IDLE;
4509 mActiveTrack = recordTrack;
4510 mLock.unlock();
4511 status_t status = AudioSystem::startInput(mId);
4512 mLock.lock();
4513 if (status != NO_ERROR) {
4514 mActiveTrack.clear();
4515 return status;
4516 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004517 mRsmpInIndex = mFrameCount;
4518 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004519 if (mResampler != NULL) {
4520 mResampler->reset();
4521 }
4522 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004523 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004524 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004525 mWaitWorkCV.signal();
4526 // do not wait for mStartStopCond if exiting
4527 if (mExiting) {
4528 mActiveTrack.clear();
4529 status = INVALID_OPERATION;
4530 goto startError;
4531 }
4532 mStartStopCond.wait(mLock);
4533 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01004534 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004535 status = BAD_VALUE;
4536 goto startError;
4537 }
Steve Block71f2cf12011-10-20 11:56:00 +01004538 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004539 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004540 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004541startError:
4542 AudioSystem::stopInput(mId);
4543 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004544}
4545
Eric Laurenta553c252009-07-17 12:17:14 -07004546void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01004547 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004548 sp <ThreadBase> strongMe = this;
4549 {
4550 AutoMutex lock(&mLock);
4551 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4552 mActiveTrack->mState = TrackBase::PAUSING;
4553 // do not wait for mStartStopCond if exiting
4554 if (mExiting) {
4555 return;
4556 }
4557 mStartStopCond.wait(mLock);
4558 // if we have been restarted, recordTrack == mActiveTrack.get() here
4559 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4560 mLock.unlock();
4561 AudioSystem::stopInput(mId);
4562 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01004563 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004564 }
4565 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004566 }
4567}
4568
Eric Laurenta553c252009-07-17 12:17:14 -07004569status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570{
4571 const size_t SIZE = 256;
4572 char buffer[SIZE];
4573 String8 result;
4574 pid_t pid = 0;
4575
Eric Laurent3fdb1262009-11-07 00:01:32 -08004576 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4577 result.append(buffer);
4578
4579 if (mActiveTrack != 0) {
4580 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004581 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004582 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004584
4585 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4586 result.append(buffer);
4587 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4588 result.append(buffer);
4589 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4590 result.append(buffer);
4591 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4592 result.append(buffer);
4593 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4594 result.append(buffer);
4595
4596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004597 } else {
4598 result.append("No record client\n");
4599 }
4600 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004601
4602 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004603 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 return NO_ERROR;
4606}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004607
Eric Laurenta553c252009-07-17 12:17:14 -07004608status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4609{
4610 size_t framesReq = buffer->frameCount;
4611 size_t framesReady = mFrameCount - mRsmpInIndex;
4612 int channelCount;
4613
4614 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004615 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004616 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004617 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004618 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004619 // Force input into standby so that it tries to
4620 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004621 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004622 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004623 }
Eric Laurenta553c252009-07-17 12:17:14 -07004624 buffer->raw = 0;
4625 buffer->frameCount = 0;
4626 return NOT_ENOUGH_DATA;
4627 }
4628 mRsmpInIndex = 0;
4629 framesReady = mFrameCount;
4630 }
4631
4632 if (framesReq > framesReady) {
4633 framesReq = framesReady;
4634 }
4635
4636 if (mChannelCount == 1 && mReqChannelCount == 2) {
4637 channelCount = 1;
4638 } else {
4639 channelCount = 2;
4640 }
4641 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4642 buffer->frameCount = framesReq;
4643 return NO_ERROR;
4644}
4645
4646void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4647{
4648 mRsmpInIndex += buffer->frameCount;
4649 buffer->frameCount = 0;
4650}
4651
4652bool AudioFlinger::RecordThread::checkForNewParameters_l()
4653{
4654 bool reconfig = false;
4655
Eric Laurent8fce46a2009-08-04 09:45:33 -07004656 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004657 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004658 String8 keyValuePair = mNewParameters[0];
4659 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004660 int value;
4661 int reqFormat = mFormat;
4662 int reqSamplingRate = mReqSampleRate;
4663 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004664
Eric Laurenta553c252009-07-17 12:17:14 -07004665 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4666 reqSamplingRate = value;
4667 reconfig = true;
4668 }
4669 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4670 reqFormat = value;
4671 reconfig = true;
4672 }
4673 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004674 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004675 reconfig = true;
4676 }
4677 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4678 // do not accept frame count changes if tracks are open as the track buffer
4679 // size depends on frame count and correct behavior would not be garantied
4680 // if frame count is changed after track creation
4681 if (mActiveTrack != 0) {
4682 status = INVALID_OPERATION;
4683 } else {
4684 reconfig = true;
4685 }
4686 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004687 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4688 // forward device change to effects that have requested to be
4689 // aware of attached audio device.
4690 for (size_t i = 0; i < mEffectChains.size(); i++) {
4691 mEffectChains[i]->setDevice_l(value);
4692 }
4693 // store input device and output device but do not forward output device to audio HAL.
4694 // Note that status is ignored by the caller for output device
4695 // (see AudioFlinger::setParameters()
4696 if (value & AUDIO_DEVICE_OUT_ALL) {
4697 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4698 status = BAD_VALUE;
4699 } else {
4700 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004701 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4702 if (mTrack != NULL) {
4703 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004704 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004705 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4706 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4707 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004708 }
4709 mDevice |= (uint32_t)value;
4710 }
Eric Laurenta553c252009-07-17 12:17:14 -07004711 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004712 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004713 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004714 mInput->stream->common.standby(&mInput->stream->common);
4715 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004716 }
4717 if (reconfig) {
4718 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004719 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004720 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004721 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4722 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004723 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004724 status = NO_ERROR;
4725 }
4726 if (status == NO_ERROR) {
4727 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004728 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004729 }
4730 }
4731 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004732
4733 mNewParameters.removeAt(0);
4734
Eric Laurenta553c252009-07-17 12:17:14 -07004735 mParamStatus = status;
4736 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004737 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4738 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004739 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07004740 }
4741 return reconfig;
4742}
4743
4744String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4745{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004746 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004747 String8 out_s8 = String8();
4748
4749 Mutex::Autolock _l(mLock);
4750 if (initCheck() != NO_ERROR) {
4751 return out_s8;
4752 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004753
Dima Zavin31f188892011-04-18 16:57:27 -07004754 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004755 out_s8 = String8(s);
4756 free(s);
4757 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004758}
4759
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004760void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004761 AudioSystem::OutputDescriptor desc;
4762 void *param2 = 0;
4763
4764 switch (event) {
4765 case AudioSystem::INPUT_OPENED:
4766 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004767 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004768 desc.samplingRate = mSampleRate;
4769 desc.format = mFormat;
4770 desc.frameCount = mFrameCount;
4771 desc.latency = 0;
4772 param2 = &desc;
4773 break;
4774
4775 case AudioSystem::INPUT_CLOSED:
4776 default:
4777 break;
4778 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004779 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004780}
4781
4782void AudioFlinger::RecordThread::readInputParameters()
4783{
4784 if (mRsmpInBuffer) delete mRsmpInBuffer;
4785 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4786 if (mResampler) delete mResampler;
4787 mResampler = 0;
4788
Dima Zavin31f188892011-04-18 16:57:27 -07004789 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004790 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4791 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004792 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4793 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4794 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004795 mFrameCount = mInputBytes / mFrameSize;
4796 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4797
4798 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4799 {
4800 int channelCount;
4801 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4802 // stereo to mono post process as the resampler always outputs stereo.
4803 if (mChannelCount == 1 && mReqChannelCount == 2) {
4804 channelCount = 1;
4805 } else {
4806 channelCount = 2;
4807 }
4808 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4809 mResampler->setSampleRate(mSampleRate);
4810 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4811 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4812
4813 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4814 if (mChannelCount == 1 && mReqChannelCount == 1) {
4815 mFrameCount >>= 1;
4816 }
4817
4818 }
4819 mRsmpInIndex = mFrameCount;
4820}
4821
Eric Laurent47d0a922010-02-26 02:47:27 -08004822unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4823{
Eric Laurent828b9772011-08-07 16:32:26 -07004824 Mutex::Autolock _l(mLock);
4825 if (initCheck() != NO_ERROR) {
4826 return 0;
4827 }
4828
Dima Zavin31f188892011-04-18 16:57:27 -07004829 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004830}
4831
Eric Laurent464d5b32011-06-17 21:29:58 -07004832uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4833{
4834 Mutex::Autolock _l(mLock);
4835 uint32_t result = 0;
4836 if (getEffectChain_l(sessionId) != 0) {
4837 result = EFFECT_SESSION;
4838 }
4839
4840 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4841 result |= TRACK_SESSION;
4842 }
4843
4844 return result;
4845}
4846
Eric Laurent6639b552011-08-01 09:52:20 -07004847AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4848{
4849 Mutex::Autolock _l(mLock);
4850 return mTrack;
4851}
4852
Eric Laurent828b9772011-08-07 16:32:26 -07004853AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4854{
4855 Mutex::Autolock _l(mLock);
4856 return mInput;
4857}
4858
4859AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4860{
4861 Mutex::Autolock _l(mLock);
4862 AudioStreamIn *input = mInput;
4863 mInput = NULL;
4864 return input;
4865}
4866
4867// this method must always be called either with ThreadBase mLock held or inside the thread loop
4868audio_stream_t* AudioFlinger::RecordThread::stream()
4869{
4870 if (mInput == NULL) {
4871 return NULL;
4872 }
4873 return &mInput->stream->common;
4874}
4875
4876
Eric Laurenta553c252009-07-17 12:17:14 -07004877// ----------------------------------------------------------------------------
4878
Eric Laurentddb78e72009-07-28 08:44:33 -07004879int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004880 uint32_t *pSamplingRate,
4881 uint32_t *pFormat,
4882 uint32_t *pChannels,
4883 uint32_t *pLatencyMs,
4884 uint32_t flags)
4885{
4886 status_t status;
4887 PlaybackThread *thread = NULL;
4888 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4889 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4890 uint32_t format = pFormat ? *pFormat : 0;
4891 uint32_t channels = pChannels ? *pChannels : 0;
4892 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004893 audio_stream_out_t *outStream;
4894 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004895
Steve Block71f2cf12011-10-20 11:56:00 +01004896 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07004897 pDevices ? *pDevices : 0,
4898 samplingRate,
4899 format,
4900 channels,
4901 flags);
4902
4903 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004904 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004905 }
Dima Zavin31f188892011-04-18 16:57:27 -07004906
Eric Laurenta553c252009-07-17 12:17:14 -07004907 Mutex::Autolock _l(mLock);
4908
Dima Zavin31f188892011-04-18 16:57:27 -07004909 outHwDev = findSuitableHwDev_l(*pDevices);
4910 if (outHwDev == NULL)
4911 return 0;
4912
4913 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4914 &channels, &samplingRate, &outStream);
Steve Block71f2cf12011-10-20 11:56:00 +01004915 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004916 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004917 samplingRate,
4918 format,
4919 channels,
4920 status);
4921
4922 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004923 if (outStream != NULL) {
4924 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent464d5b32011-06-17 21:29:58 -07004925 int id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004926
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004927 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4928 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4929 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004930 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004931 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004932 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004933 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004934 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004935 }
Eric Laurent65b65452010-06-01 23:49:17 -07004936 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004937
4938 if (pSamplingRate) *pSamplingRate = samplingRate;
4939 if (pFormat) *pFormat = format;
4940 if (pChannels) *pChannels = channels;
4941 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004942
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004943 // notify client processes of the new output creation
4944 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004945 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004946 }
4947
Eric Laurent9cc489a22009-12-05 05:20:01 -08004948 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004949}
4950
Eric Laurentddb78e72009-07-28 08:44:33 -07004951int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004952{
4953 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004954 MixerThread *thread1 = checkMixerThread_l(output1);
4955 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004956
Eric Laurentddb78e72009-07-28 08:44:33 -07004957 if (thread1 == NULL || thread2 == NULL) {
4958 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4959 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004960 }
4961
Eric Laurent464d5b32011-06-17 21:29:58 -07004962 int id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004963 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004964 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004965 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004966 // notify client processes of the new output creation
4967 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004968 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004969}
4970
Eric Laurentddb78e72009-07-28 08:44:33 -07004971status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004972{
Eric Laurent49018a52009-08-04 08:37:05 -07004973 // keep strong reference on the playback thread so that
4974 // it is not destroyed while exit() is executed
4975 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004976 {
4977 Mutex::Autolock _l(mLock);
4978 thread = checkPlaybackThread_l(output);
4979 if (thread == NULL) {
4980 return BAD_VALUE;
4981 }
4982
Steve Block71f2cf12011-10-20 11:56:00 +01004983 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004984
Eric Laurent464d5b32011-06-17 21:29:58 -07004985 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07004986 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004987 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004988 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004989 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004990 }
4991 }
4992 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004993 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004994 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004995 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004996 }
4997 thread->exit();
4998
Eric Laurent464d5b32011-06-17 21:29:58 -07004999 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07005000 AudioStreamOut *out = thread->clearOutput();
5001 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005002 out->hwDev->close_output_stream(out->hwDev, out->stream);
5003 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005004 }
Eric Laurenta553c252009-07-17 12:17:14 -07005005 return NO_ERROR;
5006}
5007
Eric Laurentddb78e72009-07-28 08:44:33 -07005008status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005009{
5010 Mutex::Autolock _l(mLock);
5011 PlaybackThread *thread = checkPlaybackThread_l(output);
5012
5013 if (thread == NULL) {
5014 return BAD_VALUE;
5015 }
5016
Steve Block71f2cf12011-10-20 11:56:00 +01005017 ALOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005018 thread->suspend();
5019
5020 return NO_ERROR;
5021}
5022
Eric Laurentddb78e72009-07-28 08:44:33 -07005023status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005024{
5025 Mutex::Autolock _l(mLock);
5026 PlaybackThread *thread = checkPlaybackThread_l(output);
5027
5028 if (thread == NULL) {
5029 return BAD_VALUE;
5030 }
5031
Steve Block71f2cf12011-10-20 11:56:00 +01005032 ALOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005033
5034 thread->restore();
5035
5036 return NO_ERROR;
5037}
5038
Eric Laurentddb78e72009-07-28 08:44:33 -07005039int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005040 uint32_t *pSamplingRate,
5041 uint32_t *pFormat,
5042 uint32_t *pChannels,
5043 uint32_t acoustics)
5044{
5045 status_t status;
5046 RecordThread *thread = NULL;
5047 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5048 uint32_t format = pFormat ? *pFormat : 0;
5049 uint32_t channels = pChannels ? *pChannels : 0;
5050 uint32_t reqSamplingRate = samplingRate;
5051 uint32_t reqFormat = format;
5052 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005053 audio_stream_in_t *inStream;
5054 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005055
5056 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005057 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005058 }
Dima Zavin31f188892011-04-18 16:57:27 -07005059
Eric Laurenta553c252009-07-17 12:17:14 -07005060 Mutex::Autolock _l(mLock);
5061
Dima Zavin31f188892011-04-18 16:57:27 -07005062 inHwDev = findSuitableHwDev_l(*pDevices);
5063 if (inHwDev == NULL)
5064 return 0;
5065
5066 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5067 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005068 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005069 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005070 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005071 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005072 samplingRate,
5073 format,
5074 channels,
5075 acoustics,
5076 status);
5077
5078 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5079 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5080 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005081 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005082 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005083 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005084 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005085 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin31f188892011-04-18 16:57:27 -07005086 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5087 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005088 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005089 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005090 }
5091
Dima Zavin31f188892011-04-18 16:57:27 -07005092 if (inStream != NULL) {
5093 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5094
Eric Laurent464d5b32011-06-17 21:29:58 -07005095 int id = nextUniqueId();
5096 // Start record thread
5097 // RecorThread require both input and output device indication to forward to audio
5098 // pre processing modules
5099 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5100 thread = new RecordThread(this,
5101 input,
5102 reqSamplingRate,
5103 reqChannels,
5104 id,
5105 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005106 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005107 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005108 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5109 if (pFormat) *pFormat = format;
5110 if (pChannels) *pChannels = reqChannels;
5111
Dima Zavin31f188892011-04-18 16:57:27 -07005112 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005113
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005114 // notify client processes of the new input creation
5115 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005116 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005117 }
5118
Eric Laurent9cc489a22009-12-05 05:20:01 -08005119 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005120}
5121
Eric Laurentddb78e72009-07-28 08:44:33 -07005122status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07005123{
Eric Laurent49018a52009-08-04 08:37:05 -07005124 // keep strong reference on the record thread so that
5125 // it is not destroyed while exit() is executed
5126 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005127 {
5128 Mutex::Autolock _l(mLock);
5129 thread = checkRecordThread_l(input);
5130 if (thread == NULL) {
5131 return BAD_VALUE;
5132 }
5133
Steve Block71f2cf12011-10-20 11:56:00 +01005134 ALOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07005135 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005136 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005137 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005138 }
5139 thread->exit();
5140
Eric Laurent828b9772011-08-07 16:32:26 -07005141 AudioStreamIn *in = thread->clearInput();
5142 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005143 in->hwDev->close_input_stream(in->hwDev, in->stream);
5144 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005145
Eric Laurenta553c252009-07-17 12:17:14 -07005146 return NO_ERROR;
5147}
5148
Eric Laurentddb78e72009-07-28 08:44:33 -07005149status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005150{
5151 Mutex::Autolock _l(mLock);
5152 MixerThread *dstThread = checkMixerThread_l(output);
5153 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005154 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005155 return BAD_VALUE;
5156 }
5157
Steve Block71f2cf12011-10-20 11:56:00 +01005158 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005159 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005160
Eric Laurent05ce0942011-08-30 10:18:54 -07005161 dstThread->setStreamValid(stream, true);
5162
Eric Laurenta553c252009-07-17 12:17:14 -07005163 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005164 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005165 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005166 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005167 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005168 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005169 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005170 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005171 }
Eric Laurentd069f322009-09-01 05:56:26 -07005172
Eric Laurenta553c252009-07-17 12:17:14 -07005173 return NO_ERROR;
5174}
5175
Eric Laurent65b65452010-06-01 23:49:17 -07005176
5177int AudioFlinger::newAudioSessionId()
5178{
Eric Laurent464d5b32011-06-17 21:29:58 -07005179 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005180}
5181
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005182void AudioFlinger::acquireAudioSessionId(int audioSession)
5183{
5184 Mutex::Autolock _l(mLock);
5185 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005186 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005187 int num = mAudioSessionRefs.size();
5188 for (int i = 0; i< num; i++) {
5189 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5190 if (ref->sessionid == audioSession && ref->pid == caller) {
5191 ref->cnt++;
Steve Block71f2cf12011-10-20 11:56:00 +01005192 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005193 return;
5194 }
5195 }
5196 AudioSessionRef *ref = new AudioSessionRef();
5197 ref->sessionid = audioSession;
5198 ref->pid = caller;
5199 ref->cnt = 1;
5200 mAudioSessionRefs.push(ref);
Steve Block71f2cf12011-10-20 11:56:00 +01005201 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005202}
5203
5204void AudioFlinger::releaseAudioSessionId(int audioSession)
5205{
5206 Mutex::Autolock _l(mLock);
5207 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005208 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005209 int num = mAudioSessionRefs.size();
5210 for (int i = 0; i< num; i++) {
5211 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5212 if (ref->sessionid == audioSession && ref->pid == caller) {
5213 ref->cnt--;
Steve Block71f2cf12011-10-20 11:56:00 +01005214 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005215 if (ref->cnt == 0) {
5216 mAudioSessionRefs.removeAt(i);
5217 delete ref;
5218 purgeStaleEffects_l();
5219 }
5220 return;
5221 }
5222 }
5223 LOGW("session id %d not found for pid %d", audioSession, caller);
5224}
5225
5226void AudioFlinger::purgeStaleEffects_l() {
5227
Steve Block71f2cf12011-10-20 11:56:00 +01005228 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005229
5230 Vector< sp<EffectChain> > chains;
5231
5232 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5233 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5234 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5235 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005236 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5237 chains.push(ec);
5238 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005239 }
5240 }
5241 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5242 sp<RecordThread> t = mRecordThreads.valueAt(i);
5243 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5244 sp<EffectChain> ec = t->mEffectChains[j];
5245 chains.push(ec);
5246 }
5247 }
5248
5249 for (size_t i = 0; i < chains.size(); i++) {
5250 sp<EffectChain> ec = chains[i];
5251 int sessionid = ec->sessionId();
5252 sp<ThreadBase> t = ec->mThread.promote();
5253 if (t == 0) {
5254 continue;
5255 }
5256 size_t numsessionrefs = mAudioSessionRefs.size();
5257 bool found = false;
5258 for (size_t k = 0; k < numsessionrefs; k++) {
5259 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5260 if (ref->sessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005261 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005262 sessionid, ref->pid, ref->cnt);
5263 found = true;
5264 break;
5265 }
5266 }
5267 if (!found) {
5268 // remove all effects from the chain
5269 while (ec->mEffects.size()) {
5270 sp<EffectModule> effect = ec->mEffects[0];
5271 effect->unPin();
5272 Mutex::Autolock _l (t->mLock);
5273 t->removeEffect_l(effect);
5274 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5275 sp<EffectHandle> handle = effect->mHandles[j].promote();
5276 if (handle != 0) {
5277 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005278 if (handle->mHasControl && handle->mEnabled) {
5279 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5280 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005281 }
5282 }
5283 AudioSystem::unregisterEffect(effect->id());
5284 }
5285 }
5286 }
5287 return;
5288}
5289
Eric Laurenta553c252009-07-17 12:17:14 -07005290// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005291AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005292{
5293 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005294 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5295 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005296 }
Eric Laurenta553c252009-07-17 12:17:14 -07005297 return thread;
5298}
5299
5300// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005301AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005302{
5303 PlaybackThread *thread = checkPlaybackThread_l(output);
5304 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005305 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005306 thread = NULL;
5307 }
5308 }
5309 return (MixerThread *)thread;
5310}
5311
5312// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005313AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005314{
5315 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005316 if (mRecordThreads.indexOfKey(input) >= 0) {
5317 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005318 }
Eric Laurenta553c252009-07-17 12:17:14 -07005319 return thread;
5320}
5321
Eric Laurent464d5b32011-06-17 21:29:58 -07005322uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005323{
Eric Laurent464d5b32011-06-17 21:29:58 -07005324 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005325}
5326
Eric Laurent464d5b32011-06-17 21:29:58 -07005327AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5328{
5329 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5330 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005331 AudioStreamOut *output = thread->getOutput();
5332 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005333 return thread;
5334 }
5335 }
5336 return NULL;
5337}
5338
5339uint32_t AudioFlinger::primaryOutputDevice_l()
5340{
5341 PlaybackThread *thread = primaryPlaybackThread_l();
5342
5343 if (thread == NULL) {
5344 return 0;
5345 }
5346
5347 return thread->device();
5348}
5349
5350
Eric Laurent65b65452010-06-01 23:49:17 -07005351// ----------------------------------------------------------------------------
5352// Effect management
5353// ----------------------------------------------------------------------------
5354
5355
Eric Laurent65b65452010-06-01 23:49:17 -07005356status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5357{
5358 Mutex::Autolock _l(mLock);
5359 return EffectQueryNumberEffects(numEffects);
5360}
5361
Eric Laurent53334cd2010-06-23 17:38:20 -07005362status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07005363{
5364 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005365 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005366}
5367
5368status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5369{
5370 Mutex::Autolock _l(mLock);
5371 return EffectGetDescriptor(pUuid, descriptor);
5372}
5373
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005374
Eric Laurent65b65452010-06-01 23:49:17 -07005375sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5376 effect_descriptor_t *pDesc,
5377 const sp<IEffectClient>& effectClient,
5378 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005379 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005380 int sessionId,
5381 status_t *status,
5382 int *id,
5383 int *enabled)
5384{
5385 status_t lStatus = NO_ERROR;
5386 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005387 effect_descriptor_t desc;
5388 sp<Client> client;
5389 wp<Client> wclient;
5390
Steve Block71f2cf12011-10-20 11:56:00 +01005391 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005392 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005393
5394 if (pDesc == NULL) {
5395 lStatus = BAD_VALUE;
5396 goto Exit;
5397 }
5398
Eric Laurent98c92592010-09-23 16:10:16 -07005399 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005400 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005401 lStatus = PERMISSION_DENIED;
5402 goto Exit;
5403 }
5404
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005405 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005406 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005407 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005408 lStatus = PERMISSION_DENIED;
5409 goto Exit;
5410 }
5411
Eric Laurent464d5b32011-06-17 21:29:58 -07005412 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005413 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005414 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005415 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005416 lStatus = BAD_VALUE;
5417 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005418 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005419 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005420 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005421 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005422 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005423 }
5424 }
5425
Eric Laurent65b65452010-06-01 23:49:17 -07005426 {
5427 Mutex::Autolock _l(mLock);
5428
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005429
Eric Laurent65b65452010-06-01 23:49:17 -07005430 if (!EffectIsNullUuid(&pDesc->uuid)) {
5431 // if uuid is specified, request effect descriptor
5432 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5433 if (lStatus < 0) {
5434 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5435 goto Exit;
5436 }
5437 } else {
5438 // if uuid is not specified, look for an available implementation
5439 // of the required type in effect factory
5440 if (EffectIsNullUuid(&pDesc->type)) {
5441 LOGW("createEffect() no effect type");
5442 lStatus = BAD_VALUE;
5443 goto Exit;
5444 }
5445 uint32_t numEffects = 0;
5446 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005447 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005448 bool found = false;
5449
5450 lStatus = EffectQueryNumberEffects(&numEffects);
5451 if (lStatus < 0) {
5452 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5453 goto Exit;
5454 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005455 for (uint32_t i = 0; i < numEffects; i++) {
5456 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005457 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005458 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005459 continue;
5460 }
5461 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5462 // If matching type found save effect descriptor. If the session is
5463 // 0 and the effect is not auxiliary, continue enumeration in case
5464 // an auxiliary version of this effect type is available
5465 found = true;
5466 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005467 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005468 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5469 break;
5470 }
5471 }
5472 }
5473 if (!found) {
5474 lStatus = BAD_VALUE;
5475 LOGW("createEffect() effect not found");
5476 goto Exit;
5477 }
5478 // For same effect type, chose auxiliary version over insert version if
5479 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005480 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005481 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5482 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5483 }
5484 }
5485
5486 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005487 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005488 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5489 lStatus = INVALID_OPERATION;
5490 goto Exit;
5491 }
5492
Eric Laurentf82fccd2011-07-27 19:49:51 -07005493 // check recording permission for visualizer
5494 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5495 !recordingAllowed()) {
5496 lStatus = PERMISSION_DENIED;
5497 goto Exit;
5498 }
5499
Eric Laurent65b65452010-06-01 23:49:17 -07005500 // return effect descriptor
5501 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5502
5503 // If output is not specified try to find a matching audio session ID in one of the
5504 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005505 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5506 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005507 // Note: io is never 0 when creating an effect on an input
5508 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005509 // look for the thread where the specified audio session is present
5510 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5511 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005512 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005513 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005514 }
Eric Laurent65b65452010-06-01 23:49:17 -07005515 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005516 if (io == 0) {
5517 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5518 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5519 io = mRecordThreads.keyAt(i);
5520 break;
5521 }
5522 }
5523 }
Eric Laurent98c92592010-09-23 16:10:16 -07005524 // If no output thread contains the requested session ID, default to
5525 // first output. The effect chain will be moved to the correct output
5526 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005527 if (io == 0 && mPlaybackThreads.size()) {
5528 io = mPlaybackThreads.keyAt(0);
5529 }
Steve Block71f2cf12011-10-20 11:56:00 +01005530 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005531 }
5532 ThreadBase *thread = checkRecordThread_l(io);
5533 if (thread == NULL) {
5534 thread = checkPlaybackThread_l(io);
5535 if (thread == NULL) {
5536 LOGE("createEffect() unknown output thread");
5537 lStatus = BAD_VALUE;
5538 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005539 }
Eric Laurent65b65452010-06-01 23:49:17 -07005540 }
Eric Laurent98c92592010-09-23 16:10:16 -07005541
Eric Laurent65b65452010-06-01 23:49:17 -07005542 wclient = mClients.valueFor(pid);
5543
5544 if (wclient != NULL) {
5545 client = wclient.promote();
5546 } else {
5547 client = new Client(this, pid);
5548 mClients.add(pid, client);
5549 }
5550
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005551 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005552 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5553 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005554 if (handle != 0 && id != NULL) {
5555 *id = handle->id();
5556 }
5557 }
5558
5559Exit:
5560 if(status) {
5561 *status = lStatus;
5562 }
5563 return handle;
5564}
5565
Eric Laurentf82fccd2011-07-27 19:49:51 -07005566status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005567{
Steve Block71f2cf12011-10-20 11:56:00 +01005568 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005569 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005570 Mutex::Autolock _l(mLock);
5571 if (srcOutput == dstOutput) {
5572 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5573 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005574 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005575 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5576 if (srcThread == NULL) {
5577 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5578 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005579 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005580 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5581 if (dstThread == NULL) {
5582 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5583 return BAD_VALUE;
5584 }
5585
5586 Mutex::Autolock _dl(dstThread->mLock);
5587 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005588 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005589
Eric Laurent53334cd2010-06-23 17:38:20 -07005590 return NO_ERROR;
5591}
5592
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005593// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005594status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005595 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005596 AudioFlinger::PlaybackThread *dstThread,
5597 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005598{
Steve Block71f2cf12011-10-20 11:56:00 +01005599 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005600 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005601
Eric Laurentf82fccd2011-07-27 19:49:51 -07005602 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005603 if (chain == 0) {
5604 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005605 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005606 return INVALID_OPERATION;
5607 }
5608
Eric Laurent493941b2010-07-28 01:32:47 -07005609 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005610 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005611 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005612 // removed.
5613 srcThread->removeEffectChain_l(chain);
5614
5615 // transfer all effects one by one so that new effect chain is created on new thread with
5616 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005617 int dstOutput = dstThread->id();
5618 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005619 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005620 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5621 while (effect != 0) {
5622 srcThread->removeEffect_l(effect);
5623 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005624 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5625 if (effect->state() == EffectModule::ACTIVE ||
5626 effect->state() == EffectModule::STOPPING) {
5627 effect->start();
5628 }
Eric Laurent493941b2010-07-28 01:32:47 -07005629 // if the move request is not received from audio policy manager, the effect must be
5630 // re-registered with the new strategy and output
5631 if (dstChain == 0) {
5632 dstChain = effect->chain().promote();
5633 if (dstChain == 0) {
5634 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5635 srcThread->addEffect_l(effect);
5636 return NO_INIT;
5637 }
5638 strategy = dstChain->strategy();
5639 }
5640 if (reRegister) {
5641 AudioSystem::unregisterEffect(effect->id());
5642 AudioSystem::registerEffect(&effect->desc(),
5643 dstOutput,
5644 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005645 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005646 effect->id());
5647 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005648 effect = chain->getEffectFromId_l(0);
5649 }
5650
5651 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005652}
5653
Eric Laurent464d5b32011-06-17 21:29:58 -07005654
Eric Laurent65b65452010-06-01 23:49:17 -07005655// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005656sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005657 const sp<AudioFlinger::Client>& client,
5658 const sp<IEffectClient>& effectClient,
5659 int32_t priority,
5660 int sessionId,
5661 effect_descriptor_t *desc,
5662 int *enabled,
5663 status_t *status
5664 )
5665{
5666 sp<EffectModule> effect;
5667 sp<EffectHandle> handle;
5668 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005669 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005670 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005671 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005672 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005673
Eric Laurent464d5b32011-06-17 21:29:58 -07005674 lStatus = initCheck();
5675 if (lStatus != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07005676 LOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005677 goto Exit;
5678 }
5679
5680 // Do not allow effects with session ID 0 on direct output or duplicating threads
5681 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005682 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005683 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5684 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005685 lStatus = BAD_VALUE;
5686 goto Exit;
5687 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005688 // Only Pre processor effects are allowed on input threads and only on input threads
5689 if ((mType == RECORD &&
5690 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5691 (mType != RECORD &&
5692 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5693 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5694 desc->name, desc->flags, mType);
5695 lStatus = BAD_VALUE;
5696 goto Exit;
5697 }
Eric Laurent65b65452010-06-01 23:49:17 -07005698
Steve Block71f2cf12011-10-20 11:56:00 +01005699 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005700
5701 { // scope for mLock
5702 Mutex::Autolock _l(mLock);
5703
5704 // check for existing effect chain with the requested audio session
5705 chain = getEffectChain_l(sessionId);
5706 if (chain == 0) {
5707 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005708 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005709 chain = new EffectChain(this, sessionId);
5710 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005711 chain->setStrategy(getStrategyForSession_l(sessionId));
5712 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005713 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005714 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005715 }
5716
Steve Block71f2cf12011-10-20 11:56:00 +01005717 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005718
5719 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005720 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005721 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005722 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005723 if (lStatus != NO_ERROR) {
5724 goto Exit;
5725 }
5726 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005727 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005728 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005729 lStatus = effect->status();
5730 if (lStatus != NO_ERROR) {
5731 goto Exit;
5732 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005733 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005734 if (lStatus != NO_ERROR) {
5735 goto Exit;
5736 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005737 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005738
5739 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005740 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005741 }
5742 // create effect handle and connect it to effect module
5743 handle = new EffectHandle(effect, client, effectClient, priority);
5744 lStatus = effect->addHandle(handle);
5745 if (enabled) {
5746 *enabled = (int)effect->isEnabled();
5747 }
5748 }
5749
5750Exit:
5751 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005752 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005753 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005754 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005755 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005756 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005757 AudioSystem::unregisterEffect(effect->id());
5758 }
5759 if (chainCreated) {
5760 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005761 }
Eric Laurent65b65452010-06-01 23:49:17 -07005762 handle.clear();
5763 }
5764
5765 if(status) {
5766 *status = lStatus;
5767 }
5768 return handle;
5769}
5770
Eric Laurent464d5b32011-06-17 21:29:58 -07005771sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5772{
5773 sp<EffectModule> effect;
5774
5775 sp<EffectChain> chain = getEffectChain_l(sessionId);
5776 if (chain != 0) {
5777 effect = chain->getEffectFromId_l(effectId);
5778 }
5779 return effect;
5780}
5781
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005782// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5783// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005784status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005785{
5786 // check for existing effect chain with the requested audio session
5787 int sessionId = effect->sessionId();
5788 sp<EffectChain> chain = getEffectChain_l(sessionId);
5789 bool chainCreated = false;
5790
5791 if (chain == 0) {
5792 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005793 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005794 chain = new EffectChain(this, sessionId);
5795 addEffectChain_l(chain);
5796 chain->setStrategy(getStrategyForSession_l(sessionId));
5797 chainCreated = true;
5798 }
Steve Block71f2cf12011-10-20 11:56:00 +01005799 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005800
5801 if (chain->getEffectFromId_l(effect->id()) != 0) {
5802 LOGW("addEffect_l() %p effect %s already present in chain %p",
5803 this, effect->desc().name, chain.get());
5804 return BAD_VALUE;
5805 }
5806
5807 status_t status = chain->addEffect_l(effect);
5808 if (status != NO_ERROR) {
5809 if (chainCreated) {
5810 removeEffectChain_l(chain);
5811 }
5812 return status;
5813 }
5814
5815 effect->setDevice(mDevice);
5816 effect->setMode(mAudioFlinger->getMode());
5817 return NO_ERROR;
5818}
5819
Eric Laurent464d5b32011-06-17 21:29:58 -07005820void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005821
Steve Block71f2cf12011-10-20 11:56:00 +01005822 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005823 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005824 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5825 detachAuxEffect_l(effect->id());
5826 }
5827
5828 sp<EffectChain> chain = effect->chain().promote();
5829 if (chain != 0) {
5830 // remove effect chain if removing last effect
5831 if (chain->removeEffect_l(effect) == 0) {
5832 removeEffectChain_l(chain);
5833 }
5834 } else {
5835 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5836 }
5837}
5838
Eric Laurent464d5b32011-06-17 21:29:58 -07005839void AudioFlinger::ThreadBase::lockEffectChains_l(
5840 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5841{
5842 effectChains = mEffectChains;
5843 for (size_t i = 0; i < mEffectChains.size(); i++) {
5844 mEffectChains[i]->lock();
5845 }
5846}
5847
5848void AudioFlinger::ThreadBase::unlockEffectChains(
5849 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5850{
5851 for (size_t i = 0; i < effectChains.size(); i++) {
5852 effectChains[i]->unlock();
5853 }
5854}
5855
5856sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5857{
5858 Mutex::Autolock _l(mLock);
5859 return getEffectChain_l(sessionId);
5860}
5861
5862sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5863{
5864 sp<EffectChain> chain;
5865
5866 size_t size = mEffectChains.size();
5867 for (size_t i = 0; i < size; i++) {
5868 if (mEffectChains[i]->sessionId() == sessionId) {
5869 chain = mEffectChains[i];
5870 break;
5871 }
5872 }
5873 return chain;
5874}
5875
5876void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5877{
5878 Mutex::Autolock _l(mLock);
5879 size_t size = mEffectChains.size();
5880 for (size_t i = 0; i < size; i++) {
5881 mEffectChains[i]->setMode_l(mode);
5882 }
5883}
5884
5885void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005886 const wp<EffectHandle>& handle,
5887 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005888
Eric Laurent53334cd2010-06-23 17:38:20 -07005889 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01005890 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005891 // delete the effect module if removing last handle on it
5892 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005893 if (!effect->isPinned() || unpiniflast) {
5894 removeEffect_l(effect);
5895 AudioSystem::unregisterEffect(effect->id());
5896 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005897 }
5898}
5899
Eric Laurent65b65452010-06-01 23:49:17 -07005900status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5901{
5902 int session = chain->sessionId();
5903 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005904 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005905
Steve Block71f2cf12011-10-20 11:56:00 +01005906 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005907 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005908 // Only one effect chain can be present in direct output thread and it uses
5909 // the mix buffer as input
5910 if (mType != DIRECT) {
5911 size_t numSamples = mFrameCount * mChannelCount;
5912 buffer = new int16_t[numSamples];
5913 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01005914 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005915 ownsBuffer = true;
5916 }
Eric Laurent65b65452010-06-01 23:49:17 -07005917
Eric Laurent53334cd2010-06-23 17:38:20 -07005918 // Attach all tracks with same session ID to this chain.
5919 for (size_t i = 0; i < mTracks.size(); ++i) {
5920 sp<Track> track = mTracks[i];
5921 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005922 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07005923 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005924 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005925 }
5926 }
5927
5928 // indicate all active tracks in the chain
5929 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5930 sp<Track> track = mActiveTracks[i].promote();
5931 if (track == 0) continue;
5932 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005933 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005934 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005935 }
Eric Laurent65b65452010-06-01 23:49:17 -07005936 }
5937 }
5938
Eric Laurent53334cd2010-06-23 17:38:20 -07005939 chain->setInBuffer(buffer, ownsBuffer);
5940 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005941 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005942 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005943 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5944 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005945 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005946 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5947 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005948 // Effect chain for other sessions are inserted at beginning of effect
5949 // chains list to be processed before output mix effects. Relative order between other
5950 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005951 size_t size = mEffectChains.size();
5952 size_t i = 0;
5953 for (i = 0; i < size; i++) {
5954 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005955 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005956 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005957 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005958
5959 return NO_ERROR;
5960}
5961
5962size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5963{
5964 int session = chain->sessionId();
5965
Steve Block71f2cf12011-10-20 11:56:00 +01005966 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005967
5968 for (size_t i = 0; i < mEffectChains.size(); i++) {
5969 if (chain == mEffectChains[i]) {
5970 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005971 // detach all active tracks from the chain
5972 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5973 sp<Track> track = mActiveTracks[i].promote();
5974 if (track == 0) continue;
5975 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005976 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07005977 chain.get(), session);
5978 chain->decActiveTrackCnt();
5979 }
5980 }
5981
Eric Laurent65b65452010-06-01 23:49:17 -07005982 // detach all tracks with same session ID from this chain
5983 for (size_t i = 0; i < mTracks.size(); ++i) {
5984 sp<Track> track = mTracks[i];
5985 if (session == track->sessionId()) {
5986 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005987 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005988 }
5989 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005990 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005991 }
5992 }
5993 return mEffectChains.size();
5994}
5995
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005996status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5997 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005998{
5999 Mutex::Autolock _l(mLock);
6000 return attachAuxEffect_l(track, EffectId);
6001}
6002
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006003status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6004 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006005{
6006 status_t status = NO_ERROR;
6007
6008 if (EffectId == 0) {
6009 track->setAuxBuffer(0, NULL);
6010 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006011 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6012 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006013 if (effect != 0) {
6014 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6015 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6016 } else {
6017 status = INVALID_OPERATION;
6018 }
6019 } else {
6020 status = BAD_VALUE;
6021 }
6022 }
6023 return status;
6024}
6025
6026void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6027{
6028 for (size_t i = 0; i < mTracks.size(); ++i) {
6029 sp<Track> track = mTracks[i];
6030 if (track->auxEffectId() == effectId) {
6031 attachAuxEffect_l(track, 0);
6032 }
6033 }
6034}
6035
Eric Laurent464d5b32011-06-17 21:29:58 -07006036status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6037{
6038 // only one chain per input thread
6039 if (mEffectChains.size() != 0) {
6040 return INVALID_OPERATION;
6041 }
Steve Block71f2cf12011-10-20 11:56:00 +01006042 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006043
6044 chain->setInBuffer(NULL);
6045 chain->setOutBuffer(NULL);
6046
Eric Laurentf82fccd2011-07-27 19:49:51 -07006047 checkSuspendOnAddEffectChain_l(chain);
6048
Eric Laurent464d5b32011-06-17 21:29:58 -07006049 mEffectChains.add(chain);
6050
6051 return NO_ERROR;
6052}
6053
6054size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6055{
Steve Block71f2cf12011-10-20 11:56:00 +01006056 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006057 LOGW_IF(mEffectChains.size() != 1,
6058 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6059 chain.get(), mEffectChains.size(), this);
6060 if (mEffectChains.size() == 1) {
6061 mEffectChains.removeAt(0);
6062 }
6063 return 0;
6064}
6065
Eric Laurent65b65452010-06-01 23:49:17 -07006066// ----------------------------------------------------------------------------
6067// EffectModule implementation
6068// ----------------------------------------------------------------------------
6069
6070#undef LOG_TAG
6071#define LOG_TAG "AudioFlinger::EffectModule"
6072
6073AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6074 const wp<AudioFlinger::EffectChain>& chain,
6075 effect_descriptor_t *desc,
6076 int id,
6077 int sessionId)
6078 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006079 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006080{
Steve Block71f2cf12011-10-20 11:56:00 +01006081 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006082 int lStatus;
6083 sp<ThreadBase> thread = mThread.promote();
6084 if (thread == 0) {
6085 return;
6086 }
Eric Laurent65b65452010-06-01 23:49:17 -07006087
6088 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6089
6090 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006091 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006092
Eric Laurent65b65452010-06-01 23:49:17 -07006093 if (mStatus != NO_ERROR) {
6094 return;
6095 }
6096 lStatus = init();
6097 if (lStatus < 0) {
6098 mStatus = lStatus;
6099 goto Error;
6100 }
6101
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006102 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6103 mPinned = true;
6104 }
Steve Block71f2cf12011-10-20 11:56:00 +01006105 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006106 return;
6107Error:
6108 EffectRelease(mEffectInterface);
6109 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006110 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006111}
6112
6113AudioFlinger::EffectModule::~EffectModule()
6114{
Steve Block71f2cf12011-10-20 11:56:00 +01006115 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006116 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006117 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6118 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6119 sp<ThreadBase> thread = mThread.promote();
6120 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006121 audio_stream_t *stream = thread->stream();
6122 if (stream != NULL) {
6123 stream->remove_audio_effect(stream, mEffectInterface);
6124 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006125 }
6126 }
Eric Laurent65b65452010-06-01 23:49:17 -07006127 // release effect engine
6128 EffectRelease(mEffectInterface);
6129 }
6130}
6131
6132status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6133{
6134 status_t status;
6135
6136 Mutex::Autolock _l(mLock);
6137 // First handle in mHandles has highest priority and controls the effect module
6138 int priority = handle->priority();
6139 size_t size = mHandles.size();
6140 sp<EffectHandle> h;
6141 size_t i;
6142 for (i = 0; i < size; i++) {
6143 h = mHandles[i].promote();
6144 if (h == 0) continue;
6145 if (h->priority() <= priority) break;
6146 }
6147 // if inserted in first place, move effect control from previous owner to this handle
6148 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006149 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006150 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006151 enabled = h->enabled();
6152 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006153 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006154 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006155 status = NO_ERROR;
6156 } else {
6157 status = ALREADY_EXISTS;
6158 }
Steve Block71f2cf12011-10-20 11:56:00 +01006159 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006160 mHandles.insertAt(handle, i);
6161 return status;
6162}
6163
6164size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6165{
6166 Mutex::Autolock _l(mLock);
6167 size_t size = mHandles.size();
6168 size_t i;
6169 for (i = 0; i < size; i++) {
6170 if (mHandles[i] == handle) break;
6171 }
6172 if (i == size) {
6173 return size;
6174 }
Steve Block71f2cf12011-10-20 11:56:00 +01006175 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006176
6177 bool enabled = false;
6178 EffectHandle *hdl = handle.unsafe_get();
6179 if (hdl) {
Steve Block71f2cf12011-10-20 11:56:00 +01006180 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006181 enabled = hdl->enabled();
6182 }
Eric Laurent65b65452010-06-01 23:49:17 -07006183 mHandles.removeAt(i);
6184 size = mHandles.size();
6185 // if removed from first place, move effect control from this handle to next in line
6186 if (i == 0 && size != 0) {
6187 sp<EffectHandle> h = mHandles[0].promote();
6188 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006189 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006190 }
6191 }
6192
Eric Laurent21b5c472011-07-26 20:54:46 -07006193 // Prevent calls to process() and other functions on effect interface from now on.
6194 // The effect engine will be released by the destructor when the last strong reference on
6195 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006196 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006197 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006198 }
6199
Eric Laurent65b65452010-06-01 23:49:17 -07006200 return size;
6201}
6202
Eric Laurentf82fccd2011-07-27 19:49:51 -07006203sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6204{
6205 Mutex::Autolock _l(mLock);
6206 sp<EffectHandle> handle;
6207 if (mHandles.size() != 0) {
6208 handle = mHandles[0].promote();
6209 }
6210 return handle;
6211}
6212
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006213void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006214{
Steve Block71f2cf12011-10-20 11:56:00 +01006215 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006216 // keep a strong reference on this EffectModule to avoid calling the
6217 // destructor before we exit
6218 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006219 {
6220 sp<ThreadBase> thread = mThread.promote();
6221 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006222 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006223 }
6224 }
6225}
6226
Eric Laurent7d850f22010-07-09 13:34:17 -07006227void AudioFlinger::EffectModule::updateState() {
6228 Mutex::Autolock _l(mLock);
6229
6230 switch (mState) {
6231 case RESTART:
6232 reset_l();
6233 // FALL THROUGH
6234
6235 case STARTING:
6236 // clear auxiliary effect input buffer for next accumulation
6237 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6238 memset(mConfig.inputCfg.buffer.raw,
6239 0,
6240 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6241 }
6242 start_l();
6243 mState = ACTIVE;
6244 break;
6245 case STOPPING:
6246 stop_l();
6247 mDisableWaitCnt = mMaxDisableWaitCnt;
6248 mState = STOPPED;
6249 break;
6250 case STOPPED:
6251 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6252 // turn off sequence.
6253 if (--mDisableWaitCnt == 0) {
6254 reset_l();
6255 mState = IDLE;
6256 }
6257 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006258 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006259 break;
6260 }
6261}
6262
Eric Laurent65b65452010-06-01 23:49:17 -07006263void AudioFlinger::EffectModule::process()
6264{
6265 Mutex::Autolock _l(mLock);
6266
Eric Laurent21b5c472011-07-26 20:54:46 -07006267 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006268 mConfig.inputCfg.buffer.raw == NULL ||
6269 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006270 return;
6271 }
6272
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006273 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006274 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6275 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6276 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6277 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006278 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006279 }
6280
Eric Laurent65b65452010-06-01 23:49:17 -07006281 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006282 int ret = (*mEffectInterface)->process(mEffectInterface,
6283 &mConfig.inputCfg.buffer,
6284 &mConfig.outputCfg.buffer);
6285
6286 // force transition to IDLE state when engine is ready
6287 if (mState == STOPPED && ret == -ENODATA) {
6288 mDisableWaitCnt = 1;
6289 }
Eric Laurent65b65452010-06-01 23:49:17 -07006290
6291 // clear auxiliary effect input buffer for next accumulation
6292 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006293 memset(mConfig.inputCfg.buffer.raw, 0,
6294 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006295 }
6296 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006297 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6298 // If an insert effect is idle and input buffer is different from output buffer,
6299 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006300 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006301 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006302 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6303 int16_t *in = mConfig.inputCfg.buffer.s16;
6304 int16_t *out = mConfig.outputCfg.buffer.s16;
6305 for (size_t i = 0; i < frameCnt; i++) {
6306 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006307 }
Eric Laurent65b65452010-06-01 23:49:17 -07006308 }
6309 }
6310}
6311
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006312void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006313{
6314 if (mEffectInterface == NULL) {
6315 return;
6316 }
6317 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6318}
6319
6320status_t AudioFlinger::EffectModule::configure()
6321{
6322 uint32_t channels;
6323 if (mEffectInterface == NULL) {
6324 return NO_INIT;
6325 }
6326
6327 sp<ThreadBase> thread = mThread.promote();
6328 if (thread == 0) {
6329 return DEAD_OBJECT;
6330 }
6331
6332 // TODO: handle configuration of effects replacing track process
6333 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006334 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006335 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006336 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006337 }
6338
6339 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006340 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006341 } else {
6342 mConfig.inputCfg.channels = channels;
6343 }
6344 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006345 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6346 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006347 mConfig.inputCfg.samplingRate = thread->sampleRate();
6348 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6349 mConfig.inputCfg.bufferProvider.cookie = NULL;
6350 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6351 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6352 mConfig.outputCfg.bufferProvider.cookie = NULL;
6353 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6354 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6355 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6356 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006357 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006358 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006359 // - in other sessions:
6360 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6361 // other effect: overwrites output buffer: input buffer == output buffer
6362 // Auxiliary effect:
6363 // accumulates in output buffer: input buffer != output buffer
6364 // Therefore: accumulate <=> input buffer != output buffer
6365 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6366 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6367 } else {
6368 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6369 }
6370 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6371 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6372 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6373 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6374
Steve Block71f2cf12011-10-20 11:56:00 +01006375 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006376 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6377
Eric Laurent65b65452010-06-01 23:49:17 -07006378 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006379 uint32_t size = sizeof(int);
6380 status_t status = (*mEffectInterface)->command(mEffectInterface,
6381 EFFECT_CMD_CONFIGURE,
6382 sizeof(effect_config_t),
6383 &mConfig,
6384 &size,
6385 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006386 if (status == 0) {
6387 status = cmdStatus;
6388 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006389
6390 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6391 (1000 * mConfig.outputCfg.buffer.frameCount);
6392
Eric Laurent65b65452010-06-01 23:49:17 -07006393 return status;
6394}
6395
6396status_t AudioFlinger::EffectModule::init()
6397{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006398 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006399 if (mEffectInterface == NULL) {
6400 return NO_INIT;
6401 }
6402 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006403 uint32_t size = sizeof(status_t);
6404 status_t status = (*mEffectInterface)->command(mEffectInterface,
6405 EFFECT_CMD_INIT,
6406 0,
6407 NULL,
6408 &size,
6409 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006410 if (status == 0) {
6411 status = cmdStatus;
6412 }
6413 return status;
6414}
6415
Eric Laurent6fccbd02011-10-05 17:42:25 -07006416status_t AudioFlinger::EffectModule::start()
6417{
6418 Mutex::Autolock _l(mLock);
6419 return start_l();
6420}
6421
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006422status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006423{
6424 if (mEffectInterface == NULL) {
6425 return NO_INIT;
6426 }
6427 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006428 uint32_t size = sizeof(status_t);
6429 status_t status = (*mEffectInterface)->command(mEffectInterface,
6430 EFFECT_CMD_ENABLE,
6431 0,
6432 NULL,
6433 &size,
6434 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006435 if (status == 0) {
6436 status = cmdStatus;
6437 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006438 if (status == 0 &&
6439 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6440 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6441 sp<ThreadBase> thread = mThread.promote();
6442 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006443 audio_stream_t *stream = thread->stream();
6444 if (stream != NULL) {
6445 stream->add_audio_effect(stream, mEffectInterface);
6446 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006447 }
6448 }
Eric Laurent65b65452010-06-01 23:49:17 -07006449 return status;
6450}
6451
Eric Laurent21b5c472011-07-26 20:54:46 -07006452status_t AudioFlinger::EffectModule::stop()
6453{
6454 Mutex::Autolock _l(mLock);
6455 return stop_l();
6456}
6457
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006458status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006459{
6460 if (mEffectInterface == NULL) {
6461 return NO_INIT;
6462 }
6463 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006464 uint32_t size = sizeof(status_t);
6465 status_t status = (*mEffectInterface)->command(mEffectInterface,
6466 EFFECT_CMD_DISABLE,
6467 0,
6468 NULL,
6469 &size,
6470 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006471 if (status == 0) {
6472 status = cmdStatus;
6473 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006474 if (status == 0 &&
6475 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6476 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6477 sp<ThreadBase> thread = mThread.promote();
6478 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006479 audio_stream_t *stream = thread->stream();
6480 if (stream != NULL) {
6481 stream->remove_audio_effect(stream, mEffectInterface);
6482 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006483 }
6484 }
Eric Laurent65b65452010-06-01 23:49:17 -07006485 return status;
6486}
6487
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006488status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6489 uint32_t cmdSize,
6490 void *pCmdData,
6491 uint32_t *replySize,
6492 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006493{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006494 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006495// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006496
Eric Laurent21b5c472011-07-26 20:54:46 -07006497 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006498 return NO_INIT;
6499 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006500 status_t status = (*mEffectInterface)->command(mEffectInterface,
6501 cmdCode,
6502 cmdSize,
6503 pCmdData,
6504 replySize,
6505 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006506 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006507 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006508 for (size_t i = 1; i < mHandles.size(); i++) {
6509 sp<EffectHandle> h = mHandles[i].promote();
6510 if (h != 0) {
6511 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6512 }
6513 }
6514 }
6515 return status;
6516}
6517
6518status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6519{
Eric Laurent6752ec82011-08-10 10:37:50 -07006520
Eric Laurent65b65452010-06-01 23:49:17 -07006521 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006522 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006523
6524 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006525 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6526 if (enabled && status != NO_ERROR) {
6527 return status;
6528 }
6529
Eric Laurent65b65452010-06-01 23:49:17 -07006530 switch (mState) {
6531 // going from disabled to enabled
6532 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006533 mState = STARTING;
6534 break;
6535 case STOPPED:
6536 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006537 break;
6538 case STOPPING:
6539 mState = ACTIVE;
6540 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006541
6542 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006543 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006544 mState = STOPPED;
6545 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006546 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006547 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006548 break;
6549 case ACTIVE:
6550 mState = STOPPING;
6551 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006552 case DESTROYED:
6553 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006554 }
6555 for (size_t i = 1; i < mHandles.size(); i++) {
6556 sp<EffectHandle> h = mHandles[i].promote();
6557 if (h != 0) {
6558 h->setEnabled(enabled);
6559 }
6560 }
6561 }
6562 return NO_ERROR;
6563}
6564
6565bool AudioFlinger::EffectModule::isEnabled()
6566{
6567 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006568 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006569 case STARTING:
6570 case ACTIVE:
6571 return true;
6572 case IDLE:
6573 case STOPPING:
6574 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006575 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006576 default:
6577 return false;
6578 }
6579}
6580
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006581bool AudioFlinger::EffectModule::isProcessEnabled()
6582{
6583 switch (mState) {
6584 case RESTART:
6585 case ACTIVE:
6586 case STOPPING:
6587 case STOPPED:
6588 return true;
6589 case IDLE:
6590 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006591 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006592 default:
6593 return false;
6594 }
6595}
6596
Eric Laurent65b65452010-06-01 23:49:17 -07006597status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6598{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006599 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006600 status_t status = NO_ERROR;
6601
6602 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6603 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006604 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006605 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6606 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006607 status_t cmdStatus;
6608 uint32_t volume[2];
6609 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006610 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006611 volume[0] = *left;
6612 volume[1] = *right;
6613 if (controller) {
6614 pVolume = volume;
6615 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006616 status = (*mEffectInterface)->command(mEffectInterface,
6617 EFFECT_CMD_SET_VOLUME,
6618 size,
6619 volume,
6620 &size,
6621 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006622 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6623 *left = volume[0];
6624 *right = volume[1];
6625 }
6626 }
6627 return status;
6628}
6629
6630status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6631{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006632 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006633 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006634 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6635 // audio pre processing modules on RecordThread can receive both output and
6636 // input device indication in the same call
6637 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6638 if (dev) {
6639 status_t cmdStatus;
6640 uint32_t size = sizeof(status_t);
6641
6642 status = (*mEffectInterface)->command(mEffectInterface,
6643 EFFECT_CMD_SET_DEVICE,
6644 sizeof(uint32_t),
6645 &dev,
6646 &size,
6647 &cmdStatus);
6648 if (status == NO_ERROR) {
6649 status = cmdStatus;
6650 }
6651 }
6652 dev = device & AUDIO_DEVICE_IN_ALL;
6653 if (dev) {
6654 status_t cmdStatus;
6655 uint32_t size = sizeof(status_t);
6656
6657 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6658 EFFECT_CMD_SET_INPUT_DEVICE,
6659 sizeof(uint32_t),
6660 &dev,
6661 &size,
6662 &cmdStatus);
6663 if (status2 == NO_ERROR) {
6664 status2 = cmdStatus;
6665 }
6666 if (status == NO_ERROR) {
6667 status = status2;
6668 }
Eric Laurent65b65452010-06-01 23:49:17 -07006669 }
6670 }
6671 return status;
6672}
6673
Eric Laurent53334cd2010-06-23 17:38:20 -07006674status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6675{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006676 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006677 status_t status = NO_ERROR;
6678 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006679 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006680 uint32_t size = sizeof(status_t);
6681 status = (*mEffectInterface)->command(mEffectInterface,
6682 EFFECT_CMD_SET_AUDIO_MODE,
6683 sizeof(int),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006684 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006685 &size,
6686 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006687 if (status == NO_ERROR) {
6688 status = cmdStatus;
6689 }
6690 }
6691 return status;
6692}
6693
Eric Laurentf82fccd2011-07-27 19:49:51 -07006694void AudioFlinger::EffectModule::setSuspended(bool suspended)
6695{
6696 Mutex::Autolock _l(mLock);
6697 mSuspended = suspended;
6698}
6699bool AudioFlinger::EffectModule::suspended()
6700{
6701 Mutex::Autolock _l(mLock);
6702 return mSuspended;
6703}
6704
Eric Laurent65b65452010-06-01 23:49:17 -07006705status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6706{
6707 const size_t SIZE = 256;
6708 char buffer[SIZE];
6709 String8 result;
6710
6711 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6712 result.append(buffer);
6713
6714 bool locked = tryLock(mLock);
6715 // failed to lock - AudioFlinger is probably deadlocked
6716 if (!locked) {
6717 result.append("\t\tCould not lock Fx mutex:\n");
6718 }
6719
6720 result.append("\t\tSession Status State Engine:\n");
6721 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6722 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6723 result.append(buffer);
6724
6725 result.append("\t\tDescriptor:\n");
6726 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6727 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6728 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6729 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6730 result.append(buffer);
6731 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6732 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6733 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6734 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6735 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006736 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006737 mDescriptor.apiVersion,
6738 mDescriptor.flags);
6739 result.append(buffer);
6740 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6741 mDescriptor.name);
6742 result.append(buffer);
6743 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6744 mDescriptor.implementor);
6745 result.append(buffer);
6746
6747 result.append("\t\t- Input configuration:\n");
6748 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6749 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6750 (uint32_t)mConfig.inputCfg.buffer.raw,
6751 mConfig.inputCfg.buffer.frameCount,
6752 mConfig.inputCfg.samplingRate,
6753 mConfig.inputCfg.channels,
6754 mConfig.inputCfg.format);
6755 result.append(buffer);
6756
6757 result.append("\t\t- Output configuration:\n");
6758 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6759 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6760 (uint32_t)mConfig.outputCfg.buffer.raw,
6761 mConfig.outputCfg.buffer.frameCount,
6762 mConfig.outputCfg.samplingRate,
6763 mConfig.outputCfg.channels,
6764 mConfig.outputCfg.format);
6765 result.append(buffer);
6766
6767 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6768 result.append(buffer);
6769 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6770 for (size_t i = 0; i < mHandles.size(); ++i) {
6771 sp<EffectHandle> handle = mHandles[i].promote();
6772 if (handle != 0) {
6773 handle->dump(buffer, SIZE);
6774 result.append(buffer);
6775 }
6776 }
6777
6778 result.append("\n");
6779
6780 write(fd, result.string(), result.length());
6781
6782 if (locked) {
6783 mLock.unlock();
6784 }
6785
6786 return NO_ERROR;
6787}
6788
6789// ----------------------------------------------------------------------------
6790// EffectHandle implementation
6791// ----------------------------------------------------------------------------
6792
6793#undef LOG_TAG
6794#define LOG_TAG "AudioFlinger::EffectHandle"
6795
6796AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6797 const sp<AudioFlinger::Client>& client,
6798 const sp<IEffectClient>& effectClient,
6799 int32_t priority)
6800 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006801 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006802 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006803{
Steve Block71f2cf12011-10-20 11:56:00 +01006804 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006805
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006806 if (client == 0) {
6807 return;
6808 }
Eric Laurent65b65452010-06-01 23:49:17 -07006809 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6810 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6811 if (mCblkMemory != 0) {
6812 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6813
6814 if (mCblk) {
6815 new(mCblk) effect_param_cblk_t();
6816 mBuffer = (uint8_t *)mCblk + bufOffset;
6817 }
6818 } else {
6819 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6820 return;
6821 }
6822}
6823
6824AudioFlinger::EffectHandle::~EffectHandle()
6825{
Steve Block71f2cf12011-10-20 11:56:00 +01006826 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006827 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01006828 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006829}
6830
6831status_t AudioFlinger::EffectHandle::enable()
6832{
Steve Block71f2cf12011-10-20 11:56:00 +01006833 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006834 if (!mHasControl) return INVALID_OPERATION;
6835 if (mEffect == 0) return DEAD_OBJECT;
6836
Eric Laurent6752ec82011-08-10 10:37:50 -07006837 if (mEnabled) {
6838 return NO_ERROR;
6839 }
6840
Eric Laurentf82fccd2011-07-27 19:49:51 -07006841 mEnabled = true;
6842
6843 sp<ThreadBase> thread = mEffect->thread().promote();
6844 if (thread != 0) {
6845 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6846 }
6847
6848 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6849 if (mEffect->suspended()) {
6850 return NO_ERROR;
6851 }
6852
Eric Laurent6752ec82011-08-10 10:37:50 -07006853 status_t status = mEffect->setEnabled(true);
6854 if (status != NO_ERROR) {
6855 if (thread != 0) {
6856 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6857 }
6858 mEnabled = false;
6859 }
6860 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006861}
6862
6863status_t AudioFlinger::EffectHandle::disable()
6864{
Steve Block71f2cf12011-10-20 11:56:00 +01006865 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006866 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006867 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006868
Eric Laurent6752ec82011-08-10 10:37:50 -07006869 if (!mEnabled) {
6870 return NO_ERROR;
6871 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006872 mEnabled = false;
6873
6874 if (mEffect->suspended()) {
6875 return NO_ERROR;
6876 }
6877
6878 status_t status = mEffect->setEnabled(false);
6879
6880 sp<ThreadBase> thread = mEffect->thread().promote();
6881 if (thread != 0) {
6882 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6883 }
6884
6885 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006886}
6887
6888void AudioFlinger::EffectHandle::disconnect()
6889{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006890 disconnect(true);
6891}
6892
6893void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6894{
Steve Block71f2cf12011-10-20 11:56:00 +01006895 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006896 if (mEffect == 0) {
6897 return;
6898 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006899 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006900
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006901 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006902 sp<ThreadBase> thread = mEffect->thread().promote();
6903 if (thread != 0) {
6904 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6905 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006906 }
6907
Eric Laurent65b65452010-06-01 23:49:17 -07006908 // release sp on module => module destructor can be called now
6909 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006910 if (mClient != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006911 if (mCblk) {
6912 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6913 }
6914 mCblkMemory.clear(); // and free the shared memory
Eric Laurent65b65452010-06-01 23:49:17 -07006915 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6916 mClient.clear();
6917 }
6918}
6919
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006920status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6921 uint32_t cmdSize,
6922 void *pCmdData,
6923 uint32_t *replySize,
6924 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006925{
Steve Block71f2cf12011-10-20 11:56:00 +01006926// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006927// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006928
6929 // only get parameter command is permitted for applications not controlling the effect
6930 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6931 return INVALID_OPERATION;
6932 }
6933 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006934 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006935
6936 // handle commands that are not forwarded transparently to effect engine
6937 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6938 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6939 // no risk to block the whole media server process or mixer threads is we are stuck here
6940 Mutex::Autolock _l(mCblk->lock);
6941 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6942 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6943 mCblk->serverIndex = 0;
6944 mCblk->clientIndex = 0;
6945 return BAD_VALUE;
6946 }
6947 status_t status = NO_ERROR;
6948 while (mCblk->serverIndex < mCblk->clientIndex) {
6949 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006950 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006951 int *p = (int *)(mBuffer + mCblk->serverIndex);
6952 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006953 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6954 LOGW("command(): invalid parameter block size");
6955 break;
6956 }
Eric Laurent65b65452010-06-01 23:49:17 -07006957 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006958 if (param->psize == 0 || param->vsize == 0) {
6959 LOGW("command(): null parameter or value size");
6960 mCblk->serverIndex += size;
6961 continue;
6962 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006963 uint32_t psize = sizeof(effect_param_t) +
6964 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6965 param->vsize;
6966 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6967 psize,
6968 p,
6969 &rsize,
6970 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006971 // stop at first error encountered
6972 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006973 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006974 *(int *)pReplyData = reply;
6975 break;
6976 } else if (reply != NO_ERROR) {
6977 *(int *)pReplyData = reply;
6978 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006979 }
6980 mCblk->serverIndex += size;
6981 }
6982 mCblk->serverIndex = 0;
6983 mCblk->clientIndex = 0;
6984 return status;
6985 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006986 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006987 return enable();
6988 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006989 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006990 return disable();
6991 }
6992
6993 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6994}
6995
6996sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6997 return mCblkMemory;
6998}
6999
Eric Laurentf82fccd2011-07-27 19:49:51 -07007000void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07007001{
Steve Block71f2cf12011-10-20 11:56:00 +01007002 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07007003
7004 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007005 mEnabled = enabled;
7006
Eric Laurent65b65452010-06-01 23:49:17 -07007007 if (signal && mEffectClient != 0) {
7008 mEffectClient->controlStatusChanged(hasControl);
7009 }
7010}
7011
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007012void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7013 uint32_t cmdSize,
7014 void *pCmdData,
7015 uint32_t replySize,
7016 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007017{
7018 if (mEffectClient != 0) {
7019 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7020 }
7021}
7022
7023
7024
7025void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7026{
7027 if (mEffectClient != 0) {
7028 mEffectClient->enableStatusChanged(enabled);
7029 }
7030}
7031
7032status_t AudioFlinger::EffectHandle::onTransact(
7033 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7034{
7035 return BnEffect::onTransact(code, data, reply, flags);
7036}
7037
7038
7039void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7040{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007041 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Eric Laurent65b65452010-06-01 23:49:17 -07007042
7043 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7044 (mClient == NULL) ? getpid() : mClient->pid(),
7045 mPriority,
7046 mHasControl,
7047 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007048 mCblk ? mCblk->clientIndex : 0,
7049 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007050 );
7051
7052 if (locked) {
7053 mCblk->lock.unlock();
7054 }
7055}
7056
7057#undef LOG_TAG
7058#define LOG_TAG "AudioFlinger::EffectChain"
7059
7060AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7061 int sessionId)
Eric Laurentf9c361d2011-11-11 15:42:52 -08007062 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007063 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7064 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007065{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007066 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007067 sp<ThreadBase> thread = mThread.promote();
7068 if (thread == 0) {
7069 return;
7070 }
7071 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7072 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007073}
7074
7075AudioFlinger::EffectChain::~EffectChain()
7076{
7077 if (mOwnInBuffer) {
7078 delete mInBuffer;
7079 }
7080
7081}
7082
Eric Laurentf82fccd2011-07-27 19:49:51 -07007083// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007084sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007085{
7086 sp<EffectModule> effect;
7087 size_t size = mEffects.size();
7088
7089 for (size_t i = 0; i < size; i++) {
7090 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7091 effect = mEffects[i];
7092 break;
7093 }
7094 }
7095 return effect;
7096}
7097
Eric Laurentf82fccd2011-07-27 19:49:51 -07007098// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007099sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007100{
7101 sp<EffectModule> effect;
7102 size_t size = mEffects.size();
7103
7104 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007105 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7106 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07007107 effect = mEffects[i];
7108 break;
7109 }
7110 }
7111 return effect;
7112}
7113
Eric Laurentf82fccd2011-07-27 19:49:51 -07007114// getEffectFromType_l() must be called with ThreadBase::mLock held
7115sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7116 const effect_uuid_t *type)
7117{
7118 sp<EffectModule> effect;
7119 size_t size = mEffects.size();
7120
7121 for (size_t i = 0; i < size; i++) {
7122 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7123 effect = mEffects[i];
7124 break;
7125 }
7126 }
7127 return effect;
7128}
7129
Eric Laurent65b65452010-06-01 23:49:17 -07007130// Must be called with EffectChain::mLock locked
7131void AudioFlinger::EffectChain::process_l()
7132{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007133 sp<ThreadBase> thread = mThread.promote();
7134 if (thread == 0) {
7135 LOGW("process_l(): cannot promote mixer thread");
7136 return;
7137 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007138 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7139 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007140 // always process effects unless no more tracks are on the session and the effect tail
7141 // has been rendered
7142 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007143 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007144 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007145
Eric Laurentf9c361d2011-11-11 15:42:52 -08007146 if (!tracksOnSession && mTailBufferCount == 0) {
7147 doProcess = false;
7148 }
7149
7150 if (activeTrackCnt() == 0) {
7151 // if no track is active and the effect tail has not been rendered,
7152 // the input buffer must be cleared here as the mixer process will not do it
7153 if (tracksOnSession || mTailBufferCount > 0) {
7154 size_t numSamples = thread->frameCount() * thread->channelCount();
7155 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7156 if (mTailBufferCount > 0) {
7157 mTailBufferCount--;
7158 }
7159 }
7160 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007161 }
7162
Eric Laurent65b65452010-06-01 23:49:17 -07007163 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007164 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007165 for (size_t i = 0; i < size; i++) {
7166 mEffects[i]->process();
7167 }
Eric Laurent65b65452010-06-01 23:49:17 -07007168 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007169 for (size_t i = 0; i < size; i++) {
7170 mEffects[i]->updateState();
7171 }
Eric Laurent65b65452010-06-01 23:49:17 -07007172}
7173
Eric Laurent76c40f72010-07-15 12:50:15 -07007174// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007175status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007176{
7177 effect_descriptor_t desc = effect->desc();
7178 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7179
7180 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007181 effect->setChain(this);
7182 sp<ThreadBase> thread = mThread.promote();
7183 if (thread == 0) {
7184 return NO_INIT;
7185 }
7186 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007187
7188 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7189 // Auxiliary effects are inserted at the beginning of mEffects vector as
7190 // they are processed first and accumulated in chain input buffer
7191 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007192
Eric Laurent65b65452010-06-01 23:49:17 -07007193 // the input buffer for auxiliary effect contains mono samples in
7194 // 32 bit format. This is to avoid saturation in AudoMixer
7195 // accumulation stage. Saturation is done in EffectModule::process() before
7196 // calling the process in effect engine
7197 size_t numSamples = thread->frameCount();
7198 int32_t *buffer = new int32_t[numSamples];
7199 memset(buffer, 0, numSamples * sizeof(int32_t));
7200 effect->setInBuffer((int16_t *)buffer);
7201 // auxiliary effects output samples to chain input buffer for further processing
7202 // by insert effects
7203 effect->setOutBuffer(mInBuffer);
7204 } else {
7205 // Insert effects are inserted at the end of mEffects vector as they are processed
7206 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007207 // Insert effect order as a function of indicated preference:
7208 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7209 // another effect is present
7210 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7211 // last effect claiming first position
7212 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7213 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007214 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007215 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7216 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007217
7218 int size = (int)mEffects.size();
7219 int idx_insert = size;
7220 int idx_insert_first = -1;
7221 int idx_insert_last = -1;
7222
7223 for (int i = 0; i < size; i++) {
7224 effect_descriptor_t d = mEffects[i]->desc();
7225 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7226 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7227 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7228 // check invalid effect chaining combinations
7229 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007230 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007231 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007232 return INVALID_OPERATION;
7233 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007234 // remember position of first insert effect and by default
7235 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007236 if (idx_insert == size) {
7237 idx_insert = i;
7238 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007239 // remember position of last insert effect claiming
7240 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007241 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7242 idx_insert_first = i;
7243 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007244 // remember position of first insert effect claiming
7245 // last position
7246 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7247 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007248 idx_insert_last = i;
7249 }
7250 }
7251 }
7252
Eric Laurent53334cd2010-06-23 17:38:20 -07007253 // modify idx_insert from first position if needed
7254 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7255 if (idx_insert_last != -1) {
7256 idx_insert = idx_insert_last;
7257 } else {
7258 idx_insert = size;
7259 }
7260 } else {
7261 if (idx_insert_first != -1) {
7262 idx_insert = idx_insert_first + 1;
7263 }
Eric Laurent65b65452010-06-01 23:49:17 -07007264 }
7265
7266 // always read samples from chain input buffer
7267 effect->setInBuffer(mInBuffer);
7268
7269 // if last effect in the chain, output samples to chain
7270 // output buffer, otherwise to chain input buffer
7271 if (idx_insert == size) {
7272 if (idx_insert != 0) {
7273 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7274 mEffects[idx_insert-1]->configure();
7275 }
7276 effect->setOutBuffer(mOutBuffer);
7277 } else {
7278 effect->setOutBuffer(mInBuffer);
7279 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007280 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007281
Steve Block71f2cf12011-10-20 11:56:00 +01007282 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007283 }
7284 effect->configure();
7285 return NO_ERROR;
7286}
7287
Eric Laurent76c40f72010-07-15 12:50:15 -07007288// removeEffect_l() must be called with PlaybackThread::mLock held
7289size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007290{
7291 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007292 int size = (int)mEffects.size();
7293 int i;
7294 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7295
7296 for (i = 0; i < size; i++) {
7297 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007298 // calling stop here will remove pre-processing effect from the audio HAL.
7299 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7300 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007301 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7302 mEffects[i]->state() == EffectModule::STOPPING) {
7303 mEffects[i]->stop();
7304 }
Eric Laurent65b65452010-06-01 23:49:17 -07007305 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7306 delete[] effect->inBuffer();
7307 } else {
7308 if (i == size - 1 && i != 0) {
7309 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7310 mEffects[i - 1]->configure();
7311 }
7312 }
7313 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007314 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007315 break;
7316 }
7317 }
Eric Laurent65b65452010-06-01 23:49:17 -07007318
7319 return mEffects.size();
7320}
7321
Eric Laurent76c40f72010-07-15 12:50:15 -07007322// setDevice_l() must be called with PlaybackThread::mLock held
7323void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007324{
7325 size_t size = mEffects.size();
7326 for (size_t i = 0; i < size; i++) {
7327 mEffects[i]->setDevice(device);
7328 }
7329}
7330
Eric Laurent76c40f72010-07-15 12:50:15 -07007331// setMode_l() must be called with PlaybackThread::mLock held
7332void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007333{
7334 size_t size = mEffects.size();
7335 for (size_t i = 0; i < size; i++) {
7336 mEffects[i]->setMode(mode);
7337 }
7338}
7339
Eric Laurent76c40f72010-07-15 12:50:15 -07007340// setVolume_l() must be called with PlaybackThread::mLock held
7341bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007342{
7343 uint32_t newLeft = *left;
7344 uint32_t newRight = *right;
7345 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007346 int ctrlIdx = -1;
7347 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007348
Eric Laurent76c40f72010-07-15 12:50:15 -07007349 // first update volume controller
7350 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007351 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007352 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7353 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007354 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007355 break;
7356 }
7357 }
7358
7359 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007360 if (hasControl) {
7361 *left = mNewLeftVolume;
7362 *right = mNewRightVolume;
7363 }
7364 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007365 }
7366
7367 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007368 mLeftVolume = newLeft;
7369 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007370
7371 // second get volume update from volume controller
7372 if (ctrlIdx >= 0) {
7373 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007374 mNewLeftVolume = newLeft;
7375 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007376 }
7377 // then indicate volume to all other effects in chain.
7378 // Pass altered volume to effects before volume controller
7379 // and requested volume to effects after controller
7380 uint32_t lVol = newLeft;
7381 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007382
Eric Laurent65b65452010-06-01 23:49:17 -07007383 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007384 if ((int)i == ctrlIdx) continue;
7385 // this also works for ctrlIdx == -1 when there is no volume controller
7386 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007387 lVol = *left;
7388 rVol = *right;
7389 }
7390 mEffects[i]->setVolume(&lVol, &rVol, false);
7391 }
7392 *left = newLeft;
7393 *right = newRight;
7394
7395 return hasControl;
7396}
7397
Eric Laurent65b65452010-06-01 23:49:17 -07007398status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7399{
7400 const size_t SIZE = 256;
7401 char buffer[SIZE];
7402 String8 result;
7403
7404 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7405 result.append(buffer);
7406
7407 bool locked = tryLock(mLock);
7408 // failed to lock - AudioFlinger is probably deadlocked
7409 if (!locked) {
7410 result.append("\tCould not lock mutex:\n");
7411 }
7412
Eric Laurent76c40f72010-07-15 12:50:15 -07007413 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7414 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007415 mEffects.size(),
7416 (uint32_t)mInBuffer,
7417 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007418 mActiveTrackCnt);
7419 result.append(buffer);
7420 write(fd, result.string(), result.size());
7421
7422 for (size_t i = 0; i < mEffects.size(); ++i) {
7423 sp<EffectModule> effect = mEffects[i];
7424 if (effect != 0) {
7425 effect->dump(fd, args);
7426 }
7427 }
7428
7429 if (locked) {
7430 mLock.unlock();
7431 }
7432
7433 return NO_ERROR;
7434}
7435
Eric Laurentf82fccd2011-07-27 19:49:51 -07007436// must be called with ThreadBase::mLock held
7437void AudioFlinger::EffectChain::setEffectSuspended_l(
7438 const effect_uuid_t *type, bool suspend)
7439{
7440 sp<SuspendedEffectDesc> desc;
7441 // use effect type UUID timelow as key as there is no real risk of identical
7442 // timeLow fields among effect type UUIDs.
7443 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7444 if (suspend) {
7445 if (index >= 0) {
7446 desc = mSuspendedEffects.valueAt(index);
7447 } else {
7448 desc = new SuspendedEffectDesc();
7449 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7450 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007451 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007452 }
7453 if (desc->mRefCount++ == 0) {
7454 sp<EffectModule> effect = getEffectIfEnabled(type);
7455 if (effect != 0) {
7456 desc->mEffect = effect;
7457 effect->setSuspended(true);
7458 effect->setEnabled(false);
7459 }
7460 }
7461 } else {
7462 if (index < 0) {
7463 return;
7464 }
7465 desc = mSuspendedEffects.valueAt(index);
7466 if (desc->mRefCount <= 0) {
7467 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7468 desc->mRefCount = 1;
7469 }
7470 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007471 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007472 if (desc->mEffect != 0) {
7473 sp<EffectModule> effect = desc->mEffect.promote();
7474 if (effect != 0) {
7475 effect->setSuspended(false);
7476 sp<EffectHandle> handle = effect->controlHandle();
7477 if (handle != 0) {
7478 effect->setEnabled(handle->enabled());
7479 }
7480 }
7481 desc->mEffect.clear();
7482 }
7483 mSuspendedEffects.removeItemsAt(index);
7484 }
7485 }
7486}
7487
7488// must be called with ThreadBase::mLock held
7489void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7490{
7491 sp<SuspendedEffectDesc> desc;
7492
7493 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7494 if (suspend) {
7495 if (index >= 0) {
7496 desc = mSuspendedEffects.valueAt(index);
7497 } else {
7498 desc = new SuspendedEffectDesc();
7499 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007500 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007501 }
7502 if (desc->mRefCount++ == 0) {
7503 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7504 for (size_t i = 0; i < effects.size(); i++) {
7505 setEffectSuspended_l(&effects[i]->desc().type, true);
7506 }
7507 }
7508 } else {
7509 if (index < 0) {
7510 return;
7511 }
7512 desc = mSuspendedEffects.valueAt(index);
7513 if (desc->mRefCount <= 0) {
7514 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7515 desc->mRefCount = 1;
7516 }
7517 if (--desc->mRefCount == 0) {
7518 Vector<const effect_uuid_t *> types;
7519 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7520 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7521 continue;
7522 }
7523 types.add(&mSuspendedEffects.valueAt(i)->mType);
7524 }
7525 for (size_t i = 0; i < types.size(); i++) {
7526 setEffectSuspended_l(types[i], false);
7527 }
Steve Block71f2cf12011-10-20 11:56:00 +01007528 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007529 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7530 }
7531 }
7532}
7533
Eric Laurent5e7acae2011-09-23 08:40:41 -07007534
7535// The volume effect is used for automated tests only
7536#ifndef OPENSL_ES_H_
7537static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7538 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7539const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7540#endif //OPENSL_ES_H_
7541
Eric Laurent6752ec82011-08-10 10:37:50 -07007542bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7543{
7544 // auxiliary effects and visualizer are never suspended on output mix
7545 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7546 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007547 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7548 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007549 return false;
7550 }
7551 return true;
7552}
7553
Eric Laurentf82fccd2011-07-27 19:49:51 -07007554Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7555{
7556 Vector< sp<EffectModule> > effects;
7557 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007558 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07007559 continue;
7560 }
7561 effects.add(mEffects[i]);
7562 }
7563 return effects;
7564}
7565
7566sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7567 const effect_uuid_t *type)
7568{
7569 sp<EffectModule> effect;
7570 effect = getEffectFromType_l(type);
7571 if (effect != 0 && !effect->isEnabled()) {
7572 effect.clear();
7573 }
7574 return effect;
7575}
7576
7577void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7578 bool enabled)
7579{
7580 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7581 if (enabled) {
7582 if (index < 0) {
7583 // if the effect is not suspend check if all effects are suspended
7584 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7585 if (index < 0) {
7586 return;
7587 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007588 if (!isEffectEligibleForSuspend(effect->desc())) {
7589 return;
7590 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007591 setEffectSuspended_l(&effect->desc().type, enabled);
7592 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007593 if (index < 0) {
7594 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7595 return;
7596 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007597 }
Steve Block71f2cf12011-10-20 11:56:00 +01007598 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007599 effect->desc().type.timeLow);
7600 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7601 // if effect is requested to suspended but was not yet enabled, supend it now.
7602 if (desc->mEffect == 0) {
7603 desc->mEffect = effect;
7604 effect->setEnabled(false);
7605 effect->setSuspended(true);
7606 }
7607 } else {
7608 if (index < 0) {
7609 return;
7610 }
Steve Block71f2cf12011-10-20 11:56:00 +01007611 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007612 effect->desc().type.timeLow);
7613 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7614 desc->mEffect.clear();
7615 effect->setSuspended(false);
7616 }
7617}
7618
Eric Laurent65b65452010-06-01 23:49:17 -07007619#undef LOG_TAG
7620#define LOG_TAG "AudioFlinger"
7621
Eric Laurenta553c252009-07-17 12:17:14 -07007622// ----------------------------------------------------------------------------
7623
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007624status_t AudioFlinger::onTransact(
7625 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7626{
7627 return BnAudioFlinger::onTransact(code, data, reply, flags);
7628}
7629
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007630}; // namespace android