blob: fb508a7741caff3079f73858b777d687bcae8a25 [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>
Glenn Kastene80a4cc2011-12-15 09:51:17 -080038#include <cutils/compiler.h>
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080039
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040#include <media/AudioTrack.h>
41#include <media/AudioRecord.h>
Gloria Wang9b3f1522011-02-24 14:51:45 -080042#include <media/IMediaPlayerService.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070043
44#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070045#include <private/media/AudioEffectShared.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070046
Dima Zavin34bb4192011-05-11 14:15:23 -070047#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070048#include <hardware/audio.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070049
50#include "AudioMixer.h"
51#include "AudioFlinger.h"
52
Eric Laurent53334cd2010-06-23 17:38:20 -070053#include <media/EffectsFactoryApi.h>
Eric Laurent5cc05262011-06-24 07:01:31 -070054#include <audio_effects/effect_visualizer.h>
Eric Laurent6639b552011-08-01 09:52:20 -070055#include <audio_effects/effect_ns.h>
56#include <audio_effects/effect_aec.h>
Eric Laurent65b65452010-06-01 23:49:17 -070057
Glenn Kasten490909d2011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Glenn Kastenda494f92011-07-08 15:26:12 -070060#include <cpustats/ThreadCpuUsage.h>
Eric Laurent6dbdc402011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kastenda494f92011-07-08 15:26:12 -070062// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
63
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064// ----------------------------------------------------------------------------
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
Eric Laurent8ed6ed02010-07-13 04:45:46 -070066
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070067namespace android {
68
Glenn Kasten62de3db2011-12-12 09:04:45 -080069static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
70static const char kHardwareLockedString[] = "Hardware lock is taken\n";
The Android Open Source Project10592532009-03-18 17:39:46 -070071
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080072//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070073static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070074static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070075
76// retry counts for buffer fill timeout
77// 50 * ~20msecs = 1 second
78static const int8_t kMaxTrackRetries = 50;
79static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080080// allow less retry attempts on direct output thread.
81// direct outputs can be a scarce resource in audio hardware and should
82// be released as quickly as possible.
83static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070084
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070085static const int kDumpLockRetries = 50;
Glenn Kastencbfe2e12011-12-13 11:04:14 -080086static const int kDumpLockSleepUs = 20000;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070087
Glenn Kastencbfe2e12011-12-13 11:04:14 -080088// don't warn about blocked writes or record buffer overflows more often than this
89static const nsecs_t kWarningThrottleNs = seconds(5);
Dave Sparksd0ac8c02009-09-30 03:09:03 -070090
Eric Laurent464d5b32011-06-17 21:29:58 -070091// RecordThread loop sleep time upon application overrun or audio HAL read error
92static const int kRecordThreadSleepUs = 5000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
Glenn Kastencbfe2e12011-12-13 11:04:14 -080094// maximum time to wait for setParameters to complete
95static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent5f37be32011-09-13 11:40:21 -070096
Eric Laurentf1f5fc82011-11-22 18:50:29 -080097// minimum sleep time for the mixer thread loop when tracks are active but in underrun
98static const uint32_t kMinThreadSleepTimeUs = 5000;
99// maximum divider applied to the active sleep time in the mixer thread loop
100static const uint32_t kMaxThreadSleepTimeShift = 2;
101
102
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700103// ----------------------------------------------------------------------------
104
105static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700106 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
107 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
108 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
109 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700110}
111
112static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700113 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
114 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
115 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
116 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700117}
118
Gloria Wang9b3f1522011-02-24 14:51:45 -0800119// To collect the amplifier usage
120static void addBatteryData(uint32_t params) {
121 sp<IBinder> binder =
122 defaultServiceManager()->getService(String16("media.player"));
123 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
124 if (service.get() == NULL) {
125 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
126 return;
127 }
128
129 service->addBatteryData(params);
130}
131
Dima Zavin31f188892011-04-18 16:57:27 -0700132static int load_audio_interface(const char *if_name, const hw_module_t **mod,
133 audio_hw_device_t **dev)
134{
135 int rc;
136
137 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
138 if (rc)
139 goto out;
140
141 rc = audio_hw_device_open(*mod, dev);
142 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
143 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
144 if (rc)
145 goto out;
146
147 return 0;
148
149out:
150 *mod = NULL;
151 *dev = NULL;
152 return rc;
153}
154
Glenn Kasten62de3db2011-12-12 09:04:45 -0800155static const char * const audio_interfaces[] = {
Dima Zavin31f188892011-04-18 16:57:27 -0700156 "primary",
157 "a2dp",
158 "usb",
159};
160#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
161
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700162// ----------------------------------------------------------------------------
163
164AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 : BnAudioFlinger(),
Glenn Kastenc434c902011-12-13 11:53:26 -0800166 mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700167 mBtNrecIsOff(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700168{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700169}
170
171void AudioFlinger::onFirstRef()
172{
Dima Zavin31f188892011-04-18 16:57:27 -0700173 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700174
Eric Laurent01635942011-01-18 18:39:02 -0800175 Mutex::Autolock _l(mLock);
176
Dima Zavin31f188892011-04-18 16:57:27 -0700177 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700178 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700179
Dima Zavin31f188892011-04-18 16:57:27 -0700180 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
181 const hw_module_t *mod;
182 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700183
Dima Zavin31f188892011-04-18 16:57:27 -0700184 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
185 if (rc)
186 continue;
187
188 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
189 mod->name, mod->id);
190 mAudioHwDevs.push(dev);
191
192 if (!mPrimaryHardwareDev) {
193 mPrimaryHardwareDev = dev;
194 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700195 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700196 }
197 }
Eric Laurenta553c252009-07-17 12:17:14 -0700198
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700199 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700200
Dima Zavin31f188892011-04-18 16:57:27 -0700201 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
202 LOGE("Primary audio interface not found");
203 return;
204 }
205
206 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
207 audio_hw_device_t *dev = mAudioHwDevs[i];
208
209 mHardwareStatus = AUDIO_HW_INIT;
210 rc = dev->init_check(dev);
211 if (rc == 0) {
212 AutoMutex lock(mHardwareLock);
213
214 mMode = AUDIO_MODE_NORMAL;
215 mHardwareStatus = AUDIO_HW_SET_MODE;
216 dev->set_mode(dev, mMode);
217 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
218 dev->set_master_volume(dev, 1.0f);
219 mHardwareStatus = AUDIO_HW_IDLE;
220 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700221 }
222}
223
Dima Zavin2986f5b2011-04-19 19:04:32 -0700224status_t AudioFlinger::initCheck() const
225{
226 Mutex::Autolock _l(mLock);
227 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
228 return NO_INIT;
229 return NO_ERROR;
230}
231
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700232AudioFlinger::~AudioFlinger()
233{
Dima Zavin31f188892011-04-18 16:57:27 -0700234 int num_devs = mAudioHwDevs.size();
235
Eric Laurent7954c462009-08-28 10:39:03 -0700236 while (!mRecordThreads.isEmpty()) {
237 // closeInput() will remove first entry from mRecordThreads
238 closeInput(mRecordThreads.keyAt(0));
239 }
240 while (!mPlaybackThreads.isEmpty()) {
241 // closeOutput() will remove first entry from mPlaybackThreads
242 closeOutput(mPlaybackThreads.keyAt(0));
243 }
Dima Zavin31f188892011-04-18 16:57:27 -0700244
245 for (int i = 0; i < num_devs; i++) {
246 audio_hw_device_t *dev = mAudioHwDevs[i];
247 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700248 }
Dima Zavin31f188892011-04-18 16:57:27 -0700249 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800250}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800251
Dima Zavin31f188892011-04-18 16:57:27 -0700252audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
253{
254 /* first matching HW device is returned */
255 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
256 audio_hw_device_t *dev = mAudioHwDevs[i];
257 if ((dev->get_supported_devices(dev) & devices) == devices)
258 return dev;
259 }
260 return NULL;
261}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700262
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700263status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
264{
265 const size_t SIZE = 256;
266 char buffer[SIZE];
267 String8 result;
268
269 result.append("Clients:\n");
270 for (size_t i = 0; i < mClients.size(); ++i) {
271 wp<Client> wClient = mClients.valueAt(i);
272 if (wClient != 0) {
273 sp<Client> client = wClient.promote();
274 if (client != 0) {
275 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
276 result.append(buffer);
277 }
278 }
279 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700280
281 result.append("Global session refs:\n");
282 result.append(" session pid cnt\n");
283 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
284 AudioSessionRef *r = mAudioSessionRefs[i];
285 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
286 result.append(buffer);
287 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700288 write(fd, result.string(), result.size());
289 return NO_ERROR;
290}
291
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700292
293status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
294{
295 const size_t SIZE = 256;
296 char buffer[SIZE];
297 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700298 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700299
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700300 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700301 result.append(buffer);
302 write(fd, result.string(), result.size());
303 return NO_ERROR;
304}
305
306status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
307{
308 const size_t SIZE = 256;
309 char buffer[SIZE];
310 String8 result;
311 snprintf(buffer, SIZE, "Permission Denial: "
312 "can't dump AudioFlinger from pid=%d, uid=%d\n",
313 IPCThreadState::self()->getCallingPid(),
314 IPCThreadState::self()->getCallingUid());
315 result.append(buffer);
316 write(fd, result.string(), result.size());
317 return NO_ERROR;
318}
319
The Android Open Source Project10592532009-03-18 17:39:46 -0700320static bool tryLock(Mutex& mutex)
321{
322 bool locked = false;
323 for (int i = 0; i < kDumpLockRetries; ++i) {
324 if (mutex.tryLock() == NO_ERROR) {
325 locked = true;
326 break;
327 }
Glenn Kastencbfe2e12011-12-13 11:04:14 -0800328 usleep(kDumpLockSleepUs);
The Android Open Source Project10592532009-03-18 17:39:46 -0700329 }
330 return locked;
331}
332
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700333status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
334{
335 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
336 dumpPermissionDenial(fd, args);
337 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700338 // get state of hardware lock
339 bool hardwareLocked = tryLock(mHardwareLock);
340 if (!hardwareLocked) {
341 String8 result(kHardwareLockedString);
342 write(fd, result.string(), result.size());
343 } else {
344 mHardwareLock.unlock();
345 }
346
347 bool locked = tryLock(mLock);
348
349 // failed to lock - AudioFlinger is probably deadlocked
350 if (!locked) {
351 String8 result(kDeadlockedString);
352 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700353 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700354
355 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700356 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357
Eric Laurenta553c252009-07-17 12:17:14 -0700358 // dump playback threads
359 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700360 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700361 }
362
363 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700364 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700365 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367
Dima Zavin31f188892011-04-18 16:57:27 -0700368 // dump all hardware devs
369 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
370 audio_hw_device_t *dev = mAudioHwDevs[i];
371 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700372 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700373 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700374 }
375 return NO_ERROR;
376}
377
Eric Laurenta553c252009-07-17 12:17:14 -0700378
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700379// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380
381
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700382sp<IAudioTrack> AudioFlinger::createTrack(
383 pid_t pid,
384 int streamType,
385 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700386 uint32_t format,
387 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800388 int frameCount,
389 uint32_t flags,
390 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700391 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700392 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800393 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700394{
Eric Laurenta553c252009-07-17 12:17:14 -0700395 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700396 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700397 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800398 wp<Client> wclient;
399 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700400 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700401
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700402 if (streamType >= AUDIO_STREAM_CNT) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -0700403 LOGE("createTrack() invalid stream type %d", streamType);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800404 lStatus = BAD_VALUE;
405 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700406 }
407
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800408 {
409 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700410 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700411 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700412 if (thread == NULL) {
413 LOGE("unknown output thread");
414 lStatus = BAD_VALUE;
415 goto Exit;
416 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800417
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800418 wclient = mClients.valueFor(pid);
419
420 if (wclient != NULL) {
421 client = wclient.promote();
422 } else {
423 client = new Client(this, pid);
424 mClients.add(pid, client);
425 }
Eric Laurent65b65452010-06-01 23:49:17 -0700426
Steve Block71f2cf12011-10-20 11:56:00 +0100427 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700428 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700429 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700430 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
431 if (mPlaybackThreads.keyAt(i) != output) {
432 // prevent same audio session on different output threads
433 uint32_t sessions = t->hasAudioSession(*sessionId);
434 if (sessions & PlaybackThread::TRACK_SESSION) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -0700435 LOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent493941b2010-07-28 01:32:47 -0700436 lStatus = BAD_VALUE;
437 goto Exit;
438 }
439 // check if an effect with same session ID is waiting for a track to be created
440 if (sessions & PlaybackThread::EFFECT_SESSION) {
441 effectThread = t.get();
442 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700443 }
444 }
Eric Laurent65b65452010-06-01 23:49:17 -0700445 lSessionId = *sessionId;
446 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700447 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700448 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700449 if (sessionId != NULL) {
450 *sessionId = lSessionId;
451 }
452 }
Steve Block71f2cf12011-10-20 11:56:00 +0100453 ALOGV("createTrack() lSessionId: %d", lSessionId);
Eric Laurent65b65452010-06-01 23:49:17 -0700454
Eric Laurenta553c252009-07-17 12:17:14 -0700455 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700456 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700457
458 // move effect chain to this output thread if an effect on same session was waiting
459 // for a track to be created
460 if (lStatus == NO_ERROR && effectThread != NULL) {
461 Mutex::Autolock _dl(thread->mLock);
462 Mutex::Autolock _sl(effectThread->mLock);
463 moveEffectChain_l(lSessionId, effectThread, thread, true);
464 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700465 }
466 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800467 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700468 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700469 // remove local strong reference to Client before deleting the Track so that the Client
470 // destructor is called by the TrackBase destructor with mLock held
471 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700472 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800473 }
474
475Exit:
476 if(status) {
477 *status = lStatus;
478 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700479 return trackHandle;
480}
481
Eric Laurentddb78e72009-07-28 08:44:33 -0700482uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700483{
Eric Laurenta553c252009-07-17 12:17:14 -0700484 Mutex::Autolock _l(mLock);
485 PlaybackThread *thread = checkPlaybackThread_l(output);
486 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700487 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700488 return 0;
489 }
490 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700491}
492
Eric Laurentddb78e72009-07-28 08:44:33 -0700493int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700494{
Eric Laurenta553c252009-07-17 12:17:14 -0700495 Mutex::Autolock _l(mLock);
496 PlaybackThread *thread = checkPlaybackThread_l(output);
497 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700498 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700499 return 0;
500 }
501 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700502}
503
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700504uint32_t AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700505{
Eric Laurenta553c252009-07-17 12:17:14 -0700506 Mutex::Autolock _l(mLock);
507 PlaybackThread *thread = checkPlaybackThread_l(output);
508 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700509 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700510 return 0;
511 }
512 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700513}
514
Eric Laurentddb78e72009-07-28 08:44:33 -0700515size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700516{
Eric Laurenta553c252009-07-17 12:17:14 -0700517 Mutex::Autolock _l(mLock);
518 PlaybackThread *thread = checkPlaybackThread_l(output);
519 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700520 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700521 return 0;
522 }
523 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700524}
525
Eric Laurentddb78e72009-07-28 08:44:33 -0700526uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800527{
Eric Laurenta553c252009-07-17 12:17:14 -0700528 Mutex::Autolock _l(mLock);
529 PlaybackThread *thread = checkPlaybackThread_l(output);
530 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700531 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700532 return 0;
533 }
534 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800535}
536
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700537status_t AudioFlinger::setMasterVolume(float value)
538{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700539 status_t ret = initCheck();
540 if (ret != NO_ERROR) {
541 return ret;
542 }
543
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700544 // check calling permissions
545 if (!settingsAllowed()) {
546 return PERMISSION_DENIED;
547 }
548
549 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800550 { // scope for the lock
551 AutoMutex lock(mHardwareLock);
552 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700553 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800554 value = 1.0f;
555 }
556 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700557 }
Eric Laurenta553c252009-07-17 12:17:14 -0700558
Eric Laurent01635942011-01-18 18:39:02 -0800559 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700560 mMasterVolume = value;
561 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700562 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700563
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700564 return NO_ERROR;
565}
566
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700567status_t AudioFlinger::setMode(int mode)
568{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700569 status_t ret = initCheck();
570 if (ret != NO_ERROR) {
571 return ret;
572 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700573
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700574 // check calling permissions
575 if (!settingsAllowed()) {
576 return PERMISSION_DENIED;
577 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700578 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700579 LOGW("Illegal value: setMode(%d)", mode);
580 return BAD_VALUE;
581 }
582
Eric Laurent53334cd2010-06-23 17:38:20 -0700583 { // scope for the lock
584 AutoMutex lock(mHardwareLock);
585 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700586 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700587 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800588 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700589
590 if (NO_ERROR == ret) {
591 Mutex::Autolock _l(mLock);
592 mMode = mode;
593 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
594 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700595 }
596
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700597 return ret;
598}
599
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700600status_t AudioFlinger::setMicMute(bool state)
601{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700602 status_t ret = initCheck();
603 if (ret != NO_ERROR) {
604 return ret;
605 }
606
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700607 // check calling permissions
608 if (!settingsAllowed()) {
609 return PERMISSION_DENIED;
610 }
611
612 AutoMutex lock(mHardwareLock);
613 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700614 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700615 mHardwareStatus = AUDIO_HW_IDLE;
616 return ret;
617}
618
619bool AudioFlinger::getMicMute() const
620{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700621 status_t ret = initCheck();
622 if (ret != NO_ERROR) {
623 return false;
624 }
625
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700626 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700627 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700628 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700629 mHardwareStatus = AUDIO_HW_IDLE;
630 return state;
631}
632
633status_t AudioFlinger::setMasterMute(bool muted)
634{
635 // check calling permissions
636 if (!settingsAllowed()) {
637 return PERMISSION_DENIED;
638 }
Eric Laurenta553c252009-07-17 12:17:14 -0700639
Eric Laurent01635942011-01-18 18:39:02 -0800640 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700641 mMasterMute = muted;
642 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700643 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700644
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700645 return NO_ERROR;
646}
647
648float AudioFlinger::masterVolume() const
649{
Eric Laurenta553c252009-07-17 12:17:14 -0700650 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700651}
652
653bool AudioFlinger::masterMute() const
654{
Eric Laurenta553c252009-07-17 12:17:14 -0700655 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700656}
657
Eric Laurentddb78e72009-07-28 08:44:33 -0700658status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700659{
660 // check calling permissions
661 if (!settingsAllowed()) {
662 return PERMISSION_DENIED;
663 }
664
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700665 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -0700666 LOGE("setStreamVolume() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700667 return BAD_VALUE;
668 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800669
Eric Laurenta553c252009-07-17 12:17:14 -0700670 AutoMutex lock(mLock);
671 PlaybackThread *thread = NULL;
672 if (output) {
673 thread = checkPlaybackThread_l(output);
674 if (thread == NULL) {
675 return BAD_VALUE;
676 }
677 }
678
Eric Laurenta553c252009-07-17 12:17:14 -0700679 mStreamTypes[stream].volume = value;
680
681 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700682 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700683 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700684 }
Eric Laurenta553c252009-07-17 12:17:14 -0700685 } else {
686 thread->setStreamVolume(stream, value);
687 }
Eric Laurentef028272009-04-21 07:56:33 -0700688
Eric Laurent415f3e22009-10-21 08:14:22 -0700689 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700690}
691
692status_t AudioFlinger::setStreamMute(int stream, bool muted)
693{
694 // check calling permissions
695 if (!settingsAllowed()) {
696 return PERMISSION_DENIED;
697 }
698
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700699 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
700 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -0700701 LOGE("setStreamMute() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700702 return BAD_VALUE;
703 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700704
Eric Laurent01635942011-01-18 18:39:02 -0800705 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700706 mStreamTypes[stream].mute = muted;
707 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700708 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700710 return NO_ERROR;
711}
712
Eric Laurentddb78e72009-07-28 08:44:33 -0700713float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700714{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700715 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700716 return 0.0f;
717 }
Eric Laurenta553c252009-07-17 12:17:14 -0700718
719 AutoMutex lock(mLock);
720 float volume;
721 if (output) {
722 PlaybackThread *thread = checkPlaybackThread_l(output);
723 if (thread == NULL) {
724 return 0.0f;
725 }
726 volume = thread->streamVolume(stream);
727 } else {
728 volume = mStreamTypes[stream].volume;
729 }
730
Eric Laurentef028272009-04-21 07:56:33 -0700731 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700732}
733
734bool AudioFlinger::streamMute(int stream) const
735{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700736 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700737 return true;
738 }
Eric Laurenta553c252009-07-17 12:17:14 -0700739
740 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700741}
742
Eric Laurentddb78e72009-07-28 08:44:33 -0700743status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700744{
Eric Laurenta553c252009-07-17 12:17:14 -0700745 status_t result;
746
Steve Block71f2cf12011-10-20 11:56:00 +0100747 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700748 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
749 // check calling permissions
750 if (!settingsAllowed()) {
751 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800752 }
Eric Laurenta553c252009-07-17 12:17:14 -0700753
754 // ioHandle == 0 means the parameters are global to the audio hardware interface
755 if (ioHandle == 0) {
756 AutoMutex lock(mHardwareLock);
757 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700758 status_t final_result = NO_ERROR;
759 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
760 audio_hw_device_t *dev = mAudioHwDevs[i];
761 result = dev->set_parameters(dev, keyValuePairs.string());
762 final_result = result ?: final_result;
763 }
Eric Laurenta553c252009-07-17 12:17:14 -0700764 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent6639b552011-08-01 09:52:20 -0700765 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
766 AudioParameter param = AudioParameter(keyValuePairs);
767 String8 value;
768 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
769 Mutex::Autolock _l(mLock);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700770 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
771 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent6639b552011-08-01 09:52:20 -0700772 for (size_t i = 0; i < mRecordThreads.size(); i++) {
773 sp<RecordThread> thread = mRecordThreads.valueAt(i);
774 RecordThread::RecordTrack *track = thread->track();
775 if (track != NULL) {
776 audio_devices_t device = (audio_devices_t)(
777 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700778 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700779 thread->setEffectSuspended(FX_IID_AEC,
780 suspend,
781 track->sessionId());
782 thread->setEffectSuspended(FX_IID_NS,
783 suspend,
784 track->sessionId());
785 }
786 }
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700787 mBtNrecIsOff = btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700788 }
789 }
Dima Zavin31f188892011-04-18 16:57:27 -0700790 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700791 }
792
Eric Laurentb7d94602009-09-29 11:12:57 -0700793 // hold a strong ref on thread in case closeOutput() or closeInput() is called
794 // and the thread is exited once the lock is released
795 sp<ThreadBase> thread;
796 {
797 Mutex::Autolock _l(mLock);
798 thread = checkPlaybackThread_l(ioHandle);
799 if (thread == NULL) {
800 thread = checkRecordThread_l(ioHandle);
Eric Laurent464d5b32011-06-17 21:29:58 -0700801 } else if (thread.get() == primaryPlaybackThread_l()) {
802 // indicate output device change to all input threads for pre processing
803 AudioParameter param = AudioParameter(keyValuePairs);
804 int value;
805 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
806 for (size_t i = 0; i < mRecordThreads.size(); i++) {
807 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
808 }
809 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700810 }
Eric Laurenta553c252009-07-17 12:17:14 -0700811 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700812 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800813 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800814 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700815 }
Eric Laurenta553c252009-07-17 12:17:14 -0700816 return BAD_VALUE;
817}
818
Eric Laurentddb78e72009-07-28 08:44:33 -0700819String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700820{
Steve Block71f2cf12011-10-20 11:56:00 +0100821// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700822// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
823
824 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700825 String8 out_s8;
826
Dima Zavin31f188892011-04-18 16:57:27 -0700827 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
828 audio_hw_device_t *dev = mAudioHwDevs[i];
829 char *s = dev->get_parameters(dev, keys.string());
830 out_s8 += String8(s);
831 free(s);
832 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700833 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700834 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700835
836 Mutex::Autolock _l(mLock);
837
Eric Laurenta553c252009-07-17 12:17:14 -0700838 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
839 if (playbackThread != NULL) {
840 return playbackThread->getParameters(keys);
841 }
842 RecordThread *recordThread = checkRecordThread_l(ioHandle);
843 if (recordThread != NULL) {
844 return recordThread->getParameters(keys);
845 }
846 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700847}
848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
850{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700851 status_t ret = initCheck();
852 if (ret != NO_ERROR) {
853 return 0;
854 }
855
Dima Zavin31f188892011-04-18 16:57:27 -0700856 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857}
858
Eric Laurent47d0a922010-02-26 02:47:27 -0800859unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
860{
861 if (ioHandle == 0) {
862 return 0;
863 }
864
865 Mutex::Autolock _l(mLock);
866
867 RecordThread *recordThread = checkRecordThread_l(ioHandle);
868 if (recordThread != NULL) {
869 return recordThread->getInputFramesLost();
870 }
871 return 0;
872}
873
Eric Laurent415f3e22009-10-21 08:14:22 -0700874status_t AudioFlinger::setVoiceVolume(float value)
875{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700876 status_t ret = initCheck();
877 if (ret != NO_ERROR) {
878 return ret;
879 }
880
Eric Laurent415f3e22009-10-21 08:14:22 -0700881 // check calling permissions
882 if (!settingsAllowed()) {
883 return PERMISSION_DENIED;
884 }
885
886 AutoMutex lock(mHardwareLock);
887 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700888 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700889 mHardwareStatus = AUDIO_HW_IDLE;
890
891 return ret;
892}
893
Eric Laurent0986e792010-01-19 17:37:09 -0800894status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
895{
896 status_t status;
897
898 Mutex::Autolock _l(mLock);
899
900 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
901 if (playbackThread != NULL) {
902 return playbackThread->getRenderPosition(halFrames, dspFrames);
903 }
904
905 return BAD_VALUE;
906}
907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
909{
Eric Laurenta553c252009-07-17 12:17:14 -0700910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 Mutex::Autolock _l(mLock);
912
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700913 int pid = IPCThreadState::self()->getCallingPid();
914 if (mNotificationClients.indexOfKey(pid) < 0) {
915 sp<NotificationClient> notificationClient = new NotificationClient(this,
916 client,
917 pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100918 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700919
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700920 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700921
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700922 sp<IBinder> binder = client->asBinder();
923 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700925 // the config change is always sent from playback or record threads to avoid deadlock
926 // with AudioSystem::gLock
927 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
928 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
929 }
Eric Laurenta553c252009-07-17 12:17:14 -0700930
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700931 for (size_t i = 0; i < mRecordThreads.size(); i++) {
932 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 }
934 }
935}
936
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700937void AudioFlinger::removeNotificationClient(pid_t pid)
938{
939 Mutex::Autolock _l(mLock);
940
941 int index = mNotificationClients.indexOfKey(pid);
942 if (index >= 0) {
943 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100944 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700945 mNotificationClients.removeItem(pid);
946 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700947
Steve Block71f2cf12011-10-20 11:56:00 +0100948 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700949 int num = mAudioSessionRefs.size();
950 bool removed = false;
951 for (int i = 0; i< num; i++) {
952 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +0100953 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700954 if (ref->pid == pid) {
Steve Block71f2cf12011-10-20 11:56:00 +0100955 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700956 mAudioSessionRefs.removeAt(i);
957 delete ref;
958 removed = true;
959 i--;
960 num--;
961 }
962 }
963 if (removed) {
964 purgeStaleEffects_l();
965 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700966}
967
Eric Laurent296a0ec2009-09-15 07:10:12 -0700968// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700969void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
970{
Eric Laurent49f02be2009-11-19 09:00:56 -0800971 size_t size = mNotificationClients.size();
972 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700973 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700974 }
975}
976
Eric Laurentb9481d82009-09-17 05:12:56 -0700977// removeClient_l() must be called with AudioFlinger::mLock held
978void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700979{
Steve Block71f2cf12011-10-20 11:56:00 +0100980 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 -0700981 mClients.removeItem(pid);
982}
983
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700984
Eric Laurenta553c252009-07-17 12:17:14 -0700985// ----------------------------------------------------------------------------
986
Eric Laurent464d5b32011-06-17 21:29:58 -0700987AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Eric Laurenta553c252009-07-17 12:17:14 -0700988 : Thread(false),
989 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent6dbdc402011-07-22 09:04:31 -0700990 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
991 mDevice(device)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700992{
Eric Laurent6dbdc402011-07-22 09:04:31 -0700993 mDeathRecipient = new PMDeathRecipient(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994}
995
Eric Laurenta553c252009-07-17 12:17:14 -0700996AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700998 mParamCond.broadcast();
Eric Laurent6dbdc402011-07-22 09:04:31 -0700999 // do not lock the mutex in destructor
1000 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -07001001 if (mPowerManager != 0) {
1002 sp<IBinder> binder = mPowerManager->asBinder();
1003 binder->unlinkToDeath(mDeathRecipient);
1004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005}
1006
Eric Laurenta553c252009-07-17 12:17:14 -07001007void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001008{
Glenn Kastene5fb2632011-12-14 10:28:06 -08001009 // keep a strong ref on ourself so that we won't get
Eric Laurenta553c252009-07-17 12:17:14 -07001010 // destroyed in the middle of requestExitAndWait()
1011 sp <ThreadBase> strongMe = this;
1012
Steve Block71f2cf12011-10-20 11:56:00 +01001013 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001014 {
1015 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001016 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001017 requestExit();
1018 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001019 }
Eric Laurenta553c252009-07-17 12:17:14 -07001020 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001021}
Eric Laurenta553c252009-07-17 12:17:14 -07001022
1023uint32_t AudioFlinger::ThreadBase::sampleRate() const
1024{
1025 return mSampleRate;
1026}
1027
1028int AudioFlinger::ThreadBase::channelCount() const
1029{
Eric Laurentb0a01472010-05-14 05:45:46 -07001030 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07001031}
1032
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001033uint32_t AudioFlinger::ThreadBase::format() const
Eric Laurenta553c252009-07-17 12:17:14 -07001034{
1035 return mFormat;
1036}
1037
1038size_t AudioFlinger::ThreadBase::frameCount() const
1039{
1040 return mFrameCount;
1041}
1042
1043status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1044{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001045 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001046
Steve Block71f2cf12011-10-20 11:56:00 +01001047 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001048 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001049
Eric Laurent8fce46a2009-08-04 09:45:33 -07001050 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001051 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001052 // wait condition with timeout in case the thread loop has exited
1053 // before the request could be processed
Glenn Kastencbfe2e12011-12-13 11:04:14 -08001054 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001055 status = mParamStatus;
1056 mWaitWorkCV.signal();
1057 } else {
1058 status = TIMED_OUT;
1059 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001060 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001061}
1062
1063void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1064{
1065 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001066 sendConfigEvent_l(event, param);
1067}
1068
1069// sendConfigEvent_l() must be called with ThreadBase::mLock held
1070void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1071{
Glenn Kasten4b220f02011-12-13 11:50:00 -08001072 ConfigEvent configEvent;
1073 configEvent.mEvent = event;
1074 configEvent.mParam = param;
Eric Laurenta553c252009-07-17 12:17:14 -07001075 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001076 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001077 mWaitWorkCV.signal();
1078}
1079
1080void AudioFlinger::ThreadBase::processConfigEvents()
1081{
1082 mLock.lock();
1083 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001084 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kasten4b220f02011-12-13 11:50:00 -08001085 ConfigEvent configEvent = mConfigEvents[0];
Eric Laurenta553c252009-07-17 12:17:14 -07001086 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001087 // release mLock before locking AudioFlinger mLock: lock order is always
1088 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001089 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001090 mAudioFlinger->mLock.lock();
Glenn Kasten4b220f02011-12-13 11:50:00 -08001091 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001092 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001093 mLock.lock();
1094 }
1095 mLock.unlock();
1096}
1097
Eric Laurent3fdb1262009-11-07 00:01:32 -08001098status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1099{
1100 const size_t SIZE = 256;
1101 char buffer[SIZE];
1102 String8 result;
1103
1104 bool locked = tryLock(mLock);
1105 if (!locked) {
1106 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1107 write(fd, buffer, strlen(buffer));
1108 }
1109
1110 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1111 result.append(buffer);
1112 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1113 result.append(buffer);
1114 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1115 result.append(buffer);
1116 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1117 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001118 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1119 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001120 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1121 result.append(buffer);
1122 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1123 result.append(buffer);
1124
1125 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1126 result.append(buffer);
1127 result.append(" Index Command");
1128 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1129 snprintf(buffer, SIZE, "\n %02d ", i);
1130 result.append(buffer);
1131 result.append(mNewParameters[i]);
1132 }
1133
1134 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1135 result.append(buffer);
1136 snprintf(buffer, SIZE, " Index event param\n");
1137 result.append(buffer);
1138 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kasten4b220f02011-12-13 11:50:00 -08001139 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001140 result.append(buffer);
1141 }
1142 result.append("\n");
1143
1144 write(fd, result.string(), result.size());
1145
1146 if (locked) {
1147 mLock.unlock();
1148 }
1149 return NO_ERROR;
1150}
1151
Eric Laurent1345d332011-07-24 17:49:51 -07001152status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1153{
1154 const size_t SIZE = 256;
1155 char buffer[SIZE];
1156 String8 result;
1157
1158 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1159 write(fd, buffer, strlen(buffer));
1160
1161 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1162 sp<EffectChain> chain = mEffectChains[i];
1163 if (chain != 0) {
1164 chain->dump(fd, args);
1165 }
1166 }
1167 return NO_ERROR;
1168}
1169
Eric Laurent6dbdc402011-07-22 09:04:31 -07001170void AudioFlinger::ThreadBase::acquireWakeLock()
1171{
1172 Mutex::Autolock _l(mLock);
1173 acquireWakeLock_l();
1174}
1175
1176void AudioFlinger::ThreadBase::acquireWakeLock_l()
1177{
1178 if (mPowerManager == 0) {
1179 // use checkService() to avoid blocking if power service is not up yet
1180 sp<IBinder> binder =
1181 defaultServiceManager()->checkService(String16("power"));
1182 if (binder == 0) {
1183 LOGW("Thread %s cannot connect to the power manager service", mName);
1184 } else {
1185 mPowerManager = interface_cast<IPowerManager>(binder);
1186 binder->linkToDeath(mDeathRecipient);
1187 }
1188 }
1189 if (mPowerManager != 0) {
1190 sp<IBinder> binder = new BBinder();
1191 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1192 binder,
1193 String16(mName));
1194 if (status == NO_ERROR) {
1195 mWakeLockToken = binder;
1196 }
Steve Block71f2cf12011-10-20 11:56:00 +01001197 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001198 }
1199}
1200
1201void AudioFlinger::ThreadBase::releaseWakeLock()
1202{
1203 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001204 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001205}
1206
1207void AudioFlinger::ThreadBase::releaseWakeLock_l()
1208{
1209 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001210 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001211 if (mPowerManager != 0) {
1212 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1213 }
1214 mWakeLockToken.clear();
1215 }
1216}
1217
1218void AudioFlinger::ThreadBase::clearPowerManager()
1219{
1220 Mutex::Autolock _l(mLock);
1221 releaseWakeLock_l();
1222 mPowerManager.clear();
1223}
1224
1225void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1226{
1227 sp<ThreadBase> thread = mThread.promote();
1228 if (thread != 0) {
1229 thread->clearPowerManager();
1230 }
1231 LOGW("power manager service died !!!");
1232}
Eric Laurent1345d332011-07-24 17:49:51 -07001233
Eric Laurentf82fccd2011-07-27 19:49:51 -07001234void AudioFlinger::ThreadBase::setEffectSuspended(
1235 const effect_uuid_t *type, bool suspend, int sessionId)
1236{
1237 Mutex::Autolock _l(mLock);
1238 setEffectSuspended_l(type, suspend, sessionId);
1239}
1240
1241void AudioFlinger::ThreadBase::setEffectSuspended_l(
1242 const effect_uuid_t *type, bool suspend, int sessionId)
1243{
1244 sp<EffectChain> chain;
1245 chain = getEffectChain_l(sessionId);
1246 if (chain != 0) {
1247 if (type != NULL) {
1248 chain->setEffectSuspended_l(type, suspend);
1249 } else {
1250 chain->setEffectSuspendedAll_l(suspend);
1251 }
1252 }
1253
1254 updateSuspendedSessions_l(type, suspend, sessionId);
1255}
1256
1257void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1258{
1259 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1260 if (index < 0) {
1261 return;
1262 }
1263
1264 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1265 mSuspendedSessions.editValueAt(index);
1266
1267 for (size_t i = 0; i < sessionEffects.size(); i++) {
1268 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1269 for (int j = 0; j < desc->mRefCount; j++) {
1270 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1271 chain->setEffectSuspendedAll_l(true);
1272 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001273 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001274 desc->mType.timeLow);
1275 chain->setEffectSuspended_l(&desc->mType, true);
1276 }
1277 }
1278 }
1279}
1280
Eric Laurentf82fccd2011-07-27 19:49:51 -07001281void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1282 bool suspend,
1283 int sessionId)
1284{
1285 int index = mSuspendedSessions.indexOfKey(sessionId);
1286
1287 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1288
1289 if (suspend) {
1290 if (index >= 0) {
1291 sessionEffects = mSuspendedSessions.editValueAt(index);
1292 } else {
1293 mSuspendedSessions.add(sessionId, sessionEffects);
1294 }
1295 } else {
1296 if (index < 0) {
1297 return;
1298 }
1299 sessionEffects = mSuspendedSessions.editValueAt(index);
1300 }
1301
1302
1303 int key = EffectChain::kKeyForSuspendAll;
1304 if (type != NULL) {
1305 key = type->timeLow;
1306 }
1307 index = sessionEffects.indexOfKey(key);
1308
1309 sp <SuspendedSessionDesc> desc;
1310 if (suspend) {
1311 if (index >= 0) {
1312 desc = sessionEffects.valueAt(index);
1313 } else {
1314 desc = new SuspendedSessionDesc();
1315 if (type != NULL) {
1316 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1317 }
1318 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001319 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001320 }
1321 desc->mRefCount++;
1322 } else {
1323 if (index < 0) {
1324 return;
1325 }
1326 desc = sessionEffects.valueAt(index);
1327 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001328 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001329 sessionEffects.removeItemsAt(index);
1330 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001331 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001332 sessionId);
1333 mSuspendedSessions.removeItem(sessionId);
1334 }
1335 }
1336 }
1337 if (!sessionEffects.isEmpty()) {
1338 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1339 }
1340}
1341
1342void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1343 bool enabled,
1344 int sessionId)
1345{
1346 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001347 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1348}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001349
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001350void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1351 bool enabled,
1352 int sessionId)
1353{
Eric Laurent6752ec82011-08-10 10:37:50 -07001354 if (mType != RECORD) {
1355 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1356 // another session. This gives the priority to well behaved effect control panels
1357 // and applications not using global effects.
1358 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1359 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1360 }
1361 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001362
1363 sp<EffectChain> chain = getEffectChain_l(sessionId);
1364 if (chain != 0) {
1365 chain->checkSuspendOnEffectEnabled(effect, enabled);
1366 }
1367}
1368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369// ----------------------------------------------------------------------------
1370
Eric Laurent464d5b32011-06-17 21:29:58 -07001371AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1372 AudioStreamOut* output,
1373 int id,
1374 uint32_t device)
1375 : ThreadBase(audioFlinger, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08001376 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent464d5b32011-06-17 21:29:58 -07001377 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001379 snprintf(mName, kNameLength, "AudioOut_%d", id);
1380
Eric Laurenta553c252009-07-17 12:17:14 -07001381 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382
Eric Laurenta553c252009-07-17 12:17:14 -07001383 mMasterVolume = mAudioFlinger->masterVolume();
1384 mMasterMute = mAudioFlinger->masterMute();
1385
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001386 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurenta553c252009-07-17 12:17:14 -07001387 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1388 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent05ce0942011-08-30 10:18:54 -07001389 mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391}
1392
Eric Laurenta553c252009-07-17 12:17:14 -07001393AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394{
1395 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396}
1397
Eric Laurenta553c252009-07-17 12:17:14 -07001398status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399{
1400 dumpInternals(fd, args);
1401 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001402 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 return NO_ERROR;
1404}
1405
Eric Laurenta553c252009-07-17 12:17:14 -07001406status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407{
1408 const size_t SIZE = 256;
1409 char buffer[SIZE];
1410 String8 result;
1411
Eric Laurenta553c252009-07-17 12:17:14 -07001412 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001414 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 -08001415 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001416 sp<Track> track = mTracks[i];
1417 if (track != 0) {
1418 track->dump(buffer, SIZE);
1419 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421 }
1422
Eric Laurenta553c252009-07-17 12:17:14 -07001423 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001425 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 -08001426 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001427 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 if (wTrack != 0) {
1429 sp<Track> track = wTrack.promote();
1430 if (track != 0) {
1431 track->dump(buffer, SIZE);
1432 result.append(buffer);
1433 }
1434 }
1435 }
1436 write(fd, result.string(), result.size());
1437 return NO_ERROR;
1438}
1439
Eric Laurenta553c252009-07-17 12:17:14 -07001440status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441{
1442 const size_t SIZE = 256;
1443 char buffer[SIZE];
1444 String8 result;
1445
Eric Laurent3fdb1262009-11-07 00:01:32 -08001446 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 result.append(buffer);
1448 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1449 result.append(buffer);
1450 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1451 result.append(buffer);
1452 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1453 result.append(buffer);
1454 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1455 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001456 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1457 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001458 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1459 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001461
1462 dumpBase(fd, args);
1463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 return NO_ERROR;
1465}
1466
1467// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001468status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469{
Eric Laurent828b9772011-08-07 16:32:26 -07001470 status_t status = initCheck();
1471 if (status == NO_ERROR) {
1472 LOGI("AudioFlinger's thread %p ready to run", this);
1473 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 LOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 }
Eric Laurent828b9772011-08-07 16:32:26 -07001476 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477}
1478
Eric Laurenta553c252009-07-17 12:17:14 -07001479void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001481 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482}
1483
Eric Laurenta553c252009-07-17 12:17:14 -07001484// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1485sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 const sp<AudioFlinger::Client>& client,
1487 int streamType,
1488 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001489 uint32_t format,
1490 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 int frameCount,
1492 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001493 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 status_t *status)
1495{
1496 sp<Track> track;
1497 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001498
1499 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001500 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1501 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1502 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1503 "for output %p with format %d",
1504 sampleRate, format, channelMask, mOutput, mFormat);
1505 lStatus = BAD_VALUE;
1506 goto Exit;
1507 }
Eric Laurenta553c252009-07-17 12:17:14 -07001508 }
1509 } else {
1510 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1511 if (sampleRate > mSampleRate*2) {
1512 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1513 lStatus = BAD_VALUE;
1514 goto Exit;
1515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517
Eric Laurent464d5b32011-06-17 21:29:58 -07001518 lStatus = initCheck();
1519 if (lStatus != NO_ERROR) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001520 LOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001521 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 }
1523
Eric Laurenta553c252009-07-17 12:17:14 -07001524 { // scope for mLock
1525 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001526
1527 // all tracks in same audio session must share the same routing strategy otherwise
1528 // conflicts will happen when tracks are moved from one output to another by audio policy
1529 // manager
1530 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001531 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001532 for (size_t i = 0; i < mTracks.size(); ++i) {
1533 sp<Track> t = mTracks[i];
1534 if (t != 0) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001535 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1536 if (sessionId == t->sessionId() && strategy != actual) {
1537 LOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1538 strategy, actual);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001539 lStatus = BAD_VALUE;
1540 goto Exit;
1541 }
1542 }
1543 }
1544
Eric Laurenta553c252009-07-17 12:17:14 -07001545 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001546 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001547 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001548 lStatus = NO_MEMORY;
1549 goto Exit;
1550 }
1551 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001552
1553 sp<EffectChain> chain = getEffectChain_l(sessionId);
1554 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001555 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001556 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001557 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001558 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001559 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001560
1561 // invalidate track immediately if the stream type was moved to another thread since
1562 // createTrack() was called by the client process.
1563 if (!mStreamTypes[streamType].valid) {
1564 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1565 this, streamType);
1566 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1567 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001568 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001569 lStatus = NO_ERROR;
1570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571Exit:
1572 if(status) {
1573 *status = lStatus;
1574 }
1575 return track;
1576}
1577
Eric Laurenta553c252009-07-17 12:17:14 -07001578uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579{
Eric Laurent828b9772011-08-07 16:32:26 -07001580 Mutex::Autolock _l(mLock);
1581 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001582 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001583 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 return 0;
1585 }
1586}
1587
Eric Laurenta553c252009-07-17 12:17:14 -07001588status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589{
1590 mMasterVolume = value;
1591 return NO_ERROR;
1592}
1593
Eric Laurenta553c252009-07-17 12:17:14 -07001594status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595{
1596 mMasterMute = muted;
1597 return NO_ERROR;
1598}
1599
Eric Laurenta553c252009-07-17 12:17:14 -07001600float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601{
1602 return mMasterVolume;
1603}
1604
Eric Laurenta553c252009-07-17 12:17:14 -07001605bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606{
1607 return mMasterMute;
1608}
1609
Eric Laurenta553c252009-07-17 12:17:14 -07001610status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611{
1612 mStreamTypes[stream].volume = value;
1613 return NO_ERROR;
1614}
1615
Eric Laurenta553c252009-07-17 12:17:14 -07001616status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617{
1618 mStreamTypes[stream].mute = muted;
1619 return NO_ERROR;
1620}
1621
Eric Laurenta553c252009-07-17 12:17:14 -07001622float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623{
1624 return mStreamTypes[stream].volume;
1625}
1626
Eric Laurenta553c252009-07-17 12:17:14 -07001627bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628{
1629 return mStreamTypes[stream].mute;
1630}
1631
Eric Laurenta553c252009-07-17 12:17:14 -07001632// addTrack_l() must be called with ThreadBase::mLock held
1633status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634{
1635 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001636
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001637 // set retry count for buffer fill
1638 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001639 if (mActiveTracks.indexOf(track) < 0) {
1640 // the track is newly added, make sure it fills up all its
1641 // buffers before playing. This is to ensure the client will
1642 // effectively get the latency it requested.
1643 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001644 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001645 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001646 if (track->mainBuffer() != mMixBuffer) {
1647 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1648 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001649 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001650 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001651 }
1652 }
1653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001655 }
Eric Laurenta553c252009-07-17 12:17:14 -07001656
Steve Block71f2cf12011-10-20 11:56:00 +01001657 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001658 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659
1660 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001661}
1662
Eric Laurenta553c252009-07-17 12:17:14 -07001663// destroyTrack_l() must be called with ThreadBase::mLock held
1664void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001665{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001666 track->mState = TrackBase::TERMINATED;
1667 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001668 removeTrack_l(track);
1669 }
1670}
1671
1672void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1673{
1674 mTracks.remove(track);
1675 deleteTrackName_l(track->name());
1676 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1677 if (chain != 0) {
1678 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001679 }
1680}
1681
Eric Laurenta553c252009-07-17 12:17:14 -07001682String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001683{
Eric Laurent828b9772011-08-07 16:32:26 -07001684 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001685 char *s;
1686
Eric Laurent828b9772011-08-07 16:32:26 -07001687 Mutex::Autolock _l(mLock);
1688 if (initCheck() != NO_ERROR) {
1689 return out_s8;
1690 }
1691
Dima Zavin31f188892011-04-18 16:57:27 -07001692 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001693 out_s8 = String8(s);
1694 free(s);
1695 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001696}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001697
Eric Laurent828b9772011-08-07 16:32:26 -07001698// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001699void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001700 AudioSystem::OutputDescriptor desc;
1701 void *param2 = 0;
1702
Steve Block71f2cf12011-10-20 11:56:00 +01001703 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001704
1705 switch (event) {
1706 case AudioSystem::OUTPUT_OPENED:
1707 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001708 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001709 desc.samplingRate = mSampleRate;
1710 desc.format = mFormat;
1711 desc.frameCount = mFrameCount;
1712 desc.latency = latency();
1713 param2 = &desc;
1714 break;
1715
1716 case AudioSystem::STREAM_CONFIG_CHANGED:
1717 param2 = &param;
1718 case AudioSystem::OUTPUT_CLOSED:
1719 default:
1720 break;
1721 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001722 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001723}
1724
1725void AudioFlinger::PlaybackThread::readOutputParameters()
1726{
Dima Zavin31f188892011-04-18 16:57:27 -07001727 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001728 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1729 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001730 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1731 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1732 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001733
Eric Laurenta553c252009-07-17 12:17:14 -07001734 // FIXME - Current mixer implementation only supports stereo output: Always
1735 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001736 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001737 mMixBuffer = new int16_t[mFrameCount * 2];
1738 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001739
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001740 // force reconfiguration of effect chains and engines to take new buffer size and audio
1741 // parameters into account
1742 // Note that mLock is not held when readOutputParameters() is called from the constructor
1743 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1744 // matter.
1745 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1746 Vector< sp<EffectChain> > effectChains = mEffectChains;
1747 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001748 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001749 }
Eric Laurenta553c252009-07-17 12:17:14 -07001750}
1751
Eric Laurent0986e792010-01-19 17:37:09 -08001752status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1753{
1754 if (halFrames == 0 || dspFrames == 0) {
1755 return BAD_VALUE;
1756 }
Eric Laurent828b9772011-08-07 16:32:26 -07001757 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001758 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001759 return INVALID_OPERATION;
1760 }
Dima Zavin31f188892011-04-18 16:57:27 -07001761 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001762
Dima Zavin31f188892011-04-18 16:57:27 -07001763 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001764}
1765
Eric Laurent493941b2010-07-28 01:32:47 -07001766uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001767{
1768 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001769 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001770 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001771 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001772 }
1773
1774 for (size_t i = 0; i < mTracks.size(); ++i) {
1775 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001776 if (sessionId == track->sessionId() &&
1777 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001778 result |= TRACK_SESSION;
1779 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001780 }
1781 }
1782
Eric Laurent493941b2010-07-28 01:32:47 -07001783 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001784}
1785
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001786uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1787{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001788 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001789 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001790 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1791 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001792 }
1793 for (size_t i = 0; i < mTracks.size(); i++) {
1794 sp<Track> track = mTracks[i];
1795 if (sessionId == track->sessionId() &&
1796 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001797 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001798 }
1799 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001800 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001801}
1802
Eric Laurent53334cd2010-06-23 17:38:20 -07001803
Eric Laurent828b9772011-08-07 16:32:26 -07001804AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1805{
1806 Mutex::Autolock _l(mLock);
1807 return mOutput;
1808}
1809
1810AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1811{
1812 Mutex::Autolock _l(mLock);
1813 AudioStreamOut *output = mOutput;
1814 mOutput = NULL;
1815 return output;
1816}
1817
1818// this method must always be called either with ThreadBase mLock held or inside the thread loop
1819audio_stream_t* AudioFlinger::PlaybackThread::stream()
1820{
1821 if (mOutput == NULL) {
1822 return NULL;
1823 }
1824 return &mOutput->stream->common;
1825}
1826
Eric Laurent44331692011-12-05 09:47:19 -08001827uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1828{
1829 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1830 // decoding and transfer time. So sleeping for half of the latency would likely cause
1831 // underruns
1832 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1833 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1834 } else {
1835 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1836 }
1837}
1838
Eric Laurenta553c252009-07-17 12:17:14 -07001839// ----------------------------------------------------------------------------
1840
Dima Zavin31f188892011-04-18 16:57:27 -07001841AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001842 : PlaybackThread(audioFlinger, output, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08001843 mAudioMixer(NULL)
Eric Laurenta553c252009-07-17 12:17:14 -07001844{
Eric Laurent464d5b32011-06-17 21:29:58 -07001845 mType = ThreadBase::MIXER;
Eric Laurenta553c252009-07-17 12:17:14 -07001846 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1847
1848 // FIXME - Current mixer implementation only supports stereo output
1849 if (mChannelCount == 1) {
1850 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001852}
1853
Eric Laurenta553c252009-07-17 12:17:14 -07001854AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001855{
Eric Laurenta553c252009-07-17 12:17:14 -07001856 delete mAudioMixer;
1857}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858
Eric Laurenta553c252009-07-17 12:17:14 -07001859bool AudioFlinger::MixerThread::threadLoop()
1860{
Eric Laurenta553c252009-07-17 12:17:14 -07001861 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001862 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001863 nsecs_t standbyTime = systemTime();
1864 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001865 // FIXME: Relaxed timing because of a certain device that can't meet latency
1866 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001867 // increase threshold again due to low power audio mode. The way this warning threshold is
1868 // calculated and its usefulness should be reconsidered anyway.
1869 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001870 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001871 bool longStandbyExit = false;
1872 uint32_t activeSleepTime = activeSleepTimeUs();
1873 uint32_t idleSleepTime = idleSleepTimeUs();
1874 uint32_t sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001875 uint32_t sleepTimeShift = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001876 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001877#ifdef DEBUG_CPU_USAGE
1878 ThreadCpuUsage cpu;
1879 const CentralTendencyStatistics& stats = cpu.statistics();
1880#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881
Eric Laurent6dbdc402011-07-22 09:04:31 -07001882 acquireWakeLock();
1883
Eric Laurenta553c252009-07-17 12:17:14 -07001884 while (!exitPending())
1885 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001886#ifdef DEBUG_CPU_USAGE
1887 cpu.sampleAndEnable();
1888 unsigned n = stats.n();
1889 // cpu.elapsed() is expensive, so don't call it every loop
1890 if ((n & 127) == 1) {
1891 long long elapsed = cpu.elapsed();
1892 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1893 double perLoop = elapsed / (double) n;
1894 double perLoop100 = perLoop * 0.01;
1895 double mean = stats.mean();
1896 double stddev = stats.stddev();
1897 double minimum = stats.minimum();
1898 double maximum = stats.maximum();
1899 cpu.resetStatistics();
1900 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",
1901 elapsed * .000000001, n, perLoop * .000001,
1902 mean * .001,
1903 stddev * .001,
1904 minimum * .001,
1905 maximum * .001,
1906 mean / perLoop100,
1907 stddev / perLoop100,
1908 minimum / perLoop100,
1909 maximum / perLoop100);
1910 }
1911 }
1912#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001913 processConfigEvents();
1914
Eric Laurent059b4be2009-11-09 23:32:22 -08001915 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001916 { // scope for mLock
1917
1918 Mutex::Autolock _l(mLock);
1919
1920 if (checkForNewParameters_l()) {
1921 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001922 // FIXME: Relaxed timing because of a certain device that can't meet latency
1923 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001924 // increase threshold again due to low power audio mode. The way this warning
1925 // threshold is calculated and its usefulness should be reconsidered anyway.
1926 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001927 activeSleepTime = activeSleepTimeUs();
1928 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001929 }
1930
1931 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1932
1933 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001934 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1935 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001936 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01001937 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001938 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001939 mStandby = true;
1940 mBytesWritten = 0;
1941 }
1942
1943 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1944 // we're about to wait, flush the binder command buffer
1945 IPCThreadState::self()->flushCommands();
1946
1947 if (exitPending()) break;
1948
Eric Laurent6dbdc402011-07-22 09:04:31 -07001949 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001950 // wait until we have something to do...
Steve Block71f2cf12011-10-20 11:56:00 +01001951 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07001952 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01001953 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001954 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001955
1956 if (mMasterMute == false) {
1957 char value[PROPERTY_VALUE_MAX];
1958 property_get("ro.audio.silent", value, "0");
1959 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00001960 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07001961 setMasterMute(true);
1962 }
1963 }
1964
1965 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001966 sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001967 sleepTimeShift = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001968 continue;
1969 }
1970 }
1971
Eric Laurent059b4be2009-11-09 23:32:22 -08001972 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001973
1974 // prevent any changes in effect chain list and in each effect chain
1975 // during mixing and effect process as the audio buffers could be deleted
1976 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001977 lockEffectChains_l(effectChains);
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08001978 }
Eric Laurenta553c252009-07-17 12:17:14 -07001979
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001980 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001981 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001982 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001983 sleepTime = 0;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001984 // increase sleep time progressively when application underrun condition clears
1985 if (sleepTimeShift > 0) {
1986 sleepTimeShift--;
1987 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07001988 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001989 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001990 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001991 // If no tracks are ready, sleep once for the duration of an output
1992 // buffer size, then write 0s to the output
1993 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001994 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001995 sleepTime = activeSleepTime >> sleepTimeShift;
1996 if (sleepTime < kMinThreadSleepTimeUs) {
1997 sleepTime = kMinThreadSleepTimeUs;
1998 }
1999 // reduce sleep time in case of consecutive application underruns to avoid
2000 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2001 // duration we would end up writing less data than needed by the audio HAL if
2002 // the condition persists.
2003 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2004 sleepTimeShift++;
2005 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002006 } else {
2007 sleepTime = idleSleepTime;
2008 }
2009 } else if (mBytesWritten != 0 ||
2010 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002011 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002012 sleepTime = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01002013 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07002014 }
Eric Laurent65b65452010-06-01 23:49:17 -07002015 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07002016 }
2017
2018 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002019 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002020 }
2021 // sleepTime == 0 means we must write to audio hardware
2022 if (sleepTime == 0) {
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08002023 for (size_t i = 0; i < effectChains.size(); i ++) {
2024 effectChains[i]->process_l();
2025 }
2026 // enable changes in effect chain
2027 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002028 mLastWriteTime = systemTime();
2029 mInWrite = true;
2030 mBytesWritten += mixBufferSize;
2031
Dima Zavin31f188892011-04-18 16:57:27 -07002032 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002033 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002034 mNumWrites++;
2035 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002036 nsecs_t now = systemTime();
2037 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07002038 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002039 mNumDelayedWrites++;
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002040 if ((now - lastWarning) > kWarningThrottleNs) {
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002041 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2042 ns2ms(delta), mNumDelayedWrites, this);
2043 lastWarning = now;
2044 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002045 if (mStandby) {
2046 longStandbyExit = true;
2047 }
Eric Laurenta553c252009-07-17 12:17:14 -07002048 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002049 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002050 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002051 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002052 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002053 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002054 }
2055
2056 // finally let go of all our tracks, without the lock held
2057 // since we can't guarantee the destructors won't acquire that
2058 // same lock.
2059 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002060
2061 // Effect chains will be actually deleted here if they were removed from
2062 // mEffectChains list during mixing or effects processing
2063 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002064 }
2065
2066 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002067 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002068 }
Eric Laurenta553c252009-07-17 12:17:14 -07002069
Eric Laurent6dbdc402011-07-22 09:04:31 -07002070 releaseWakeLock();
2071
Steve Block71f2cf12011-10-20 11:56:00 +01002072 ALOGV("MixerThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002073 return false;
2074}
2075
2076// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08002077uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002078{
2079
Eric Laurent059b4be2009-11-09 23:32:22 -08002080 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002081 // find out which tracks need to be processed
2082 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002083 size_t mixedTracks = 0;
2084 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002085
2086 float masterVolume = mMasterVolume;
2087 bool masterMute = mMasterMute;
2088
Eric Laurent8cc93b92010-08-11 05:20:11 -07002089 if (masterMute) {
2090 masterVolume = 0;
2091 }
Eric Laurent65b65452010-06-01 23:49:17 -07002092 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002093 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002094 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002095 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002096 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002097 masterVolume = (float)((v + (1 << 23)) >> 24);
2098 chain.clear();
2099 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002100
Eric Laurenta553c252009-07-17 12:17:14 -07002101 for (size_t i=0 ; i<count ; i++) {
2102 sp<Track> t = activeTracks[i].promote();
2103 if (t == 0) continue;
2104
2105 Track* const track = t.get();
2106 audio_track_cblk_t* cblk = track->cblk();
2107
2108 // The first time a track is added we wait
2109 // for all its buffers to be filled before processing it
2110 mAudioMixer->setActiveTrack(track->name());
Eric Laurent8a04fe02011-11-08 18:10:16 -08002111 // make sure that we have enough frames to mix one full buffer.
2112 // enforce this condition only once to enable draining the buffer in case the client
2113 // app does not call stop() and relies on underrun to stop:
2114 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2115 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002116 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002117 if (!track->isStopped() && !track->isPausing() &&
2118 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002119 if (t->sampleRate() == (int)mSampleRate) {
2120 minFrames = mFrameCount;
2121 } else {
Eric Laurent72dafb22011-12-22 16:08:41 -08002122 // +1 for rounding and +1 for additional sample needed for interpolation
2123 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2124 // add frames already consumed but not yet released by the resampler
2125 // because cblk->framesReady() will include these frames
2126 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2127 // the minimum track buffer size is normally twice the number of frames necessary
2128 // to fill one buffer and the resampler should not leave more than one buffer worth
2129 // of unreleased frames after each pass, but just in case...
2130 LOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002131 }
2132 }
2133 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002134 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002135 {
Steve Block71f2cf12011-10-20 11:56:00 +01002136 //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 -07002137
Eric Laurent65b65452010-06-01 23:49:17 -07002138 mixedTracks++;
2139
2140 // track->mainBuffer() != mMixBuffer means there is an effect chain
2141 // connected to the track
2142 chain.clear();
2143 if (track->mainBuffer() != mMixBuffer) {
2144 chain = getEffectChain_l(track->sessionId());
2145 // Delegate volume control to effect in track effect chain if needed
2146 if (chain != 0) {
2147 tracksWithEffect++;
2148 } else {
2149 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2150 track->name(), track->sessionId());
2151 }
2152 }
2153
2154
2155 int param = AudioMixer::VOLUME;
2156 if (track->mFillingUpStatus == Track::FS_FILLED) {
2157 // no ramp for the first volume setting
2158 track->mFillingUpStatus = Track::FS_ACTIVE;
2159 if (track->mState == TrackBase::RESUMING) {
2160 track->mState = TrackBase::ACTIVE;
2161 param = AudioMixer::RAMP_VOLUME;
2162 }
Eric Laurent4bb21c42011-02-28 16:52:51 -08002163 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002164 } else if (cblk->server != 0) {
2165 // If the track is stopped before the first frame was mixed,
2166 // do not apply ramp
2167 param = AudioMixer::RAMP_VOLUME;
2168 }
2169
Eric Laurenta553c252009-07-17 12:17:14 -07002170 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002171 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002172 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002173 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002174 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002175 if (track->isPausing()) {
2176 track->setPaused();
2177 }
2178 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002179
Glenn Kasten871c16c2010-03-05 12:18:01 -08002180 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002181 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002182 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002183 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2184 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07002185
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002186 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002187 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002188 // Delegate volume control to effect in track effect chain if needed
2189 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2190 // Do not ramp volume if volume is controlled by effect
2191 param = AudioMixer::VOLUME;
2192 track->mHasVolumeController = true;
2193 } else {
2194 // force no volume ramp when volume controller was just disabled or removed
2195 // from effect chain to avoid volume spike
2196 if (track->mHasVolumeController) {
2197 param = AudioMixer::VOLUME;
2198 }
2199 track->mHasVolumeController = false;
2200 }
2201
2202 // Convert volumes from 8.24 to 4.12 format
2203 int16_t left, right, aux;
2204 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2205 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2206 left = int16_t(v_clamped);
2207 v_clamped = (vr + (1 << 11)) >> 12;
2208 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2209 right = int16_t(v_clamped);
2210
2211 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2212 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002213
Eric Laurent65b65452010-06-01 23:49:17 -07002214 // XXX: these things DON'T need to be done each time
2215 mAudioMixer->setBufferProvider(track);
Glenn Kastenaf62dbc2011-12-15 14:54:01 -08002216 mAudioMixer->enable();
Eric Laurent65b65452010-06-01 23:49:17 -07002217
2218 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2219 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2220 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002221 mAudioMixer->setParameter(
2222 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002223 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002224 mAudioMixer->setParameter(
2225 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002226 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002227 mAudioMixer->setParameter(
2228 AudioMixer::RESAMPLE,
2229 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002230 (void *)(cblk->sampleRate));
2231 mAudioMixer->setParameter(
2232 AudioMixer::TRACK,
2233 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2234 mAudioMixer->setParameter(
2235 AudioMixer::TRACK,
2236 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002237
2238 // reset retry count
2239 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08002240 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002241 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002242 //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 -07002243 if (track->isStopped()) {
2244 track->reset();
2245 }
2246 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2247 // We have consumed all the buffers of this track.
2248 // Remove it from the list of active tracks.
2249 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002250 } else {
2251 // No buffers for this track. Give it a few chances to
2252 // fill a buffer, then remove it from active list.
2253 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002254 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07002255 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002256 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002257 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -08002258 } else if (mixerStatus != MIXER_TRACKS_READY) {
2259 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002260 }
Eric Laurenta553c252009-07-17 12:17:14 -07002261 }
Glenn Kastenaf62dbc2011-12-15 14:54:01 -08002262 mAudioMixer->disable();
Eric Laurenta553c252009-07-17 12:17:14 -07002263 }
2264 }
2265
2266 // remove all the tracks that need to be...
2267 count = tracksToRemove->size();
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002268 if (CC_UNLIKELY(count)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002269 for (size_t i=0 ; i<count ; i++) {
2270 const sp<Track>& track = tracksToRemove->itemAt(i);
2271 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002272 if (track->mainBuffer() != mMixBuffer) {
2273 chain = getEffectChain_l(track->sessionId());
2274 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002275 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002276 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002277 }
2278 }
Eric Laurenta553c252009-07-17 12:17:14 -07002279 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002280 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002281 }
2282 }
2283 }
2284
Eric Laurent65b65452010-06-01 23:49:17 -07002285 // mix buffer must be cleared if all tracks are connected to an
2286 // effect chain as in this case the mixer will not write to
2287 // mix buffer and track effects will accumulate into it
2288 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2289 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2290 }
2291
Eric Laurent059b4be2009-11-09 23:32:22 -08002292 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002293}
2294
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002295void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002296{
Steve Block71f2cf12011-10-20 11:56:00 +01002297 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002298 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002299 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002300
Eric Laurenta553c252009-07-17 12:17:14 -07002301 size_t size = mTracks.size();
2302 for (size_t i = 0; i < size; i++) {
2303 sp<Track> t = mTracks[i];
2304 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002305 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002306 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002307 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002308 }
2309}
Eric Laurenta553c252009-07-17 12:17:14 -07002310
Eric Laurent05ce0942011-08-30 10:18:54 -07002311void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2312{
Steve Block71f2cf12011-10-20 11:56:00 +01002313 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002314 this, streamType, valid);
2315 Mutex::Autolock _l(mLock);
2316
2317 mStreamTypes[streamType].valid = valid;
2318}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319
Eric Laurenta553c252009-07-17 12:17:14 -07002320// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002321int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322{
2323 return mAudioMixer->getTrackName();
2324}
2325
Eric Laurenta553c252009-07-17 12:17:14 -07002326// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002327void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328{
Steve Block71f2cf12011-10-20 11:56:00 +01002329 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 mAudioMixer->deleteTrackName(name);
2331}
2332
Eric Laurenta553c252009-07-17 12:17:14 -07002333// checkForNewParameters_l() must be called with ThreadBase::mLock held
2334bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335{
Eric Laurenta553c252009-07-17 12:17:14 -07002336 bool reconfig = false;
2337
Eric Laurent8fce46a2009-08-04 09:45:33 -07002338 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002339 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002340 String8 keyValuePair = mNewParameters[0];
2341 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002342 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002343
Eric Laurenta553c252009-07-17 12:17:14 -07002344 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2345 reconfig = true;
2346 }
2347 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002348 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002349 status = BAD_VALUE;
2350 } else {
2351 reconfig = true;
2352 }
2353 }
2354 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002355 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002356 status = BAD_VALUE;
2357 } else {
2358 reconfig = true;
2359 }
2360 }
2361 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2362 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastene5fb2632011-12-14 10:28:06 -08002363 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07002364 // if frame count is changed after track creation
2365 if (!mTracks.isEmpty()) {
2366 status = INVALID_OPERATION;
2367 } else {
2368 reconfig = true;
2369 }
2370 }
Eric Laurent65b65452010-06-01 23:49:17 -07002371 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002372 // when changing the audio output device, call addBatteryData to notify
2373 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002374 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002375 uint32_t params = 0;
2376 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002377 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002378 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2379 }
2380
2381 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002382 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002383 // check if any other device (except speaker) is on
2384 if (value & deviceWithoutSpeaker ) {
2385 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2386 }
2387
2388 if (params != 0) {
2389 addBatteryData(params);
2390 }
2391 }
2392
Eric Laurent65b65452010-06-01 23:49:17 -07002393 // forward device change to effects that have requested to be
2394 // aware of attached audio device.
2395 mDevice = (uint32_t)value;
2396 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002397 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002398 }
2399 }
2400
Eric Laurenta553c252009-07-17 12:17:14 -07002401 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002402 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002403 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002404 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002405 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002406 mStandby = true;
2407 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002408 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002409 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002410 }
2411 if (status == NO_ERROR && reconfig) {
2412 delete mAudioMixer;
2413 readOutputParameters();
2414 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2415 for (size_t i = 0; i < mTracks.size() ; i++) {
2416 int name = getTrackName_l();
2417 if (name < 0) break;
2418 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002419 // limit track sample rate to 2 x new output sample rate
2420 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2421 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2422 }
Eric Laurenta553c252009-07-17 12:17:14 -07002423 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002424 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002425 }
2426 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002427
2428 mNewParameters.removeAt(0);
2429
Eric Laurenta553c252009-07-17 12:17:14 -07002430 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002431 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002432 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2433 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002434 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002435 }
2436 return reconfig;
2437}
2438
2439status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2440{
2441 const size_t SIZE = 256;
2442 char buffer[SIZE];
2443 String8 result;
2444
2445 PlaybackThread::dumpInternals(fd, args);
2446
2447 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2448 result.append(buffer);
2449 write(fd, result.string(), result.size());
2450 return NO_ERROR;
2451}
2452
Eric Laurent059b4be2009-11-09 23:32:22 -08002453uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2454{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002455 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002456}
2457
Eric Laurent8448a792010-08-18 18:13:17 -07002458uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2459{
2460 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2461}
2462
Eric Laurenta553c252009-07-17 12:17:14 -07002463// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002464AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002465 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002466{
Eric Laurent464d5b32011-06-17 21:29:58 -07002467 mType = ThreadBase::DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -07002468}
2469
2470AudioFlinger::DirectOutputThread::~DirectOutputThread()
2471{
2472}
2473
Eric Laurent65b65452010-06-01 23:49:17 -07002474static inline
2475int32_t mul(int16_t in, int16_t v)
2476{
2477#if defined(__arm__) && !defined(__thumb__)
2478 int32_t out;
2479 asm( "smulbb %[out], %[in], %[v] \n"
2480 : [out]"=r"(out)
2481 : [in]"%r"(in), [v]"r"(v)
2482 : );
2483 return out;
2484#else
2485 return in * int32_t(v);
2486#endif
2487}
2488
2489void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2490{
2491 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002492 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002493 return;
2494 }
2495
2496 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002497 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002498 size_t count = mFrameCount * mChannelCount;
2499 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2500 int16_t *dst = mMixBuffer + count-1;
2501 while(count--) {
2502 *dst-- = (int16_t)(*src--^0x80) << 8;
2503 }
2504 }
2505
2506 size_t frameCount = mFrameCount;
2507 int16_t *out = mMixBuffer;
2508 if (ramp) {
2509 if (mChannelCount == 1) {
2510 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2511 int32_t vlInc = d / (int32_t)frameCount;
2512 int32_t vl = ((int32_t)mLeftVolShort << 16);
2513 do {
2514 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2515 out++;
2516 vl += vlInc;
2517 } while (--frameCount);
2518
2519 } else {
2520 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2521 int32_t vlInc = d / (int32_t)frameCount;
2522 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2523 int32_t vrInc = d / (int32_t)frameCount;
2524 int32_t vl = ((int32_t)mLeftVolShort << 16);
2525 int32_t vr = ((int32_t)mRightVolShort << 16);
2526 do {
2527 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2528 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2529 out += 2;
2530 vl += vlInc;
2531 vr += vrInc;
2532 } while (--frameCount);
2533 }
2534 } else {
2535 if (mChannelCount == 1) {
2536 do {
2537 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2538 out++;
2539 } while (--frameCount);
2540 } else {
2541 do {
2542 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2543 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2544 out += 2;
2545 } while (--frameCount);
2546 }
2547 }
2548
2549 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002550 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002551 size_t count = mFrameCount * mChannelCount;
2552 int16_t *src = mMixBuffer;
2553 uint8_t *dst = (uint8_t *)mMixBuffer;
2554 while(count--) {
2555 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2556 }
2557 }
2558
2559 mLeftVolShort = leftVol;
2560 mRightVolShort = rightVol;
2561}
2562
Eric Laurenta553c252009-07-17 12:17:14 -07002563bool AudioFlinger::DirectOutputThread::threadLoop()
2564{
Eric Laurent059b4be2009-11-09 23:32:22 -08002565 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002566 sp<Track> trackToRemove;
2567 sp<Track> activeTrack;
2568 nsecs_t standbyTime = systemTime();
2569 int8_t *curBuf;
2570 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002571 uint32_t activeSleepTime = activeSleepTimeUs();
2572 uint32_t idleSleepTime = idleSleepTimeUs();
2573 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002574 // use shorter standby delay as on normal output to release
2575 // hardware resources as soon as possible
2576 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002577
Eric Laurent6dbdc402011-07-22 09:04:31 -07002578 acquireWakeLock();
2579
Eric Laurenta553c252009-07-17 12:17:14 -07002580 while (!exitPending())
2581 {
Eric Laurent65b65452010-06-01 23:49:17 -07002582 bool rampVolume;
2583 uint16_t leftVol;
2584 uint16_t rightVol;
2585 Vector< sp<EffectChain> > effectChains;
2586
Eric Laurenta553c252009-07-17 12:17:14 -07002587 processConfigEvents();
2588
Eric Laurent059b4be2009-11-09 23:32:22 -08002589 mixerStatus = MIXER_IDLE;
2590
Eric Laurenta553c252009-07-17 12:17:14 -07002591 { // scope for the mLock
2592
2593 Mutex::Autolock _l(mLock);
2594
2595 if (checkForNewParameters_l()) {
2596 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002597 activeSleepTime = activeSleepTimeUs();
2598 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002599 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002600 }
2601
2602 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002603 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2604 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002605 // wait until we have something to do...
2606 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01002607 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002608 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002609 mStandby = true;
2610 mBytesWritten = 0;
2611 }
2612
2613 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2614 // we're about to wait, flush the binder command buffer
2615 IPCThreadState::self()->flushCommands();
2616
2617 if (exitPending()) break;
2618
Eric Laurent6dbdc402011-07-22 09:04:31 -07002619 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002620 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002621 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002622 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002623 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002624
2625 if (mMasterMute == false) {
2626 char value[PROPERTY_VALUE_MAX];
2627 property_get("ro.audio.silent", value, "0");
2628 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00002629 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07002630 setMasterMute(true);
2631 }
2632 }
2633
Eric Laurentef9500f2010-03-11 14:47:00 -08002634 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002635 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002636 continue;
2637 }
2638 }
2639
Eric Laurent65b65452010-06-01 23:49:17 -07002640 effectChains = mEffectChains;
2641
Eric Laurenta553c252009-07-17 12:17:14 -07002642 // find out which tracks need to be processed
2643 if (mActiveTracks.size() != 0) {
2644 sp<Track> t = mActiveTracks[0].promote();
2645 if (t == 0) continue;
2646
2647 Track* const track = t.get();
2648 audio_track_cblk_t* cblk = track->cblk();
2649
2650 // The first time a track is added we wait
2651 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002652 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002653 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002654 {
Steve Block71f2cf12011-10-20 11:56:00 +01002655 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002656
Eric Laurent65b65452010-06-01 23:49:17 -07002657 if (track->mFillingUpStatus == Track::FS_FILLED) {
2658 track->mFillingUpStatus = Track::FS_ACTIVE;
2659 mLeftVolFloat = mRightVolFloat = 0;
2660 mLeftVolShort = mRightVolShort = 0;
2661 if (track->mState == TrackBase::RESUMING) {
2662 track->mState = TrackBase::ACTIVE;
2663 rampVolume = true;
2664 }
2665 } else if (cblk->server != 0) {
2666 // If the track is stopped before the first frame was mixed,
2667 // do not apply ramp
2668 rampVolume = true;
2669 }
Eric Laurenta553c252009-07-17 12:17:14 -07002670 // compute volume for this track
2671 float left, right;
2672 if (track->isMuted() || mMasterMute || track->isPausing() ||
2673 mStreamTypes[track->type()].mute) {
2674 left = right = 0;
2675 if (track->isPausing()) {
2676 track->setPaused();
2677 }
2678 } else {
2679 float typeVolume = mStreamTypes[track->type()].volume;
2680 float v = mMasterVolume * typeVolume;
2681 float v_clamped = v * cblk->volume[0];
2682 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2683 left = v_clamped/MAX_GAIN;
2684 v_clamped = v * cblk->volume[1];
2685 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2686 right = v_clamped/MAX_GAIN;
2687 }
2688
Eric Laurent65b65452010-06-01 23:49:17 -07002689 if (left != mLeftVolFloat || right != mRightVolFloat) {
2690 mLeftVolFloat = left;
2691 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002692
Eric Laurent65b65452010-06-01 23:49:17 -07002693 // If audio HAL implements volume control,
2694 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002695 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002696 left = 1.0f;
2697 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002698 }
Eric Laurent65b65452010-06-01 23:49:17 -07002699
2700 // Convert volumes from float to 8.24
2701 uint32_t vl = (uint32_t)(left * (1 << 24));
2702 uint32_t vr = (uint32_t)(right * (1 << 24));
2703
2704 // Delegate volume control to effect in track effect chain if needed
2705 // only one effect chain can be present on DirectOutputThread, so if
2706 // there is one, the track is connected to it
2707 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002708 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002709 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002710 rampVolume = false;
2711 }
2712 }
2713
2714 // Convert volumes from 8.24 to 4.12 format
2715 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2716 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2717 leftVol = (uint16_t)v_clamped;
2718 v_clamped = (vr + (1 << 11)) >> 12;
2719 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2720 rightVol = (uint16_t)v_clamped;
2721 } else {
2722 leftVol = mLeftVolShort;
2723 rightVol = mRightVolShort;
2724 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002725 }
2726
2727 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002728 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002729 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002730 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002731 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002732 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002733 if (track->isStopped()) {
2734 track->reset();
2735 }
2736 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2737 // We have consumed all the buffers of this track.
2738 // Remove it from the list of active tracks.
2739 trackToRemove = track;
2740 } else {
2741 // No buffers for this track. Give it a few chances to
2742 // fill a buffer, then remove it from active list.
2743 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002744 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurenta553c252009-07-17 12:17:14 -07002745 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002746 } else {
2747 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002748 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002749 }
Eric Laurenta553c252009-07-17 12:17:14 -07002750 }
2751 }
2752
2753 // remove all the tracks that need to be...
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002754 if (CC_UNLIKELY(trackToRemove != 0)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002755 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002756 if (!effectChains.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01002757 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002758 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002759 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002760 }
Eric Laurenta553c252009-07-17 12:17:14 -07002761 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002762 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002763 }
2764 }
Eric Laurent65b65452010-06-01 23:49:17 -07002765
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002766 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002767 }
2768
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002769 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002770 AudioBufferProvider::Buffer buffer;
2771 size_t frameCount = mFrameCount;
2772 curBuf = (int8_t *)mMixBuffer;
2773 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002774 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002775 buffer.frameCount = frameCount;
2776 activeTrack->getNextBuffer(&buffer);
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002777 if (CC_UNLIKELY(buffer.raw == NULL)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002778 memset(curBuf, 0, frameCount * mFrameSize);
2779 break;
2780 }
2781 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2782 frameCount -= buffer.frameCount;
2783 curBuf += buffer.frameCount * mFrameSize;
2784 activeTrack->releaseBuffer(&buffer);
2785 }
2786 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002787 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002788 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002789 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002790 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2791 sleepTime = activeSleepTime;
2792 } else {
2793 sleepTime = idleSleepTime;
2794 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002795 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002796 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002797 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002798 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002799 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002800
Eric Laurentf69a3f82009-09-22 00:35:48 -07002801 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002802 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002803 }
2804 // sleepTime == 0 means we must write to audio hardware
2805 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002806 if (mixerStatus == MIXER_TRACKS_READY) {
2807 applyVolume(leftVol, rightVol, rampVolume);
2808 }
2809 for (size_t i = 0; i < effectChains.size(); i ++) {
2810 effectChains[i]->process_l();
2811 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002812 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002813
Eric Laurentf69a3f82009-09-22 00:35:48 -07002814 mLastWriteTime = systemTime();
2815 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002816 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002817 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002818 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002819 mNumWrites++;
2820 mInWrite = false;
2821 mStandby = false;
2822 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002823 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002824 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002825 }
2826
2827 // finally let go of removed track, without the lock held
2828 // since we can't guarantee the destructors won't acquire that
2829 // same lock.
2830 trackToRemove.clear();
2831 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002832
2833 // Effect chains will be actually deleted here if they were removed from
2834 // mEffectChains list during mixing or effects processing
2835 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002836 }
2837
2838 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002839 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002840 }
Eric Laurenta553c252009-07-17 12:17:14 -07002841
Eric Laurent6dbdc402011-07-22 09:04:31 -07002842 releaseWakeLock();
2843
Steve Block71f2cf12011-10-20 11:56:00 +01002844 ALOGV("DirectOutputThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002845 return false;
2846}
2847
2848// getTrackName_l() must be called with ThreadBase::mLock held
2849int AudioFlinger::DirectOutputThread::getTrackName_l()
2850{
2851 return 0;
2852}
2853
2854// deleteTrackName_l() must be called with ThreadBase::mLock held
2855void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2856{
2857}
2858
2859// checkForNewParameters_l() must be called with ThreadBase::mLock held
2860bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2861{
2862 bool reconfig = false;
2863
Eric Laurent8fce46a2009-08-04 09:45:33 -07002864 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002865 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002866 String8 keyValuePair = mNewParameters[0];
2867 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002868 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002869
Eric Laurenta553c252009-07-17 12:17:14 -07002870 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2871 // do not accept frame count changes if tracks are open as the track buffer
2872 // size depends on frame count and correct behavior would not be garantied
2873 // if frame count is changed after track creation
2874 if (!mTracks.isEmpty()) {
2875 status = INVALID_OPERATION;
2876 } else {
2877 reconfig = true;
2878 }
2879 }
2880 if (status == NO_ERROR) {
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 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002884 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002885 mStandby = true;
2886 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002887 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002888 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002889 }
2890 if (status == NO_ERROR && reconfig) {
2891 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002892 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002893 }
2894 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002895
2896 mNewParameters.removeAt(0);
2897
Eric Laurenta553c252009-07-17 12:17:14 -07002898 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002899 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002900 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2901 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002902 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002903 }
2904 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002905}
2906
Eric Laurent059b4be2009-11-09 23:32:22 -08002907uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002908{
2909 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002910 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08002911 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08002912 } else {
2913 time = 10000;
2914 }
2915 return time;
2916}
2917
2918uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2919{
2920 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002921 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002922 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002923 } else {
2924 time = 10000;
2925 }
2926 return time;
2927}
2928
Eric Laurent8448a792010-08-18 18:13:17 -07002929uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2930{
2931 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002932 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002933 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2934 } else {
2935 time = 10000;
2936 }
2937 return time;
2938}
2939
2940
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002941// ----------------------------------------------------------------------------
2942
Eric Laurent49f02be2009-11-19 09:00:56 -08002943AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002944 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002945{
Eric Laurent464d5b32011-06-17 21:29:58 -07002946 mType = ThreadBase::DUPLICATING;
Eric Laurenta553c252009-07-17 12:17:14 -07002947 addOutputTrack(mainThread);
2948}
2949
2950AudioFlinger::DuplicatingThread::~DuplicatingThread()
2951{
Eric Laurent0a080292009-12-07 10:53:10 -08002952 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2953 mOutputTracks[i]->destroy();
2954 }
Eric Laurenta553c252009-07-17 12:17:14 -07002955 mOutputTracks.clear();
2956}
2957
2958bool AudioFlinger::DuplicatingThread::threadLoop()
2959{
Eric Laurenta553c252009-07-17 12:17:14 -07002960 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002961 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002962 nsecs_t standbyTime = systemTime();
2963 size_t mixBufferSize = mFrameCount*mFrameSize;
2964 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002965 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002966 uint32_t activeSleepTime = activeSleepTimeUs();
2967 uint32_t idleSleepTime = idleSleepTimeUs();
2968 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002969 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002970
Eric Laurent6dbdc402011-07-22 09:04:31 -07002971 acquireWakeLock();
2972
Eric Laurenta553c252009-07-17 12:17:14 -07002973 while (!exitPending())
2974 {
2975 processConfigEvents();
2976
Eric Laurent059b4be2009-11-09 23:32:22 -08002977 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002978 { // scope for the mLock
2979
2980 Mutex::Autolock _l(mLock);
2981
2982 if (checkForNewParameters_l()) {
2983 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002984 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002985 activeSleepTime = activeSleepTimeUs();
2986 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002987 }
2988
2989 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2990
2991 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2992 outputTracks.add(mOutputTracks[i]);
2993 }
2994
2995 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002996 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2997 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002998 if (!mStandby) {
2999 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07003000 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07003001 }
3002 mStandby = true;
3003 mBytesWritten = 0;
3004 }
3005
3006 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3007 // we're about to wait, flush the binder command buffer
3008 IPCThreadState::self()->flushCommands();
3009 outputTracks.clear();
3010
3011 if (exitPending()) break;
3012
Eric Laurent6dbdc402011-07-22 09:04:31 -07003013 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01003014 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07003015 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01003016 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07003017 acquireWakeLock_l();
3018
Eric Laurenta553c252009-07-17 12:17:14 -07003019 if (mMasterMute == false) {
3020 char value[PROPERTY_VALUE_MAX];
3021 property_get("ro.audio.silent", value, "0");
3022 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00003023 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07003024 setMasterMute(true);
3025 }
3026 }
3027
3028 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08003029 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07003030 continue;
3031 }
3032 }
3033
Eric Laurent059b4be2009-11-09 23:32:22 -08003034 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07003035
3036 // prevent any changes in effect chain list and in each effect chain
3037 // during mixing and effect process as the audio buffers could be deleted
3038 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003039 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003040 }
Eric Laurenta553c252009-07-17 12:17:14 -07003041
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003042 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003043 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003044 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003045 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003046 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003047 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003048 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003049 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003050 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003051 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003052 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003053 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3054 sleepTime = activeSleepTime;
3055 } else {
3056 sleepTime = idleSleepTime;
3057 }
Eric Laurent62443f52009-10-05 20:29:18 -07003058 } else if (mBytesWritten != 0) {
3059 // flush remaining overflow buffers in output tracks
3060 for (size_t i = 0; i < outputTracks.size(); i++) {
3061 if (outputTracks[i]->isActive()) {
3062 sleepTime = 0;
3063 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003064 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003065 break;
3066 }
3067 }
Eric Laurenta553c252009-07-17 12:17:14 -07003068 }
3069 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003070
3071 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003072 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003073 }
3074 // sleepTime == 0 means we must write to audio hardware
3075 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003076 for (size_t i = 0; i < effectChains.size(); i ++) {
3077 effectChains[i]->process_l();
3078 }
3079 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003080 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003081
Eric Laurent62443f52009-10-05 20:29:18 -07003082 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003083 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003084 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003085 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003086 mStandby = false;
3087 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003088 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003089 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003090 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003091 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003092 }
3093
3094 // finally let go of all our tracks, without the lock held
3095 // since we can't guarantee the destructors won't acquire that
3096 // same lock.
3097 tracksToRemove.clear();
3098 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003099
3100 // Effect chains will be actually deleted here if they were removed from
3101 // mEffectChains list during mixing or effects processing
3102 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003103 }
3104
Eric Laurent6dbdc402011-07-22 09:04:31 -07003105 releaseWakeLock();
3106
Eric Laurenta553c252009-07-17 12:17:14 -07003107 return false;
3108}
3109
3110void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3111{
3112 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3113 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003114 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003115 mSampleRate,
3116 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003117 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003118 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003119 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003120 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003121 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003122 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003123 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003124 }
Eric Laurenta553c252009-07-17 12:17:14 -07003125}
3126
3127void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3128{
3129 Mutex::Autolock _l(mLock);
3130 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3131 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003132 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003133 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003134 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003135 return;
3136 }
3137 }
Steve Block71f2cf12011-10-20 11:56:00 +01003138 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003139}
3140
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003141void AudioFlinger::DuplicatingThread::updateWaitTime()
3142{
3143 mWaitTimeMs = UINT_MAX;
3144 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3145 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3146 if (strong != NULL) {
3147 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3148 if (waitTimeMs < mWaitTimeMs) {
3149 mWaitTimeMs = waitTimeMs;
3150 }
3151 }
3152 }
3153}
3154
3155
3156bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3157{
3158 for (size_t i = 0; i < outputTracks.size(); i++) {
3159 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3160 if (thread == 0) {
3161 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3162 return false;
3163 }
3164 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3165 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003166 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003167 return false;
3168 }
3169 }
3170 return true;
3171}
3172
3173uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3174{
3175 return (mWaitTimeMs * 1000) / 2;
3176}
3177
Eric Laurenta553c252009-07-17 12:17:14 -07003178// ----------------------------------------------------------------------------
3179
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003180// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003181AudioFlinger::ThreadBase::TrackBase::TrackBase(
3182 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003183 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003184 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003185 uint32_t format,
3186 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003187 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003189 const sp<IMemory>& sharedBuffer,
3190 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003191 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003192 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003193 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07003194 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003195 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003196 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003197 mClientTid(-1),
3198 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003199 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3200 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003201{
Steve Block71f2cf12011-10-20 11:56:00 +01003202 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003203
Steve Block5baa3a62011-12-20 16:23:08 +00003204 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003205 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003206 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003207 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3208 if (sharedBuffer == 0) {
3209 size += bufferSize;
3210 }
3211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 if (client != NULL) {
3213 mCblkMemory = client->heap()->allocate(size);
3214 if (mCblkMemory != 0) {
3215 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3216 if (mCblk) { // construct the shared structure in-place.
3217 new(mCblk) audio_track_cblk_t();
3218 // clear all buffers
3219 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003220 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003221 mChannelCount = channelCount;
3222 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 if (sharedBuffer == 0) {
3224 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3225 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3226 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003227 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003228 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 } else {
3230 mBuffer = sharedBuffer->pointer();
3231 }
3232 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 } else {
3235 LOGE("not enough memory for AudioTrack size=%u", size);
3236 client->heap()->dump("AudioTrack");
3237 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 } else {
3240 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenc95ca2c2012-01-06 15:03:11 -08003241 // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 new(mCblk) audio_track_cblk_t();
3243 // clear all buffers
3244 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003245 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003246 mChannelCount = channelCount;
3247 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3249 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3250 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003251 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003252 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003255}
3256
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003257AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003258{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07003260 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3261 if (mClient == NULL) {
3262 delete mCblk;
3263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003265 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07003266 if (mClient != NULL) {
3267 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3268 mClient.clear();
3269 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003270}
3271
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003272void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003273{
Glenn Kastenc434c902011-12-13 11:53:26 -08003274 buffer->raw = NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003275 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003276 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003277 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003278}
3279
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003280bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003281 bool result;
3282 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003283
3284 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003285 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003286 ALOGV("stepServer failed acquiring cblk mutex");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003287 mFlags |= STEPSERVER_FAILED;
3288 }
3289 return result;
3290}
3291
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003292void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003293 audio_track_cblk_t* cblk = this->cblk();
3294
3295 cblk->user = 0;
3296 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003297 cblk->userBase = 0;
3298 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block71f2cf12011-10-20 11:56:00 +01003300 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003301}
3302
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003303sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003304{
3305 return mCblkMemory;
3306}
3307
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003308int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003309 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003310}
3311
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003312int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003313 return (const int)mChannelCount;
3314}
3315
3316uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3317 return mChannelMask;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003318}
3319
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003320void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003321 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07003322 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3323 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003324
3325 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003326 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3327 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07003328 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 -07003329 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003330 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003331 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003332 return 0;
3333 }
3334
3335 return bufferStart;
3336}
3337
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003338// ----------------------------------------------------------------------------
3339
Eric Laurenta553c252009-07-17 12:17:14 -07003340// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3341AudioFlinger::PlaybackThread::Track::Track(
3342 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003343 const sp<Client>& client,
3344 int streamType,
3345 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003346 uint32_t format,
3347 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003348 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003349 const sp<IMemory>& sharedBuffer,
3350 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003351 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003352 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3353 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003354{
Eric Laurent8a77a992009-09-09 05:16:08 -07003355 if (mCblk != NULL) {
3356 sp<ThreadBase> baseThread = thread.promote();
3357 if (baseThread != 0) {
3358 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3359 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003360 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003361 }
Steve Block71f2cf12011-10-20 11:56:00 +01003362 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003363 if (mName < 0) {
3364 LOGE("no more track names available");
3365 }
3366 mVolume[0] = 1.0f;
3367 mVolume[1] = 1.0f;
3368 mStreamType = streamType;
3369 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3370 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003371 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003372 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003373}
3374
Eric Laurenta553c252009-07-17 12:17:14 -07003375AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003376{
Steve Block71f2cf12011-10-20 11:56:00 +01003377 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003378 sp<ThreadBase> thread = mThread.promote();
3379 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003380 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003381 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003382 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003383}
3384
Eric Laurenta553c252009-07-17 12:17:14 -07003385void AudioFlinger::PlaybackThread::Track::destroy()
3386{
3387 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3388 // by removing it from mTracks vector, so there is a risk that this Tracks's
3389 // desctructor is called. As the destructor needs to lock mLock,
3390 // we must acquire a strong reference on this Track before locking mLock
3391 // here so that the destructor is called only when exiting this function.
3392 // On the other hand, as long as Track::destroy() is only called by
3393 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3394 // this Track with its member mTrack.
3395 sp<Track> keep(this);
3396 { // scope for mLock
3397 sp<ThreadBase> thread = mThread.promote();
3398 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003399 if (!isOutputTrack()) {
3400 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003401 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003402 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003403 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003404
3405 // to track the speaker usage
3406 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003407 }
3408 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003409 }
Eric Laurenta553c252009-07-17 12:17:14 -07003410 Mutex::Autolock _l(thread->mLock);
3411 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3412 playbackThread->destroyTrack_l(this);
3413 }
3414 }
3415}
3416
3417void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003418{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003419 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 -07003420 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003422 mStreamType,
3423 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003424 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003425 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003426 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003427 mState,
3428 mMute,
3429 mFillingUpStatus,
3430 mCblk->sampleRate,
3431 mCblk->volume[0],
3432 mCblk->volume[1],
3433 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003434 mCblk->user,
3435 (int)mMainBuffer,
3436 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003437}
3438
Eric Laurenta553c252009-07-17 12:17:14 -07003439status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003440{
3441 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003442 uint32_t framesReady;
3443 uint32_t framesReq = buffer->frameCount;
3444
3445 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003446 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3447 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003448 ALOGV("stepServer recovered");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003449 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3450 }
3451
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003452 framesReady = cblk->framesReady();
3453
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003454 if (CC_LIKELY(framesReady)) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003455 uint32_t s = cblk->server;
3456 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3457
3458 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3459 if (framesReq > framesReady) {
3460 framesReq = framesReady;
3461 }
3462 if (s + framesReq > bufferEnd) {
3463 framesReq = bufferEnd - s;
3464 }
3465
3466 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003467 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003468
3469 buffer->frameCount = framesReq;
3470 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003471 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003472
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003473getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003474 buffer->raw = NULL;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003475 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003476 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 -07003477 return NOT_ENOUGH_DATA;
3478}
3479
Eric Laurenta553c252009-07-17 12:17:14 -07003480bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003481 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003482
3483 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003484 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003485 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003486 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003487 return true;
3488 }
3489 return false;
3490}
3491
Eric Laurenta553c252009-07-17 12:17:14 -07003492status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003493{
Eric Laurent49f02be2009-11-19 09:00:56 -08003494 status_t status = NO_ERROR;
Steve Block71f2cf12011-10-20 11:56:00 +01003495 ALOGV("start(%d), calling thread %d session %d",
Eric Laurent0d7e0482010-07-19 06:24:46 -07003496 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003497 sp<ThreadBase> thread = mThread.promote();
3498 if (thread != 0) {
3499 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003500 int state = mState;
3501 // here the track could be either new, or restarted
3502 // in both cases "unstop" the track
3503 if (mState == PAUSED) {
3504 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003505 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003506 } else {
3507 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003508 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003509 }
3510
3511 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3512 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003513 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003514 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003515 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003516 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003517
3518 // to track the speaker usage
3519 if (status == NO_ERROR) {
3520 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3521 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003522 }
3523 if (status == NO_ERROR) {
3524 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3525 playbackThread->addTrack_l(this);
3526 } else {
3527 mState = state;
3528 }
3529 } else {
3530 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003531 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003532 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003533}
3534
Eric Laurenta553c252009-07-17 12:17:14 -07003535void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003536{
Steve Block71f2cf12011-10-20 11:56:00 +01003537 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003538 sp<ThreadBase> thread = mThread.promote();
3539 if (thread != 0) {
3540 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003541 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003542 if (mState > STOPPED) {
3543 mState = STOPPED;
3544 // If the track is not active (PAUSED and buffers full), flush buffers
3545 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3546 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3547 reset();
3548 }
Steve Block71f2cf12011-10-20 11:56:00 +01003549 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003550 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003551 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3552 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003553 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003554 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003555 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003556 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003557
3558 // to track the speaker usage
3559 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003560 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003561 }
3562}
3563
Eric Laurenta553c252009-07-17 12:17:14 -07003564void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003565{
Steve Block71f2cf12011-10-20 11:56:00 +01003566 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003567 sp<ThreadBase> thread = mThread.promote();
3568 if (thread != 0) {
3569 Mutex::Autolock _l(thread->mLock);
3570 if (mState == ACTIVE || mState == RESUMING) {
3571 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003572 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003573 if (!isOutputTrack()) {
3574 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003575 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003576 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003577 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003578 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003579
3580 // to track the speaker usage
3581 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003582 }
Eric Laurenta553c252009-07-17 12:17:14 -07003583 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003584 }
3585}
3586
Eric Laurenta553c252009-07-17 12:17:14 -07003587void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003588{
Steve Block71f2cf12011-10-20 11:56:00 +01003589 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003590 sp<ThreadBase> thread = mThread.promote();
3591 if (thread != 0) {
3592 Mutex::Autolock _l(thread->mLock);
3593 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3594 return;
3595 }
3596 // No point remaining in PAUSED state after a flush => go to
3597 // STOPPED state
3598 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003599
Eric Laurentae29b762011-03-28 18:37:07 -07003600 // do not reset the track if it is still in the process of being stopped or paused.
3601 // this will be done by prepareTracks_l() when the track is stopped.
3602 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3603 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3604 reset();
3605 }
Eric Laurenta553c252009-07-17 12:17:14 -07003606 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003607}
3608
Eric Laurenta553c252009-07-17 12:17:14 -07003609void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003610{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003611 // Do not reset twice to avoid discarding data written just after a flush and before
3612 // the audioflinger thread detects the track is stopped.
3613 if (!mResetDone) {
3614 TrackBase::reset();
3615 // Force underrun condition to avoid false underrun callback until first data is
3616 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003617 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3618 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003619 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003620 mResetDone = true;
3621 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003622}
3623
Eric Laurenta553c252009-07-17 12:17:14 -07003624void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003625{
3626 mMute = muted;
3627}
3628
Eric Laurenta553c252009-07-17 12:17:14 -07003629void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003630{
3631 mVolume[0] = left;
3632 mVolume[1] = right;
3633}
3634
Eric Laurent65b65452010-06-01 23:49:17 -07003635status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3636{
3637 status_t status = DEAD_OBJECT;
3638 sp<ThreadBase> thread = mThread.promote();
3639 if (thread != 0) {
3640 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3641 status = playbackThread->attachAuxEffect(this, EffectId);
3642 }
3643 return status;
3644}
3645
3646void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3647{
3648 mAuxEffectId = EffectId;
3649 mAuxBuffer = buffer;
3650}
3651
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003652// ----------------------------------------------------------------------------
3653
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003654// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003655AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3656 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003659 uint32_t format,
3660 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003662 uint32_t flags,
3663 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003664 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003665 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003666 mOverflow(false)
3667{
Eric Laurent8a77a992009-09-09 05:16:08 -07003668 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003669 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003670 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003671 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003672 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003673 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003674 } else {
3675 mCblk->frameSize = sizeof(int8_t);
3676 }
3677 }
Eric Laurenta553c252009-07-17 12:17:14 -07003678}
3679
3680AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681{
Eric Laurent49f02be2009-11-19 09:00:56 -08003682 sp<ThreadBase> thread = mThread.promote();
3683 if (thread != 0) {
3684 AudioSystem::releaseInput(thread->id());
3685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686}
3687
Eric Laurenta553c252009-07-17 12:17:14 -07003688status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689{
3690 audio_track_cblk_t* cblk = this->cblk();
3691 uint32_t framesAvail;
3692 uint32_t framesReq = buffer->frameCount;
3693
3694 // Check if last stepServer failed, try to step now
3695 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3696 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003697 ALOGV("stepServer recovered");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3699 }
3700
3701 framesAvail = cblk->framesAvailable_l();
3702
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003703 if (CC_LIKELY(framesAvail)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 uint32_t s = cblk->server;
3705 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3706
3707 if (framesReq > framesAvail) {
3708 framesReq = framesAvail;
3709 }
3710 if (s + framesReq > bufferEnd) {
3711 framesReq = bufferEnd - s;
3712 }
3713
3714 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003715 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716
3717 buffer->frameCount = framesReq;
3718 return NO_ERROR;
3719 }
3720
3721getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003722 buffer->raw = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 buffer->frameCount = 0;
3724 return NOT_ENOUGH_DATA;
3725}
3726
Eric Laurenta553c252009-07-17 12:17:14 -07003727status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728{
Eric Laurenta553c252009-07-17 12:17:14 -07003729 sp<ThreadBase> thread = mThread.promote();
3730 if (thread != 0) {
3731 RecordThread *recordThread = (RecordThread *)thread.get();
3732 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003733 } else {
3734 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736}
3737
Eric Laurenta553c252009-07-17 12:17:14 -07003738void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739{
Eric Laurenta553c252009-07-17 12:17:14 -07003740 sp<ThreadBase> thread = mThread.promote();
3741 if (thread != 0) {
3742 RecordThread *recordThread = (RecordThread *)thread.get();
3743 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003744 TrackBase::reset();
3745 // Force overerrun condition to avoid false overrun callback until first data is
3746 // read from buffer
3747 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749}
3750
Eric Laurent3fdb1262009-11-07 00:01:32 -08003751void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3752{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003753 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003754 (mClient == NULL) ? getpid() : mClient->pid(),
3755 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003756 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003757 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003758 mFrameCount,
3759 mState,
3760 mCblk->sampleRate,
3761 mCblk->server,
3762 mCblk->user);
3763}
3764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765
3766// ----------------------------------------------------------------------------
3767
Eric Laurenta553c252009-07-17 12:17:14 -07003768AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3769 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003770 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003772 uint32_t format,
3773 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003774 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003775 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003776 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777{
Eric Laurenta553c252009-07-17 12:17:14 -07003778
3779 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003780 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003781 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003782 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3783 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3784 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003785 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01003786 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003787 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3788 mCblk, mBuffer, mCblk->buffers,
3789 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003790 } else {
3791 LOGW("Error creating output track on thread %p", playbackThread);
3792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793}
3794
Eric Laurenta553c252009-07-17 12:17:14 -07003795AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796{
Eric Laurent6c30a712009-08-10 23:22:32 -07003797 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798}
3799
Eric Laurenta553c252009-07-17 12:17:14 -07003800status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801{
3802 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003803 if (status != NO_ERROR) {
3804 return status;
3805 }
3806
3807 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 mRetryCount = 127;
3809 return status;
3810}
3811
Eric Laurenta553c252009-07-17 12:17:14 -07003812void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813{
3814 Track::stop();
3815 clearBufferQueue();
3816 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003817 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003818}
3819
Eric Laurenta553c252009-07-17 12:17:14 -07003820bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821{
3822 Buffer *pInBuffer;
3823 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003824 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003825 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826 inBuffer.frameCount = frames;
3827 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003828
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003829 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003830
Eric Laurent62443f52009-10-05 20:29:18 -07003831 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003832 start();
3833 sp<ThreadBase> thread = mThread.promote();
3834 if (thread != 0) {
3835 MixerThread *mixerThread = (MixerThread *)thread.get();
3836 if (mCblk->frameCount > frames){
3837 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3838 uint32_t startFrames = (mCblk->frameCount - frames);
3839 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003840 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003841 pInBuffer->frameCount = startFrames;
3842 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003843 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003844 mBufferQueue.add(pInBuffer);
3845 } else {
3846 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003848 }
Eric Laurenta553c252009-07-17 12:17:14 -07003849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 }
3851
Eric Laurenta553c252009-07-17 12:17:14 -07003852 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 // First write pending buffers, then new data
3854 if (mBufferQueue.size()) {
3855 pInBuffer = mBufferQueue.itemAt(0);
3856 } else {
3857 pInBuffer = &inBuffer;
3858 }
Eric Laurenta553c252009-07-17 12:17:14 -07003859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 if (pInBuffer->frameCount == 0) {
3861 break;
3862 }
Eric Laurenta553c252009-07-17 12:17:14 -07003863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 if (mOutBuffer.frameCount == 0) {
3865 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003866 nsecs_t startTime = systemTime();
3867 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01003868 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003869 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 break;
3871 }
Eric Laurenta553c252009-07-17 12:17:14 -07003872 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003873 if (waitTimeLeftMs >= waitTimeMs) {
3874 waitTimeLeftMs -= waitTimeMs;
3875 } else {
3876 waitTimeLeftMs = 0;
3877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 }
Eric Laurenta553c252009-07-17 12:17:14 -07003879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003881 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 mCblk->stepUser(outFrames);
3883 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003884 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003886 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 if (pInBuffer->frameCount == 0) {
3889 if (mBufferQueue.size()) {
3890 mBufferQueue.removeAt(0);
3891 delete [] pInBuffer->mBuffer;
3892 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01003893 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 -08003894 } else {
3895 break;
3896 }
3897 }
3898 }
Eric Laurenta553c252009-07-17 12:17:14 -07003899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 // If we could not write all frames, allocate a buffer and queue it for next time.
3901 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003902 sp<ThreadBase> thread = mThread.promote();
3903 if (thread != 0 && !thread->standby()) {
3904 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3905 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003906 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003907 pInBuffer->frameCount = inBuffer.frameCount;
3908 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003909 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003910 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01003911 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003912 } else {
3913 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 }
3916 }
Eric Laurenta553c252009-07-17 12:17:14 -07003917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003919 // 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 -08003920 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003921 if (frames == 0 && mBufferQueue.size() == 0) {
3922 if (mCblk->user < mCblk->frameCount) {
3923 frames = mCblk->frameCount - mCblk->user;
3924 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003925 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003926 pInBuffer->frameCount = frames;
3927 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003928 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003929 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003930 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003931 stop();
3932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 }
3934
Eric Laurenta553c252009-07-17 12:17:14 -07003935 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936}
3937
Eric Laurenta553c252009-07-17 12:17:14 -07003938status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939{
3940 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 status_t result;
3942 audio_track_cblk_t* cblk = mCblk;
3943 uint32_t framesReq = buffer->frameCount;
3944
Steve Block71f2cf12011-10-20 11:56:00 +01003945// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 uint32_t framesAvail = cblk->framesAvailable();
3949
Eric Laurenta553c252009-07-17 12:17:14 -07003950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003952 Mutex::Autolock _l(cblk->lock);
3953 goto start_loop_here;
3954 while (framesAvail == 0) {
3955 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003956 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01003957 ALOGV("Not active and NO_MORE_BUFFERS");
Eric Laurenta553c252009-07-17 12:17:14 -07003958 return AudioTrack::NO_MORE_BUFFERS;
3959 }
3960 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3961 if (result != NO_ERROR) {
3962 return AudioTrack::NO_MORE_BUFFERS;
3963 }
3964 // read the server count again
3965 start_loop_here:
3966 framesAvail = cblk->framesAvailable_l();
3967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 }
3969
Eric Laurenta553c252009-07-17 12:17:14 -07003970// if (framesAvail < framesReq) {
3971// return AudioTrack::NO_MORE_BUFFERS;
3972// }
3973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 if (framesReq > framesAvail) {
3975 framesReq = framesAvail;
3976 }
3977
3978 uint32_t u = cblk->user;
3979 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3980
3981 if (u + framesReq > bufferEnd) {
3982 framesReq = bufferEnd - u;
3983 }
3984
3985 buffer->frameCount = framesReq;
3986 buffer->raw = (void *)cblk->buffer(u);
3987 return NO_ERROR;
3988}
3989
3990
Eric Laurenta553c252009-07-17 12:17:14 -07003991void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992{
3993 size_t size = mBufferQueue.size();
3994 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 for (size_t i = 0; i < size; i++) {
3997 pBuffer = mBufferQueue.itemAt(i);
3998 delete [] pBuffer->mBuffer;
3999 delete pBuffer;
4000 }
4001 mBufferQueue.clear();
4002}
4003
4004// ----------------------------------------------------------------------------
4005
4006AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4007 : RefBase(),
4008 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08004009 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 mPid(pid)
4011{
4012 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4013}
4014
Eric Laurentb9481d82009-09-17 05:12:56 -07004015// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016AudioFlinger::Client::~Client()
4017{
Eric Laurentb9481d82009-09-17 05:12:56 -07004018 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019}
4020
4021const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4022{
4023 return mMemoryDealer;
4024}
4025
4026// ----------------------------------------------------------------------------
4027
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004028AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4029 const sp<IAudioFlingerClient>& client,
4030 pid_t pid)
4031 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4032{
4033}
4034
4035AudioFlinger::NotificationClient::~NotificationClient()
4036{
4037 mClient.clear();
4038}
4039
4040void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4041{
4042 sp<NotificationClient> keep(this);
4043 {
4044 mAudioFlinger->removeNotificationClient(mPid);
4045 }
4046}
4047
4048// ----------------------------------------------------------------------------
4049
Eric Laurenta553c252009-07-17 12:17:14 -07004050AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004051 : BnAudioTrack(),
4052 mTrack(track)
4053{
4054}
4055
4056AudioFlinger::TrackHandle::~TrackHandle() {
4057 // just stop the track on deletion, associated resources
4058 // will be freed from the main thread once all pending buffers have
4059 // been played. Unless it's not in the active track list, in which
4060 // case we free everything now...
4061 mTrack->destroy();
4062}
4063
4064status_t AudioFlinger::TrackHandle::start() {
4065 return mTrack->start();
4066}
4067
4068void AudioFlinger::TrackHandle::stop() {
4069 mTrack->stop();
4070}
4071
4072void AudioFlinger::TrackHandle::flush() {
4073 mTrack->flush();
4074}
4075
4076void AudioFlinger::TrackHandle::mute(bool e) {
4077 mTrack->mute(e);
4078}
4079
4080void AudioFlinger::TrackHandle::pause() {
4081 mTrack->pause();
4082}
4083
4084void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4085 mTrack->setVolume(left, right);
4086}
4087
4088sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4089 return mTrack->getCblk();
4090}
4091
Eric Laurent65b65452010-06-01 23:49:17 -07004092status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4093{
4094 return mTrack->attachAuxEffect(EffectId);
4095}
4096
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004097status_t AudioFlinger::TrackHandle::onTransact(
4098 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4099{
4100 return BnAudioTrack::onTransact(code, data, reply, flags);
4101}
4102
4103// ----------------------------------------------------------------------------
4104
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004105sp<IAudioRecord> AudioFlinger::openRecord(
4106 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07004107 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004108 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004109 uint32_t format,
4110 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004111 int frameCount,
4112 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004113 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004114 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004115{
Eric Laurenta553c252009-07-17 12:17:14 -07004116 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004117 sp<RecordHandle> recordHandle;
4118 sp<Client> client;
4119 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004120 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004121 RecordThread *thread;
4122 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004123 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004124
4125 // check calling permissions
4126 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004127 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004128 goto Exit;
4129 }
4130
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004131 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004132 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004133 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004134 thread = checkRecordThread_l(input);
4135 if (thread == NULL) {
4136 lStatus = BAD_VALUE;
4137 goto Exit;
4138 }
4139
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004140 wclient = mClients.valueFor(pid);
4141 if (wclient != NULL) {
4142 client = wclient.promote();
4143 } else {
4144 client = new Client(this, pid);
4145 mClients.add(pid, client);
4146 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004147
Eric Laurent65b65452010-06-01 23:49:17 -07004148 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004149 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004150 lSessionId = *sessionId;
4151 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004152 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004153 if (sessionId != NULL) {
4154 *sessionId = lSessionId;
4155 }
4156 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004157 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004158 recordTrack = thread->createRecordTrack_l(client,
4159 sampleRate,
4160 format,
4161 channelMask,
4162 frameCount,
4163 flags,
4164 lSessionId,
4165 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004166 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004167 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004168 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4169 // destructor is called by the TrackBase destructor with mLock held
4170 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 goto Exit;
4173 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004174
4175 // return to handle to client
4176 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004177 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004178
4179Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004180 if (status) {
4181 *status = lStatus;
4182 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004183 return recordHandle;
4184}
4185
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004186// ----------------------------------------------------------------------------
4187
Eric Laurenta553c252009-07-17 12:17:14 -07004188AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004189 : BnAudioRecord(),
4190 mRecordTrack(recordTrack)
4191{
4192}
4193
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004194AudioFlinger::RecordHandle::~RecordHandle() {
4195 stop();
4196}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004197
4198status_t AudioFlinger::RecordHandle::start() {
Steve Block71f2cf12011-10-20 11:56:00 +01004199 ALOGV("RecordHandle::start()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004200 return mRecordTrack->start();
4201}
4202
4203void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004204 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004205 mRecordTrack->stop();
4206}
4207
4208sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4209 return mRecordTrack->getCblk();
4210}
4211
4212status_t AudioFlinger::RecordHandle::onTransact(
4213 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4214{
4215 return BnAudioRecord::onTransact(code, data, reply, flags);
4216}
4217
4218// ----------------------------------------------------------------------------
4219
Eric Laurent464d5b32011-06-17 21:29:58 -07004220AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4221 AudioStreamIn *input,
4222 uint32_t sampleRate,
4223 uint32_t channels,
4224 int id,
4225 uint32_t device) :
4226 ThreadBase(audioFlinger, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08004227 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004228{
Eric Laurent464d5b32011-06-17 21:29:58 -07004229 mType = ThreadBase::RECORD;
Eric Laurent6dbdc402011-07-22 09:04:31 -07004230
4231 snprintf(mName, kNameLength, "AudioIn_%d", id);
4232
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004233 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07004234 mReqSampleRate = sampleRate;
4235 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004236}
4237
Eric Laurenta553c252009-07-17 12:17:14 -07004238
4239AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004240{
Eric Laurenta553c252009-07-17 12:17:14 -07004241 delete[] mRsmpInBuffer;
Glenn Kastenc434c902011-12-13 11:53:26 -08004242 if (mResampler != NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004243 delete mResampler;
4244 delete[] mRsmpOutBuffer;
4245 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004246}
4247
Eric Laurenta553c252009-07-17 12:17:14 -07004248void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004249{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004250 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004251}
Eric Laurent49f02be2009-11-19 09:00:56 -08004252
Eric Laurent828b9772011-08-07 16:32:26 -07004253status_t AudioFlinger::RecordThread::readyToRun()
4254{
4255 status_t status = initCheck();
4256 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4257 return status;
4258}
4259
Eric Laurenta553c252009-07-17 12:17:14 -07004260bool AudioFlinger::RecordThread::threadLoop()
4261{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004262 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004263 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004264 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004265
Eric Laurent4712baa2010-09-30 16:12:31 -07004266 nsecs_t lastWarning = 0;
4267
Eric Laurent6dbdc402011-07-22 09:04:31 -07004268 acquireWakeLock();
4269
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004270 // start recording
4271 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004272
Eric Laurenta553c252009-07-17 12:17:14 -07004273 processConfigEvents();
4274
4275 { // scope for mLock
4276 Mutex::Autolock _l(mLock);
4277 checkForNewParameters_l();
4278 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4279 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004280 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004281 mStandby = true;
4282 }
4283
4284 if (exitPending()) break;
4285
Eric Laurent6dbdc402011-07-22 09:04:31 -07004286 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004287 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004288 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004289 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004290 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004291 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004292 continue;
4293 }
4294 if (mActiveTrack != 0) {
4295 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004296 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004297 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004298 mStandby = true;
4299 }
Eric Laurenta553c252009-07-17 12:17:14 -07004300 mActiveTrack.clear();
4301 mStartStopCond.broadcast();
4302 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004303 if (mReqChannelCount != mActiveTrack->channelCount()) {
4304 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004305 mStartStopCond.broadcast();
4306 } else if (mBytesRead != 0) {
4307 // record start succeeds only if first read from audio input
4308 // succeeds
4309 if (mBytesRead > 0) {
4310 mActiveTrack->mState = TrackBase::ACTIVE;
4311 } else {
4312 mActiveTrack.clear();
4313 }
4314 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004315 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004316 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004317 }
Eric Laurenta553c252009-07-17 12:17:14 -07004318 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004319 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004320 }
4321
4322 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004323 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4324 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004325 unlockEffectChains(effectChains);
4326 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004327 continue;
4328 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004329 for (size_t i = 0; i < effectChains.size(); i ++) {
4330 effectChains[i]->process_l();
4331 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004332
Eric Laurenta553c252009-07-17 12:17:14 -07004333 buffer.frameCount = mFrameCount;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004334 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004335 size_t framesOut = buffer.frameCount;
Glenn Kastenc434c902011-12-13 11:53:26 -08004336 if (mResampler == NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004337 // no resampling
4338 while (framesOut) {
4339 size_t framesIn = mFrameCount - mRsmpInIndex;
4340 if (framesIn) {
4341 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4342 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4343 if (framesIn > framesOut)
4344 framesIn = framesOut;
4345 mRsmpInIndex += framesIn;
4346 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004347 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004348 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004349 memcpy(dst, src, framesIn * mFrameSize);
4350 } else {
4351 int16_t *src16 = (int16_t *)src;
4352 int16_t *dst16 = (int16_t *)dst;
4353 if (mChannelCount == 1) {
4354 while (framesIn--) {
4355 *dst16++ = *src16;
4356 *dst16++ = *src16++;
4357 }
4358 } else {
4359 while (framesIn--) {
4360 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4361 src16 += 2;
4362 }
4363 }
4364 }
4365 }
4366 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004367 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004368 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004369 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004370 framesOut = 0;
4371 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004372 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004373 mRsmpInIndex = 0;
4374 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004375 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004376 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004377 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004378 // Force input into standby so that it tries to
4379 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004380 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004381 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004382 }
Eric Laurenta553c252009-07-17 12:17:14 -07004383 mRsmpInIndex = mFrameCount;
4384 framesOut = 0;
4385 buffer.frameCount = 0;
4386 }
4387 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004388 }
4389 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004390 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004391
Eric Laurenta553c252009-07-17 12:17:14 -07004392 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4393 // alter output frame count as if we were expecting stereo samples
4394 if (mChannelCount == 1 && mReqChannelCount == 1) {
4395 framesOut >>= 1;
4396 }
4397 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4398 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4399 // are 32 bit aligned which should be always true.
4400 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten490909d2011-12-15 09:52:39 -08004401 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004402 // the resampler always outputs stereo samples: do post stereo to mono conversion
4403 int16_t *src = (int16_t *)mRsmpOutBuffer;
4404 int16_t *dst = buffer.i16;
4405 while (framesOut--) {
4406 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4407 src += 2;
4408 }
4409 } else {
Glenn Kasten490909d2011-12-15 09:52:39 -08004410 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004411 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004412
Eric Laurenta553c252009-07-17 12:17:14 -07004413 }
4414 mActiveTrack->releaseBuffer(&buffer);
4415 mActiveTrack->overflow();
4416 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004417 // client isn't retrieving buffers fast enough
4418 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004419 if (!mActiveTrack->setOverflow()) {
4420 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004421 if ((now - lastWarning) > kWarningThrottleNs) {
Eric Laurent4712baa2010-09-30 16:12:31 -07004422 LOGW("RecordThread: buffer overflow");
4423 lastWarning = now;
4424 }
4425 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004426 // Release the processor for a while before asking for a new buffer.
4427 // This will give the application more chance to read from the buffer and
4428 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004429 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004430 }
4431 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004432 // enable changes in effect chain
4433 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004434 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004435 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004436
Eric Laurenta553c252009-07-17 12:17:14 -07004437 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004438 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004439 }
Eric Laurenta553c252009-07-17 12:17:14 -07004440 mActiveTrack.clear();
4441
Eric Laurent49f02be2009-11-19 09:00:56 -08004442 mStartStopCond.broadcast();
4443
Eric Laurent6dbdc402011-07-22 09:04:31 -07004444 releaseWakeLock();
4445
Steve Block71f2cf12011-10-20 11:56:00 +01004446 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004447 return false;
4448}
4449
Eric Laurent464d5b32011-06-17 21:29:58 -07004450
4451sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4452 const sp<AudioFlinger::Client>& client,
4453 uint32_t sampleRate,
4454 int format,
4455 int channelMask,
4456 int frameCount,
4457 uint32_t flags,
4458 int sessionId,
4459 status_t *status)
4460{
4461 sp<RecordTrack> track;
4462 status_t lStatus;
4463
4464 lStatus = initCheck();
4465 if (lStatus != NO_ERROR) {
4466 LOGE("Audio driver not initialized.");
4467 goto Exit;
4468 }
4469
4470 { // scope for mLock
4471 Mutex::Autolock _l(mLock);
4472
4473 track = new RecordTrack(this, client, sampleRate,
4474 format, channelMask, frameCount, flags, sessionId);
4475
4476 if (track->getCblk() == NULL) {
4477 lStatus = NO_MEMORY;
4478 goto Exit;
4479 }
4480
4481 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004482 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4483 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004484 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004485 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4486 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004487 }
4488 lStatus = NO_ERROR;
4489
4490Exit:
4491 if (status) {
4492 *status = lStatus;
4493 }
4494 return track;
4495}
4496
Eric Laurenta553c252009-07-17 12:17:14 -07004497status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004498{
Steve Block71f2cf12011-10-20 11:56:00 +01004499 ALOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004500 sp <ThreadBase> strongMe = this;
4501 status_t status = NO_ERROR;
4502 {
4503 AutoMutex lock(&mLock);
4504 if (mActiveTrack != 0) {
4505 if (recordTrack != mActiveTrack.get()) {
4506 status = -EBUSY;
4507 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004508 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004509 }
4510 return status;
4511 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004512
Eric Laurent49f02be2009-11-19 09:00:56 -08004513 recordTrack->mState = TrackBase::IDLE;
4514 mActiveTrack = recordTrack;
4515 mLock.unlock();
4516 status_t status = AudioSystem::startInput(mId);
4517 mLock.lock();
4518 if (status != NO_ERROR) {
4519 mActiveTrack.clear();
4520 return status;
4521 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004522 mRsmpInIndex = mFrameCount;
4523 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004524 if (mResampler != NULL) {
4525 mResampler->reset();
4526 }
4527 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004528 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004529 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004530 mWaitWorkCV.signal();
4531 // do not wait for mStartStopCond if exiting
4532 if (mExiting) {
4533 mActiveTrack.clear();
4534 status = INVALID_OPERATION;
4535 goto startError;
4536 }
4537 mStartStopCond.wait(mLock);
4538 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01004539 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004540 status = BAD_VALUE;
4541 goto startError;
4542 }
Steve Block71f2cf12011-10-20 11:56:00 +01004543 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004544 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004545 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004546startError:
4547 AudioSystem::stopInput(mId);
4548 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004549}
4550
Eric Laurenta553c252009-07-17 12:17:14 -07004551void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01004552 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004553 sp <ThreadBase> strongMe = this;
4554 {
4555 AutoMutex lock(&mLock);
4556 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4557 mActiveTrack->mState = TrackBase::PAUSING;
4558 // do not wait for mStartStopCond if exiting
4559 if (mExiting) {
4560 return;
4561 }
4562 mStartStopCond.wait(mLock);
4563 // if we have been restarted, recordTrack == mActiveTrack.get() here
4564 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4565 mLock.unlock();
4566 AudioSystem::stopInput(mId);
4567 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01004568 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004569 }
4570 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004571 }
4572}
4573
Eric Laurenta553c252009-07-17 12:17:14 -07004574status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575{
4576 const size_t SIZE = 256;
4577 char buffer[SIZE];
4578 String8 result;
4579 pid_t pid = 0;
4580
Eric Laurent3fdb1262009-11-07 00:01:32 -08004581 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4582 result.append(buffer);
4583
4584 if (mActiveTrack != 0) {
4585 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004586 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004587 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004589
4590 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4591 result.append(buffer);
4592 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4593 result.append(buffer);
Glenn Kastenc434c902011-12-13 11:53:26 -08004594 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Eric Laurent3fdb1262009-11-07 00:01:32 -08004595 result.append(buffer);
4596 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4597 result.append(buffer);
4598 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4599 result.append(buffer);
4600
4601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 } else {
4603 result.append("No record client\n");
4604 }
4605 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004606
4607 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004608 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004610 return NO_ERROR;
4611}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004612
Eric Laurenta553c252009-07-17 12:17:14 -07004613status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4614{
4615 size_t framesReq = buffer->frameCount;
4616 size_t framesReady = mFrameCount - mRsmpInIndex;
4617 int channelCount;
4618
4619 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004620 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004621 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004622 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004623 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004624 // Force input into standby so that it tries to
4625 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004626 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004627 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004628 }
Glenn Kastenc434c902011-12-13 11:53:26 -08004629 buffer->raw = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004630 buffer->frameCount = 0;
4631 return NOT_ENOUGH_DATA;
4632 }
4633 mRsmpInIndex = 0;
4634 framesReady = mFrameCount;
4635 }
4636
4637 if (framesReq > framesReady) {
4638 framesReq = framesReady;
4639 }
4640
4641 if (mChannelCount == 1 && mReqChannelCount == 2) {
4642 channelCount = 1;
4643 } else {
4644 channelCount = 2;
4645 }
4646 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4647 buffer->frameCount = framesReq;
4648 return NO_ERROR;
4649}
4650
4651void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4652{
4653 mRsmpInIndex += buffer->frameCount;
4654 buffer->frameCount = 0;
4655}
4656
4657bool AudioFlinger::RecordThread::checkForNewParameters_l()
4658{
4659 bool reconfig = false;
4660
Eric Laurent8fce46a2009-08-04 09:45:33 -07004661 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004662 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004663 String8 keyValuePair = mNewParameters[0];
4664 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004665 int value;
4666 int reqFormat = mFormat;
4667 int reqSamplingRate = mReqSampleRate;
4668 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004669
Eric Laurenta553c252009-07-17 12:17:14 -07004670 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4671 reqSamplingRate = value;
4672 reconfig = true;
4673 }
4674 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4675 reqFormat = value;
4676 reconfig = true;
4677 }
4678 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004679 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004680 reconfig = true;
4681 }
4682 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4683 // do not accept frame count changes if tracks are open as the track buffer
4684 // size depends on frame count and correct behavior would not be garantied
4685 // if frame count is changed after track creation
4686 if (mActiveTrack != 0) {
4687 status = INVALID_OPERATION;
4688 } else {
4689 reconfig = true;
4690 }
4691 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004692 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4693 // forward device change to effects that have requested to be
4694 // aware of attached audio device.
4695 for (size_t i = 0; i < mEffectChains.size(); i++) {
4696 mEffectChains[i]->setDevice_l(value);
4697 }
4698 // store input device and output device but do not forward output device to audio HAL.
4699 // Note that status is ignored by the caller for output device
4700 // (see AudioFlinger::setParameters()
4701 if (value & AUDIO_DEVICE_OUT_ALL) {
4702 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4703 status = BAD_VALUE;
4704 } else {
4705 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004706 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4707 if (mTrack != NULL) {
4708 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004709 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004710 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4711 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4712 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004713 }
4714 mDevice |= (uint32_t)value;
4715 }
Eric Laurenta553c252009-07-17 12:17:14 -07004716 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004717 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004718 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004719 mInput->stream->common.standby(&mInput->stream->common);
4720 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004721 }
4722 if (reconfig) {
4723 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004724 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004725 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004726 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4727 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004728 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004729 status = NO_ERROR;
4730 }
4731 if (status == NO_ERROR) {
4732 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004733 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004734 }
4735 }
4736 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004737
4738 mNewParameters.removeAt(0);
4739
Eric Laurenta553c252009-07-17 12:17:14 -07004740 mParamStatus = status;
4741 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004742 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4743 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004744 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07004745 }
4746 return reconfig;
4747}
4748
4749String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4750{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004751 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004752 String8 out_s8 = String8();
4753
4754 Mutex::Autolock _l(mLock);
4755 if (initCheck() != NO_ERROR) {
4756 return out_s8;
4757 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004758
Dima Zavin31f188892011-04-18 16:57:27 -07004759 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004760 out_s8 = String8(s);
4761 free(s);
4762 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004763}
4764
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004765void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004766 AudioSystem::OutputDescriptor desc;
4767 void *param2 = 0;
4768
4769 switch (event) {
4770 case AudioSystem::INPUT_OPENED:
4771 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004772 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004773 desc.samplingRate = mSampleRate;
4774 desc.format = mFormat;
4775 desc.frameCount = mFrameCount;
4776 desc.latency = 0;
4777 param2 = &desc;
4778 break;
4779
4780 case AudioSystem::INPUT_CLOSED:
4781 default:
4782 break;
4783 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004784 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004785}
4786
4787void AudioFlinger::RecordThread::readInputParameters()
4788{
4789 if (mRsmpInBuffer) delete mRsmpInBuffer;
4790 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4791 if (mResampler) delete mResampler;
Glenn Kastenc434c902011-12-13 11:53:26 -08004792 mResampler = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004793
Dima Zavin31f188892011-04-18 16:57:27 -07004794 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004795 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4796 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004797 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4798 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4799 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004800 mFrameCount = mInputBytes / mFrameSize;
4801 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4802
4803 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4804 {
4805 int channelCount;
4806 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4807 // stereo to mono post process as the resampler always outputs stereo.
4808 if (mChannelCount == 1 && mReqChannelCount == 2) {
4809 channelCount = 1;
4810 } else {
4811 channelCount = 2;
4812 }
4813 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4814 mResampler->setSampleRate(mSampleRate);
4815 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4816 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4817
4818 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4819 if (mChannelCount == 1 && mReqChannelCount == 1) {
4820 mFrameCount >>= 1;
4821 }
4822
4823 }
4824 mRsmpInIndex = mFrameCount;
4825}
4826
Eric Laurent47d0a922010-02-26 02:47:27 -08004827unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4828{
Eric Laurent828b9772011-08-07 16:32:26 -07004829 Mutex::Autolock _l(mLock);
4830 if (initCheck() != NO_ERROR) {
4831 return 0;
4832 }
4833
Dima Zavin31f188892011-04-18 16:57:27 -07004834 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004835}
4836
Eric Laurent464d5b32011-06-17 21:29:58 -07004837uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4838{
4839 Mutex::Autolock _l(mLock);
4840 uint32_t result = 0;
4841 if (getEffectChain_l(sessionId) != 0) {
4842 result = EFFECT_SESSION;
4843 }
4844
4845 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4846 result |= TRACK_SESSION;
4847 }
4848
4849 return result;
4850}
4851
Eric Laurent6639b552011-08-01 09:52:20 -07004852AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4853{
4854 Mutex::Autolock _l(mLock);
4855 return mTrack;
4856}
4857
Eric Laurent828b9772011-08-07 16:32:26 -07004858AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4859{
4860 Mutex::Autolock _l(mLock);
4861 return mInput;
4862}
4863
4864AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4865{
4866 Mutex::Autolock _l(mLock);
4867 AudioStreamIn *input = mInput;
4868 mInput = NULL;
4869 return input;
4870}
4871
4872// this method must always be called either with ThreadBase mLock held or inside the thread loop
4873audio_stream_t* AudioFlinger::RecordThread::stream()
4874{
4875 if (mInput == NULL) {
4876 return NULL;
4877 }
4878 return &mInput->stream->common;
4879}
4880
4881
Eric Laurenta553c252009-07-17 12:17:14 -07004882// ----------------------------------------------------------------------------
4883
Eric Laurentddb78e72009-07-28 08:44:33 -07004884int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004885 uint32_t *pSamplingRate,
4886 uint32_t *pFormat,
4887 uint32_t *pChannels,
4888 uint32_t *pLatencyMs,
4889 uint32_t flags)
4890{
4891 status_t status;
4892 PlaybackThread *thread = NULL;
4893 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4894 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4895 uint32_t format = pFormat ? *pFormat : 0;
4896 uint32_t channels = pChannels ? *pChannels : 0;
4897 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004898 audio_stream_out_t *outStream;
4899 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004900
Steve Block71f2cf12011-10-20 11:56:00 +01004901 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07004902 pDevices ? *pDevices : 0,
4903 samplingRate,
4904 format,
4905 channels,
4906 flags);
4907
4908 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004909 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004910 }
Dima Zavin31f188892011-04-18 16:57:27 -07004911
Eric Laurenta553c252009-07-17 12:17:14 -07004912 Mutex::Autolock _l(mLock);
4913
Dima Zavin31f188892011-04-18 16:57:27 -07004914 outHwDev = findSuitableHwDev_l(*pDevices);
4915 if (outHwDev == NULL)
4916 return 0;
4917
4918 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4919 &channels, &samplingRate, &outStream);
Steve Block71f2cf12011-10-20 11:56:00 +01004920 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004921 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004922 samplingRate,
4923 format,
4924 channels,
4925 status);
4926
4927 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004928 if (outStream != NULL) {
4929 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent464d5b32011-06-17 21:29:58 -07004930 int id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004931
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004932 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4933 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4934 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004935 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004936 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004937 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004938 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004939 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004940 }
Eric Laurent65b65452010-06-01 23:49:17 -07004941 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004942
4943 if (pSamplingRate) *pSamplingRate = samplingRate;
4944 if (pFormat) *pFormat = format;
4945 if (pChannels) *pChannels = channels;
4946 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004947
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004948 // notify client processes of the new output creation
4949 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004950 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004951 }
4952
Eric Laurent9cc489a22009-12-05 05:20:01 -08004953 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004954}
4955
Eric Laurentddb78e72009-07-28 08:44:33 -07004956int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004957{
4958 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004959 MixerThread *thread1 = checkMixerThread_l(output1);
4960 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004961
Eric Laurentddb78e72009-07-28 08:44:33 -07004962 if (thread1 == NULL || thread2 == NULL) {
4963 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4964 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004965 }
4966
Eric Laurent464d5b32011-06-17 21:29:58 -07004967 int id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004968 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004969 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004970 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004971 // notify client processes of the new output creation
4972 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004973 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004974}
4975
Eric Laurentddb78e72009-07-28 08:44:33 -07004976status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004977{
Eric Laurent49018a52009-08-04 08:37:05 -07004978 // keep strong reference on the playback thread so that
4979 // it is not destroyed while exit() is executed
4980 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004981 {
4982 Mutex::Autolock _l(mLock);
4983 thread = checkPlaybackThread_l(output);
4984 if (thread == NULL) {
4985 return BAD_VALUE;
4986 }
4987
Steve Block71f2cf12011-10-20 11:56:00 +01004988 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004989
Eric Laurent464d5b32011-06-17 21:29:58 -07004990 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07004991 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004992 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004993 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004994 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004995 }
4996 }
4997 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004998 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004999 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005000 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07005001 }
5002 thread->exit();
5003
Eric Laurent464d5b32011-06-17 21:29:58 -07005004 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07005005 AudioStreamOut *out = thread->clearOutput();
5006 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005007 out->hwDev->close_output_stream(out->hwDev, out->stream);
5008 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005009 }
Eric Laurenta553c252009-07-17 12:17:14 -07005010 return NO_ERROR;
5011}
5012
Eric Laurentddb78e72009-07-28 08:44:33 -07005013status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005014{
5015 Mutex::Autolock _l(mLock);
5016 PlaybackThread *thread = checkPlaybackThread_l(output);
5017
5018 if (thread == NULL) {
5019 return BAD_VALUE;
5020 }
5021
Steve Block71f2cf12011-10-20 11:56:00 +01005022 ALOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005023 thread->suspend();
5024
5025 return NO_ERROR;
5026}
5027
Eric Laurentddb78e72009-07-28 08:44:33 -07005028status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005029{
5030 Mutex::Autolock _l(mLock);
5031 PlaybackThread *thread = checkPlaybackThread_l(output);
5032
5033 if (thread == NULL) {
5034 return BAD_VALUE;
5035 }
5036
Steve Block71f2cf12011-10-20 11:56:00 +01005037 ALOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005038
5039 thread->restore();
5040
5041 return NO_ERROR;
5042}
5043
Eric Laurentddb78e72009-07-28 08:44:33 -07005044int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005045 uint32_t *pSamplingRate,
5046 uint32_t *pFormat,
5047 uint32_t *pChannels,
5048 uint32_t acoustics)
5049{
5050 status_t status;
5051 RecordThread *thread = NULL;
5052 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5053 uint32_t format = pFormat ? *pFormat : 0;
5054 uint32_t channels = pChannels ? *pChannels : 0;
5055 uint32_t reqSamplingRate = samplingRate;
5056 uint32_t reqFormat = format;
5057 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005058 audio_stream_in_t *inStream;
5059 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005060
5061 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005062 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005063 }
Dima Zavin31f188892011-04-18 16:57:27 -07005064
Eric Laurenta553c252009-07-17 12:17:14 -07005065 Mutex::Autolock _l(mLock);
5066
Dima Zavin31f188892011-04-18 16:57:27 -07005067 inHwDev = findSuitableHwDev_l(*pDevices);
5068 if (inHwDev == NULL)
5069 return 0;
5070
5071 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5072 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005073 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005074 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005075 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005076 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005077 samplingRate,
5078 format,
5079 channels,
5080 acoustics,
5081 status);
5082
5083 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5084 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5085 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005086 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005087 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005088 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005089 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005090 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin31f188892011-04-18 16:57:27 -07005091 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5092 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005093 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005094 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005095 }
5096
Dima Zavin31f188892011-04-18 16:57:27 -07005097 if (inStream != NULL) {
5098 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5099
Eric Laurent464d5b32011-06-17 21:29:58 -07005100 int id = nextUniqueId();
5101 // Start record thread
5102 // RecorThread require both input and output device indication to forward to audio
5103 // pre processing modules
5104 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5105 thread = new RecordThread(this,
5106 input,
5107 reqSamplingRate,
5108 reqChannels,
5109 id,
5110 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005111 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005112 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005113 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5114 if (pFormat) *pFormat = format;
5115 if (pChannels) *pChannels = reqChannels;
5116
Dima Zavin31f188892011-04-18 16:57:27 -07005117 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005118
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005119 // notify client processes of the new input creation
5120 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005121 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005122 }
5123
Eric Laurent9cc489a22009-12-05 05:20:01 -08005124 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005125}
5126
Eric Laurentddb78e72009-07-28 08:44:33 -07005127status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07005128{
Eric Laurent49018a52009-08-04 08:37:05 -07005129 // keep strong reference on the record thread so that
5130 // it is not destroyed while exit() is executed
5131 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005132 {
5133 Mutex::Autolock _l(mLock);
5134 thread = checkRecordThread_l(input);
5135 if (thread == NULL) {
5136 return BAD_VALUE;
5137 }
5138
Steve Block71f2cf12011-10-20 11:56:00 +01005139 ALOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07005140 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005141 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005142 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005143 }
5144 thread->exit();
5145
Eric Laurent828b9772011-08-07 16:32:26 -07005146 AudioStreamIn *in = thread->clearInput();
5147 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005148 in->hwDev->close_input_stream(in->hwDev, in->stream);
5149 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005150
Eric Laurenta553c252009-07-17 12:17:14 -07005151 return NO_ERROR;
5152}
5153
Eric Laurentddb78e72009-07-28 08:44:33 -07005154status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005155{
5156 Mutex::Autolock _l(mLock);
5157 MixerThread *dstThread = checkMixerThread_l(output);
5158 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005159 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005160 return BAD_VALUE;
5161 }
5162
Steve Block71f2cf12011-10-20 11:56:00 +01005163 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005164 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005165
Eric Laurent05ce0942011-08-30 10:18:54 -07005166 dstThread->setStreamValid(stream, true);
5167
Eric Laurenta553c252009-07-17 12:17:14 -07005168 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005169 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005170 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005171 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005172 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005173 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005174 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005175 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005176 }
Eric Laurentd069f322009-09-01 05:56:26 -07005177
Eric Laurenta553c252009-07-17 12:17:14 -07005178 return NO_ERROR;
5179}
5180
Eric Laurent65b65452010-06-01 23:49:17 -07005181
5182int AudioFlinger::newAudioSessionId()
5183{
Eric Laurent464d5b32011-06-17 21:29:58 -07005184 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005185}
5186
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005187void AudioFlinger::acquireAudioSessionId(int audioSession)
5188{
5189 Mutex::Autolock _l(mLock);
5190 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005191 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005192 int num = mAudioSessionRefs.size();
5193 for (int i = 0; i< num; i++) {
5194 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5195 if (ref->sessionid == audioSession && ref->pid == caller) {
5196 ref->cnt++;
Steve Block71f2cf12011-10-20 11:56:00 +01005197 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005198 return;
5199 }
5200 }
5201 AudioSessionRef *ref = new AudioSessionRef();
5202 ref->sessionid = audioSession;
5203 ref->pid = caller;
5204 ref->cnt = 1;
5205 mAudioSessionRefs.push(ref);
Steve Block71f2cf12011-10-20 11:56:00 +01005206 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005207}
5208
5209void AudioFlinger::releaseAudioSessionId(int audioSession)
5210{
5211 Mutex::Autolock _l(mLock);
5212 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005213 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005214 int num = mAudioSessionRefs.size();
5215 for (int i = 0; i< num; i++) {
5216 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5217 if (ref->sessionid == audioSession && ref->pid == caller) {
5218 ref->cnt--;
Steve Block71f2cf12011-10-20 11:56:00 +01005219 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005220 if (ref->cnt == 0) {
5221 mAudioSessionRefs.removeAt(i);
5222 delete ref;
5223 purgeStaleEffects_l();
5224 }
5225 return;
5226 }
5227 }
5228 LOGW("session id %d not found for pid %d", audioSession, caller);
5229}
5230
5231void AudioFlinger::purgeStaleEffects_l() {
5232
Steve Block71f2cf12011-10-20 11:56:00 +01005233 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005234
5235 Vector< sp<EffectChain> > chains;
5236
5237 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5238 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5239 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5240 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005241 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5242 chains.push(ec);
5243 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005244 }
5245 }
5246 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5247 sp<RecordThread> t = mRecordThreads.valueAt(i);
5248 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5249 sp<EffectChain> ec = t->mEffectChains[j];
5250 chains.push(ec);
5251 }
5252 }
5253
5254 for (size_t i = 0; i < chains.size(); i++) {
5255 sp<EffectChain> ec = chains[i];
5256 int sessionid = ec->sessionId();
5257 sp<ThreadBase> t = ec->mThread.promote();
5258 if (t == 0) {
5259 continue;
5260 }
5261 size_t numsessionrefs = mAudioSessionRefs.size();
5262 bool found = false;
5263 for (size_t k = 0; k < numsessionrefs; k++) {
5264 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5265 if (ref->sessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005266 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005267 sessionid, ref->pid, ref->cnt);
5268 found = true;
5269 break;
5270 }
5271 }
5272 if (!found) {
5273 // remove all effects from the chain
5274 while (ec->mEffects.size()) {
5275 sp<EffectModule> effect = ec->mEffects[0];
5276 effect->unPin();
5277 Mutex::Autolock _l (t->mLock);
5278 t->removeEffect_l(effect);
5279 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5280 sp<EffectHandle> handle = effect->mHandles[j].promote();
5281 if (handle != 0) {
5282 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005283 if (handle->mHasControl && handle->mEnabled) {
5284 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5285 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005286 }
5287 }
5288 AudioSystem::unregisterEffect(effect->id());
5289 }
5290 }
5291 }
5292 return;
5293}
5294
Eric Laurenta553c252009-07-17 12:17:14 -07005295// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005296AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005297{
5298 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005299 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5300 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005301 }
Eric Laurenta553c252009-07-17 12:17:14 -07005302 return thread;
5303}
5304
5305// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005306AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005307{
5308 PlaybackThread *thread = checkPlaybackThread_l(output);
5309 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005310 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005311 thread = NULL;
5312 }
5313 }
5314 return (MixerThread *)thread;
5315}
5316
5317// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005318AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005319{
5320 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005321 if (mRecordThreads.indexOfKey(input) >= 0) {
5322 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005323 }
Eric Laurenta553c252009-07-17 12:17:14 -07005324 return thread;
5325}
5326
Eric Laurent464d5b32011-06-17 21:29:58 -07005327uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005328{
Eric Laurent464d5b32011-06-17 21:29:58 -07005329 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005330}
5331
Eric Laurent464d5b32011-06-17 21:29:58 -07005332AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5333{
5334 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5335 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005336 AudioStreamOut *output = thread->getOutput();
5337 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005338 return thread;
5339 }
5340 }
5341 return NULL;
5342}
5343
5344uint32_t AudioFlinger::primaryOutputDevice_l()
5345{
5346 PlaybackThread *thread = primaryPlaybackThread_l();
5347
5348 if (thread == NULL) {
5349 return 0;
5350 }
5351
5352 return thread->device();
5353}
5354
5355
Eric Laurent65b65452010-06-01 23:49:17 -07005356// ----------------------------------------------------------------------------
5357// Effect management
5358// ----------------------------------------------------------------------------
5359
5360
Eric Laurent65b65452010-06-01 23:49:17 -07005361status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5362{
5363 Mutex::Autolock _l(mLock);
5364 return EffectQueryNumberEffects(numEffects);
5365}
5366
Eric Laurent53334cd2010-06-23 17:38:20 -07005367status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07005368{
5369 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005370 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005371}
5372
5373status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5374{
5375 Mutex::Autolock _l(mLock);
5376 return EffectGetDescriptor(pUuid, descriptor);
5377}
5378
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005379
Eric Laurent65b65452010-06-01 23:49:17 -07005380sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5381 effect_descriptor_t *pDesc,
5382 const sp<IEffectClient>& effectClient,
5383 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005384 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005385 int sessionId,
5386 status_t *status,
5387 int *id,
5388 int *enabled)
5389{
5390 status_t lStatus = NO_ERROR;
5391 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005392 effect_descriptor_t desc;
5393 sp<Client> client;
5394 wp<Client> wclient;
5395
Steve Block71f2cf12011-10-20 11:56:00 +01005396 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005397 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005398
5399 if (pDesc == NULL) {
5400 lStatus = BAD_VALUE;
5401 goto Exit;
5402 }
5403
Eric Laurent98c92592010-09-23 16:10:16 -07005404 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005405 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005406 lStatus = PERMISSION_DENIED;
5407 goto Exit;
5408 }
5409
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005410 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005411 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005412 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005413 lStatus = PERMISSION_DENIED;
5414 goto Exit;
5415 }
5416
Eric Laurent464d5b32011-06-17 21:29:58 -07005417 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005418 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005419 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005420 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005421 lStatus = BAD_VALUE;
5422 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005423 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005424 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005425 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005426 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005427 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005428 }
5429 }
5430
Eric Laurent65b65452010-06-01 23:49:17 -07005431 {
5432 Mutex::Autolock _l(mLock);
5433
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005434
Eric Laurent65b65452010-06-01 23:49:17 -07005435 if (!EffectIsNullUuid(&pDesc->uuid)) {
5436 // if uuid is specified, request effect descriptor
5437 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5438 if (lStatus < 0) {
5439 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5440 goto Exit;
5441 }
5442 } else {
5443 // if uuid is not specified, look for an available implementation
5444 // of the required type in effect factory
5445 if (EffectIsNullUuid(&pDesc->type)) {
5446 LOGW("createEffect() no effect type");
5447 lStatus = BAD_VALUE;
5448 goto Exit;
5449 }
5450 uint32_t numEffects = 0;
5451 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005452 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005453 bool found = false;
5454
5455 lStatus = EffectQueryNumberEffects(&numEffects);
5456 if (lStatus < 0) {
5457 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5458 goto Exit;
5459 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005460 for (uint32_t i = 0; i < numEffects; i++) {
5461 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005462 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005463 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005464 continue;
5465 }
5466 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5467 // If matching type found save effect descriptor. If the session is
5468 // 0 and the effect is not auxiliary, continue enumeration in case
5469 // an auxiliary version of this effect type is available
5470 found = true;
5471 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005472 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005473 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5474 break;
5475 }
5476 }
5477 }
5478 if (!found) {
5479 lStatus = BAD_VALUE;
5480 LOGW("createEffect() effect not found");
5481 goto Exit;
5482 }
5483 // For same effect type, chose auxiliary version over insert version if
5484 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005485 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005486 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5487 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5488 }
5489 }
5490
5491 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005492 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005493 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5494 lStatus = INVALID_OPERATION;
5495 goto Exit;
5496 }
5497
Eric Laurentf82fccd2011-07-27 19:49:51 -07005498 // check recording permission for visualizer
5499 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5500 !recordingAllowed()) {
5501 lStatus = PERMISSION_DENIED;
5502 goto Exit;
5503 }
5504
Eric Laurent65b65452010-06-01 23:49:17 -07005505 // return effect descriptor
5506 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5507
5508 // If output is not specified try to find a matching audio session ID in one of the
5509 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005510 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5511 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005512 // Note: io is never 0 when creating an effect on an input
5513 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005514 // look for the thread where the specified audio session is present
5515 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5516 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005517 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005518 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005519 }
Eric Laurent65b65452010-06-01 23:49:17 -07005520 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005521 if (io == 0) {
5522 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5523 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5524 io = mRecordThreads.keyAt(i);
5525 break;
5526 }
5527 }
5528 }
Eric Laurent98c92592010-09-23 16:10:16 -07005529 // If no output thread contains the requested session ID, default to
5530 // first output. The effect chain will be moved to the correct output
5531 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005532 if (io == 0 && mPlaybackThreads.size()) {
5533 io = mPlaybackThreads.keyAt(0);
5534 }
Steve Block71f2cf12011-10-20 11:56:00 +01005535 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005536 }
5537 ThreadBase *thread = checkRecordThread_l(io);
5538 if (thread == NULL) {
5539 thread = checkPlaybackThread_l(io);
5540 if (thread == NULL) {
5541 LOGE("createEffect() unknown output thread");
5542 lStatus = BAD_VALUE;
5543 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005544 }
Eric Laurent65b65452010-06-01 23:49:17 -07005545 }
Eric Laurent98c92592010-09-23 16:10:16 -07005546
Eric Laurent65b65452010-06-01 23:49:17 -07005547 wclient = mClients.valueFor(pid);
5548
5549 if (wclient != NULL) {
5550 client = wclient.promote();
5551 } else {
5552 client = new Client(this, pid);
5553 mClients.add(pid, client);
5554 }
5555
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005556 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005557 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5558 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005559 if (handle != 0 && id != NULL) {
5560 *id = handle->id();
5561 }
5562 }
5563
5564Exit:
5565 if(status) {
5566 *status = lStatus;
5567 }
5568 return handle;
5569}
5570
Eric Laurentf82fccd2011-07-27 19:49:51 -07005571status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005572{
Steve Block71f2cf12011-10-20 11:56:00 +01005573 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005574 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005575 Mutex::Autolock _l(mLock);
5576 if (srcOutput == dstOutput) {
5577 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5578 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005579 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005580 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5581 if (srcThread == NULL) {
5582 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5583 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005584 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005585 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5586 if (dstThread == NULL) {
5587 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5588 return BAD_VALUE;
5589 }
5590
5591 Mutex::Autolock _dl(dstThread->mLock);
5592 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005593 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005594
Eric Laurent53334cd2010-06-23 17:38:20 -07005595 return NO_ERROR;
5596}
5597
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005598// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005599status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005600 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005601 AudioFlinger::PlaybackThread *dstThread,
5602 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005603{
Steve Block71f2cf12011-10-20 11:56:00 +01005604 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005605 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005606
Eric Laurentf82fccd2011-07-27 19:49:51 -07005607 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005608 if (chain == 0) {
5609 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005610 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005611 return INVALID_OPERATION;
5612 }
5613
Eric Laurent493941b2010-07-28 01:32:47 -07005614 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005615 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005616 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005617 // removed.
5618 srcThread->removeEffectChain_l(chain);
5619
5620 // transfer all effects one by one so that new effect chain is created on new thread with
5621 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005622 int dstOutput = dstThread->id();
5623 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005624 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005625 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5626 while (effect != 0) {
5627 srcThread->removeEffect_l(effect);
5628 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005629 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5630 if (effect->state() == EffectModule::ACTIVE ||
5631 effect->state() == EffectModule::STOPPING) {
5632 effect->start();
5633 }
Eric Laurent493941b2010-07-28 01:32:47 -07005634 // if the move request is not received from audio policy manager, the effect must be
5635 // re-registered with the new strategy and output
5636 if (dstChain == 0) {
5637 dstChain = effect->chain().promote();
5638 if (dstChain == 0) {
5639 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5640 srcThread->addEffect_l(effect);
5641 return NO_INIT;
5642 }
5643 strategy = dstChain->strategy();
5644 }
5645 if (reRegister) {
5646 AudioSystem::unregisterEffect(effect->id());
5647 AudioSystem::registerEffect(&effect->desc(),
5648 dstOutput,
5649 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005650 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005651 effect->id());
5652 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005653 effect = chain->getEffectFromId_l(0);
5654 }
5655
5656 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005657}
5658
Eric Laurent464d5b32011-06-17 21:29:58 -07005659
Eric Laurent65b65452010-06-01 23:49:17 -07005660// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005661sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005662 const sp<AudioFlinger::Client>& client,
5663 const sp<IEffectClient>& effectClient,
5664 int32_t priority,
5665 int sessionId,
5666 effect_descriptor_t *desc,
5667 int *enabled,
5668 status_t *status
5669 )
5670{
5671 sp<EffectModule> effect;
5672 sp<EffectHandle> handle;
5673 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005674 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005675 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005676 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005677 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005678
Eric Laurent464d5b32011-06-17 21:29:58 -07005679 lStatus = initCheck();
5680 if (lStatus != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07005681 LOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005682 goto Exit;
5683 }
5684
5685 // Do not allow effects with session ID 0 on direct output or duplicating threads
5686 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005687 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005688 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5689 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005690 lStatus = BAD_VALUE;
5691 goto Exit;
5692 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005693 // Only Pre processor effects are allowed on input threads and only on input threads
5694 if ((mType == RECORD &&
5695 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5696 (mType != RECORD &&
5697 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5698 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5699 desc->name, desc->flags, mType);
5700 lStatus = BAD_VALUE;
5701 goto Exit;
5702 }
Eric Laurent65b65452010-06-01 23:49:17 -07005703
Steve Block71f2cf12011-10-20 11:56:00 +01005704 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005705
5706 { // scope for mLock
5707 Mutex::Autolock _l(mLock);
5708
5709 // check for existing effect chain with the requested audio session
5710 chain = getEffectChain_l(sessionId);
5711 if (chain == 0) {
5712 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005713 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005714 chain = new EffectChain(this, sessionId);
5715 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005716 chain->setStrategy(getStrategyForSession_l(sessionId));
5717 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005718 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005719 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005720 }
5721
Steve Block71f2cf12011-10-20 11:56:00 +01005722 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005723
5724 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005725 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005726 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005727 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005728 if (lStatus != NO_ERROR) {
5729 goto Exit;
5730 }
5731 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005732 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005733 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005734 lStatus = effect->status();
5735 if (lStatus != NO_ERROR) {
5736 goto Exit;
5737 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005738 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005739 if (lStatus != NO_ERROR) {
5740 goto Exit;
5741 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005742 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005743
5744 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005745 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005746 }
5747 // create effect handle and connect it to effect module
5748 handle = new EffectHandle(effect, client, effectClient, priority);
5749 lStatus = effect->addHandle(handle);
5750 if (enabled) {
5751 *enabled = (int)effect->isEnabled();
5752 }
5753 }
5754
5755Exit:
5756 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005757 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005758 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005759 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005760 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005761 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005762 AudioSystem::unregisterEffect(effect->id());
5763 }
5764 if (chainCreated) {
5765 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005766 }
Eric Laurent65b65452010-06-01 23:49:17 -07005767 handle.clear();
5768 }
5769
5770 if(status) {
5771 *status = lStatus;
5772 }
5773 return handle;
5774}
5775
Eric Laurent464d5b32011-06-17 21:29:58 -07005776sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5777{
5778 sp<EffectModule> effect;
5779
5780 sp<EffectChain> chain = getEffectChain_l(sessionId);
5781 if (chain != 0) {
5782 effect = chain->getEffectFromId_l(effectId);
5783 }
5784 return effect;
5785}
5786
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005787// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5788// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005789status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005790{
5791 // check for existing effect chain with the requested audio session
5792 int sessionId = effect->sessionId();
5793 sp<EffectChain> chain = getEffectChain_l(sessionId);
5794 bool chainCreated = false;
5795
5796 if (chain == 0) {
5797 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005798 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005799 chain = new EffectChain(this, sessionId);
5800 addEffectChain_l(chain);
5801 chain->setStrategy(getStrategyForSession_l(sessionId));
5802 chainCreated = true;
5803 }
Steve Block71f2cf12011-10-20 11:56:00 +01005804 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005805
5806 if (chain->getEffectFromId_l(effect->id()) != 0) {
5807 LOGW("addEffect_l() %p effect %s already present in chain %p",
5808 this, effect->desc().name, chain.get());
5809 return BAD_VALUE;
5810 }
5811
5812 status_t status = chain->addEffect_l(effect);
5813 if (status != NO_ERROR) {
5814 if (chainCreated) {
5815 removeEffectChain_l(chain);
5816 }
5817 return status;
5818 }
5819
5820 effect->setDevice(mDevice);
5821 effect->setMode(mAudioFlinger->getMode());
5822 return NO_ERROR;
5823}
5824
Eric Laurent464d5b32011-06-17 21:29:58 -07005825void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005826
Steve Block71f2cf12011-10-20 11:56:00 +01005827 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005828 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005829 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5830 detachAuxEffect_l(effect->id());
5831 }
5832
5833 sp<EffectChain> chain = effect->chain().promote();
5834 if (chain != 0) {
5835 // remove effect chain if removing last effect
5836 if (chain->removeEffect_l(effect) == 0) {
5837 removeEffectChain_l(chain);
5838 }
5839 } else {
5840 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5841 }
5842}
5843
Eric Laurent464d5b32011-06-17 21:29:58 -07005844void AudioFlinger::ThreadBase::lockEffectChains_l(
5845 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5846{
5847 effectChains = mEffectChains;
5848 for (size_t i = 0; i < mEffectChains.size(); i++) {
5849 mEffectChains[i]->lock();
5850 }
5851}
5852
5853void AudioFlinger::ThreadBase::unlockEffectChains(
5854 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5855{
5856 for (size_t i = 0; i < effectChains.size(); i++) {
5857 effectChains[i]->unlock();
5858 }
5859}
5860
5861sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5862{
5863 Mutex::Autolock _l(mLock);
5864 return getEffectChain_l(sessionId);
5865}
5866
5867sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5868{
5869 sp<EffectChain> chain;
5870
5871 size_t size = mEffectChains.size();
5872 for (size_t i = 0; i < size; i++) {
5873 if (mEffectChains[i]->sessionId() == sessionId) {
5874 chain = mEffectChains[i];
5875 break;
5876 }
5877 }
5878 return chain;
5879}
5880
5881void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5882{
5883 Mutex::Autolock _l(mLock);
5884 size_t size = mEffectChains.size();
5885 for (size_t i = 0; i < size; i++) {
5886 mEffectChains[i]->setMode_l(mode);
5887 }
5888}
5889
5890void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005891 const wp<EffectHandle>& handle,
5892 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005893
Eric Laurent53334cd2010-06-23 17:38:20 -07005894 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01005895 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005896 // delete the effect module if removing last handle on it
5897 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005898 if (!effect->isPinned() || unpiniflast) {
5899 removeEffect_l(effect);
5900 AudioSystem::unregisterEffect(effect->id());
5901 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005902 }
5903}
5904
Eric Laurent65b65452010-06-01 23:49:17 -07005905status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5906{
5907 int session = chain->sessionId();
5908 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005909 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005910
Steve Block71f2cf12011-10-20 11:56:00 +01005911 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005912 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005913 // Only one effect chain can be present in direct output thread and it uses
5914 // the mix buffer as input
5915 if (mType != DIRECT) {
5916 size_t numSamples = mFrameCount * mChannelCount;
5917 buffer = new int16_t[numSamples];
5918 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01005919 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005920 ownsBuffer = true;
5921 }
Eric Laurent65b65452010-06-01 23:49:17 -07005922
Eric Laurent53334cd2010-06-23 17:38:20 -07005923 // Attach all tracks with same session ID to this chain.
5924 for (size_t i = 0; i < mTracks.size(); ++i) {
5925 sp<Track> track = mTracks[i];
5926 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005927 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07005928 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005929 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005930 }
5931 }
5932
5933 // indicate all active tracks in the chain
5934 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5935 sp<Track> track = mActiveTracks[i].promote();
5936 if (track == 0) continue;
5937 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005938 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005939 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005940 }
Eric Laurent65b65452010-06-01 23:49:17 -07005941 }
5942 }
5943
Eric Laurent53334cd2010-06-23 17:38:20 -07005944 chain->setInBuffer(buffer, ownsBuffer);
5945 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005946 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005947 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005948 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5949 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005950 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005951 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5952 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005953 // Effect chain for other sessions are inserted at beginning of effect
5954 // chains list to be processed before output mix effects. Relative order between other
5955 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005956 size_t size = mEffectChains.size();
5957 size_t i = 0;
5958 for (i = 0; i < size; i++) {
5959 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005960 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005961 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005962 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005963
5964 return NO_ERROR;
5965}
5966
5967size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5968{
5969 int session = chain->sessionId();
5970
Steve Block71f2cf12011-10-20 11:56:00 +01005971 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005972
5973 for (size_t i = 0; i < mEffectChains.size(); i++) {
5974 if (chain == mEffectChains[i]) {
5975 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005976 // detach all active tracks from the chain
5977 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5978 sp<Track> track = mActiveTracks[i].promote();
5979 if (track == 0) continue;
5980 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005981 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07005982 chain.get(), session);
5983 chain->decActiveTrackCnt();
5984 }
5985 }
5986
Eric Laurent65b65452010-06-01 23:49:17 -07005987 // detach all tracks with same session ID from this chain
5988 for (size_t i = 0; i < mTracks.size(); ++i) {
5989 sp<Track> track = mTracks[i];
5990 if (session == track->sessionId()) {
5991 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005992 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005993 }
5994 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005995 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005996 }
5997 }
5998 return mEffectChains.size();
5999}
6000
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006001status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6002 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006003{
6004 Mutex::Autolock _l(mLock);
6005 return attachAuxEffect_l(track, EffectId);
6006}
6007
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006008status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6009 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006010{
6011 status_t status = NO_ERROR;
6012
6013 if (EffectId == 0) {
6014 track->setAuxBuffer(0, NULL);
6015 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006016 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6017 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006018 if (effect != 0) {
6019 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6020 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6021 } else {
6022 status = INVALID_OPERATION;
6023 }
6024 } else {
6025 status = BAD_VALUE;
6026 }
6027 }
6028 return status;
6029}
6030
6031void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6032{
6033 for (size_t i = 0; i < mTracks.size(); ++i) {
6034 sp<Track> track = mTracks[i];
6035 if (track->auxEffectId() == effectId) {
6036 attachAuxEffect_l(track, 0);
6037 }
6038 }
6039}
6040
Eric Laurent464d5b32011-06-17 21:29:58 -07006041status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6042{
6043 // only one chain per input thread
6044 if (mEffectChains.size() != 0) {
6045 return INVALID_OPERATION;
6046 }
Steve Block71f2cf12011-10-20 11:56:00 +01006047 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006048
6049 chain->setInBuffer(NULL);
6050 chain->setOutBuffer(NULL);
6051
Eric Laurentf82fccd2011-07-27 19:49:51 -07006052 checkSuspendOnAddEffectChain_l(chain);
6053
Eric Laurent464d5b32011-06-17 21:29:58 -07006054 mEffectChains.add(chain);
6055
6056 return NO_ERROR;
6057}
6058
6059size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6060{
Steve Block71f2cf12011-10-20 11:56:00 +01006061 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006062 LOGW_IF(mEffectChains.size() != 1,
6063 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6064 chain.get(), mEffectChains.size(), this);
6065 if (mEffectChains.size() == 1) {
6066 mEffectChains.removeAt(0);
6067 }
6068 return 0;
6069}
6070
Eric Laurent65b65452010-06-01 23:49:17 -07006071// ----------------------------------------------------------------------------
6072// EffectModule implementation
6073// ----------------------------------------------------------------------------
6074
6075#undef LOG_TAG
6076#define LOG_TAG "AudioFlinger::EffectModule"
6077
6078AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6079 const wp<AudioFlinger::EffectChain>& chain,
6080 effect_descriptor_t *desc,
6081 int id,
6082 int sessionId)
6083 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006084 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006085{
Steve Block71f2cf12011-10-20 11:56:00 +01006086 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006087 int lStatus;
6088 sp<ThreadBase> thread = mThread.promote();
6089 if (thread == 0) {
6090 return;
6091 }
Eric Laurent65b65452010-06-01 23:49:17 -07006092
6093 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6094
6095 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006096 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006097
Eric Laurent65b65452010-06-01 23:49:17 -07006098 if (mStatus != NO_ERROR) {
6099 return;
6100 }
6101 lStatus = init();
6102 if (lStatus < 0) {
6103 mStatus = lStatus;
6104 goto Error;
6105 }
6106
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006107 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6108 mPinned = true;
6109 }
Steve Block71f2cf12011-10-20 11:56:00 +01006110 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006111 return;
6112Error:
6113 EffectRelease(mEffectInterface);
6114 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006115 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006116}
6117
6118AudioFlinger::EffectModule::~EffectModule()
6119{
Steve Block71f2cf12011-10-20 11:56:00 +01006120 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006121 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006122 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6123 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6124 sp<ThreadBase> thread = mThread.promote();
6125 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006126 audio_stream_t *stream = thread->stream();
6127 if (stream != NULL) {
6128 stream->remove_audio_effect(stream, mEffectInterface);
6129 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006130 }
6131 }
Eric Laurent65b65452010-06-01 23:49:17 -07006132 // release effect engine
6133 EffectRelease(mEffectInterface);
6134 }
6135}
6136
6137status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6138{
6139 status_t status;
6140
6141 Mutex::Autolock _l(mLock);
6142 // First handle in mHandles has highest priority and controls the effect module
6143 int priority = handle->priority();
6144 size_t size = mHandles.size();
6145 sp<EffectHandle> h;
6146 size_t i;
6147 for (i = 0; i < size; i++) {
6148 h = mHandles[i].promote();
6149 if (h == 0) continue;
6150 if (h->priority() <= priority) break;
6151 }
6152 // if inserted in first place, move effect control from previous owner to this handle
6153 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006154 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006155 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006156 enabled = h->enabled();
6157 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006158 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006159 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006160 status = NO_ERROR;
6161 } else {
6162 status = ALREADY_EXISTS;
6163 }
Steve Block71f2cf12011-10-20 11:56:00 +01006164 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006165 mHandles.insertAt(handle, i);
6166 return status;
6167}
6168
6169size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6170{
6171 Mutex::Autolock _l(mLock);
6172 size_t size = mHandles.size();
6173 size_t i;
6174 for (i = 0; i < size; i++) {
6175 if (mHandles[i] == handle) break;
6176 }
6177 if (i == size) {
6178 return size;
6179 }
Steve Block71f2cf12011-10-20 11:56:00 +01006180 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006181
6182 bool enabled = false;
6183 EffectHandle *hdl = handle.unsafe_get();
6184 if (hdl) {
Steve Block71f2cf12011-10-20 11:56:00 +01006185 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006186 enabled = hdl->enabled();
6187 }
Eric Laurent65b65452010-06-01 23:49:17 -07006188 mHandles.removeAt(i);
6189 size = mHandles.size();
6190 // if removed from first place, move effect control from this handle to next in line
6191 if (i == 0 && size != 0) {
6192 sp<EffectHandle> h = mHandles[0].promote();
6193 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006194 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006195 }
6196 }
6197
Eric Laurent21b5c472011-07-26 20:54:46 -07006198 // Prevent calls to process() and other functions on effect interface from now on.
6199 // The effect engine will be released by the destructor when the last strong reference on
6200 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006201 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006202 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006203 }
6204
Eric Laurent65b65452010-06-01 23:49:17 -07006205 return size;
6206}
6207
Eric Laurentf82fccd2011-07-27 19:49:51 -07006208sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6209{
6210 Mutex::Autolock _l(mLock);
6211 sp<EffectHandle> handle;
6212 if (mHandles.size() != 0) {
6213 handle = mHandles[0].promote();
6214 }
6215 return handle;
6216}
6217
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006218void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006219{
Steve Block71f2cf12011-10-20 11:56:00 +01006220 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006221 // keep a strong reference on this EffectModule to avoid calling the
6222 // destructor before we exit
6223 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006224 {
6225 sp<ThreadBase> thread = mThread.promote();
6226 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006227 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006228 }
6229 }
6230}
6231
Eric Laurent7d850f22010-07-09 13:34:17 -07006232void AudioFlinger::EffectModule::updateState() {
6233 Mutex::Autolock _l(mLock);
6234
6235 switch (mState) {
6236 case RESTART:
6237 reset_l();
6238 // FALL THROUGH
6239
6240 case STARTING:
6241 // clear auxiliary effect input buffer for next accumulation
6242 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6243 memset(mConfig.inputCfg.buffer.raw,
6244 0,
6245 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6246 }
6247 start_l();
6248 mState = ACTIVE;
6249 break;
6250 case STOPPING:
6251 stop_l();
6252 mDisableWaitCnt = mMaxDisableWaitCnt;
6253 mState = STOPPED;
6254 break;
6255 case STOPPED:
6256 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6257 // turn off sequence.
6258 if (--mDisableWaitCnt == 0) {
6259 reset_l();
6260 mState = IDLE;
6261 }
6262 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006263 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006264 break;
6265 }
6266}
6267
Eric Laurent65b65452010-06-01 23:49:17 -07006268void AudioFlinger::EffectModule::process()
6269{
6270 Mutex::Autolock _l(mLock);
6271
Eric Laurent21b5c472011-07-26 20:54:46 -07006272 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006273 mConfig.inputCfg.buffer.raw == NULL ||
6274 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006275 return;
6276 }
6277
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006278 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006279 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6280 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten490909d2011-12-15 09:52:39 -08006281 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Eric Laurent65b65452010-06-01 23:49:17 -07006282 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006283 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006284 }
6285
Eric Laurent65b65452010-06-01 23:49:17 -07006286 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006287 int ret = (*mEffectInterface)->process(mEffectInterface,
6288 &mConfig.inputCfg.buffer,
6289 &mConfig.outputCfg.buffer);
6290
6291 // force transition to IDLE state when engine is ready
6292 if (mState == STOPPED && ret == -ENODATA) {
6293 mDisableWaitCnt = 1;
6294 }
Eric Laurent65b65452010-06-01 23:49:17 -07006295
6296 // clear auxiliary effect input buffer for next accumulation
6297 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006298 memset(mConfig.inputCfg.buffer.raw, 0,
6299 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006300 }
6301 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006302 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6303 // If an insert effect is idle and input buffer is different from output buffer,
6304 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006305 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006306 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006307 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6308 int16_t *in = mConfig.inputCfg.buffer.s16;
6309 int16_t *out = mConfig.outputCfg.buffer.s16;
6310 for (size_t i = 0; i < frameCnt; i++) {
6311 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006312 }
Eric Laurent65b65452010-06-01 23:49:17 -07006313 }
6314 }
6315}
6316
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006317void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006318{
6319 if (mEffectInterface == NULL) {
6320 return;
6321 }
6322 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6323}
6324
6325status_t AudioFlinger::EffectModule::configure()
6326{
6327 uint32_t channels;
6328 if (mEffectInterface == NULL) {
6329 return NO_INIT;
6330 }
6331
6332 sp<ThreadBase> thread = mThread.promote();
6333 if (thread == 0) {
6334 return DEAD_OBJECT;
6335 }
6336
6337 // TODO: handle configuration of effects replacing track process
6338 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006339 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006340 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006341 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006342 }
6343
6344 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006345 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006346 } else {
6347 mConfig.inputCfg.channels = channels;
6348 }
6349 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006350 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6351 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006352 mConfig.inputCfg.samplingRate = thread->sampleRate();
6353 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6354 mConfig.inputCfg.bufferProvider.cookie = NULL;
6355 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6356 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6357 mConfig.outputCfg.bufferProvider.cookie = NULL;
6358 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6359 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6360 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6361 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006362 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006363 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006364 // - in other sessions:
6365 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6366 // other effect: overwrites output buffer: input buffer == output buffer
6367 // Auxiliary effect:
6368 // accumulates in output buffer: input buffer != output buffer
6369 // Therefore: accumulate <=> input buffer != output buffer
6370 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6371 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6372 } else {
6373 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6374 }
6375 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6376 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6377 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6378 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6379
Steve Block71f2cf12011-10-20 11:56:00 +01006380 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006381 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6382
Eric Laurent65b65452010-06-01 23:49:17 -07006383 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006384 uint32_t size = sizeof(int);
6385 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent4abf8822011-12-16 15:30:36 -08006386 EFFECT_CMD_SET_CONFIG,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006387 sizeof(effect_config_t),
6388 &mConfig,
6389 &size,
6390 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006391 if (status == 0) {
6392 status = cmdStatus;
6393 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006394
6395 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6396 (1000 * mConfig.outputCfg.buffer.frameCount);
6397
Eric Laurent65b65452010-06-01 23:49:17 -07006398 return status;
6399}
6400
6401status_t AudioFlinger::EffectModule::init()
6402{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006403 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006404 if (mEffectInterface == NULL) {
6405 return NO_INIT;
6406 }
6407 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006408 uint32_t size = sizeof(status_t);
6409 status_t status = (*mEffectInterface)->command(mEffectInterface,
6410 EFFECT_CMD_INIT,
6411 0,
6412 NULL,
6413 &size,
6414 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006415 if (status == 0) {
6416 status = cmdStatus;
6417 }
6418 return status;
6419}
6420
Eric Laurent6fccbd02011-10-05 17:42:25 -07006421status_t AudioFlinger::EffectModule::start()
6422{
6423 Mutex::Autolock _l(mLock);
6424 return start_l();
6425}
6426
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006427status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006428{
6429 if (mEffectInterface == NULL) {
6430 return NO_INIT;
6431 }
6432 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006433 uint32_t size = sizeof(status_t);
6434 status_t status = (*mEffectInterface)->command(mEffectInterface,
6435 EFFECT_CMD_ENABLE,
6436 0,
6437 NULL,
6438 &size,
6439 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006440 if (status == 0) {
6441 status = cmdStatus;
6442 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006443 if (status == 0 &&
6444 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6445 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6446 sp<ThreadBase> thread = mThread.promote();
6447 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006448 audio_stream_t *stream = thread->stream();
6449 if (stream != NULL) {
6450 stream->add_audio_effect(stream, mEffectInterface);
6451 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006452 }
6453 }
Eric Laurent65b65452010-06-01 23:49:17 -07006454 return status;
6455}
6456
Eric Laurent21b5c472011-07-26 20:54:46 -07006457status_t AudioFlinger::EffectModule::stop()
6458{
6459 Mutex::Autolock _l(mLock);
6460 return stop_l();
6461}
6462
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006463status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006464{
6465 if (mEffectInterface == NULL) {
6466 return NO_INIT;
6467 }
6468 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006469 uint32_t size = sizeof(status_t);
6470 status_t status = (*mEffectInterface)->command(mEffectInterface,
6471 EFFECT_CMD_DISABLE,
6472 0,
6473 NULL,
6474 &size,
6475 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006476 if (status == 0) {
6477 status = cmdStatus;
6478 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006479 if (status == 0 &&
6480 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6481 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6482 sp<ThreadBase> thread = mThread.promote();
6483 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006484 audio_stream_t *stream = thread->stream();
6485 if (stream != NULL) {
6486 stream->remove_audio_effect(stream, mEffectInterface);
6487 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006488 }
6489 }
Eric Laurent65b65452010-06-01 23:49:17 -07006490 return status;
6491}
6492
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006493status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6494 uint32_t cmdSize,
6495 void *pCmdData,
6496 uint32_t *replySize,
6497 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006498{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006499 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006500// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006501
Eric Laurent21b5c472011-07-26 20:54:46 -07006502 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006503 return NO_INIT;
6504 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006505 status_t status = (*mEffectInterface)->command(mEffectInterface,
6506 cmdCode,
6507 cmdSize,
6508 pCmdData,
6509 replySize,
6510 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006511 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006512 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006513 for (size_t i = 1; i < mHandles.size(); i++) {
6514 sp<EffectHandle> h = mHandles[i].promote();
6515 if (h != 0) {
6516 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6517 }
6518 }
6519 }
6520 return status;
6521}
6522
6523status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6524{
Eric Laurent6752ec82011-08-10 10:37:50 -07006525
Eric Laurent65b65452010-06-01 23:49:17 -07006526 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006527 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006528
6529 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006530 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6531 if (enabled && status != NO_ERROR) {
6532 return status;
6533 }
6534
Eric Laurent65b65452010-06-01 23:49:17 -07006535 switch (mState) {
6536 // going from disabled to enabled
6537 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006538 mState = STARTING;
6539 break;
6540 case STOPPED:
6541 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006542 break;
6543 case STOPPING:
6544 mState = ACTIVE;
6545 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006546
6547 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006548 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006549 mState = STOPPED;
6550 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006551 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006552 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006553 break;
6554 case ACTIVE:
6555 mState = STOPPING;
6556 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006557 case DESTROYED:
6558 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006559 }
6560 for (size_t i = 1; i < mHandles.size(); i++) {
6561 sp<EffectHandle> h = mHandles[i].promote();
6562 if (h != 0) {
6563 h->setEnabled(enabled);
6564 }
6565 }
6566 }
6567 return NO_ERROR;
6568}
6569
6570bool AudioFlinger::EffectModule::isEnabled()
6571{
6572 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006573 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006574 case STARTING:
6575 case ACTIVE:
6576 return true;
6577 case IDLE:
6578 case STOPPING:
6579 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006580 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006581 default:
6582 return false;
6583 }
6584}
6585
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006586bool AudioFlinger::EffectModule::isProcessEnabled()
6587{
6588 switch (mState) {
6589 case RESTART:
6590 case ACTIVE:
6591 case STOPPING:
6592 case STOPPED:
6593 return true;
6594 case IDLE:
6595 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006596 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006597 default:
6598 return false;
6599 }
6600}
6601
Eric Laurent65b65452010-06-01 23:49:17 -07006602status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6603{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006604 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006605 status_t status = NO_ERROR;
6606
6607 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6608 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006609 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006610 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6611 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006612 status_t cmdStatus;
6613 uint32_t volume[2];
6614 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006615 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006616 volume[0] = *left;
6617 volume[1] = *right;
6618 if (controller) {
6619 pVolume = volume;
6620 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006621 status = (*mEffectInterface)->command(mEffectInterface,
6622 EFFECT_CMD_SET_VOLUME,
6623 size,
6624 volume,
6625 &size,
6626 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006627 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6628 *left = volume[0];
6629 *right = volume[1];
6630 }
6631 }
6632 return status;
6633}
6634
6635status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6636{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006637 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006638 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006639 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6640 // audio pre processing modules on RecordThread can receive both output and
6641 // input device indication in the same call
6642 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6643 if (dev) {
6644 status_t cmdStatus;
6645 uint32_t size = sizeof(status_t);
6646
6647 status = (*mEffectInterface)->command(mEffectInterface,
6648 EFFECT_CMD_SET_DEVICE,
6649 sizeof(uint32_t),
6650 &dev,
6651 &size,
6652 &cmdStatus);
6653 if (status == NO_ERROR) {
6654 status = cmdStatus;
6655 }
6656 }
6657 dev = device & AUDIO_DEVICE_IN_ALL;
6658 if (dev) {
6659 status_t cmdStatus;
6660 uint32_t size = sizeof(status_t);
6661
6662 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6663 EFFECT_CMD_SET_INPUT_DEVICE,
6664 sizeof(uint32_t),
6665 &dev,
6666 &size,
6667 &cmdStatus);
6668 if (status2 == NO_ERROR) {
6669 status2 = cmdStatus;
6670 }
6671 if (status == NO_ERROR) {
6672 status = status2;
6673 }
Eric Laurent65b65452010-06-01 23:49:17 -07006674 }
6675 }
6676 return status;
6677}
6678
Eric Laurent53334cd2010-06-23 17:38:20 -07006679status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6680{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006681 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006682 status_t status = NO_ERROR;
6683 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006684 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006685 uint32_t size = sizeof(status_t);
6686 status = (*mEffectInterface)->command(mEffectInterface,
6687 EFFECT_CMD_SET_AUDIO_MODE,
6688 sizeof(int),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006689 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006690 &size,
6691 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006692 if (status == NO_ERROR) {
6693 status = cmdStatus;
6694 }
6695 }
6696 return status;
6697}
6698
Eric Laurentf82fccd2011-07-27 19:49:51 -07006699void AudioFlinger::EffectModule::setSuspended(bool suspended)
6700{
6701 Mutex::Autolock _l(mLock);
6702 mSuspended = suspended;
6703}
6704bool AudioFlinger::EffectModule::suspended()
6705{
6706 Mutex::Autolock _l(mLock);
6707 return mSuspended;
6708}
6709
Eric Laurent65b65452010-06-01 23:49:17 -07006710status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6711{
6712 const size_t SIZE = 256;
6713 char buffer[SIZE];
6714 String8 result;
6715
6716 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6717 result.append(buffer);
6718
6719 bool locked = tryLock(mLock);
6720 // failed to lock - AudioFlinger is probably deadlocked
6721 if (!locked) {
6722 result.append("\t\tCould not lock Fx mutex:\n");
6723 }
6724
6725 result.append("\t\tSession Status State Engine:\n");
6726 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6727 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6728 result.append(buffer);
6729
6730 result.append("\t\tDescriptor:\n");
6731 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6732 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6733 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6734 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6735 result.append(buffer);
6736 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6737 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6738 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6739 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6740 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006741 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006742 mDescriptor.apiVersion,
6743 mDescriptor.flags);
6744 result.append(buffer);
6745 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6746 mDescriptor.name);
6747 result.append(buffer);
6748 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6749 mDescriptor.implementor);
6750 result.append(buffer);
6751
6752 result.append("\t\t- Input configuration:\n");
6753 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6754 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6755 (uint32_t)mConfig.inputCfg.buffer.raw,
6756 mConfig.inputCfg.buffer.frameCount,
6757 mConfig.inputCfg.samplingRate,
6758 mConfig.inputCfg.channels,
6759 mConfig.inputCfg.format);
6760 result.append(buffer);
6761
6762 result.append("\t\t- Output configuration:\n");
6763 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6764 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6765 (uint32_t)mConfig.outputCfg.buffer.raw,
6766 mConfig.outputCfg.buffer.frameCount,
6767 mConfig.outputCfg.samplingRate,
6768 mConfig.outputCfg.channels,
6769 mConfig.outputCfg.format);
6770 result.append(buffer);
6771
6772 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6773 result.append(buffer);
6774 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6775 for (size_t i = 0; i < mHandles.size(); ++i) {
6776 sp<EffectHandle> handle = mHandles[i].promote();
6777 if (handle != 0) {
6778 handle->dump(buffer, SIZE);
6779 result.append(buffer);
6780 }
6781 }
6782
6783 result.append("\n");
6784
6785 write(fd, result.string(), result.length());
6786
6787 if (locked) {
6788 mLock.unlock();
6789 }
6790
6791 return NO_ERROR;
6792}
6793
6794// ----------------------------------------------------------------------------
6795// EffectHandle implementation
6796// ----------------------------------------------------------------------------
6797
6798#undef LOG_TAG
6799#define LOG_TAG "AudioFlinger::EffectHandle"
6800
6801AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6802 const sp<AudioFlinger::Client>& client,
6803 const sp<IEffectClient>& effectClient,
6804 int32_t priority)
6805 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006806 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006807 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006808{
Steve Block71f2cf12011-10-20 11:56:00 +01006809 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006810
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006811 if (client == 0) {
6812 return;
6813 }
Eric Laurent65b65452010-06-01 23:49:17 -07006814 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6815 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6816 if (mCblkMemory != 0) {
6817 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6818
6819 if (mCblk) {
6820 new(mCblk) effect_param_cblk_t();
6821 mBuffer = (uint8_t *)mCblk + bufOffset;
6822 }
6823 } else {
6824 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6825 return;
6826 }
6827}
6828
6829AudioFlinger::EffectHandle::~EffectHandle()
6830{
Steve Block71f2cf12011-10-20 11:56:00 +01006831 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006832 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01006833 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006834}
6835
6836status_t AudioFlinger::EffectHandle::enable()
6837{
Steve Block71f2cf12011-10-20 11:56:00 +01006838 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006839 if (!mHasControl) return INVALID_OPERATION;
6840 if (mEffect == 0) return DEAD_OBJECT;
6841
Eric Laurent6752ec82011-08-10 10:37:50 -07006842 if (mEnabled) {
6843 return NO_ERROR;
6844 }
6845
Eric Laurentf82fccd2011-07-27 19:49:51 -07006846 mEnabled = true;
6847
6848 sp<ThreadBase> thread = mEffect->thread().promote();
6849 if (thread != 0) {
6850 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6851 }
6852
6853 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6854 if (mEffect->suspended()) {
6855 return NO_ERROR;
6856 }
6857
Eric Laurent6752ec82011-08-10 10:37:50 -07006858 status_t status = mEffect->setEnabled(true);
6859 if (status != NO_ERROR) {
6860 if (thread != 0) {
6861 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6862 }
6863 mEnabled = false;
6864 }
6865 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006866}
6867
6868status_t AudioFlinger::EffectHandle::disable()
6869{
Steve Block71f2cf12011-10-20 11:56:00 +01006870 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006871 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006872 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006873
Eric Laurent6752ec82011-08-10 10:37:50 -07006874 if (!mEnabled) {
6875 return NO_ERROR;
6876 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006877 mEnabled = false;
6878
6879 if (mEffect->suspended()) {
6880 return NO_ERROR;
6881 }
6882
6883 status_t status = mEffect->setEnabled(false);
6884
6885 sp<ThreadBase> thread = mEffect->thread().promote();
6886 if (thread != 0) {
6887 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6888 }
6889
6890 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006891}
6892
6893void AudioFlinger::EffectHandle::disconnect()
6894{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006895 disconnect(true);
6896}
6897
6898void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6899{
Steve Block71f2cf12011-10-20 11:56:00 +01006900 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006901 if (mEffect == 0) {
6902 return;
6903 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006904 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006905
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006906 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006907 sp<ThreadBase> thread = mEffect->thread().promote();
6908 if (thread != 0) {
6909 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6910 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006911 }
6912
Eric Laurent65b65452010-06-01 23:49:17 -07006913 // release sp on module => module destructor can be called now
6914 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006915 if (mClient != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006916 if (mCblk) {
6917 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6918 }
6919 mCblkMemory.clear(); // and free the shared memory
Eric Laurent65b65452010-06-01 23:49:17 -07006920 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6921 mClient.clear();
6922 }
6923}
6924
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006925status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6926 uint32_t cmdSize,
6927 void *pCmdData,
6928 uint32_t *replySize,
6929 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006930{
Steve Block71f2cf12011-10-20 11:56:00 +01006931// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006932// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006933
6934 // only get parameter command is permitted for applications not controlling the effect
6935 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6936 return INVALID_OPERATION;
6937 }
6938 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006939 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006940
6941 // handle commands that are not forwarded transparently to effect engine
6942 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6943 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6944 // no risk to block the whole media server process or mixer threads is we are stuck here
6945 Mutex::Autolock _l(mCblk->lock);
6946 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6947 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6948 mCblk->serverIndex = 0;
6949 mCblk->clientIndex = 0;
6950 return BAD_VALUE;
6951 }
6952 status_t status = NO_ERROR;
6953 while (mCblk->serverIndex < mCblk->clientIndex) {
6954 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006955 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006956 int *p = (int *)(mBuffer + mCblk->serverIndex);
6957 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006958 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6959 LOGW("command(): invalid parameter block size");
6960 break;
6961 }
Eric Laurent65b65452010-06-01 23:49:17 -07006962 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006963 if (param->psize == 0 || param->vsize == 0) {
6964 LOGW("command(): null parameter or value size");
6965 mCblk->serverIndex += size;
6966 continue;
6967 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006968 uint32_t psize = sizeof(effect_param_t) +
6969 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6970 param->vsize;
6971 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6972 psize,
6973 p,
6974 &rsize,
6975 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006976 // stop at first error encountered
6977 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006978 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006979 *(int *)pReplyData = reply;
6980 break;
6981 } else if (reply != NO_ERROR) {
6982 *(int *)pReplyData = reply;
6983 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006984 }
6985 mCblk->serverIndex += size;
6986 }
6987 mCblk->serverIndex = 0;
6988 mCblk->clientIndex = 0;
6989 return status;
6990 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006991 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006992 return enable();
6993 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006994 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006995 return disable();
6996 }
6997
6998 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6999}
7000
7001sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7002 return mCblkMemory;
7003}
7004
Eric Laurentf82fccd2011-07-27 19:49:51 -07007005void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07007006{
Steve Block71f2cf12011-10-20 11:56:00 +01007007 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07007008
7009 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007010 mEnabled = enabled;
7011
Eric Laurent65b65452010-06-01 23:49:17 -07007012 if (signal && mEffectClient != 0) {
7013 mEffectClient->controlStatusChanged(hasControl);
7014 }
7015}
7016
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007017void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7018 uint32_t cmdSize,
7019 void *pCmdData,
7020 uint32_t replySize,
7021 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007022{
7023 if (mEffectClient != 0) {
7024 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7025 }
7026}
7027
7028
7029
7030void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7031{
7032 if (mEffectClient != 0) {
7033 mEffectClient->enableStatusChanged(enabled);
7034 }
7035}
7036
7037status_t AudioFlinger::EffectHandle::onTransact(
7038 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7039{
7040 return BnEffect::onTransact(code, data, reply, flags);
7041}
7042
7043
7044void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7045{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007046 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Eric Laurent65b65452010-06-01 23:49:17 -07007047
7048 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7049 (mClient == NULL) ? getpid() : mClient->pid(),
7050 mPriority,
7051 mHasControl,
7052 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007053 mCblk ? mCblk->clientIndex : 0,
7054 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007055 );
7056
7057 if (locked) {
7058 mCblk->lock.unlock();
7059 }
7060}
7061
7062#undef LOG_TAG
7063#define LOG_TAG "AudioFlinger::EffectChain"
7064
7065AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7066 int sessionId)
Eric Laurentf9c361d2011-11-11 15:42:52 -08007067 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007068 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7069 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007070{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007071 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007072 sp<ThreadBase> thread = mThread.promote();
7073 if (thread == 0) {
7074 return;
7075 }
7076 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7077 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007078}
7079
7080AudioFlinger::EffectChain::~EffectChain()
7081{
7082 if (mOwnInBuffer) {
7083 delete mInBuffer;
7084 }
7085
7086}
7087
Eric Laurentf82fccd2011-07-27 19:49:51 -07007088// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007089sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007090{
7091 sp<EffectModule> effect;
7092 size_t size = mEffects.size();
7093
7094 for (size_t i = 0; i < size; i++) {
7095 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7096 effect = mEffects[i];
7097 break;
7098 }
7099 }
7100 return effect;
7101}
7102
Eric Laurentf82fccd2011-07-27 19:49:51 -07007103// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007104sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007105{
7106 sp<EffectModule> effect;
7107 size_t size = mEffects.size();
7108
7109 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007110 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7111 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07007112 effect = mEffects[i];
7113 break;
7114 }
7115 }
7116 return effect;
7117}
7118
Eric Laurentf82fccd2011-07-27 19:49:51 -07007119// getEffectFromType_l() must be called with ThreadBase::mLock held
7120sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7121 const effect_uuid_t *type)
7122{
7123 sp<EffectModule> effect;
7124 size_t size = mEffects.size();
7125
7126 for (size_t i = 0; i < size; i++) {
7127 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7128 effect = mEffects[i];
7129 break;
7130 }
7131 }
7132 return effect;
7133}
7134
Eric Laurent65b65452010-06-01 23:49:17 -07007135// Must be called with EffectChain::mLock locked
7136void AudioFlinger::EffectChain::process_l()
7137{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007138 sp<ThreadBase> thread = mThread.promote();
7139 if (thread == 0) {
7140 LOGW("process_l(): cannot promote mixer thread");
7141 return;
7142 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007143 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7144 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007145 // always process effects unless no more tracks are on the session and the effect tail
7146 // has been rendered
7147 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007148 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007149 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007150
Eric Laurentf9c361d2011-11-11 15:42:52 -08007151 if (!tracksOnSession && mTailBufferCount == 0) {
7152 doProcess = false;
7153 }
7154
7155 if (activeTrackCnt() == 0) {
7156 // if no track is active and the effect tail has not been rendered,
7157 // the input buffer must be cleared here as the mixer process will not do it
7158 if (tracksOnSession || mTailBufferCount > 0) {
7159 size_t numSamples = thread->frameCount() * thread->channelCount();
7160 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7161 if (mTailBufferCount > 0) {
7162 mTailBufferCount--;
7163 }
7164 }
7165 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007166 }
7167
Eric Laurent65b65452010-06-01 23:49:17 -07007168 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007169 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007170 for (size_t i = 0; i < size; i++) {
7171 mEffects[i]->process();
7172 }
Eric Laurent65b65452010-06-01 23:49:17 -07007173 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007174 for (size_t i = 0; i < size; i++) {
7175 mEffects[i]->updateState();
7176 }
Eric Laurent65b65452010-06-01 23:49:17 -07007177}
7178
Eric Laurent76c40f72010-07-15 12:50:15 -07007179// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007180status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007181{
7182 effect_descriptor_t desc = effect->desc();
7183 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7184
7185 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007186 effect->setChain(this);
7187 sp<ThreadBase> thread = mThread.promote();
7188 if (thread == 0) {
7189 return NO_INIT;
7190 }
7191 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007192
7193 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7194 // Auxiliary effects are inserted at the beginning of mEffects vector as
7195 // they are processed first and accumulated in chain input buffer
7196 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007197
Eric Laurent65b65452010-06-01 23:49:17 -07007198 // the input buffer for auxiliary effect contains mono samples in
7199 // 32 bit format. This is to avoid saturation in AudoMixer
7200 // accumulation stage. Saturation is done in EffectModule::process() before
7201 // calling the process in effect engine
7202 size_t numSamples = thread->frameCount();
7203 int32_t *buffer = new int32_t[numSamples];
7204 memset(buffer, 0, numSamples * sizeof(int32_t));
7205 effect->setInBuffer((int16_t *)buffer);
7206 // auxiliary effects output samples to chain input buffer for further processing
7207 // by insert effects
7208 effect->setOutBuffer(mInBuffer);
7209 } else {
7210 // Insert effects are inserted at the end of mEffects vector as they are processed
7211 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007212 // Insert effect order as a function of indicated preference:
7213 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7214 // another effect is present
7215 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7216 // last effect claiming first position
7217 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7218 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007219 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007220 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7221 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007222
7223 int size = (int)mEffects.size();
7224 int idx_insert = size;
7225 int idx_insert_first = -1;
7226 int idx_insert_last = -1;
7227
7228 for (int i = 0; i < size; i++) {
7229 effect_descriptor_t d = mEffects[i]->desc();
7230 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7231 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7232 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7233 // check invalid effect chaining combinations
7234 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007235 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007236 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007237 return INVALID_OPERATION;
7238 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007239 // remember position of first insert effect and by default
7240 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007241 if (idx_insert == size) {
7242 idx_insert = i;
7243 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007244 // remember position of last insert effect claiming
7245 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007246 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7247 idx_insert_first = i;
7248 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007249 // remember position of first insert effect claiming
7250 // last position
7251 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7252 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007253 idx_insert_last = i;
7254 }
7255 }
7256 }
7257
Eric Laurent53334cd2010-06-23 17:38:20 -07007258 // modify idx_insert from first position if needed
7259 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7260 if (idx_insert_last != -1) {
7261 idx_insert = idx_insert_last;
7262 } else {
7263 idx_insert = size;
7264 }
7265 } else {
7266 if (idx_insert_first != -1) {
7267 idx_insert = idx_insert_first + 1;
7268 }
Eric Laurent65b65452010-06-01 23:49:17 -07007269 }
7270
7271 // always read samples from chain input buffer
7272 effect->setInBuffer(mInBuffer);
7273
7274 // if last effect in the chain, output samples to chain
7275 // output buffer, otherwise to chain input buffer
7276 if (idx_insert == size) {
7277 if (idx_insert != 0) {
7278 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7279 mEffects[idx_insert-1]->configure();
7280 }
7281 effect->setOutBuffer(mOutBuffer);
7282 } else {
7283 effect->setOutBuffer(mInBuffer);
7284 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007285 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007286
Steve Block71f2cf12011-10-20 11:56:00 +01007287 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007288 }
7289 effect->configure();
7290 return NO_ERROR;
7291}
7292
Eric Laurent76c40f72010-07-15 12:50:15 -07007293// removeEffect_l() must be called with PlaybackThread::mLock held
7294size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007295{
7296 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007297 int size = (int)mEffects.size();
7298 int i;
7299 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7300
7301 for (i = 0; i < size; i++) {
7302 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007303 // calling stop here will remove pre-processing effect from the audio HAL.
7304 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7305 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007306 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7307 mEffects[i]->state() == EffectModule::STOPPING) {
7308 mEffects[i]->stop();
7309 }
Eric Laurent65b65452010-06-01 23:49:17 -07007310 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7311 delete[] effect->inBuffer();
7312 } else {
7313 if (i == size - 1 && i != 0) {
7314 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7315 mEffects[i - 1]->configure();
7316 }
7317 }
7318 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007319 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007320 break;
7321 }
7322 }
Eric Laurent65b65452010-06-01 23:49:17 -07007323
7324 return mEffects.size();
7325}
7326
Eric Laurent76c40f72010-07-15 12:50:15 -07007327// setDevice_l() must be called with PlaybackThread::mLock held
7328void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007329{
7330 size_t size = mEffects.size();
7331 for (size_t i = 0; i < size; i++) {
7332 mEffects[i]->setDevice(device);
7333 }
7334}
7335
Eric Laurent76c40f72010-07-15 12:50:15 -07007336// setMode_l() must be called with PlaybackThread::mLock held
7337void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007338{
7339 size_t size = mEffects.size();
7340 for (size_t i = 0; i < size; i++) {
7341 mEffects[i]->setMode(mode);
7342 }
7343}
7344
Eric Laurent76c40f72010-07-15 12:50:15 -07007345// setVolume_l() must be called with PlaybackThread::mLock held
7346bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007347{
7348 uint32_t newLeft = *left;
7349 uint32_t newRight = *right;
7350 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007351 int ctrlIdx = -1;
7352 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007353
Eric Laurent76c40f72010-07-15 12:50:15 -07007354 // first update volume controller
7355 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007356 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007357 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7358 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007359 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007360 break;
7361 }
7362 }
7363
7364 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007365 if (hasControl) {
7366 *left = mNewLeftVolume;
7367 *right = mNewRightVolume;
7368 }
7369 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007370 }
7371
7372 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007373 mLeftVolume = newLeft;
7374 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007375
7376 // second get volume update from volume controller
7377 if (ctrlIdx >= 0) {
7378 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007379 mNewLeftVolume = newLeft;
7380 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007381 }
7382 // then indicate volume to all other effects in chain.
7383 // Pass altered volume to effects before volume controller
7384 // and requested volume to effects after controller
7385 uint32_t lVol = newLeft;
7386 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007387
Eric Laurent65b65452010-06-01 23:49:17 -07007388 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007389 if ((int)i == ctrlIdx) continue;
7390 // this also works for ctrlIdx == -1 when there is no volume controller
7391 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007392 lVol = *left;
7393 rVol = *right;
7394 }
7395 mEffects[i]->setVolume(&lVol, &rVol, false);
7396 }
7397 *left = newLeft;
7398 *right = newRight;
7399
7400 return hasControl;
7401}
7402
Eric Laurent65b65452010-06-01 23:49:17 -07007403status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7404{
7405 const size_t SIZE = 256;
7406 char buffer[SIZE];
7407 String8 result;
7408
7409 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7410 result.append(buffer);
7411
7412 bool locked = tryLock(mLock);
7413 // failed to lock - AudioFlinger is probably deadlocked
7414 if (!locked) {
7415 result.append("\tCould not lock mutex:\n");
7416 }
7417
Eric Laurent76c40f72010-07-15 12:50:15 -07007418 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7419 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007420 mEffects.size(),
7421 (uint32_t)mInBuffer,
7422 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007423 mActiveTrackCnt);
7424 result.append(buffer);
7425 write(fd, result.string(), result.size());
7426
7427 for (size_t i = 0; i < mEffects.size(); ++i) {
7428 sp<EffectModule> effect = mEffects[i];
7429 if (effect != 0) {
7430 effect->dump(fd, args);
7431 }
7432 }
7433
7434 if (locked) {
7435 mLock.unlock();
7436 }
7437
7438 return NO_ERROR;
7439}
7440
Eric Laurentf82fccd2011-07-27 19:49:51 -07007441// must be called with ThreadBase::mLock held
7442void AudioFlinger::EffectChain::setEffectSuspended_l(
7443 const effect_uuid_t *type, bool suspend)
7444{
7445 sp<SuspendedEffectDesc> desc;
7446 // use effect type UUID timelow as key as there is no real risk of identical
7447 // timeLow fields among effect type UUIDs.
7448 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7449 if (suspend) {
7450 if (index >= 0) {
7451 desc = mSuspendedEffects.valueAt(index);
7452 } else {
7453 desc = new SuspendedEffectDesc();
7454 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7455 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007456 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007457 }
7458 if (desc->mRefCount++ == 0) {
7459 sp<EffectModule> effect = getEffectIfEnabled(type);
7460 if (effect != 0) {
7461 desc->mEffect = effect;
7462 effect->setSuspended(true);
7463 effect->setEnabled(false);
7464 }
7465 }
7466 } else {
7467 if (index < 0) {
7468 return;
7469 }
7470 desc = mSuspendedEffects.valueAt(index);
7471 if (desc->mRefCount <= 0) {
7472 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7473 desc->mRefCount = 1;
7474 }
7475 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007476 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007477 if (desc->mEffect != 0) {
7478 sp<EffectModule> effect = desc->mEffect.promote();
7479 if (effect != 0) {
7480 effect->setSuspended(false);
7481 sp<EffectHandle> handle = effect->controlHandle();
7482 if (handle != 0) {
7483 effect->setEnabled(handle->enabled());
7484 }
7485 }
7486 desc->mEffect.clear();
7487 }
7488 mSuspendedEffects.removeItemsAt(index);
7489 }
7490 }
7491}
7492
7493// must be called with ThreadBase::mLock held
7494void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7495{
7496 sp<SuspendedEffectDesc> desc;
7497
7498 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7499 if (suspend) {
7500 if (index >= 0) {
7501 desc = mSuspendedEffects.valueAt(index);
7502 } else {
7503 desc = new SuspendedEffectDesc();
7504 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007505 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007506 }
7507 if (desc->mRefCount++ == 0) {
7508 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7509 for (size_t i = 0; i < effects.size(); i++) {
7510 setEffectSuspended_l(&effects[i]->desc().type, true);
7511 }
7512 }
7513 } else {
7514 if (index < 0) {
7515 return;
7516 }
7517 desc = mSuspendedEffects.valueAt(index);
7518 if (desc->mRefCount <= 0) {
7519 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7520 desc->mRefCount = 1;
7521 }
7522 if (--desc->mRefCount == 0) {
7523 Vector<const effect_uuid_t *> types;
7524 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7525 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7526 continue;
7527 }
7528 types.add(&mSuspendedEffects.valueAt(i)->mType);
7529 }
7530 for (size_t i = 0; i < types.size(); i++) {
7531 setEffectSuspended_l(types[i], false);
7532 }
Steve Block71f2cf12011-10-20 11:56:00 +01007533 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007534 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7535 }
7536 }
7537}
7538
Eric Laurent5e7acae2011-09-23 08:40:41 -07007539
7540// The volume effect is used for automated tests only
7541#ifndef OPENSL_ES_H_
7542static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7543 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7544const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7545#endif //OPENSL_ES_H_
7546
Eric Laurent6752ec82011-08-10 10:37:50 -07007547bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7548{
7549 // auxiliary effects and visualizer are never suspended on output mix
7550 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7551 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007552 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7553 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007554 return false;
7555 }
7556 return true;
7557}
7558
Eric Laurentf82fccd2011-07-27 19:49:51 -07007559Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7560{
7561 Vector< sp<EffectModule> > effects;
7562 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007563 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07007564 continue;
7565 }
7566 effects.add(mEffects[i]);
7567 }
7568 return effects;
7569}
7570
7571sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7572 const effect_uuid_t *type)
7573{
7574 sp<EffectModule> effect;
7575 effect = getEffectFromType_l(type);
7576 if (effect != 0 && !effect->isEnabled()) {
7577 effect.clear();
7578 }
7579 return effect;
7580}
7581
7582void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7583 bool enabled)
7584{
7585 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7586 if (enabled) {
7587 if (index < 0) {
7588 // if the effect is not suspend check if all effects are suspended
7589 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7590 if (index < 0) {
7591 return;
7592 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007593 if (!isEffectEligibleForSuspend(effect->desc())) {
7594 return;
7595 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007596 setEffectSuspended_l(&effect->desc().type, enabled);
7597 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007598 if (index < 0) {
7599 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7600 return;
7601 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007602 }
Steve Block71f2cf12011-10-20 11:56:00 +01007603 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007604 effect->desc().type.timeLow);
7605 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7606 // if effect is requested to suspended but was not yet enabled, supend it now.
7607 if (desc->mEffect == 0) {
7608 desc->mEffect = effect;
7609 effect->setEnabled(false);
7610 effect->setSuspended(true);
7611 }
7612 } else {
7613 if (index < 0) {
7614 return;
7615 }
Steve Block71f2cf12011-10-20 11:56:00 +01007616 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007617 effect->desc().type.timeLow);
7618 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7619 desc->mEffect.clear();
7620 effect->setSuspended(false);
7621 }
7622}
7623
Eric Laurent65b65452010-06-01 23:49:17 -07007624#undef LOG_TAG
7625#define LOG_TAG "AudioFlinger"
7626
Eric Laurenta553c252009-07-17 12:17:14 -07007627// ----------------------------------------------------------------------------
7628
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007629status_t AudioFlinger::onTransact(
7630 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7631{
7632 return BnAudioFlinger::onTransact(code, data, reply, flags);
7633}
7634
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007635}; // namespace android