blob: fdf15701a8bd7d032ab3f3dffdfcf0d3ea463d21 [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
Gloria Wang9b3f1522011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten26f260a2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070044#include <private/media/AudioEffectShared.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070045
Dima Zavin34bb4192011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070047#include <hardware/audio.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Eric Laurent53334cd2010-06-23 17:38:20 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent5cc05262011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent6639b552011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Eric Laurent65b65452010-06-01 23:49:17 -070056
Glenn Kasten490909d2011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Glenn Kastenda494f92011-07-08 15:26:12 -070059#include <cpustats/ThreadCpuUsage.h>
Eric Laurent6dbdc402011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kastenda494f92011-07-08 15:26:12 -070061// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
62
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063// ----------------------------------------------------------------------------
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064
Eric Laurent8ed6ed02010-07-13 04:45:46 -070065
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066namespace android {
67
Glenn Kasten62de3db2011-12-12 09:04:45 -080068static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
69static const char kHardwareLockedString[] = "Hardware lock is taken\n";
The Android Open Source Project10592532009-03-18 17:39:46 -070070
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080071//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070072static const float MAX_GAIN = 4096.0f;
Glenn Kasten0632bad2012-01-17 12:20:54 -080073static const uint32_t MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070074
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080079// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070083
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070084static const int kDumpLockRetries = 50;
Glenn Kastencbfe2e12011-12-13 11:04:14 -080085static const int kDumpLockSleepUs = 20000;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070086
Glenn Kastencbfe2e12011-12-13 11:04:14 -080087// don't warn about blocked writes or record buffer overflows more often than this
88static const nsecs_t kWarningThrottleNs = seconds(5);
Dave Sparksd0ac8c02009-09-30 03:09:03 -070089
Eric Laurent464d5b32011-06-17 21:29:58 -070090// RecordThread loop sleep time upon application overrun or audio HAL read error
91static const int kRecordThreadSleepUs = 5000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
Glenn Kastencbfe2e12011-12-13 11:04:14 -080093// maximum time to wait for setParameters to complete
94static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent5f37be32011-09-13 11:40:21 -070095
Eric Laurentf1f5fc82011-11-22 18:50:29 -080096// minimum sleep time for the mixer thread loop when tracks are active but in underrun
97static const uint32_t kMinThreadSleepTimeUs = 5000;
98// maximum divider applied to the active sleep time in the mixer thread loop
99static const uint32_t kMaxThreadSleepTimeShift = 2;
100
101
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700102// ----------------------------------------------------------------------------
103
104static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block3762c312012-01-06 19:20:56 +0000107 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700108 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700109}
110
111static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700112 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
113 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block3762c312012-01-06 19:20:56 +0000114 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700115 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700116}
117
Gloria Wang9b3f1522011-02-24 14:51:45 -0800118// To collect the amplifier usage
119static void addBatteryData(uint32_t params) {
Glenn Kasten26f260a2012-01-03 15:28:29 -0800120 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
121 if (service == NULL) {
122 // it already logged
Gloria Wang9b3f1522011-02-24 14:51:45 -0800123 return;
124 }
125
126 service->addBatteryData(params);
127}
128
Dima Zavin31f188892011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
Steve Block3762c312012-01-06 19:20:56 +0000139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin31f188892011-04-18 16:57:27 -0700140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
Glenn Kasten62de3db2011-12-12 09:04:45 -0800152static const char * const audio_interfaces[] = {
Dima Zavin31f188892011-04-18 16:57:27 -0700153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 : BnAudioFlinger(),
Glenn Kastendc3ac852012-01-25 15:28:08 -0800163 mPrimaryHardwareDev(NULL),
164 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
165 mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
166 mMode(AUDIO_MODE_INVALID),
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 */
Eric Laurenta553c252009-07-17 12:17:14 -0700178
Dima Zavin31f188892011-04-18 16:57:27 -0700179 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
180 const hw_module_t *mod;
181 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700182
Dima Zavin31f188892011-04-18 16:57:27 -0700183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184 if (rc)
185 continue;
186
Steve Block6215d3f2012-01-04 20:05:49 +0000187 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin31f188892011-04-18 16:57:27 -0700188 mod->name, mod->id);
189 mAudioHwDevs.push(dev);
190
191 if (!mPrimaryHardwareDev) {
192 mPrimaryHardwareDev = dev;
Steve Block6215d3f2012-01-04 20:05:49 +0000193 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700194 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700195 }
196 }
Eric Laurenta553c252009-07-17 12:17:14 -0700197
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700198 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700199
Dima Zavin31f188892011-04-18 16:57:27 -0700200 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
Steve Block3762c312012-01-06 19:20:56 +0000201 ALOGE("Primary audio interface not found");
Dima Zavin31f188892011-04-18 16:57:27 -0700202 return;
203 }
204
205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
206 audio_hw_device_t *dev = mAudioHwDevs[i];
207
208 mHardwareStatus = AUDIO_HW_INIT;
209 rc = dev->init_check(dev);
210 if (rc == 0) {
211 AutoMutex lock(mHardwareLock);
212
213 mMode = AUDIO_MODE_NORMAL;
214 mHardwareStatus = AUDIO_HW_SET_MODE;
215 dev->set_mode(dev, mMode);
216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
217 dev->set_master_volume(dev, 1.0f);
218 mHardwareStatus = AUDIO_HW_IDLE;
219 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700220 }
221}
222
Dima Zavin2986f5b2011-04-19 19:04:32 -0700223status_t AudioFlinger::initCheck() const
224{
225 Mutex::Autolock _l(mLock);
226 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
227 return NO_INIT;
228 return NO_ERROR;
229}
230
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700231AudioFlinger::~AudioFlinger()
232{
Dima Zavin31f188892011-04-18 16:57:27 -0700233 int num_devs = mAudioHwDevs.size();
234
Eric Laurent7954c462009-08-28 10:39:03 -0700235 while (!mRecordThreads.isEmpty()) {
236 // closeInput() will remove first entry from mRecordThreads
237 closeInput(mRecordThreads.keyAt(0));
238 }
239 while (!mPlaybackThreads.isEmpty()) {
240 // closeOutput() will remove first entry from mPlaybackThreads
241 closeOutput(mPlaybackThreads.keyAt(0));
242 }
Dima Zavin31f188892011-04-18 16:57:27 -0700243
244 for (int i = 0; i < num_devs; i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700247 }
Dima Zavin31f188892011-04-18 16:57:27 -0700248 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800249}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800250
Dima Zavin31f188892011-04-18 16:57:27 -0700251audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
252{
253 /* first matching HW device is returned */
254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
255 audio_hw_device_t *dev = mAudioHwDevs[i];
256 if ((dev->get_supported_devices(dev) & devices) == devices)
257 return dev;
258 }
259 return NULL;
260}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700261
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700262status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
263{
264 const size_t SIZE = 256;
265 char buffer[SIZE];
266 String8 result;
267
268 result.append("Clients:\n");
269 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kastene4787422012-01-25 14:27:41 -0800270 sp<Client> client = mClients.valueAt(i).promote();
271 if (client != 0) {
272 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
273 result.append(buffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700274 }
275 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700276
277 result.append("Global session refs:\n");
278 result.append(" session pid cnt\n");
279 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
280 AudioSessionRef *r = mAudioSessionRefs[i];
281 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
282 result.append(buffer);
283 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700284 write(fd, result.string(), result.size());
285 return NO_ERROR;
286}
287
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700288
289status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
290{
291 const size_t SIZE = 256;
292 char buffer[SIZE];
293 String8 result;
Glenn Kastena934c2c2012-01-04 11:02:33 -0800294 hardware_call_state hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700295
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700296 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700297 result.append(buffer);
298 write(fd, result.string(), result.size());
299 return NO_ERROR;
300}
301
302status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
303{
304 const size_t SIZE = 256;
305 char buffer[SIZE];
306 String8 result;
307 snprintf(buffer, SIZE, "Permission Denial: "
308 "can't dump AudioFlinger from pid=%d, uid=%d\n",
309 IPCThreadState::self()->getCallingPid(),
310 IPCThreadState::self()->getCallingUid());
311 result.append(buffer);
312 write(fd, result.string(), result.size());
313 return NO_ERROR;
314}
315
The Android Open Source Project10592532009-03-18 17:39:46 -0700316static bool tryLock(Mutex& mutex)
317{
318 bool locked = false;
319 for (int i = 0; i < kDumpLockRetries; ++i) {
320 if (mutex.tryLock() == NO_ERROR) {
321 locked = true;
322 break;
323 }
Glenn Kastencbfe2e12011-12-13 11:04:14 -0800324 usleep(kDumpLockSleepUs);
The Android Open Source Project10592532009-03-18 17:39:46 -0700325 }
326 return locked;
327}
328
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700329status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
330{
Glenn Kastenb737dbb2012-01-13 15:54:24 -0800331 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700332 dumpPermissionDenial(fd, args);
333 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700334 // get state of hardware lock
335 bool hardwareLocked = tryLock(mHardwareLock);
336 if (!hardwareLocked) {
337 String8 result(kHardwareLockedString);
338 write(fd, result.string(), result.size());
339 } else {
340 mHardwareLock.unlock();
341 }
342
343 bool locked = tryLock(mLock);
344
345 // failed to lock - AudioFlinger is probably deadlocked
346 if (!locked) {
347 String8 result(kDeadlockedString);
348 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700349 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700350
351 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700352 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353
Eric Laurenta553c252009-07-17 12:17:14 -0700354 // dump playback threads
355 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700356 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700357 }
358
359 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700360 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700361 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363
Dima Zavin31f188892011-04-18 16:57:27 -0700364 // dump all hardware devs
365 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
366 audio_hw_device_t *dev = mAudioHwDevs[i];
367 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700368 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700369 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700370 }
371 return NO_ERROR;
372}
373
Eric Laurenta553c252009-07-17 12:17:14 -0700374
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700375// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376
377
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700378sp<IAudioTrack> AudioFlinger::createTrack(
379 pid_t pid,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800380 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700381 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800382 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700383 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800384 int frameCount,
385 uint32_t flags,
386 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700387 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700388 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800389 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700390{
Eric Laurenta553c252009-07-17 12:17:14 -0700391 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700392 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700393 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800394 wp<Client> wclient;
395 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700396 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700397
Glenn Kasten6e987a42012-01-06 08:40:01 -0800398 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
399 // but if someone uses binder directly they could bypass that and cause us to crash
400 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block3762c312012-01-06 19:20:56 +0000401 ALOGE("createTrack() invalid stream type %d", streamType);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800402 lStatus = BAD_VALUE;
403 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700404 }
405
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800406 {
407 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700408 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700409 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700410 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +0000411 ALOGE("unknown output thread");
Eric Laurenta553c252009-07-17 12:17:14 -0700412 lStatus = BAD_VALUE;
413 goto Exit;
414 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800415
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800416 wclient = mClients.valueFor(pid);
417
418 if (wclient != NULL) {
419 client = wclient.promote();
420 } else {
421 client = new Client(this, pid);
422 mClients.add(pid, client);
423 }
Eric Laurent65b65452010-06-01 23:49:17 -0700424
Steve Block71f2cf12011-10-20 11:56:00 +0100425 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700426 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700427 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700428 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
429 if (mPlaybackThreads.keyAt(i) != output) {
430 // prevent same audio session on different output threads
431 uint32_t sessions = t->hasAudioSession(*sessionId);
432 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block3762c312012-01-06 19:20:56 +0000433 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent493941b2010-07-28 01:32:47 -0700434 lStatus = BAD_VALUE;
435 goto Exit;
436 }
437 // check if an effect with same session ID is waiting for a track to be created
438 if (sessions & PlaybackThread::EFFECT_SESSION) {
439 effectThread = t.get();
440 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700441 }
442 }
Eric Laurent65b65452010-06-01 23:49:17 -0700443 lSessionId = *sessionId;
444 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700445 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700446 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700447 if (sessionId != NULL) {
448 *sessionId = lSessionId;
449 }
450 }
Steve Block71f2cf12011-10-20 11:56:00 +0100451 ALOGV("createTrack() lSessionId: %d", lSessionId);
Eric Laurent65b65452010-06-01 23:49:17 -0700452
Eric Laurenta553c252009-07-17 12:17:14 -0700453 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700454 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700455
456 // move effect chain to this output thread if an effect on same session was waiting
457 // for a track to be created
458 if (lStatus == NO_ERROR && effectThread != NULL) {
459 Mutex::Autolock _dl(thread->mLock);
460 Mutex::Autolock _sl(effectThread->mLock);
461 moveEffectChain_l(lSessionId, effectThread, thread, true);
462 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700463 }
464 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800465 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700466 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700467 // remove local strong reference to Client before deleting the Track so that the Client
468 // destructor is called by the TrackBase destructor with mLock held
469 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700470 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800471 }
472
473Exit:
474 if(status) {
475 *status = lStatus;
476 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700477 return trackHandle;
478}
479
Eric Laurentddb78e72009-07-28 08:44:33 -0700480uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700481{
Eric Laurenta553c252009-07-17 12:17:14 -0700482 Mutex::Autolock _l(mLock);
483 PlaybackThread *thread = checkPlaybackThread_l(output);
484 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000485 ALOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700486 return 0;
487 }
488 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700489}
490
Eric Laurentddb78e72009-07-28 08:44:33 -0700491int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700492{
Eric Laurenta553c252009-07-17 12:17:14 -0700493 Mutex::Autolock _l(mLock);
494 PlaybackThread *thread = checkPlaybackThread_l(output);
495 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000496 ALOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700497 return 0;
498 }
499 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700500}
501
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800502audio_format_t AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700503{
Eric Laurenta553c252009-07-17 12:17:14 -0700504 Mutex::Autolock _l(mLock);
505 PlaybackThread *thread = checkPlaybackThread_l(output);
506 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000507 ALOGW("format() unknown thread %d", output);
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800508 return AUDIO_FORMAT_INVALID;
Eric Laurenta553c252009-07-17 12:17:14 -0700509 }
510 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700511}
512
Eric Laurentddb78e72009-07-28 08:44:33 -0700513size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700514{
Eric Laurenta553c252009-07-17 12:17:14 -0700515 Mutex::Autolock _l(mLock);
516 PlaybackThread *thread = checkPlaybackThread_l(output);
517 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000518 ALOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700519 return 0;
520 }
521 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700522}
523
Eric Laurentddb78e72009-07-28 08:44:33 -0700524uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800525{
Eric Laurenta553c252009-07-17 12:17:14 -0700526 Mutex::Autolock _l(mLock);
527 PlaybackThread *thread = checkPlaybackThread_l(output);
528 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000529 ALOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700530 return 0;
531 }
532 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800533}
534
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700535status_t AudioFlinger::setMasterVolume(float value)
536{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700537 status_t ret = initCheck();
538 if (ret != NO_ERROR) {
539 return ret;
540 }
541
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700542 // check calling permissions
543 if (!settingsAllowed()) {
544 return PERMISSION_DENIED;
545 }
546
547 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800548 { // scope for the lock
549 AutoMutex lock(mHardwareLock);
550 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700551 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800552 value = 1.0f;
553 }
554 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700555 }
Eric Laurenta553c252009-07-17 12:17:14 -0700556
Eric Laurent01635942011-01-18 18:39:02 -0800557 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700558 mMasterVolume = value;
559 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700560 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700561
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700562 return NO_ERROR;
563}
564
Glenn Kastenaccb1142012-01-04 11:00:47 -0800565status_t AudioFlinger::setMode(audio_mode_t mode)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700566{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700567 status_t ret = initCheck();
568 if (ret != NO_ERROR) {
569 return ret;
570 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700571
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700572 // check calling permissions
573 if (!settingsAllowed()) {
574 return PERMISSION_DENIED;
575 }
Glenn Kasten01aaf2c2012-01-06 16:47:31 -0800576 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block8564c8d2012-01-05 23:22:43 +0000577 ALOGW("Illegal value: setMode(%d)", mode);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700578 return BAD_VALUE;
579 }
580
Eric Laurent53334cd2010-06-23 17:38:20 -0700581 { // scope for the lock
582 AutoMutex lock(mHardwareLock);
583 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700584 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700585 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800586 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700587
588 if (NO_ERROR == ret) {
589 Mutex::Autolock _l(mLock);
590 mMode = mode;
591 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
592 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700593 }
594
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700595 return ret;
596}
597
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700598status_t AudioFlinger::setMicMute(bool state)
599{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700600 status_t ret = initCheck();
601 if (ret != NO_ERROR) {
602 return ret;
603 }
604
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700605 // check calling permissions
606 if (!settingsAllowed()) {
607 return PERMISSION_DENIED;
608 }
609
610 AutoMutex lock(mHardwareLock);
611 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700612 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700613 mHardwareStatus = AUDIO_HW_IDLE;
614 return ret;
615}
616
617bool AudioFlinger::getMicMute() const
618{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700619 status_t ret = initCheck();
620 if (ret != NO_ERROR) {
621 return false;
622 }
623
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700624 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700625 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700626 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700627 mHardwareStatus = AUDIO_HW_IDLE;
628 return state;
629}
630
631status_t AudioFlinger::setMasterMute(bool muted)
632{
633 // check calling permissions
634 if (!settingsAllowed()) {
635 return PERMISSION_DENIED;
636 }
Eric Laurenta553c252009-07-17 12:17:14 -0700637
Eric Laurent01635942011-01-18 18:39:02 -0800638 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700639 mMasterMute = muted;
640 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700641 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700642
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700643 return NO_ERROR;
644}
645
646float AudioFlinger::masterVolume() const
647{
Glenn Kastene6f8a422011-12-13 11:47:54 -0800648 Mutex::Autolock _l(mLock);
649 return masterVolume_l();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700650}
651
652bool AudioFlinger::masterMute() const
653{
Glenn Kastene6f8a422011-12-13 11:47:54 -0800654 Mutex::Autolock _l(mLock);
655 return masterMute_l();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700656}
657
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800658status_t AudioFlinger::setStreamVolume(audio_stream_type_t 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
Glenn Kasten6e987a42012-01-06 08:40:01 -0800665 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block3762c312012-01-06 19:20:56 +0000666 ALOGE("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
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800692status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700693{
694 // check calling permissions
695 if (!settingsAllowed()) {
696 return PERMISSION_DENIED;
697 }
698
Glenn Kasten6e987a42012-01-06 08:40:01 -0800699 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700700 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block3762c312012-01-06 19:20:56 +0000701 ALOGE("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
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800713float AudioFlinger::streamVolume(audio_stream_type_t stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700714{
Glenn Kasten6e987a42012-01-06 08:40:01 -0800715 if (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
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800734bool AudioFlinger::streamMute(audio_stream_type_t stream) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700735{
Glenn Kasten6e987a42012-01-06 08:40:01 -0800736 if (uint32_t(stream) >= 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);
Glenn Kasten70ed6b72012-01-10 10:46:34 -0800801 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent464d5b32011-06-17 21:29:58 -0700802 // 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
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800849size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850{
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++) {
Glenn Kastendc3ac852012-01-25 15:28:08 -0800973 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
974 param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700975 }
976}
977
Eric Laurentb9481d82009-09-17 05:12:56 -0700978// removeClient_l() must be called with AudioFlinger::mLock held
979void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700980{
Steve Block71f2cf12011-10-20 11:56:00 +0100981 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 -0700982 mClients.removeItem(pid);
983}
984
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700985
Eric Laurenta553c252009-07-17 12:17:14 -0700986// ----------------------------------------------------------------------------
987
Glenn Kastenefd511a2012-01-26 10:38:26 -0800988AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device,
989 type_t type)
Eric Laurenta553c252009-07-17 12:17:14 -0700990 : Thread(false),
Glenn Kastenefd511a2012-01-26 10:38:26 -0800991 mType(type),
Glenn Kastendc3ac852012-01-25 15:28:08 -0800992 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
993 // mChannelMask
994 mChannelCount(0),
995 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
996 mParamStatus(NO_ERROR),
997 mStandby(false), mId(id), mExiting(false),
998 mDevice(device),
999 mDeathRecipient(new PMDeathRecipient(this))
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001000{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001}
1002
Eric Laurenta553c252009-07-17 12:17:14 -07001003AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001005 mParamCond.broadcast();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001006 // do not lock the mutex in destructor
1007 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -07001008 if (mPowerManager != 0) {
1009 sp<IBinder> binder = mPowerManager->asBinder();
1010 binder->unlinkToDeath(mDeathRecipient);
1011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012}
1013
Eric Laurenta553c252009-07-17 12:17:14 -07001014void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001015{
Glenn Kastene5fb2632011-12-14 10:28:06 -08001016 // keep a strong ref on ourself so that we won't get
Eric Laurenta553c252009-07-17 12:17:14 -07001017 // destroyed in the middle of requestExitAndWait()
1018 sp <ThreadBase> strongMe = this;
1019
Steve Block71f2cf12011-10-20 11:56:00 +01001020 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001021 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08001022 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001023 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001024 requestExit();
1025 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001026 }
Eric Laurenta553c252009-07-17 12:17:14 -07001027 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001028}
Eric Laurenta553c252009-07-17 12:17:14 -07001029
Eric Laurenta553c252009-07-17 12:17:14 -07001030status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1031{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001032 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001033
Steve Block71f2cf12011-10-20 11:56:00 +01001034 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001035 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001036
Eric Laurent8fce46a2009-08-04 09:45:33 -07001037 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001038 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001039 // wait condition with timeout in case the thread loop has exited
1040 // before the request could be processed
Glenn Kastencbfe2e12011-12-13 11:04:14 -08001041 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001042 status = mParamStatus;
1043 mWaitWorkCV.signal();
1044 } else {
1045 status = TIMED_OUT;
1046 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001047 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001048}
1049
1050void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1051{
1052 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001053 sendConfigEvent_l(event, param);
1054}
1055
1056// sendConfigEvent_l() must be called with ThreadBase::mLock held
1057void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1058{
Glenn Kasten4b220f02011-12-13 11:50:00 -08001059 ConfigEvent configEvent;
1060 configEvent.mEvent = event;
1061 configEvent.mParam = param;
Eric Laurenta553c252009-07-17 12:17:14 -07001062 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001063 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001064 mWaitWorkCV.signal();
1065}
1066
1067void AudioFlinger::ThreadBase::processConfigEvents()
1068{
1069 mLock.lock();
1070 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001071 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kasten4b220f02011-12-13 11:50:00 -08001072 ConfigEvent configEvent = mConfigEvents[0];
Eric Laurenta553c252009-07-17 12:17:14 -07001073 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001074 // release mLock before locking AudioFlinger mLock: lock order is always
1075 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001076 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001077 mAudioFlinger->mLock.lock();
Glenn Kasten4b220f02011-12-13 11:50:00 -08001078 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001079 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001080 mLock.lock();
1081 }
1082 mLock.unlock();
1083}
1084
Eric Laurent3fdb1262009-11-07 00:01:32 -08001085status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1086{
1087 const size_t SIZE = 256;
1088 char buffer[SIZE];
1089 String8 result;
1090
1091 bool locked = tryLock(mLock);
1092 if (!locked) {
1093 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1094 write(fd, buffer, strlen(buffer));
1095 }
1096
1097 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1098 result.append(buffer);
1099 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1100 result.append(buffer);
1101 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1102 result.append(buffer);
1103 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1104 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001105 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1106 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001107 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1108 result.append(buffer);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001109 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001110 result.append(buffer);
1111
1112 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1113 result.append(buffer);
1114 result.append(" Index Command");
1115 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1116 snprintf(buffer, SIZE, "\n %02d ", i);
1117 result.append(buffer);
1118 result.append(mNewParameters[i]);
1119 }
1120
1121 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1122 result.append(buffer);
1123 snprintf(buffer, SIZE, " Index event param\n");
1124 result.append(buffer);
1125 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kasten4b220f02011-12-13 11:50:00 -08001126 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001127 result.append(buffer);
1128 }
1129 result.append("\n");
1130
1131 write(fd, result.string(), result.size());
1132
1133 if (locked) {
1134 mLock.unlock();
1135 }
1136 return NO_ERROR;
1137}
1138
Eric Laurent1345d332011-07-24 17:49:51 -07001139status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1140{
1141 const size_t SIZE = 256;
1142 char buffer[SIZE];
1143 String8 result;
1144
1145 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1146 write(fd, buffer, strlen(buffer));
1147
1148 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1149 sp<EffectChain> chain = mEffectChains[i];
1150 if (chain != 0) {
1151 chain->dump(fd, args);
1152 }
1153 }
1154 return NO_ERROR;
1155}
1156
Eric Laurent6dbdc402011-07-22 09:04:31 -07001157void AudioFlinger::ThreadBase::acquireWakeLock()
1158{
1159 Mutex::Autolock _l(mLock);
1160 acquireWakeLock_l();
1161}
1162
1163void AudioFlinger::ThreadBase::acquireWakeLock_l()
1164{
1165 if (mPowerManager == 0) {
1166 // use checkService() to avoid blocking if power service is not up yet
1167 sp<IBinder> binder =
1168 defaultServiceManager()->checkService(String16("power"));
1169 if (binder == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00001170 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001171 } else {
1172 mPowerManager = interface_cast<IPowerManager>(binder);
1173 binder->linkToDeath(mDeathRecipient);
1174 }
1175 }
1176 if (mPowerManager != 0) {
1177 sp<IBinder> binder = new BBinder();
1178 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1179 binder,
1180 String16(mName));
1181 if (status == NO_ERROR) {
1182 mWakeLockToken = binder;
1183 }
Steve Block71f2cf12011-10-20 11:56:00 +01001184 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001185 }
1186}
1187
1188void AudioFlinger::ThreadBase::releaseWakeLock()
1189{
1190 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001191 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001192}
1193
1194void AudioFlinger::ThreadBase::releaseWakeLock_l()
1195{
1196 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001197 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001198 if (mPowerManager != 0) {
1199 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1200 }
1201 mWakeLockToken.clear();
1202 }
1203}
1204
1205void AudioFlinger::ThreadBase::clearPowerManager()
1206{
1207 Mutex::Autolock _l(mLock);
1208 releaseWakeLock_l();
1209 mPowerManager.clear();
1210}
1211
1212void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1213{
1214 sp<ThreadBase> thread = mThread.promote();
1215 if (thread != 0) {
1216 thread->clearPowerManager();
1217 }
Steve Block8564c8d2012-01-05 23:22:43 +00001218 ALOGW("power manager service died !!!");
Eric Laurent6dbdc402011-07-22 09:04:31 -07001219}
Eric Laurent1345d332011-07-24 17:49:51 -07001220
Eric Laurentf82fccd2011-07-27 19:49:51 -07001221void AudioFlinger::ThreadBase::setEffectSuspended(
1222 const effect_uuid_t *type, bool suspend, int sessionId)
1223{
1224 Mutex::Autolock _l(mLock);
1225 setEffectSuspended_l(type, suspend, sessionId);
1226}
1227
1228void AudioFlinger::ThreadBase::setEffectSuspended_l(
1229 const effect_uuid_t *type, bool suspend, int sessionId)
1230{
1231 sp<EffectChain> chain;
1232 chain = getEffectChain_l(sessionId);
1233 if (chain != 0) {
1234 if (type != NULL) {
1235 chain->setEffectSuspended_l(type, suspend);
1236 } else {
1237 chain->setEffectSuspendedAll_l(suspend);
1238 }
1239 }
1240
1241 updateSuspendedSessions_l(type, suspend, sessionId);
1242}
1243
1244void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1245{
1246 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1247 if (index < 0) {
1248 return;
1249 }
1250
1251 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1252 mSuspendedSessions.editValueAt(index);
1253
1254 for (size_t i = 0; i < sessionEffects.size(); i++) {
1255 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1256 for (int j = 0; j < desc->mRefCount; j++) {
1257 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1258 chain->setEffectSuspendedAll_l(true);
1259 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001260 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001261 desc->mType.timeLow);
1262 chain->setEffectSuspended_l(&desc->mType, true);
1263 }
1264 }
1265 }
1266}
1267
Eric Laurentf82fccd2011-07-27 19:49:51 -07001268void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1269 bool suspend,
1270 int sessionId)
1271{
1272 int index = mSuspendedSessions.indexOfKey(sessionId);
1273
1274 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1275
1276 if (suspend) {
1277 if (index >= 0) {
1278 sessionEffects = mSuspendedSessions.editValueAt(index);
1279 } else {
1280 mSuspendedSessions.add(sessionId, sessionEffects);
1281 }
1282 } else {
1283 if (index < 0) {
1284 return;
1285 }
1286 sessionEffects = mSuspendedSessions.editValueAt(index);
1287 }
1288
1289
1290 int key = EffectChain::kKeyForSuspendAll;
1291 if (type != NULL) {
1292 key = type->timeLow;
1293 }
1294 index = sessionEffects.indexOfKey(key);
1295
1296 sp <SuspendedSessionDesc> desc;
1297 if (suspend) {
1298 if (index >= 0) {
1299 desc = sessionEffects.valueAt(index);
1300 } else {
1301 desc = new SuspendedSessionDesc();
1302 if (type != NULL) {
1303 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1304 }
1305 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001306 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001307 }
1308 desc->mRefCount++;
1309 } else {
1310 if (index < 0) {
1311 return;
1312 }
1313 desc = sessionEffects.valueAt(index);
1314 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001315 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001316 sessionEffects.removeItemsAt(index);
1317 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001318 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001319 sessionId);
1320 mSuspendedSessions.removeItem(sessionId);
1321 }
1322 }
1323 }
1324 if (!sessionEffects.isEmpty()) {
1325 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1326 }
1327}
1328
1329void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1330 bool enabled,
1331 int sessionId)
1332{
1333 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001334 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1335}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001336
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001337void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1338 bool enabled,
1339 int sessionId)
1340{
Eric Laurent6752ec82011-08-10 10:37:50 -07001341 if (mType != RECORD) {
1342 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1343 // another session. This gives the priority to well behaved effect control panels
1344 // and applications not using global effects.
1345 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1346 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1347 }
1348 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001349
1350 sp<EffectChain> chain = getEffectChain_l(sessionId);
1351 if (chain != 0) {
1352 chain->checkSuspendOnEffectEnabled(effect, enabled);
1353 }
1354}
1355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356// ----------------------------------------------------------------------------
1357
Eric Laurent464d5b32011-06-17 21:29:58 -07001358AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1359 AudioStreamOut* output,
1360 int id,
Glenn Kastenefd511a2012-01-26 10:38:26 -08001361 uint32_t device,
1362 type_t type)
1363 : ThreadBase(audioFlinger, id, device, type),
Glenn Kastendc3ac852012-01-25 15:28:08 -08001364 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1365 // Assumes constructor is called by AudioFlinger with it's mLock held,
1366 // but it would be safer to explicitly pass initial masterMute as parameter
1367 mMasterMute(audioFlinger->masterMute_l()),
1368 // mStreamTypes[] initialized in constructor body
1369 mOutput(output),
1370 // Assumes constructor is called by AudioFlinger with it's mLock held,
1371 // but it would be safer to explicitly pass initial masterVolume as parameter
1372 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent464d5b32011-06-17 21:29:58 -07001373 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001375 snprintf(mName, kNameLength, "AudioOut_%d", id);
1376
Eric Laurenta553c252009-07-17 12:17:14 -07001377 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378
Glenn Kasten6e987a42012-01-06 08:40:01 -08001379 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001380 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1381 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1382 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001383 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1384 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten6e987a42012-01-06 08:40:01 -08001385 // initialized by stream_type_t default constructor
1386 // mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388}
1389
Eric Laurenta553c252009-07-17 12:17:14 -07001390AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391{
1392 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393}
1394
Eric Laurenta553c252009-07-17 12:17:14 -07001395status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396{
1397 dumpInternals(fd, args);
1398 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001399 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 return NO_ERROR;
1401}
1402
Eric Laurenta553c252009-07-17 12:17:14 -07001403status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404{
1405 const size_t SIZE = 256;
1406 char buffer[SIZE];
1407 String8 result;
1408
Eric Laurenta553c252009-07-17 12:17:14 -07001409 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001411 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 -08001412 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001413 sp<Track> track = mTracks[i];
1414 if (track != 0) {
1415 track->dump(buffer, SIZE);
1416 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418 }
1419
Eric Laurenta553c252009-07-17 12:17:14 -07001420 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001422 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 -08001423 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kastene4787422012-01-25 14:27:41 -08001424 sp<Track> track = mActiveTracks[i].promote();
1425 if (track != 0) {
1426 track->dump(buffer, SIZE);
1427 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429 }
1430 write(fd, result.string(), result.size());
1431 return NO_ERROR;
1432}
1433
Eric Laurenta553c252009-07-17 12:17:14 -07001434status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435{
1436 const size_t SIZE = 256;
1437 char buffer[SIZE];
1438 String8 result;
1439
Eric Laurent3fdb1262009-11-07 00:01:32 -08001440 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 result.append(buffer);
1442 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1443 result.append(buffer);
1444 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1445 result.append(buffer);
1446 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1447 result.append(buffer);
1448 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1449 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001450 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1451 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001452 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1453 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001455
1456 dumpBase(fd, args);
1457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 return NO_ERROR;
1459}
1460
1461// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001462status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463{
Eric Laurent828b9772011-08-07 16:32:26 -07001464 status_t status = initCheck();
1465 if (status == NO_ERROR) {
Steve Block6215d3f2012-01-04 20:05:49 +00001466 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurent828b9772011-08-07 16:32:26 -07001467 } else {
Steve Block3762c312012-01-06 19:20:56 +00001468 ALOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 }
Eric Laurent828b9772011-08-07 16:32:26 -07001470 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471}
1472
Eric Laurenta553c252009-07-17 12:17:14 -07001473void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001475 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476}
1477
Eric Laurenta553c252009-07-17 12:17:14 -07001478// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1479sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 const sp<AudioFlinger::Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001481 audio_stream_type_t streamType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08001483 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001484 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 int frameCount,
1486 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001487 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 status_t *status)
1489{
1490 sp<Track> track;
1491 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001492
1493 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001494 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1495 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block3762c312012-01-06 19:20:56 +00001496 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001497 "for output %p with format %d",
1498 sampleRate, format, channelMask, mOutput, mFormat);
1499 lStatus = BAD_VALUE;
1500 goto Exit;
1501 }
Eric Laurenta553c252009-07-17 12:17:14 -07001502 }
1503 } else {
1504 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1505 if (sampleRate > mSampleRate*2) {
Steve Block3762c312012-01-06 19:20:56 +00001506 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Eric Laurenta553c252009-07-17 12:17:14 -07001507 lStatus = BAD_VALUE;
1508 goto Exit;
1509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 }
1511
Eric Laurent464d5b32011-06-17 21:29:58 -07001512 lStatus = initCheck();
1513 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00001514 ALOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001515 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517
Eric Laurenta553c252009-07-17 12:17:14 -07001518 { // scope for mLock
1519 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001520
1521 // all tracks in same audio session must share the same routing strategy otherwise
1522 // conflicts will happen when tracks are moved from one output to another by audio policy
1523 // manager
1524 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001525 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001526 for (size_t i = 0; i < mTracks.size(); ++i) {
1527 sp<Track> t = mTracks[i];
1528 if (t != 0) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001529 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1530 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block3762c312012-01-06 19:20:56 +00001531 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001532 strategy, actual);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001533 lStatus = BAD_VALUE;
1534 goto Exit;
1535 }
1536 }
1537 }
1538
Eric Laurenta553c252009-07-17 12:17:14 -07001539 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001540 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001541 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001542 lStatus = NO_MEMORY;
1543 goto Exit;
1544 }
1545 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001546
1547 sp<EffectChain> chain = getEffectChain_l(sessionId);
1548 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001549 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001550 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001551 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001552 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001553 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001554
1555 // invalidate track immediately if the stream type was moved to another thread since
1556 // createTrack() was called by the client process.
1557 if (!mStreamTypes[streamType].valid) {
Steve Block8564c8d2012-01-05 23:22:43 +00001558 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07001559 this, streamType);
1560 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1561 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001562 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001563 lStatus = NO_ERROR;
1564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565Exit:
1566 if(status) {
1567 *status = lStatus;
1568 }
1569 return track;
1570}
1571
Eric Laurenta553c252009-07-17 12:17:14 -07001572uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573{
Eric Laurent828b9772011-08-07 16:32:26 -07001574 Mutex::Autolock _l(mLock);
1575 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001576 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001577 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 return 0;
1579 }
1580}
1581
Eric Laurenta553c252009-07-17 12:17:14 -07001582status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583{
1584 mMasterVolume = value;
1585 return NO_ERROR;
1586}
1587
Eric Laurenta553c252009-07-17 12:17:14 -07001588status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589{
1590 mMasterMute = muted;
1591 return NO_ERROR;
1592}
1593
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001594status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595{
1596 mStreamTypes[stream].volume = value;
1597 return NO_ERROR;
1598}
1599
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001600status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601{
1602 mStreamTypes[stream].mute = muted;
1603 return NO_ERROR;
1604}
1605
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001606float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607{
1608 return mStreamTypes[stream].volume;
1609}
1610
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001611bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612{
1613 return mStreamTypes[stream].mute;
1614}
1615
Eric Laurenta553c252009-07-17 12:17:14 -07001616// addTrack_l() must be called with ThreadBase::mLock held
1617status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618{
1619 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001620
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001621 // set retry count for buffer fill
1622 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001623 if (mActiveTracks.indexOf(track) < 0) {
1624 // the track is newly added, make sure it fills up all its
1625 // buffers before playing. This is to ensure the client will
1626 // effectively get the latency it requested.
1627 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001628 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001629 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001630 if (track->mainBuffer() != mMixBuffer) {
1631 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1632 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001633 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001634 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001635 }
1636 }
1637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001639 }
Eric Laurenta553c252009-07-17 12:17:14 -07001640
Steve Block71f2cf12011-10-20 11:56:00 +01001641 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001642 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643
1644 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001645}
1646
Eric Laurenta553c252009-07-17 12:17:14 -07001647// destroyTrack_l() must be called with ThreadBase::mLock held
1648void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001649{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001650 track->mState = TrackBase::TERMINATED;
1651 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001652 removeTrack_l(track);
1653 }
1654}
1655
1656void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1657{
1658 mTracks.remove(track);
1659 deleteTrackName_l(track->name());
1660 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1661 if (chain != 0) {
1662 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001663 }
1664}
1665
Eric Laurenta553c252009-07-17 12:17:14 -07001666String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001667{
Eric Laurent828b9772011-08-07 16:32:26 -07001668 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001669 char *s;
1670
Eric Laurent828b9772011-08-07 16:32:26 -07001671 Mutex::Autolock _l(mLock);
1672 if (initCheck() != NO_ERROR) {
1673 return out_s8;
1674 }
1675
Dima Zavin31f188892011-04-18 16:57:27 -07001676 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001677 out_s8 = String8(s);
1678 free(s);
1679 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001680}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001681
Eric Laurent828b9772011-08-07 16:32:26 -07001682// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001683void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001684 AudioSystem::OutputDescriptor desc;
Glenn Kasten3694ec12012-01-27 16:47:15 -08001685 void *param2 = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07001686
Steve Block71f2cf12011-10-20 11:56:00 +01001687 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001688
1689 switch (event) {
1690 case AudioSystem::OUTPUT_OPENED:
1691 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001692 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001693 desc.samplingRate = mSampleRate;
1694 desc.format = mFormat;
1695 desc.frameCount = mFrameCount;
1696 desc.latency = latency();
1697 param2 = &desc;
1698 break;
1699
1700 case AudioSystem::STREAM_CONFIG_CHANGED:
1701 param2 = &param;
1702 case AudioSystem::OUTPUT_CLOSED:
1703 default:
1704 break;
1705 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001706 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001707}
1708
1709void AudioFlinger::PlaybackThread::readOutputParameters()
1710{
Dima Zavin31f188892011-04-18 16:57:27 -07001711 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001712 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1713 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001714 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001715 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin31f188892011-04-18 16:57:27 -07001716 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001717
Eric Laurenta553c252009-07-17 12:17:14 -07001718 // FIXME - Current mixer implementation only supports stereo output: Always
1719 // Allocate a stereo buffer even if HW output is mono.
Glenn Kasten2589cf92012-01-27 18:08:45 -08001720 delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001721 mMixBuffer = new int16_t[mFrameCount * 2];
1722 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001723
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001724 // force reconfiguration of effect chains and engines to take new buffer size and audio
1725 // parameters into account
1726 // Note that mLock is not held when readOutputParameters() is called from the constructor
1727 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1728 // matter.
1729 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1730 Vector< sp<EffectChain> > effectChains = mEffectChains;
1731 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001732 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001733 }
Eric Laurenta553c252009-07-17 12:17:14 -07001734}
1735
Eric Laurent0986e792010-01-19 17:37:09 -08001736status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1737{
Glenn Kasten3694ec12012-01-27 16:47:15 -08001738 if (halFrames == NULL || dspFrames == NULL) {
Eric Laurent0986e792010-01-19 17:37:09 -08001739 return BAD_VALUE;
1740 }
Eric Laurent828b9772011-08-07 16:32:26 -07001741 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001742 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001743 return INVALID_OPERATION;
1744 }
Dima Zavin31f188892011-04-18 16:57:27 -07001745 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001746
Dima Zavin31f188892011-04-18 16:57:27 -07001747 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001748}
1749
Eric Laurent493941b2010-07-28 01:32:47 -07001750uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001751{
1752 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001753 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001754 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001755 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001756 }
1757
1758 for (size_t i = 0; i < mTracks.size(); ++i) {
1759 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001760 if (sessionId == track->sessionId() &&
1761 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001762 result |= TRACK_SESSION;
1763 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001764 }
1765 }
1766
Eric Laurent493941b2010-07-28 01:32:47 -07001767 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001768}
1769
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001770uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1771{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001772 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001773 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001774 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1775 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001776 }
1777 for (size_t i = 0; i < mTracks.size(); i++) {
1778 sp<Track> track = mTracks[i];
1779 if (sessionId == track->sessionId() &&
1780 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001781 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001782 }
1783 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001784 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001785}
1786
Eric Laurent53334cd2010-06-23 17:38:20 -07001787
Glenn Kasten5b0135e2012-01-26 09:46:34 -08001788AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent828b9772011-08-07 16:32:26 -07001789{
1790 Mutex::Autolock _l(mLock);
1791 return mOutput;
1792}
1793
1794AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1795{
1796 Mutex::Autolock _l(mLock);
1797 AudioStreamOut *output = mOutput;
1798 mOutput = NULL;
1799 return output;
1800}
1801
1802// this method must always be called either with ThreadBase mLock held or inside the thread loop
1803audio_stream_t* AudioFlinger::PlaybackThread::stream()
1804{
1805 if (mOutput == NULL) {
1806 return NULL;
1807 }
1808 return &mOutput->stream->common;
1809}
1810
Eric Laurent44331692011-12-05 09:47:19 -08001811uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1812{
1813 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1814 // decoding and transfer time. So sleeping for half of the latency would likely cause
1815 // underruns
1816 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1817 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1818 } else {
1819 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1820 }
1821}
1822
Eric Laurenta553c252009-07-17 12:17:14 -07001823// ----------------------------------------------------------------------------
1824
Glenn Kastenefd511a2012-01-26 10:38:26 -08001825AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1826 int id, uint32_t device, type_t type)
1827 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kastendc3ac852012-01-25 15:28:08 -08001828 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1829 mPrevMixerStatus(MIXER_IDLE)
Eric Laurenta553c252009-07-17 12:17:14 -07001830{
Eric Laurenta553c252009-07-17 12:17:14 -07001831 // FIXME - Current mixer implementation only supports stereo output
1832 if (mChannelCount == 1) {
Steve Block3762c312012-01-06 19:20:56 +00001833 ALOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001835}
1836
Eric Laurenta553c252009-07-17 12:17:14 -07001837AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001838{
Eric Laurenta553c252009-07-17 12:17:14 -07001839 delete mAudioMixer;
1840}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841
Eric Laurenta553c252009-07-17 12:17:14 -07001842bool AudioFlinger::MixerThread::threadLoop()
1843{
Eric Laurenta553c252009-07-17 12:17:14 -07001844 Vector< sp<Track> > tracksToRemove;
Glenn Kasten789fef12012-01-26 13:37:52 -08001845 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001846 nsecs_t standbyTime = systemTime();
1847 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001848 // FIXME: Relaxed timing because of a certain device that can't meet latency
1849 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001850 // increase threshold again due to low power audio mode. The way this warning threshold is
1851 // calculated and its usefulness should be reconsidered anyway.
1852 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001853 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001854 bool longStandbyExit = false;
1855 uint32_t activeSleepTime = activeSleepTimeUs();
1856 uint32_t idleSleepTime = idleSleepTimeUs();
1857 uint32_t sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001858 uint32_t sleepTimeShift = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001859 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001860#ifdef DEBUG_CPU_USAGE
1861 ThreadCpuUsage cpu;
1862 const CentralTendencyStatistics& stats = cpu.statistics();
1863#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864
Eric Laurent6dbdc402011-07-22 09:04:31 -07001865 acquireWakeLock();
1866
Eric Laurenta553c252009-07-17 12:17:14 -07001867 while (!exitPending())
1868 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001869#ifdef DEBUG_CPU_USAGE
1870 cpu.sampleAndEnable();
1871 unsigned n = stats.n();
1872 // cpu.elapsed() is expensive, so don't call it every loop
1873 if ((n & 127) == 1) {
1874 long long elapsed = cpu.elapsed();
1875 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1876 double perLoop = elapsed / (double) n;
1877 double perLoop100 = perLoop * 0.01;
1878 double mean = stats.mean();
1879 double stddev = stats.stddev();
1880 double minimum = stats.minimum();
1881 double maximum = stats.maximum();
1882 cpu.resetStatistics();
Steve Block6215d3f2012-01-04 20:05:49 +00001883 ALOGI("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",
Glenn Kastenda494f92011-07-08 15:26:12 -07001884 elapsed * .000000001, n, perLoop * .000001,
1885 mean * .001,
1886 stddev * .001,
1887 minimum * .001,
1888 maximum * .001,
1889 mean / perLoop100,
1890 stddev / perLoop100,
1891 minimum / perLoop100,
1892 maximum / perLoop100);
1893 }
1894 }
1895#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001896 processConfigEvents();
1897
Eric Laurent059b4be2009-11-09 23:32:22 -08001898 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001899 { // scope for mLock
1900
1901 Mutex::Autolock _l(mLock);
1902
1903 if (checkForNewParameters_l()) {
1904 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001905 // FIXME: Relaxed timing because of a certain device that can't meet latency
1906 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001907 // increase threshold again due to low power audio mode. The way this warning
1908 // threshold is calculated and its usefulness should be reconsidered anyway.
1909 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001910 activeSleepTime = activeSleepTimeUs();
1911 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001912 }
1913
1914 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1915
1916 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001917 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1918 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001919 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01001920 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001921 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001922 mStandby = true;
1923 mBytesWritten = 0;
1924 }
1925
1926 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1927 // we're about to wait, flush the binder command buffer
1928 IPCThreadState::self()->flushCommands();
1929
1930 if (exitPending()) break;
1931
Eric Laurent6dbdc402011-07-22 09:04:31 -07001932 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001933 // wait until we have something to do...
Steve Block71f2cf12011-10-20 11:56:00 +01001934 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07001935 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01001936 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001937 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001938
Eric Laurent71c44962012-01-17 19:20:12 -08001939 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenb737dbb2012-01-13 15:54:24 -08001940 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07001941 char value[PROPERTY_VALUE_MAX];
1942 property_get("ro.audio.silent", value, "0");
1943 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00001944 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07001945 setMasterMute(true);
1946 }
1947 }
1948
1949 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001950 sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001951 sleepTimeShift = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001952 continue;
1953 }
1954 }
1955
Eric Laurent059b4be2009-11-09 23:32:22 -08001956 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001957
1958 // prevent any changes in effect chain list and in each effect chain
1959 // during mixing and effect process as the audio buffers could be deleted
1960 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001961 lockEffectChains_l(effectChains);
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08001962 }
Eric Laurenta553c252009-07-17 12:17:14 -07001963
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001964 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001965 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001966 mAudioMixer->process();
Eric Laurent06092312012-01-23 18:56:59 -08001967 // increase sleep time progressively when application underrun condition clears.
1968 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1969 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1970 // such that we would underrun the audio HAL.
1971 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001972 sleepTimeShift--;
1973 }
Eric Laurent06092312012-01-23 18:56:59 -08001974 sleepTime = 0;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001975 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001976 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001977 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001978 // If no tracks are ready, sleep once for the duration of an output
1979 // buffer size, then write 0s to the output
1980 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001981 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001982 sleepTime = activeSleepTime >> sleepTimeShift;
1983 if (sleepTime < kMinThreadSleepTimeUs) {
1984 sleepTime = kMinThreadSleepTimeUs;
1985 }
1986 // reduce sleep time in case of consecutive application underruns to avoid
1987 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1988 // duration we would end up writing less data than needed by the audio HAL if
1989 // the condition persists.
1990 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1991 sleepTimeShift++;
1992 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001993 } else {
1994 sleepTime = idleSleepTime;
1995 }
1996 } else if (mBytesWritten != 0 ||
1997 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001998 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001999 sleepTime = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01002000 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07002001 }
Eric Laurent65b65452010-06-01 23:49:17 -07002002 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07002003 }
2004
2005 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002006 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002007 }
2008 // sleepTime == 0 means we must write to audio hardware
2009 if (sleepTime == 0) {
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08002010 for (size_t i = 0; i < effectChains.size(); i ++) {
2011 effectChains[i]->process_l();
2012 }
2013 // enable changes in effect chain
2014 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002015 mLastWriteTime = systemTime();
2016 mInWrite = true;
2017 mBytesWritten += mixBufferSize;
2018
Dima Zavin31f188892011-04-18 16:57:27 -07002019 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002020 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002021 mNumWrites++;
2022 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002023 nsecs_t now = systemTime();
2024 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07002025 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002026 mNumDelayedWrites++;
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002027 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00002028 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002029 ns2ms(delta), mNumDelayedWrites, this);
2030 lastWarning = now;
2031 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002032 if (mStandby) {
2033 longStandbyExit = true;
2034 }
Eric Laurenta553c252009-07-17 12:17:14 -07002035 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002036 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002037 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002038 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002039 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002040 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002041 }
2042
2043 // finally let go of all our tracks, without the lock held
2044 // since we can't guarantee the destructors won't acquire that
2045 // same lock.
2046 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002047
2048 // Effect chains will be actually deleted here if they were removed from
2049 // mEffectChains list during mixing or effects processing
2050 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002051 }
2052
2053 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002054 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002055 }
Eric Laurenta553c252009-07-17 12:17:14 -07002056
Eric Laurent6dbdc402011-07-22 09:04:31 -07002057 releaseWakeLock();
2058
Steve Block71f2cf12011-10-20 11:56:00 +01002059 ALOGV("MixerThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002060 return false;
2061}
2062
2063// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten789fef12012-01-26 13:37:52 -08002064AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2065 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002066{
2067
Glenn Kasten789fef12012-01-26 13:37:52 -08002068 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002069 // find out which tracks need to be processed
2070 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002071 size_t mixedTracks = 0;
2072 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002073
2074 float masterVolume = mMasterVolume;
2075 bool masterMute = mMasterMute;
2076
Eric Laurent8cc93b92010-08-11 05:20:11 -07002077 if (masterMute) {
2078 masterVolume = 0;
2079 }
Eric Laurent65b65452010-06-01 23:49:17 -07002080 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002081 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002082 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002083 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002084 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002085 masterVolume = (float)((v + (1 << 23)) >> 24);
2086 chain.clear();
2087 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002088
Eric Laurenta553c252009-07-17 12:17:14 -07002089 for (size_t i=0 ; i<count ; i++) {
2090 sp<Track> t = activeTracks[i].promote();
2091 if (t == 0) continue;
2092
Glenn Kasten68deb152011-12-19 15:06:39 -08002093 // this const just means the local variable doesn't change
Eric Laurenta553c252009-07-17 12:17:14 -07002094 Track* const track = t.get();
2095 audio_track_cblk_t* cblk = track->cblk();
2096
2097 // The first time a track is added we wait
2098 // for all its buffers to be filled before processing it
Glenn Kasten68deb152011-12-19 15:06:39 -08002099 int name = track->name();
Eric Laurent8a04fe02011-11-08 18:10:16 -08002100 // make sure that we have enough frames to mix one full buffer.
2101 // enforce this condition only once to enable draining the buffer in case the client
2102 // app does not call stop() and relies on underrun to stop:
Eric Laurent71c44962012-01-17 19:20:12 -08002103 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurent8a04fe02011-11-08 18:10:16 -08002104 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002105 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002106 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent71c44962012-01-17 19:20:12 -08002107 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002108 if (t->sampleRate() == (int)mSampleRate) {
2109 minFrames = mFrameCount;
2110 } else {
Eric Laurent72dafb22011-12-22 16:08:41 -08002111 // +1 for rounding and +1 for additional sample needed for interpolation
2112 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2113 // add frames already consumed but not yet released by the resampler
2114 // because cblk->framesReady() will include these frames
2115 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2116 // the minimum track buffer size is normally twice the number of frames necessary
2117 // to fill one buffer and the resampler should not leave more than one buffer worth
2118 // of unreleased frames after each pass, but just in case...
Steve Blockec193de2012-01-09 18:35:44 +00002119 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002120 }
2121 }
2122 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002123 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002124 {
Glenn Kasten68deb152011-12-19 15:06:39 -08002125 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002126
Eric Laurent65b65452010-06-01 23:49:17 -07002127 mixedTracks++;
2128
2129 // track->mainBuffer() != mMixBuffer means there is an effect chain
2130 // connected to the track
2131 chain.clear();
2132 if (track->mainBuffer() != mMixBuffer) {
2133 chain = getEffectChain_l(track->sessionId());
2134 // Delegate volume control to effect in track effect chain if needed
2135 if (chain != 0) {
2136 tracksWithEffect++;
2137 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00002138 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten68deb152011-12-19 15:06:39 -08002139 name, track->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002140 }
2141 }
2142
2143
2144 int param = AudioMixer::VOLUME;
2145 if (track->mFillingUpStatus == Track::FS_FILLED) {
2146 // no ramp for the first volume setting
2147 track->mFillingUpStatus = Track::FS_ACTIVE;
2148 if (track->mState == TrackBase::RESUMING) {
2149 track->mState = TrackBase::ACTIVE;
2150 param = AudioMixer::RAMP_VOLUME;
2151 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002152 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002153 } else if (cblk->server != 0) {
2154 // If the track is stopped before the first frame was mixed,
2155 // do not apply ramp
2156 param = AudioMixer::RAMP_VOLUME;
2157 }
2158
Eric Laurenta553c252009-07-17 12:17:14 -07002159 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002160 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002161 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002162 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002163 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002164 if (track->isPausing()) {
2165 track->setPaused();
2166 }
2167 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002168
Glenn Kasten871c16c2010-03-05 12:18:01 -08002169 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002170 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002171 float v = masterVolume * typeVolume;
Glenn Kastenbc4de882012-01-17 14:39:34 -08002172 uint32_t vlr = cblk->getVolumeLR();
Glenn Kasten0632bad2012-01-17 12:20:54 -08002173 vl = vlr & 0xFFFF;
2174 vr = vlr >> 16;
2175 // track volumes come from shared memory, so can't be trusted and must be clamped
2176 if (vl > MAX_GAIN_INT) {
2177 ALOGV("Track left volume out of range: %04X", vl);
2178 vl = MAX_GAIN_INT;
2179 }
2180 if (vr > MAX_GAIN_INT) {
2181 ALOGV("Track right volume out of range: %04X", vr);
2182 vr = MAX_GAIN_INT;
2183 }
2184 // now apply the master volume and stream type volume
2185 vl = (uint32_t)(v * vl) << 12;
2186 vr = (uint32_t)(v * vr) << 12;
2187 // assuming master volume and stream type volume each go up to 1.0,
2188 // vl and vr are now in 8.24 format
Eric Laurenta553c252009-07-17 12:17:14 -07002189
Glenn Kasten4790bd82012-01-03 14:22:33 -08002190 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2191 // send level comes from shared memory and so may be corrupt
Glenn Kasten0632bad2012-01-17 12:20:54 -08002192 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten4790bd82012-01-03 14:22:33 -08002193 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kasten0632bad2012-01-17 12:20:54 -08002194 sendLevel = MAX_GAIN_INT;
Glenn Kasten4790bd82012-01-03 14:22:33 -08002195 }
2196 va = (uint32_t)(v * sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002197 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002198 // Delegate volume control to effect in track effect chain if needed
2199 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2200 // Do not ramp volume if volume is controlled by effect
2201 param = AudioMixer::VOLUME;
2202 track->mHasVolumeController = true;
2203 } else {
2204 // force no volume ramp when volume controller was just disabled or removed
2205 // from effect chain to avoid volume spike
2206 if (track->mHasVolumeController) {
2207 param = AudioMixer::VOLUME;
2208 }
2209 track->mHasVolumeController = false;
2210 }
2211
2212 // Convert volumes from 8.24 to 4.12 format
2213 int16_t left, right, aux;
Glenn Kasten0632bad2012-01-17 12:20:54 -08002214 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002215 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2216 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2217 left = int16_t(v_clamped);
2218 v_clamped = (vr + (1 << 11)) >> 12;
2219 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2220 right = int16_t(v_clamped);
2221
2222 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2223 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002224
Eric Laurent65b65452010-06-01 23:49:17 -07002225 // XXX: these things DON'T need to be done each time
Glenn Kasten68deb152011-12-19 15:06:39 -08002226 mAudioMixer->setBufferProvider(name, track);
2227 mAudioMixer->enable(name);
Eric Laurent65b65452010-06-01 23:49:17 -07002228
Glenn Kasten68deb152011-12-19 15:06:39 -08002229 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2230 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2231 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002232 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002233 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002234 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002235 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002236 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002237 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002238 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002239 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002240 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002241 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002242 AudioMixer::RESAMPLE,
2243 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002244 (void *)(cblk->sampleRate));
2245 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002246 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002247 AudioMixer::TRACK,
2248 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2249 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002250 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002251 AudioMixer::TRACK,
2252 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002253
2254 // reset retry count
2255 track->mRetryCount = kMaxTrackRetries;
Eric Laurent71c44962012-01-17 19:20:12 -08002256 // If one track is ready, set the mixer ready if:
2257 // - the mixer was not ready during previous round OR
2258 // - no other track is not ready
2259 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2260 mixerStatus != MIXER_TRACKS_ENABLED) {
2261 mixerStatus = MIXER_TRACKS_READY;
2262 }
Eric Laurenta553c252009-07-17 12:17:14 -07002263 } else {
Glenn Kasten68deb152011-12-19 15:06:39 -08002264 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002265 if (track->isStopped()) {
2266 track->reset();
2267 }
2268 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2269 // We have consumed all the buffers of this track.
2270 // Remove it from the list of active tracks.
2271 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002272 } else {
2273 // No buffers for this track. Give it a few chances to
2274 // fill a buffer, then remove it from active list.
2275 if (--(track->mRetryCount) <= 0) {
Glenn Kasten68deb152011-12-19 15:06:39 -08002276 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002277 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002278 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002279 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent71c44962012-01-17 19:20:12 -08002280 // If one track is not ready, mark the mixer also not ready if:
2281 // - the mixer was ready during previous round OR
2282 // - no other track is ready
2283 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2284 mixerStatus != MIXER_TRACKS_READY) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002285 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002286 }
Eric Laurenta553c252009-07-17 12:17:14 -07002287 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002288 mAudioMixer->disable(name);
Eric Laurenta553c252009-07-17 12:17:14 -07002289 }
2290 }
2291
2292 // remove all the tracks that need to be...
2293 count = tracksToRemove->size();
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002294 if (CC_UNLIKELY(count)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002295 for (size_t i=0 ; i<count ; i++) {
2296 const sp<Track>& track = tracksToRemove->itemAt(i);
2297 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002298 if (track->mainBuffer() != mMixBuffer) {
2299 chain = getEffectChain_l(track->sessionId());
2300 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002301 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002302 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002303 }
2304 }
Eric Laurenta553c252009-07-17 12:17:14 -07002305 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002306 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002307 }
2308 }
2309 }
2310
Eric Laurent65b65452010-06-01 23:49:17 -07002311 // mix buffer must be cleared if all tracks are connected to an
2312 // effect chain as in this case the mixer will not write to
2313 // mix buffer and track effects will accumulate into it
2314 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2315 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2316 }
2317
Eric Laurent71c44962012-01-17 19:20:12 -08002318 mPrevMixerStatus = mixerStatus;
Eric Laurent059b4be2009-11-09 23:32:22 -08002319 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002320}
2321
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002322void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002323{
Steve Block71f2cf12011-10-20 11:56:00 +01002324 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002325 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002326 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002327
Eric Laurenta553c252009-07-17 12:17:14 -07002328 size_t size = mTracks.size();
2329 for (size_t i = 0; i < size; i++) {
2330 sp<Track> t = mTracks[i];
2331 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002332 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002333 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002334 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002335 }
2336}
Eric Laurenta553c252009-07-17 12:17:14 -07002337
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002338void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent05ce0942011-08-30 10:18:54 -07002339{
Steve Block71f2cf12011-10-20 11:56:00 +01002340 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002341 this, streamType, valid);
2342 Mutex::Autolock _l(mLock);
2343
2344 mStreamTypes[streamType].valid = valid;
2345}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346
Eric Laurenta553c252009-07-17 12:17:14 -07002347// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002348int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349{
2350 return mAudioMixer->getTrackName();
2351}
2352
Eric Laurenta553c252009-07-17 12:17:14 -07002353// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002354void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355{
Steve Block71f2cf12011-10-20 11:56:00 +01002356 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 mAudioMixer->deleteTrackName(name);
2358}
2359
Eric Laurenta553c252009-07-17 12:17:14 -07002360// checkForNewParameters_l() must be called with ThreadBase::mLock held
2361bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362{
Eric Laurenta553c252009-07-17 12:17:14 -07002363 bool reconfig = false;
2364
Eric Laurent8fce46a2009-08-04 09:45:33 -07002365 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002366 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002367 String8 keyValuePair = mNewParameters[0];
2368 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002369 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002370
Eric Laurenta553c252009-07-17 12:17:14 -07002371 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2372 reconfig = true;
2373 }
2374 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08002375 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002376 status = BAD_VALUE;
2377 } else {
2378 reconfig = true;
2379 }
2380 }
2381 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002382 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002383 status = BAD_VALUE;
2384 } else {
2385 reconfig = true;
2386 }
2387 }
2388 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2389 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastene5fb2632011-12-14 10:28:06 -08002390 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07002391 // if frame count is changed after track creation
2392 if (!mTracks.isEmpty()) {
2393 status = INVALID_OPERATION;
2394 } else {
2395 reconfig = true;
2396 }
2397 }
Eric Laurent65b65452010-06-01 23:49:17 -07002398 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002399 // when changing the audio output device, call addBatteryData to notify
2400 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002401 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002402 uint32_t params = 0;
2403 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002404 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002405 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2406 }
2407
2408 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002409 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002410 // check if any other device (except speaker) is on
2411 if (value & deviceWithoutSpeaker ) {
2412 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2413 }
2414
2415 if (params != 0) {
2416 addBatteryData(params);
2417 }
2418 }
2419
Eric Laurent65b65452010-06-01 23:49:17 -07002420 // forward device change to effects that have requested to be
2421 // aware of attached audio device.
2422 mDevice = (uint32_t)value;
2423 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002424 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002425 }
2426 }
2427
Eric Laurenta553c252009-07-17 12:17:14 -07002428 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002429 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002430 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002431 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002432 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002433 mStandby = true;
2434 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002435 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002436 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002437 }
2438 if (status == NO_ERROR && reconfig) {
2439 delete mAudioMixer;
Glenn Kasten2589cf92012-01-27 18:08:45 -08002440 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2441 mAudioMixer = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07002442 readOutputParameters();
2443 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2444 for (size_t i = 0; i < mTracks.size() ; i++) {
2445 int name = getTrackName_l();
2446 if (name < 0) break;
2447 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002448 // limit track sample rate to 2 x new output sample rate
2449 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2450 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2451 }
Eric Laurenta553c252009-07-17 12:17:14 -07002452 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002453 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002454 }
2455 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002456
2457 mNewParameters.removeAt(0);
2458
Eric Laurenta553c252009-07-17 12:17:14 -07002459 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002460 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002461 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2462 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002463 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002464 }
2465 return reconfig;
2466}
2467
2468status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2469{
2470 const size_t SIZE = 256;
2471 char buffer[SIZE];
2472 String8 result;
2473
2474 PlaybackThread::dumpInternals(fd, args);
2475
2476 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2477 result.append(buffer);
2478 write(fd, result.string(), result.size());
2479 return NO_ERROR;
2480}
2481
Eric Laurent059b4be2009-11-09 23:32:22 -08002482uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2483{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002484 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002485}
2486
Eric Laurent8448a792010-08-18 18:13:17 -07002487uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2488{
2489 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2490}
2491
Eric Laurenta553c252009-07-17 12:17:14 -07002492// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002493AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Glenn Kastenefd511a2012-01-26 10:38:26 -08002494 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kastendc3ac852012-01-25 15:28:08 -08002495 // mLeftVolFloat, mRightVolFloat
2496 // mLeftVolShort, mRightVolShort
Eric Laurenta553c252009-07-17 12:17:14 -07002497{
Eric Laurenta553c252009-07-17 12:17:14 -07002498}
2499
2500AudioFlinger::DirectOutputThread::~DirectOutputThread()
2501{
2502}
2503
Eric Laurent65b65452010-06-01 23:49:17 -07002504static inline
2505int32_t mul(int16_t in, int16_t v)
2506{
2507#if defined(__arm__) && !defined(__thumb__)
2508 int32_t out;
2509 asm( "smulbb %[out], %[in], %[v] \n"
2510 : [out]"=r"(out)
2511 : [in]"%r"(in), [v]"r"(v)
2512 : );
2513 return out;
2514#else
2515 return in * int32_t(v);
2516#endif
2517}
2518
2519void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2520{
2521 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002522 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002523 return;
2524 }
2525
2526 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002527 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002528 size_t count = mFrameCount * mChannelCount;
2529 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2530 int16_t *dst = mMixBuffer + count-1;
2531 while(count--) {
2532 *dst-- = (int16_t)(*src--^0x80) << 8;
2533 }
2534 }
2535
2536 size_t frameCount = mFrameCount;
2537 int16_t *out = mMixBuffer;
2538 if (ramp) {
2539 if (mChannelCount == 1) {
2540 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2541 int32_t vlInc = d / (int32_t)frameCount;
2542 int32_t vl = ((int32_t)mLeftVolShort << 16);
2543 do {
2544 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2545 out++;
2546 vl += vlInc;
2547 } while (--frameCount);
2548
2549 } else {
2550 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2551 int32_t vlInc = d / (int32_t)frameCount;
2552 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2553 int32_t vrInc = d / (int32_t)frameCount;
2554 int32_t vl = ((int32_t)mLeftVolShort << 16);
2555 int32_t vr = ((int32_t)mRightVolShort << 16);
2556 do {
2557 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2558 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2559 out += 2;
2560 vl += vlInc;
2561 vr += vrInc;
2562 } while (--frameCount);
2563 }
2564 } else {
2565 if (mChannelCount == 1) {
2566 do {
2567 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2568 out++;
2569 } while (--frameCount);
2570 } else {
2571 do {
2572 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2573 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2574 out += 2;
2575 } while (--frameCount);
2576 }
2577 }
2578
2579 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002580 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002581 size_t count = mFrameCount * mChannelCount;
2582 int16_t *src = mMixBuffer;
2583 uint8_t *dst = (uint8_t *)mMixBuffer;
2584 while(count--) {
2585 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2586 }
2587 }
2588
2589 mLeftVolShort = leftVol;
2590 mRightVolShort = rightVol;
2591}
2592
Eric Laurenta553c252009-07-17 12:17:14 -07002593bool AudioFlinger::DirectOutputThread::threadLoop()
2594{
Glenn Kasten789fef12012-01-26 13:37:52 -08002595 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002596 sp<Track> trackToRemove;
2597 sp<Track> activeTrack;
2598 nsecs_t standbyTime = systemTime();
2599 int8_t *curBuf;
2600 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002601 uint32_t activeSleepTime = activeSleepTimeUs();
2602 uint32_t idleSleepTime = idleSleepTimeUs();
2603 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002604 // use shorter standby delay as on normal output to release
2605 // hardware resources as soon as possible
2606 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002607
Eric Laurent6dbdc402011-07-22 09:04:31 -07002608 acquireWakeLock();
2609
Eric Laurenta553c252009-07-17 12:17:14 -07002610 while (!exitPending())
2611 {
Eric Laurent65b65452010-06-01 23:49:17 -07002612 bool rampVolume;
2613 uint16_t leftVol;
2614 uint16_t rightVol;
2615 Vector< sp<EffectChain> > effectChains;
2616
Eric Laurenta553c252009-07-17 12:17:14 -07002617 processConfigEvents();
2618
Eric Laurent059b4be2009-11-09 23:32:22 -08002619 mixerStatus = MIXER_IDLE;
2620
Eric Laurenta553c252009-07-17 12:17:14 -07002621 { // scope for the mLock
2622
2623 Mutex::Autolock _l(mLock);
2624
2625 if (checkForNewParameters_l()) {
2626 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002627 activeSleepTime = activeSleepTimeUs();
2628 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002629 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002630 }
2631
2632 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002633 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2634 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002635 // wait until we have something to do...
2636 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01002637 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002638 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002639 mStandby = true;
2640 mBytesWritten = 0;
2641 }
2642
2643 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2644 // we're about to wait, flush the binder command buffer
2645 IPCThreadState::self()->flushCommands();
2646
2647 if (exitPending()) break;
2648
Eric Laurent6dbdc402011-07-22 09:04:31 -07002649 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002650 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002651 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002652 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002653 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002654
Glenn Kastenb737dbb2012-01-13 15:54:24 -08002655 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07002656 char value[PROPERTY_VALUE_MAX];
2657 property_get("ro.audio.silent", value, "0");
2658 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00002659 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07002660 setMasterMute(true);
2661 }
2662 }
2663
Eric Laurentef9500f2010-03-11 14:47:00 -08002664 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002665 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002666 continue;
2667 }
2668 }
2669
Eric Laurent65b65452010-06-01 23:49:17 -07002670 effectChains = mEffectChains;
2671
Eric Laurenta553c252009-07-17 12:17:14 -07002672 // find out which tracks need to be processed
2673 if (mActiveTracks.size() != 0) {
2674 sp<Track> t = mActiveTracks[0].promote();
2675 if (t == 0) continue;
2676
2677 Track* const track = t.get();
2678 audio_track_cblk_t* cblk = track->cblk();
2679
2680 // The first time a track is added we wait
2681 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002682 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002683 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002684 {
Steve Block71f2cf12011-10-20 11:56:00 +01002685 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002686
Eric Laurent65b65452010-06-01 23:49:17 -07002687 if (track->mFillingUpStatus == Track::FS_FILLED) {
2688 track->mFillingUpStatus = Track::FS_ACTIVE;
2689 mLeftVolFloat = mRightVolFloat = 0;
2690 mLeftVolShort = mRightVolShort = 0;
2691 if (track->mState == TrackBase::RESUMING) {
2692 track->mState = TrackBase::ACTIVE;
2693 rampVolume = true;
2694 }
2695 } else if (cblk->server != 0) {
2696 // If the track is stopped before the first frame was mixed,
2697 // do not apply ramp
2698 rampVolume = true;
2699 }
Eric Laurenta553c252009-07-17 12:17:14 -07002700 // compute volume for this track
2701 float left, right;
2702 if (track->isMuted() || mMasterMute || track->isPausing() ||
2703 mStreamTypes[track->type()].mute) {
2704 left = right = 0;
2705 if (track->isPausing()) {
2706 track->setPaused();
2707 }
2708 } else {
2709 float typeVolume = mStreamTypes[track->type()].volume;
2710 float v = mMasterVolume * typeVolume;
Glenn Kastenbc4de882012-01-17 14:39:34 -08002711 uint32_t vlr = cblk->getVolumeLR();
Glenn Kasten0632bad2012-01-17 12:20:54 -08002712 float v_clamped = v * (vlr & 0xFFFF);
Eric Laurenta553c252009-07-17 12:17:14 -07002713 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2714 left = v_clamped/MAX_GAIN;
Glenn Kasten0632bad2012-01-17 12:20:54 -08002715 v_clamped = v * (vlr >> 16);
Eric Laurenta553c252009-07-17 12:17:14 -07002716 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2717 right = v_clamped/MAX_GAIN;
2718 }
2719
Eric Laurent65b65452010-06-01 23:49:17 -07002720 if (left != mLeftVolFloat || right != mRightVolFloat) {
2721 mLeftVolFloat = left;
2722 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002723
Eric Laurent65b65452010-06-01 23:49:17 -07002724 // If audio HAL implements volume control,
2725 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002726 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002727 left = 1.0f;
2728 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002729 }
Eric Laurent65b65452010-06-01 23:49:17 -07002730
2731 // Convert volumes from float to 8.24
2732 uint32_t vl = (uint32_t)(left * (1 << 24));
2733 uint32_t vr = (uint32_t)(right * (1 << 24));
2734
2735 // Delegate volume control to effect in track effect chain if needed
2736 // only one effect chain can be present on DirectOutputThread, so if
2737 // there is one, the track is connected to it
2738 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002739 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002740 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002741 rampVolume = false;
2742 }
2743 }
2744
2745 // Convert volumes from 8.24 to 4.12 format
2746 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2747 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2748 leftVol = (uint16_t)v_clamped;
2749 v_clamped = (vr + (1 << 11)) >> 12;
2750 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2751 rightVol = (uint16_t)v_clamped;
2752 } else {
2753 leftVol = mLeftVolShort;
2754 rightVol = mRightVolShort;
2755 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002756 }
2757
2758 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002759 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002760 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002761 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002762 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002763 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002764 if (track->isStopped()) {
2765 track->reset();
2766 }
2767 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2768 // We have consumed all the buffers of this track.
2769 // Remove it from the list of active tracks.
2770 trackToRemove = track;
2771 } else {
2772 // No buffers for this track. Give it a few chances to
2773 // fill a buffer, then remove it from active list.
2774 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002775 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurenta553c252009-07-17 12:17:14 -07002776 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002777 } else {
2778 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002779 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002780 }
Eric Laurenta553c252009-07-17 12:17:14 -07002781 }
2782 }
2783
2784 // remove all the tracks that need to be...
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002785 if (CC_UNLIKELY(trackToRemove != 0)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002786 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002787 if (!effectChains.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01002788 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002789 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002790 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002791 }
Eric Laurenta553c252009-07-17 12:17:14 -07002792 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002793 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002794 }
2795 }
Eric Laurent65b65452010-06-01 23:49:17 -07002796
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002797 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002798 }
2799
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002800 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002801 AudioBufferProvider::Buffer buffer;
2802 size_t frameCount = mFrameCount;
2803 curBuf = (int8_t *)mMixBuffer;
2804 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002805 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002806 buffer.frameCount = frameCount;
2807 activeTrack->getNextBuffer(&buffer);
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002808 if (CC_UNLIKELY(buffer.raw == NULL)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002809 memset(curBuf, 0, frameCount * mFrameSize);
2810 break;
2811 }
2812 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2813 frameCount -= buffer.frameCount;
2814 curBuf += buffer.frameCount * mFrameSize;
2815 activeTrack->releaseBuffer(&buffer);
2816 }
2817 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002818 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002819 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002820 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002821 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2822 sleepTime = activeSleepTime;
2823 } else {
2824 sleepTime = idleSleepTime;
2825 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002826 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002827 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002828 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002829 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002830 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002831
Eric Laurentf69a3f82009-09-22 00:35:48 -07002832 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002833 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002834 }
2835 // sleepTime == 0 means we must write to audio hardware
2836 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002837 if (mixerStatus == MIXER_TRACKS_READY) {
2838 applyVolume(leftVol, rightVol, rampVolume);
2839 }
2840 for (size_t i = 0; i < effectChains.size(); i ++) {
2841 effectChains[i]->process_l();
2842 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002843 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002844
Eric Laurentf69a3f82009-09-22 00:35:48 -07002845 mLastWriteTime = systemTime();
2846 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002847 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002848 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002849 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002850 mNumWrites++;
2851 mInWrite = false;
2852 mStandby = false;
2853 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002854 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002855 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002856 }
2857
2858 // finally let go of removed track, without the lock held
2859 // since we can't guarantee the destructors won't acquire that
2860 // same lock.
2861 trackToRemove.clear();
2862 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002863
2864 // Effect chains will be actually deleted here if they were removed from
2865 // mEffectChains list during mixing or effects processing
2866 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002867 }
2868
2869 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002870 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002871 }
Eric Laurenta553c252009-07-17 12:17:14 -07002872
Eric Laurent6dbdc402011-07-22 09:04:31 -07002873 releaseWakeLock();
2874
Steve Block71f2cf12011-10-20 11:56:00 +01002875 ALOGV("DirectOutputThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002876 return false;
2877}
2878
2879// getTrackName_l() must be called with ThreadBase::mLock held
2880int AudioFlinger::DirectOutputThread::getTrackName_l()
2881{
2882 return 0;
2883}
2884
2885// deleteTrackName_l() must be called with ThreadBase::mLock held
2886void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2887{
2888}
2889
2890// checkForNewParameters_l() must be called with ThreadBase::mLock held
2891bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2892{
2893 bool reconfig = false;
2894
Eric Laurent8fce46a2009-08-04 09:45:33 -07002895 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002896 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002897 String8 keyValuePair = mNewParameters[0];
2898 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002899 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002900
Eric Laurenta553c252009-07-17 12:17:14 -07002901 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2902 // do not accept frame count changes if tracks are open as the track buffer
2903 // size depends on frame count and correct behavior would not be garantied
2904 // if frame count is changed after track creation
2905 if (!mTracks.isEmpty()) {
2906 status = INVALID_OPERATION;
2907 } else {
2908 reconfig = true;
2909 }
2910 }
2911 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002912 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002913 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002914 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002915 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002916 mStandby = true;
2917 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002918 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002919 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002920 }
2921 if (status == NO_ERROR && reconfig) {
2922 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002923 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002924 }
2925 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002926
2927 mNewParameters.removeAt(0);
2928
Eric Laurenta553c252009-07-17 12:17:14 -07002929 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002930 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002931 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2932 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002933 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002934 }
2935 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002936}
2937
Eric Laurent059b4be2009-11-09 23:32:22 -08002938uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002939{
2940 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002941 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08002942 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08002943 } else {
2944 time = 10000;
2945 }
2946 return time;
2947}
2948
2949uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2950{
2951 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002952 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002953 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002954 } else {
2955 time = 10000;
2956 }
2957 return time;
2958}
2959
Eric Laurent8448a792010-08-18 18:13:17 -07002960uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2961{
2962 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002963 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002964 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2965 } else {
2966 time = 10000;
2967 }
2968 return time;
2969}
2970
2971
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002972// ----------------------------------------------------------------------------
2973
Glenn Kastenefd511a2012-01-26 10:38:26 -08002974AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
2975 AudioFlinger::MixerThread* mainThread, int id)
2976 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2977 mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002978{
Eric Laurenta553c252009-07-17 12:17:14 -07002979 addOutputTrack(mainThread);
2980}
2981
2982AudioFlinger::DuplicatingThread::~DuplicatingThread()
2983{
Eric Laurent0a080292009-12-07 10:53:10 -08002984 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2985 mOutputTracks[i]->destroy();
2986 }
Eric Laurenta553c252009-07-17 12:17:14 -07002987 mOutputTracks.clear();
2988}
2989
2990bool AudioFlinger::DuplicatingThread::threadLoop()
2991{
Eric Laurenta553c252009-07-17 12:17:14 -07002992 Vector< sp<Track> > tracksToRemove;
Glenn Kasten789fef12012-01-26 13:37:52 -08002993 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002994 nsecs_t standbyTime = systemTime();
2995 size_t mixBufferSize = mFrameCount*mFrameSize;
2996 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002997 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002998 uint32_t activeSleepTime = activeSleepTimeUs();
2999 uint32_t idleSleepTime = idleSleepTimeUs();
3000 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07003001 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07003002
Eric Laurent6dbdc402011-07-22 09:04:31 -07003003 acquireWakeLock();
3004
Eric Laurenta553c252009-07-17 12:17:14 -07003005 while (!exitPending())
3006 {
3007 processConfigEvents();
3008
Eric Laurent059b4be2009-11-09 23:32:22 -08003009 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07003010 { // scope for the mLock
3011
3012 Mutex::Autolock _l(mLock);
3013
3014 if (checkForNewParameters_l()) {
3015 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003016 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08003017 activeSleepTime = activeSleepTimeUs();
3018 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07003019 }
3020
3021 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3022
3023 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3024 outputTracks.add(mOutputTracks[i]);
3025 }
3026
3027 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003028 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3029 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003030 if (!mStandby) {
3031 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07003032 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07003033 }
3034 mStandby = true;
3035 mBytesWritten = 0;
3036 }
3037
3038 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3039 // we're about to wait, flush the binder command buffer
3040 IPCThreadState::self()->flushCommands();
3041 outputTracks.clear();
3042
3043 if (exitPending()) break;
3044
Eric Laurent6dbdc402011-07-22 09:04:31 -07003045 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01003046 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07003047 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01003048 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07003049 acquireWakeLock_l();
3050
Eric Laurent71c44962012-01-17 19:20:12 -08003051 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenb737dbb2012-01-13 15:54:24 -08003052 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07003053 char value[PROPERTY_VALUE_MAX];
3054 property_get("ro.audio.silent", value, "0");
3055 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00003056 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07003057 setMasterMute(true);
3058 }
3059 }
3060
3061 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08003062 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07003063 continue;
3064 }
3065 }
3066
Eric Laurent059b4be2009-11-09 23:32:22 -08003067 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07003068
3069 // prevent any changes in effect chain list and in each effect chain
3070 // during mixing and effect process as the audio buffers could be deleted
3071 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003072 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003073 }
Eric Laurenta553c252009-07-17 12:17:14 -07003074
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003075 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003076 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003077 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003078 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003079 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003080 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003081 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003082 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003083 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003084 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003085 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003086 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3087 sleepTime = activeSleepTime;
3088 } else {
3089 sleepTime = idleSleepTime;
3090 }
Eric Laurent62443f52009-10-05 20:29:18 -07003091 } else if (mBytesWritten != 0) {
3092 // flush remaining overflow buffers in output tracks
3093 for (size_t i = 0; i < outputTracks.size(); i++) {
3094 if (outputTracks[i]->isActive()) {
3095 sleepTime = 0;
3096 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003097 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003098 break;
3099 }
3100 }
Eric Laurenta553c252009-07-17 12:17:14 -07003101 }
3102 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003103
3104 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003105 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003106 }
3107 // sleepTime == 0 means we must write to audio hardware
3108 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003109 for (size_t i = 0; i < effectChains.size(); i ++) {
3110 effectChains[i]->process_l();
3111 }
3112 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003113 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003114
Eric Laurent62443f52009-10-05 20:29:18 -07003115 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003116 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003117 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003118 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003119 mStandby = false;
3120 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003121 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003122 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003123 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003124 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003125 }
3126
3127 // finally let go of all our tracks, without the lock held
3128 // since we can't guarantee the destructors won't acquire that
3129 // same lock.
3130 tracksToRemove.clear();
3131 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003132
3133 // Effect chains will be actually deleted here if they were removed from
3134 // mEffectChains list during mixing or effects processing
3135 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003136 }
3137
Eric Laurent6dbdc402011-07-22 09:04:31 -07003138 releaseWakeLock();
3139
Eric Laurenta553c252009-07-17 12:17:14 -07003140 return false;
3141}
3142
3143void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3144{
3145 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3146 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003147 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003148 mSampleRate,
3149 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003150 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003151 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003152 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003153 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003154 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003155 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003156 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003157 }
Eric Laurenta553c252009-07-17 12:17:14 -07003158}
3159
3160void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3161{
3162 Mutex::Autolock _l(mLock);
3163 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3164 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003165 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003166 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003167 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003168 return;
3169 }
3170 }
Steve Block71f2cf12011-10-20 11:56:00 +01003171 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003172}
3173
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003174void AudioFlinger::DuplicatingThread::updateWaitTime()
3175{
3176 mWaitTimeMs = UINT_MAX;
3177 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3178 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3179 if (strong != NULL) {
3180 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3181 if (waitTimeMs < mWaitTimeMs) {
3182 mWaitTimeMs = waitTimeMs;
3183 }
3184 }
3185 }
3186}
3187
3188
3189bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3190{
3191 for (size_t i = 0; i < outputTracks.size(); i++) {
3192 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3193 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003194 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003195 return false;
3196 }
3197 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3198 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003199 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003200 return false;
3201 }
3202 }
3203 return true;
3204}
3205
3206uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3207{
3208 return (mWaitTimeMs * 1000) / 2;
3209}
3210
Eric Laurenta553c252009-07-17 12:17:14 -07003211// ----------------------------------------------------------------------------
3212
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003213// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003214AudioFlinger::ThreadBase::TrackBase::TrackBase(
3215 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003216 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003217 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003218 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003219 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003220 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003222 const sp<IMemory>& sharedBuffer,
3223 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003224 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003225 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003226 mClient(client),
Glenn Kastendc3ac852012-01-25 15:28:08 -08003227 mCblk(NULL),
3228 // mBuffer
3229 // mBufferEnd
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003230 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003231 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003232 mClientTid(-1),
3233 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003234 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3235 mSessionId(sessionId)
Glenn Kastendc3ac852012-01-25 15:28:08 -08003236 // mChannelCount
3237 // mChannelMask
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003238{
Steve Block71f2cf12011-10-20 11:56:00 +01003239 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003240
Steve Block5baa3a62011-12-20 16:23:08 +00003241 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003242 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003243 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003244 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3245 if (sharedBuffer == 0) {
3246 size += bufferSize;
3247 }
3248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 if (client != NULL) {
3250 mCblkMemory = client->heap()->allocate(size);
3251 if (mCblkMemory != 0) {
3252 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kasten3694ec12012-01-27 16:47:15 -08003253 if (mCblk != NULL) { // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 new(mCblk) audio_track_cblk_t();
3255 // clear all buffers
3256 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003257 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003258 mChannelCount = channelCount;
3259 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 if (sharedBuffer == 0) {
3261 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3262 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3263 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003264 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003265 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 } else {
3267 mBuffer = sharedBuffer->pointer();
3268 }
3269 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 } else {
Steve Block3762c312012-01-06 19:20:56 +00003272 ALOGE("not enough memory for AudioTrack size=%u", size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 client->heap()->dump("AudioTrack");
3274 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 } else {
3277 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenc95ca2c2012-01-06 15:03:11 -08003278 // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 new(mCblk) audio_track_cblk_t();
3280 // clear all buffers
3281 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003282 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003283 mChannelCount = channelCount;
3284 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3286 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3287 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003288 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003289 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003292}
3293
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003294AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003295{
Glenn Kasten3694ec12012-01-27 16:47:15 -08003296 if (mCblk != NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07003297 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3298 if (mClient == NULL) {
3299 delete mCblk;
3300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003302 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07003303 if (mClient != NULL) {
Glenn Kastendc3ac852012-01-25 15:28:08 -08003304 // Client destructor must run with AudioFlinger mutex locked
Eric Laurentb9481d82009-09-17 05:12:56 -07003305 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3306 mClient.clear();
3307 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003308}
3309
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003310void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003311{
Glenn Kastenc434c902011-12-13 11:53:26 -08003312 buffer->raw = NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003313 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003314 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003315 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003316}
3317
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003318bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003319 bool result;
3320 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003321
3322 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003323 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003324 ALOGV("stepServer failed acquiring cblk mutex");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003325 mFlags |= STEPSERVER_FAILED;
3326 }
3327 return result;
3328}
3329
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003330void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003331 audio_track_cblk_t* cblk = this->cblk();
3332
3333 cblk->user = 0;
3334 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003335 cblk->userBase = 0;
3336 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block71f2cf12011-10-20 11:56:00 +01003338 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003339}
3340
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003341int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003342 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003343}
3344
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003345void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003346 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003347 size_t frameSize = cblk->frameSize;
3348 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3349 int8_t *bufferEnd = bufferStart + frames * frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003350
3351 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003352 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003353 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block3762c312012-01-06 19:20:56 +00003354 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003355 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003356 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003357 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kasten3694ec12012-01-27 16:47:15 -08003358 return NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003359 }
3360
3361 return bufferStart;
3362}
3363
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003364// ----------------------------------------------------------------------------
3365
Eric Laurenta553c252009-07-17 12:17:14 -07003366// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3367AudioFlinger::PlaybackThread::Track::Track(
3368 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003369 const sp<Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08003370 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003371 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003372 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003373 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003374 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003375 const sp<IMemory>& sharedBuffer,
3376 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003377 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003378 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3379 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003380{
Eric Laurent8a77a992009-09-09 05:16:08 -07003381 if (mCblk != NULL) {
3382 sp<ThreadBase> baseThread = thread.promote();
3383 if (baseThread != 0) {
3384 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3385 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003386 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003387 }
Steve Block71f2cf12011-10-20 11:56:00 +01003388 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003389 if (mName < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003390 ALOGE("no more track names available");
Eric Laurent8a77a992009-09-09 05:16:08 -07003391 }
Eric Laurent8a77a992009-09-09 05:16:08 -07003392 mStreamType = streamType;
3393 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3394 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003395 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003396 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003397}
3398
Eric Laurenta553c252009-07-17 12:17:14 -07003399AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003400{
Steve Block71f2cf12011-10-20 11:56:00 +01003401 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003402 sp<ThreadBase> thread = mThread.promote();
3403 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003404 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003405 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003406 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003407}
3408
Eric Laurenta553c252009-07-17 12:17:14 -07003409void AudioFlinger::PlaybackThread::Track::destroy()
3410{
3411 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3412 // by removing it from mTracks vector, so there is a risk that this Tracks's
3413 // desctructor is called. As the destructor needs to lock mLock,
3414 // we must acquire a strong reference on this Track before locking mLock
3415 // here so that the destructor is called only when exiting this function.
3416 // On the other hand, as long as Track::destroy() is only called by
3417 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3418 // this Track with its member mTrack.
3419 sp<Track> keep(this);
3420 { // scope for mLock
3421 sp<ThreadBase> thread = mThread.promote();
3422 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003423 if (!isOutputTrack()) {
3424 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003425 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003426 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003427 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003428
3429 // to track the speaker usage
3430 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003431 }
3432 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003433 }
Eric Laurenta553c252009-07-17 12:17:14 -07003434 Mutex::Autolock _l(thread->mLock);
3435 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3436 playbackThread->destroyTrack_l(this);
3437 }
3438 }
3439}
3440
3441void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003442{
Glenn Kastenbc4de882012-01-17 14:39:34 -08003443 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003444 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 -07003445 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003447 mStreamType,
3448 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003449 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003450 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003451 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003452 mState,
3453 mMute,
3454 mFillingUpStatus,
3455 mCblk->sampleRate,
Glenn Kasten0632bad2012-01-17 12:20:54 -08003456 vlr & 0xFFFF,
3457 vlr >> 16,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003458 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003459 mCblk->user,
3460 (int)mMainBuffer,
3461 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003462}
3463
Eric Laurenta553c252009-07-17 12:17:14 -07003464status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003465{
3466 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003467 uint32_t framesReady;
3468 uint32_t framesReq = buffer->frameCount;
3469
3470 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003471 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3472 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003473 ALOGV("stepServer recovered");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003474 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3475 }
3476
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003477 framesReady = cblk->framesReady();
3478
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003479 if (CC_LIKELY(framesReady)) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003480 uint32_t s = cblk->server;
3481 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3482
3483 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3484 if (framesReq > framesReady) {
3485 framesReq = framesReady;
3486 }
3487 if (s + framesReq > bufferEnd) {
3488 framesReq = bufferEnd - s;
3489 }
3490
3491 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003492 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003493
3494 buffer->frameCount = framesReq;
3495 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003496 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003497
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003498getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003499 buffer->raw = NULL;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003500 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003501 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 -07003502 return NOT_ENOUGH_DATA;
3503}
3504
Eric Laurenta553c252009-07-17 12:17:14 -07003505bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003506 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003507
3508 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003509 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003510 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003511 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003512 return true;
3513 }
3514 return false;
3515}
3516
Eric Laurenta553c252009-07-17 12:17:14 -07003517status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003518{
Eric Laurent49f02be2009-11-19 09:00:56 -08003519 status_t status = NO_ERROR;
Steve Block71f2cf12011-10-20 11:56:00 +01003520 ALOGV("start(%d), calling thread %d session %d",
Eric Laurent0d7e0482010-07-19 06:24:46 -07003521 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003522 sp<ThreadBase> thread = mThread.promote();
3523 if (thread != 0) {
3524 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003525 track_state state = mState;
Eric Laurent49f02be2009-11-19 09:00:56 -08003526 // here the track could be either new, or restarted
3527 // in both cases "unstop" the track
3528 if (mState == PAUSED) {
3529 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003530 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003531 } else {
3532 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003533 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003534 }
3535
3536 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3537 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003538 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003539 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003540 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003541 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003542
3543 // to track the speaker usage
3544 if (status == NO_ERROR) {
3545 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3546 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003547 }
3548 if (status == NO_ERROR) {
3549 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3550 playbackThread->addTrack_l(this);
3551 } else {
3552 mState = state;
3553 }
3554 } else {
3555 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003556 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003557 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003558}
3559
Eric Laurenta553c252009-07-17 12:17:14 -07003560void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003561{
Steve Block71f2cf12011-10-20 11:56:00 +01003562 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003563 sp<ThreadBase> thread = mThread.promote();
3564 if (thread != 0) {
3565 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003566 track_state state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003567 if (mState > STOPPED) {
3568 mState = STOPPED;
3569 // If the track is not active (PAUSED and buffers full), flush buffers
3570 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3571 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3572 reset();
3573 }
Steve Block71f2cf12011-10-20 11:56:00 +01003574 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003575 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003576 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3577 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003578 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003579 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003580 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003581 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003582
3583 // to track the speaker usage
3584 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003585 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003586 }
3587}
3588
Eric Laurenta553c252009-07-17 12:17:14 -07003589void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003590{
Steve Block71f2cf12011-10-20 11:56:00 +01003591 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003592 sp<ThreadBase> thread = mThread.promote();
3593 if (thread != 0) {
3594 Mutex::Autolock _l(thread->mLock);
3595 if (mState == ACTIVE || mState == RESUMING) {
3596 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003597 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003598 if (!isOutputTrack()) {
3599 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003600 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003601 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003602 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003603 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003604
3605 // to track the speaker usage
3606 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003607 }
Eric Laurenta553c252009-07-17 12:17:14 -07003608 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003609 }
3610}
3611
Eric Laurenta553c252009-07-17 12:17:14 -07003612void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003613{
Steve Block71f2cf12011-10-20 11:56:00 +01003614 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003615 sp<ThreadBase> thread = mThread.promote();
3616 if (thread != 0) {
3617 Mutex::Autolock _l(thread->mLock);
3618 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3619 return;
3620 }
3621 // No point remaining in PAUSED state after a flush => go to
3622 // STOPPED state
3623 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003624
Eric Laurentae29b762011-03-28 18:37:07 -07003625 // do not reset the track if it is still in the process of being stopped or paused.
3626 // this will be done by prepareTracks_l() when the track is stopped.
3627 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3628 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3629 reset();
3630 }
Eric Laurenta553c252009-07-17 12:17:14 -07003631 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003632}
3633
Eric Laurenta553c252009-07-17 12:17:14 -07003634void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003635{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003636 // Do not reset twice to avoid discarding data written just after a flush and before
3637 // the audioflinger thread detects the track is stopped.
3638 if (!mResetDone) {
3639 TrackBase::reset();
3640 // Force underrun condition to avoid false underrun callback until first data is
3641 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003642 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3643 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003644 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003645 mResetDone = true;
3646 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003647}
3648
Eric Laurenta553c252009-07-17 12:17:14 -07003649void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003650{
3651 mMute = muted;
3652}
3653
Eric Laurent65b65452010-06-01 23:49:17 -07003654status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3655{
3656 status_t status = DEAD_OBJECT;
3657 sp<ThreadBase> thread = mThread.promote();
3658 if (thread != 0) {
3659 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3660 status = playbackThread->attachAuxEffect(this, EffectId);
3661 }
3662 return status;
3663}
3664
3665void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3666{
3667 mAuxEffectId = EffectId;
3668 mAuxBuffer = buffer;
3669}
3670
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003671// ----------------------------------------------------------------------------
3672
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003673// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003674AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3675 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003678 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003679 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003680 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003681 uint32_t flags,
3682 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003683 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003684 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003685 mOverflow(false)
3686{
Eric Laurent8a77a992009-09-09 05:16:08 -07003687 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003688 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003689 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003690 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003691 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003692 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003693 } else {
3694 mCblk->frameSize = sizeof(int8_t);
3695 }
3696 }
Eric Laurenta553c252009-07-17 12:17:14 -07003697}
3698
3699AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003700{
Eric Laurent49f02be2009-11-19 09:00:56 -08003701 sp<ThreadBase> thread = mThread.promote();
3702 if (thread != 0) {
3703 AudioSystem::releaseInput(thread->id());
3704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705}
3706
Eric Laurenta553c252009-07-17 12:17:14 -07003707status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708{
3709 audio_track_cblk_t* cblk = this->cblk();
3710 uint32_t framesAvail;
3711 uint32_t framesReq = buffer->frameCount;
3712
3713 // Check if last stepServer failed, try to step now
3714 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3715 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003716 ALOGV("stepServer recovered");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3718 }
3719
3720 framesAvail = cblk->framesAvailable_l();
3721
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003722 if (CC_LIKELY(framesAvail)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 uint32_t s = cblk->server;
3724 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3725
3726 if (framesReq > framesAvail) {
3727 framesReq = framesAvail;
3728 }
3729 if (s + framesReq > bufferEnd) {
3730 framesReq = bufferEnd - s;
3731 }
3732
3733 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003734 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735
3736 buffer->frameCount = framesReq;
3737 return NO_ERROR;
3738 }
3739
3740getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003741 buffer->raw = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742 buffer->frameCount = 0;
3743 return NOT_ENOUGH_DATA;
3744}
3745
Eric Laurenta553c252009-07-17 12:17:14 -07003746status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747{
Eric Laurenta553c252009-07-17 12:17:14 -07003748 sp<ThreadBase> thread = mThread.promote();
3749 if (thread != 0) {
3750 RecordThread *recordThread = (RecordThread *)thread.get();
3751 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003752 } else {
3753 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755}
3756
Eric Laurenta553c252009-07-17 12:17:14 -07003757void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758{
Eric Laurenta553c252009-07-17 12:17:14 -07003759 sp<ThreadBase> thread = mThread.promote();
3760 if (thread != 0) {
3761 RecordThread *recordThread = (RecordThread *)thread.get();
3762 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003763 TrackBase::reset();
3764 // Force overerrun condition to avoid false overrun callback until first data is
3765 // read from buffer
3766 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003768}
3769
Eric Laurent3fdb1262009-11-07 00:01:32 -08003770void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3771{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003772 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003773 (mClient == NULL) ? getpid() : mClient->pid(),
3774 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003775 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003776 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003777 mFrameCount,
3778 mState,
3779 mCblk->sampleRate,
3780 mCblk->server,
3781 mCblk->user);
3782}
3783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784
3785// ----------------------------------------------------------------------------
3786
Eric Laurenta553c252009-07-17 12:17:14 -07003787AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3788 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003789 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003791 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003792 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003794 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003795 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796{
Eric Laurenta553c252009-07-17 12:17:14 -07003797
3798 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003799 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003800 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003801 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Eric Laurent6c30a712009-08-10 23:22:32 -07003802 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003803 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01003804 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003805 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3806 mCblk, mBuffer, mCblk->buffers,
3807 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003808 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003809 ALOGW("Error creating output track on thread %p", playbackThread);
Eric Laurent6c30a712009-08-10 23:22:32 -07003810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811}
3812
Eric Laurenta553c252009-07-17 12:17:14 -07003813AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814{
Eric Laurent6c30a712009-08-10 23:22:32 -07003815 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816}
3817
Eric Laurenta553c252009-07-17 12:17:14 -07003818status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819{
3820 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003821 if (status != NO_ERROR) {
3822 return status;
3823 }
3824
3825 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826 mRetryCount = 127;
3827 return status;
3828}
3829
Eric Laurenta553c252009-07-17 12:17:14 -07003830void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831{
3832 Track::stop();
3833 clearBufferQueue();
3834 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003835 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836}
3837
Eric Laurenta553c252009-07-17 12:17:14 -07003838bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839{
3840 Buffer *pInBuffer;
3841 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003842 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003843 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 inBuffer.frameCount = frames;
3845 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003846
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003847 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003848
Eric Laurent62443f52009-10-05 20:29:18 -07003849 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003850 start();
3851 sp<ThreadBase> thread = mThread.promote();
3852 if (thread != 0) {
3853 MixerThread *mixerThread = (MixerThread *)thread.get();
3854 if (mCblk->frameCount > frames){
3855 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3856 uint32_t startFrames = (mCblk->frameCount - frames);
3857 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003858 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003859 pInBuffer->frameCount = startFrames;
3860 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003861 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003862 mBufferQueue.add(pInBuffer);
3863 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003864 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurenta553c252009-07-17 12:17:14 -07003865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 }
Eric Laurenta553c252009-07-17 12:17:14 -07003867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 }
3869
Eric Laurenta553c252009-07-17 12:17:14 -07003870 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871 // First write pending buffers, then new data
3872 if (mBufferQueue.size()) {
3873 pInBuffer = mBufferQueue.itemAt(0);
3874 } else {
3875 pInBuffer = &inBuffer;
3876 }
Eric Laurenta553c252009-07-17 12:17:14 -07003877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 if (pInBuffer->frameCount == 0) {
3879 break;
3880 }
Eric Laurenta553c252009-07-17 12:17:14 -07003881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 if (mOutBuffer.frameCount == 0) {
3883 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003884 nsecs_t startTime = systemTime();
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003885 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01003886 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003887 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 break;
3889 }
Eric Laurenta553c252009-07-17 12:17:14 -07003890 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003891 if (waitTimeLeftMs >= waitTimeMs) {
3892 waitTimeLeftMs -= waitTimeMs;
3893 } else {
3894 waitTimeLeftMs = 0;
3895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 }
Eric Laurenta553c252009-07-17 12:17:14 -07003897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003899 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 mCblk->stepUser(outFrames);
3901 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003902 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003904 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 if (pInBuffer->frameCount == 0) {
3907 if (mBufferQueue.size()) {
3908 mBufferQueue.removeAt(0);
3909 delete [] pInBuffer->mBuffer;
3910 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01003911 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 -08003912 } else {
3913 break;
3914 }
3915 }
3916 }
Eric Laurenta553c252009-07-17 12:17:14 -07003917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 // If we could not write all frames, allocate a buffer and queue it for next time.
3919 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003920 sp<ThreadBase> thread = mThread.promote();
3921 if (thread != 0 && !thread->standby()) {
3922 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3923 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003924 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003925 pInBuffer->frameCount = inBuffer.frameCount;
3926 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003927 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003928 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01003929 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003930 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003931 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 }
3934 }
Eric Laurenta553c252009-07-17 12:17:14 -07003935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003937 // 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 -08003938 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003939 if (frames == 0 && mBufferQueue.size() == 0) {
3940 if (mCblk->user < mCblk->frameCount) {
3941 frames = mCblk->frameCount - mCblk->user;
3942 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003943 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003944 pInBuffer->frameCount = frames;
3945 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003946 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003947 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003948 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003949 stop();
3950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 }
3952
Eric Laurenta553c252009-07-17 12:17:14 -07003953 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954}
3955
Eric Laurenta553c252009-07-17 12:17:14 -07003956status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957{
3958 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 status_t result;
3960 audio_track_cblk_t* cblk = mCblk;
3961 uint32_t framesReq = buffer->frameCount;
3962
Steve Block71f2cf12011-10-20 11:56:00 +01003963// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 uint32_t framesAvail = cblk->framesAvailable();
3967
Eric Laurenta553c252009-07-17 12:17:14 -07003968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003970 Mutex::Autolock _l(cblk->lock);
3971 goto start_loop_here;
3972 while (framesAvail == 0) {
3973 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003974 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01003975 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003976 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07003977 }
3978 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3979 if (result != NO_ERROR) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003980 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07003981 }
3982 // read the server count again
3983 start_loop_here:
3984 framesAvail = cblk->framesAvailable_l();
3985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 }
3987
Eric Laurenta553c252009-07-17 12:17:14 -07003988// if (framesAvail < framesReq) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003989// return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07003990// }
3991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 if (framesReq > framesAvail) {
3993 framesReq = framesAvail;
3994 }
3995
3996 uint32_t u = cblk->user;
3997 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3998
3999 if (u + framesReq > bufferEnd) {
4000 framesReq = bufferEnd - u;
4001 }
4002
4003 buffer->frameCount = framesReq;
4004 buffer->raw = (void *)cblk->buffer(u);
4005 return NO_ERROR;
4006}
4007
4008
Eric Laurenta553c252009-07-17 12:17:14 -07004009void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010{
4011 size_t size = mBufferQueue.size();
4012 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 for (size_t i = 0; i < size; i++) {
4015 pBuffer = mBufferQueue.itemAt(i);
4016 delete [] pBuffer->mBuffer;
4017 delete pBuffer;
4018 }
4019 mBufferQueue.clear();
4020}
4021
4022// ----------------------------------------------------------------------------
4023
4024AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4025 : RefBase(),
4026 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08004027 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 mPid(pid)
4029{
4030 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4031}
4032
Eric Laurentb9481d82009-09-17 05:12:56 -07004033// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034AudioFlinger::Client::~Client()
4035{
Eric Laurentb9481d82009-09-17 05:12:56 -07004036 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037}
4038
Glenn Kasten1f812f72012-01-30 10:15:48 -08004039sp<MemoryDealer> AudioFlinger::Client::heap() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040{
4041 return mMemoryDealer;
4042}
4043
4044// ----------------------------------------------------------------------------
4045
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004046AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4047 const sp<IAudioFlingerClient>& client,
4048 pid_t pid)
Glenn Kastendc3ac852012-01-25 15:28:08 -08004049 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004050{
4051}
4052
4053AudioFlinger::NotificationClient::~NotificationClient()
4054{
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004055}
4056
4057void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4058{
4059 sp<NotificationClient> keep(this);
4060 {
4061 mAudioFlinger->removeNotificationClient(mPid);
4062 }
4063}
4064
4065// ----------------------------------------------------------------------------
4066
Eric Laurenta553c252009-07-17 12:17:14 -07004067AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004068 : BnAudioTrack(),
4069 mTrack(track)
4070{
4071}
4072
4073AudioFlinger::TrackHandle::~TrackHandle() {
4074 // just stop the track on deletion, associated resources
4075 // will be freed from the main thread once all pending buffers have
4076 // been played. Unless it's not in the active track list, in which
4077 // case we free everything now...
4078 mTrack->destroy();
4079}
4080
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004081sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4082 return mTrack->getCblk();
4083}
4084
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004085status_t AudioFlinger::TrackHandle::start() {
4086 return mTrack->start();
4087}
4088
4089void AudioFlinger::TrackHandle::stop() {
4090 mTrack->stop();
4091}
4092
4093void AudioFlinger::TrackHandle::flush() {
4094 mTrack->flush();
4095}
4096
4097void AudioFlinger::TrackHandle::mute(bool e) {
4098 mTrack->mute(e);
4099}
4100
4101void AudioFlinger::TrackHandle::pause() {
4102 mTrack->pause();
4103}
4104
Eric Laurent65b65452010-06-01 23:49:17 -07004105status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4106{
4107 return mTrack->attachAuxEffect(EffectId);
4108}
4109
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004110status_t AudioFlinger::TrackHandle::onTransact(
4111 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4112{
4113 return BnAudioTrack::onTransact(code, data, reply, flags);
4114}
4115
4116// ----------------------------------------------------------------------------
4117
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004118sp<IAudioRecord> AudioFlinger::openRecord(
4119 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07004120 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004121 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004122 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004123 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004124 int frameCount,
4125 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004126 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004127 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004128{
Eric Laurenta553c252009-07-17 12:17:14 -07004129 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004130 sp<RecordHandle> recordHandle;
4131 sp<Client> client;
4132 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004133 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004134 RecordThread *thread;
4135 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004136 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004137
4138 // check calling permissions
4139 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004140 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004141 goto Exit;
4142 }
4143
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004144 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004145 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004146 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004147 thread = checkRecordThread_l(input);
4148 if (thread == NULL) {
4149 lStatus = BAD_VALUE;
4150 goto Exit;
4151 }
4152
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004153 wclient = mClients.valueFor(pid);
4154 if (wclient != NULL) {
4155 client = wclient.promote();
4156 } else {
4157 client = new Client(this, pid);
4158 mClients.add(pid, client);
4159 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004160
Eric Laurent65b65452010-06-01 23:49:17 -07004161 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004162 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004163 lSessionId = *sessionId;
4164 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004165 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004166 if (sessionId != NULL) {
4167 *sessionId = lSessionId;
4168 }
4169 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004170 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004171 recordTrack = thread->createRecordTrack_l(client,
4172 sampleRate,
4173 format,
4174 channelMask,
4175 frameCount,
4176 flags,
4177 lSessionId,
4178 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004179 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004180 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004181 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4182 // destructor is called by the TrackBase destructor with mLock held
4183 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004185 goto Exit;
4186 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004187
4188 // return to handle to client
4189 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004190 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004191
4192Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004193 if (status) {
4194 *status = lStatus;
4195 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004196 return recordHandle;
4197}
4198
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004199// ----------------------------------------------------------------------------
4200
Eric Laurenta553c252009-07-17 12:17:14 -07004201AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004202 : BnAudioRecord(),
4203 mRecordTrack(recordTrack)
4204{
4205}
4206
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004207AudioFlinger::RecordHandle::~RecordHandle() {
4208 stop();
4209}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004210
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004211sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4212 return mRecordTrack->getCblk();
4213}
4214
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004215status_t AudioFlinger::RecordHandle::start() {
Steve Block71f2cf12011-10-20 11:56:00 +01004216 ALOGV("RecordHandle::start()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004217 return mRecordTrack->start();
4218}
4219
4220void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004221 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004222 mRecordTrack->stop();
4223}
4224
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004225status_t AudioFlinger::RecordHandle::onTransact(
4226 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4227{
4228 return BnAudioRecord::onTransact(code, data, reply, flags);
4229}
4230
4231// ----------------------------------------------------------------------------
4232
Eric Laurent464d5b32011-06-17 21:29:58 -07004233AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4234 AudioStreamIn *input,
4235 uint32_t sampleRate,
4236 uint32_t channels,
4237 int id,
4238 uint32_t device) :
Glenn Kastenefd511a2012-01-26 10:38:26 -08004239 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kastendc3ac852012-01-25 15:28:08 -08004240 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4241 // mRsmpInIndex and mInputBytes set by readInputParameters()
4242 mReqChannelCount(popcount(channels)),
4243 mReqSampleRate(sampleRate)
4244 // mBytesRead is only meaningful while active, and so is cleared in start()
4245 // (but might be better to also clear here for dump?)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004246{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004247 snprintf(mName, kNameLength, "AudioIn_%d", id);
4248
Eric Laurenta553c252009-07-17 12:17:14 -07004249 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004250}
4251
Eric Laurenta553c252009-07-17 12:17:14 -07004252
4253AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004254{
Eric Laurenta553c252009-07-17 12:17:14 -07004255 delete[] mRsmpInBuffer;
Glenn Kasten2589cf92012-01-27 18:08:45 -08004256 delete mResampler;
4257 delete[] mRsmpOutBuffer;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004258}
4259
Eric Laurenta553c252009-07-17 12:17:14 -07004260void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004261{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004262 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004263}
Eric Laurent49f02be2009-11-19 09:00:56 -08004264
Eric Laurent828b9772011-08-07 16:32:26 -07004265status_t AudioFlinger::RecordThread::readyToRun()
4266{
4267 status_t status = initCheck();
Steve Block8564c8d2012-01-05 23:22:43 +00004268 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurent828b9772011-08-07 16:32:26 -07004269 return status;
4270}
4271
Eric Laurenta553c252009-07-17 12:17:14 -07004272bool AudioFlinger::RecordThread::threadLoop()
4273{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004274 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004275 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004276 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004277
Eric Laurent4712baa2010-09-30 16:12:31 -07004278 nsecs_t lastWarning = 0;
4279
Eric Laurent6dbdc402011-07-22 09:04:31 -07004280 acquireWakeLock();
4281
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004282 // start recording
4283 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004284
Eric Laurenta553c252009-07-17 12:17:14 -07004285 processConfigEvents();
4286
4287 { // scope for mLock
4288 Mutex::Autolock _l(mLock);
4289 checkForNewParameters_l();
4290 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4291 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004292 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004293 mStandby = true;
4294 }
4295
4296 if (exitPending()) break;
4297
Eric Laurent6dbdc402011-07-22 09:04:31 -07004298 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004299 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004300 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004301 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004302 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004303 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004304 continue;
4305 }
4306 if (mActiveTrack != 0) {
4307 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004308 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004309 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004310 mStandby = true;
4311 }
Eric Laurenta553c252009-07-17 12:17:14 -07004312 mActiveTrack.clear();
4313 mStartStopCond.broadcast();
4314 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004315 if (mReqChannelCount != mActiveTrack->channelCount()) {
4316 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004317 mStartStopCond.broadcast();
4318 } else if (mBytesRead != 0) {
4319 // record start succeeds only if first read from audio input
4320 // succeeds
4321 if (mBytesRead > 0) {
4322 mActiveTrack->mState = TrackBase::ACTIVE;
4323 } else {
4324 mActiveTrack.clear();
4325 }
4326 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004327 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004328 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004329 }
Eric Laurenta553c252009-07-17 12:17:14 -07004330 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004331 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004332 }
4333
4334 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004335 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4336 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004337 unlockEffectChains(effectChains);
4338 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004339 continue;
4340 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004341 for (size_t i = 0; i < effectChains.size(); i ++) {
4342 effectChains[i]->process_l();
4343 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004344
Eric Laurenta553c252009-07-17 12:17:14 -07004345 buffer.frameCount = mFrameCount;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004346 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004347 size_t framesOut = buffer.frameCount;
Glenn Kastenc434c902011-12-13 11:53:26 -08004348 if (mResampler == NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004349 // no resampling
4350 while (framesOut) {
4351 size_t framesIn = mFrameCount - mRsmpInIndex;
4352 if (framesIn) {
4353 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4354 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4355 if (framesIn > framesOut)
4356 framesIn = framesOut;
4357 mRsmpInIndex += framesIn;
4358 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004359 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004360 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004361 memcpy(dst, src, framesIn * mFrameSize);
4362 } else {
4363 int16_t *src16 = (int16_t *)src;
4364 int16_t *dst16 = (int16_t *)dst;
4365 if (mChannelCount == 1) {
4366 while (framesIn--) {
4367 *dst16++ = *src16;
4368 *dst16++ = *src16++;
4369 }
4370 } else {
4371 while (framesIn--) {
4372 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4373 src16 += 2;
4374 }
4375 }
4376 }
4377 }
4378 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004379 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004380 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004381 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004382 framesOut = 0;
4383 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004384 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004385 mRsmpInIndex = 0;
4386 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004387 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004388 ALOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004389 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004390 // Force input into standby so that it tries to
4391 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004392 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004393 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004394 }
Eric Laurenta553c252009-07-17 12:17:14 -07004395 mRsmpInIndex = mFrameCount;
4396 framesOut = 0;
4397 buffer.frameCount = 0;
4398 }
4399 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004400 }
4401 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004402 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004403
Eric Laurenta553c252009-07-17 12:17:14 -07004404 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4405 // alter output frame count as if we were expecting stereo samples
4406 if (mChannelCount == 1 && mReqChannelCount == 1) {
4407 framesOut >>= 1;
4408 }
4409 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4410 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4411 // are 32 bit aligned which should be always true.
4412 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten490909d2011-12-15 09:52:39 -08004413 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004414 // the resampler always outputs stereo samples: do post stereo to mono conversion
4415 int16_t *src = (int16_t *)mRsmpOutBuffer;
4416 int16_t *dst = buffer.i16;
4417 while (framesOut--) {
4418 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4419 src += 2;
4420 }
4421 } else {
Glenn Kasten490909d2011-12-15 09:52:39 -08004422 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004423 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004424
Eric Laurenta553c252009-07-17 12:17:14 -07004425 }
4426 mActiveTrack->releaseBuffer(&buffer);
4427 mActiveTrack->overflow();
4428 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004429 // client isn't retrieving buffers fast enough
4430 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004431 if (!mActiveTrack->setOverflow()) {
4432 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004433 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00004434 ALOGW("RecordThread: buffer overflow");
Eric Laurent4712baa2010-09-30 16:12:31 -07004435 lastWarning = now;
4436 }
4437 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004438 // Release the processor for a while before asking for a new buffer.
4439 // This will give the application more chance to read from the buffer and
4440 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004441 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004442 }
4443 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004444 // enable changes in effect chain
4445 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004446 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004447 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004448
Eric Laurenta553c252009-07-17 12:17:14 -07004449 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004450 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004451 }
Eric Laurenta553c252009-07-17 12:17:14 -07004452 mActiveTrack.clear();
4453
Eric Laurent49f02be2009-11-19 09:00:56 -08004454 mStartStopCond.broadcast();
4455
Eric Laurent6dbdc402011-07-22 09:04:31 -07004456 releaseWakeLock();
4457
Steve Block71f2cf12011-10-20 11:56:00 +01004458 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004459 return false;
4460}
4461
Eric Laurent464d5b32011-06-17 21:29:58 -07004462
4463sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4464 const sp<AudioFlinger::Client>& client,
4465 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004466 audio_format_t format,
Eric Laurent464d5b32011-06-17 21:29:58 -07004467 int channelMask,
4468 int frameCount,
4469 uint32_t flags,
4470 int sessionId,
4471 status_t *status)
4472{
4473 sp<RecordTrack> track;
4474 status_t lStatus;
4475
4476 lStatus = initCheck();
4477 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00004478 ALOGE("Audio driver not initialized.");
Eric Laurent464d5b32011-06-17 21:29:58 -07004479 goto Exit;
4480 }
4481
4482 { // scope for mLock
4483 Mutex::Autolock _l(mLock);
4484
4485 track = new RecordTrack(this, client, sampleRate,
4486 format, channelMask, frameCount, flags, sessionId);
4487
4488 if (track->getCblk() == NULL) {
4489 lStatus = NO_MEMORY;
4490 goto Exit;
4491 }
4492
4493 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004494 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4495 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004496 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004497 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4498 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004499 }
4500 lStatus = NO_ERROR;
4501
4502Exit:
4503 if (status) {
4504 *status = lStatus;
4505 }
4506 return track;
4507}
4508
Eric Laurenta553c252009-07-17 12:17:14 -07004509status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004510{
Steve Block71f2cf12011-10-20 11:56:00 +01004511 ALOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004512 sp <ThreadBase> strongMe = this;
4513 status_t status = NO_ERROR;
4514 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004515 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004516 if (mActiveTrack != 0) {
4517 if (recordTrack != mActiveTrack.get()) {
4518 status = -EBUSY;
4519 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004520 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004521 }
4522 return status;
4523 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004524
Eric Laurent49f02be2009-11-19 09:00:56 -08004525 recordTrack->mState = TrackBase::IDLE;
4526 mActiveTrack = recordTrack;
4527 mLock.unlock();
4528 status_t status = AudioSystem::startInput(mId);
4529 mLock.lock();
4530 if (status != NO_ERROR) {
4531 mActiveTrack.clear();
4532 return status;
4533 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004534 mRsmpInIndex = mFrameCount;
4535 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004536 if (mResampler != NULL) {
4537 mResampler->reset();
4538 }
4539 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004540 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004541 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004542 mWaitWorkCV.signal();
4543 // do not wait for mStartStopCond if exiting
4544 if (mExiting) {
4545 mActiveTrack.clear();
4546 status = INVALID_OPERATION;
4547 goto startError;
4548 }
4549 mStartStopCond.wait(mLock);
4550 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01004551 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004552 status = BAD_VALUE;
4553 goto startError;
4554 }
Steve Block71f2cf12011-10-20 11:56:00 +01004555 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004556 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004557 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004558startError:
4559 AudioSystem::stopInput(mId);
4560 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004561}
4562
Eric Laurenta553c252009-07-17 12:17:14 -07004563void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01004564 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004565 sp <ThreadBase> strongMe = this;
4566 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004567 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004568 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4569 mActiveTrack->mState = TrackBase::PAUSING;
4570 // do not wait for mStartStopCond if exiting
4571 if (mExiting) {
4572 return;
4573 }
4574 mStartStopCond.wait(mLock);
4575 // if we have been restarted, recordTrack == mActiveTrack.get() here
4576 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4577 mLock.unlock();
4578 AudioSystem::stopInput(mId);
4579 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01004580 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004581 }
4582 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004583 }
4584}
4585
Eric Laurenta553c252009-07-17 12:17:14 -07004586status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587{
4588 const size_t SIZE = 256;
4589 char buffer[SIZE];
4590 String8 result;
4591 pid_t pid = 0;
4592
Eric Laurent3fdb1262009-11-07 00:01:32 -08004593 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4594 result.append(buffer);
4595
4596 if (mActiveTrack != 0) {
4597 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004598 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004599 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004600 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004601
4602 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4603 result.append(buffer);
4604 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4605 result.append(buffer);
Glenn Kastenc434c902011-12-13 11:53:26 -08004606 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Eric Laurent3fdb1262009-11-07 00:01:32 -08004607 result.append(buffer);
4608 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4609 result.append(buffer);
4610 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4611 result.append(buffer);
4612
4613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614 } else {
4615 result.append("No record client\n");
4616 }
4617 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004618
4619 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004620 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 return NO_ERROR;
4623}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004624
Eric Laurenta553c252009-07-17 12:17:14 -07004625status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4626{
4627 size_t framesReq = buffer->frameCount;
4628 size_t framesReady = mFrameCount - mRsmpInIndex;
4629 int channelCount;
4630
4631 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004632 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004633 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004634 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004635 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004636 // Force input into standby so that it tries to
4637 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004638 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004639 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004640 }
Glenn Kastenc434c902011-12-13 11:53:26 -08004641 buffer->raw = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004642 buffer->frameCount = 0;
4643 return NOT_ENOUGH_DATA;
4644 }
4645 mRsmpInIndex = 0;
4646 framesReady = mFrameCount;
4647 }
4648
4649 if (framesReq > framesReady) {
4650 framesReq = framesReady;
4651 }
4652
4653 if (mChannelCount == 1 && mReqChannelCount == 2) {
4654 channelCount = 1;
4655 } else {
4656 channelCount = 2;
4657 }
4658 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4659 buffer->frameCount = framesReq;
4660 return NO_ERROR;
4661}
4662
4663void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4664{
4665 mRsmpInIndex += buffer->frameCount;
4666 buffer->frameCount = 0;
4667}
4668
4669bool AudioFlinger::RecordThread::checkForNewParameters_l()
4670{
4671 bool reconfig = false;
4672
Eric Laurent8fce46a2009-08-04 09:45:33 -07004673 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004674 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004675 String8 keyValuePair = mNewParameters[0];
4676 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004677 int value;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004678 audio_format_t reqFormat = mFormat;
Eric Laurenta553c252009-07-17 12:17:14 -07004679 int reqSamplingRate = mReqSampleRate;
4680 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004681
Eric Laurenta553c252009-07-17 12:17:14 -07004682 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4683 reqSamplingRate = value;
4684 reconfig = true;
4685 }
4686 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004687 reqFormat = (audio_format_t) value;
Eric Laurenta553c252009-07-17 12:17:14 -07004688 reconfig = true;
4689 }
4690 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004691 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004692 reconfig = true;
4693 }
4694 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4695 // do not accept frame count changes if tracks are open as the track buffer
4696 // size depends on frame count and correct behavior would not be garantied
4697 // if frame count is changed after track creation
4698 if (mActiveTrack != 0) {
4699 status = INVALID_OPERATION;
4700 } else {
4701 reconfig = true;
4702 }
4703 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004704 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4705 // forward device change to effects that have requested to be
4706 // aware of attached audio device.
4707 for (size_t i = 0; i < mEffectChains.size(); i++) {
4708 mEffectChains[i]->setDevice_l(value);
4709 }
4710 // store input device and output device but do not forward output device to audio HAL.
4711 // Note that status is ignored by the caller for output device
4712 // (see AudioFlinger::setParameters()
4713 if (value & AUDIO_DEVICE_OUT_ALL) {
4714 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4715 status = BAD_VALUE;
4716 } else {
4717 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004718 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4719 if (mTrack != NULL) {
4720 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004721 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004722 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4723 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4724 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004725 }
4726 mDevice |= (uint32_t)value;
4727 }
Eric Laurenta553c252009-07-17 12:17:14 -07004728 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004729 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004730 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004731 mInput->stream->common.standby(&mInput->stream->common);
4732 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004733 }
4734 if (reconfig) {
4735 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004736 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004737 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004738 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4739 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004740 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004741 status = NO_ERROR;
4742 }
4743 if (status == NO_ERROR) {
4744 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004745 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004746 }
4747 }
4748 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004749
4750 mNewParameters.removeAt(0);
4751
Eric Laurenta553c252009-07-17 12:17:14 -07004752 mParamStatus = status;
4753 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004754 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4755 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004756 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07004757 }
4758 return reconfig;
4759}
4760
4761String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4762{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004763 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004764 String8 out_s8 = String8();
4765
4766 Mutex::Autolock _l(mLock);
4767 if (initCheck() != NO_ERROR) {
4768 return out_s8;
4769 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004770
Dima Zavin31f188892011-04-18 16:57:27 -07004771 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004772 out_s8 = String8(s);
4773 free(s);
4774 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004775}
4776
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004777void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004778 AudioSystem::OutputDescriptor desc;
Glenn Kasten3694ec12012-01-27 16:47:15 -08004779 void *param2 = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004780
4781 switch (event) {
4782 case AudioSystem::INPUT_OPENED:
4783 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004784 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004785 desc.samplingRate = mSampleRate;
4786 desc.format = mFormat;
4787 desc.frameCount = mFrameCount;
4788 desc.latency = 0;
4789 param2 = &desc;
4790 break;
4791
4792 case AudioSystem::INPUT_CLOSED:
4793 default:
4794 break;
4795 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004796 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004797}
4798
4799void AudioFlinger::RecordThread::readInputParameters()
4800{
Glenn Kasten2589cf92012-01-27 18:08:45 -08004801 delete mRsmpInBuffer;
4802 // mRsmpInBuffer is always assigned a new[] below
4803 delete mRsmpOutBuffer;
4804 mRsmpOutBuffer = NULL;
4805 delete mResampler;
Glenn Kastenc434c902011-12-13 11:53:26 -08004806 mResampler = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004807
Dima Zavin31f188892011-04-18 16:57:27 -07004808 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004809 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4810 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004811 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08004812 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin31f188892011-04-18 16:57:27 -07004813 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004814 mFrameCount = mInputBytes / mFrameSize;
4815 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4816
4817 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4818 {
4819 int channelCount;
4820 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4821 // stereo to mono post process as the resampler always outputs stereo.
4822 if (mChannelCount == 1 && mReqChannelCount == 2) {
4823 channelCount = 1;
4824 } else {
4825 channelCount = 2;
4826 }
4827 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4828 mResampler->setSampleRate(mSampleRate);
4829 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4830 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4831
4832 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4833 if (mChannelCount == 1 && mReqChannelCount == 1) {
4834 mFrameCount >>= 1;
4835 }
4836
4837 }
4838 mRsmpInIndex = mFrameCount;
4839}
4840
Eric Laurent47d0a922010-02-26 02:47:27 -08004841unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4842{
Eric Laurent828b9772011-08-07 16:32:26 -07004843 Mutex::Autolock _l(mLock);
4844 if (initCheck() != NO_ERROR) {
4845 return 0;
4846 }
4847
Dima Zavin31f188892011-04-18 16:57:27 -07004848 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004849}
4850
Eric Laurent464d5b32011-06-17 21:29:58 -07004851uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4852{
4853 Mutex::Autolock _l(mLock);
4854 uint32_t result = 0;
4855 if (getEffectChain_l(sessionId) != 0) {
4856 result = EFFECT_SESSION;
4857 }
4858
4859 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4860 result |= TRACK_SESSION;
4861 }
4862
4863 return result;
4864}
4865
Eric Laurent6639b552011-08-01 09:52:20 -07004866AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4867{
4868 Mutex::Autolock _l(mLock);
4869 return mTrack;
4870}
4871
Glenn Kasten5b0135e2012-01-26 09:46:34 -08004872AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurent828b9772011-08-07 16:32:26 -07004873{
4874 Mutex::Autolock _l(mLock);
4875 return mInput;
4876}
4877
4878AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4879{
4880 Mutex::Autolock _l(mLock);
4881 AudioStreamIn *input = mInput;
4882 mInput = NULL;
4883 return input;
4884}
4885
4886// this method must always be called either with ThreadBase mLock held or inside the thread loop
4887audio_stream_t* AudioFlinger::RecordThread::stream()
4888{
4889 if (mInput == NULL) {
4890 return NULL;
4891 }
4892 return &mInput->stream->common;
4893}
4894
4895
Eric Laurenta553c252009-07-17 12:17:14 -07004896// ----------------------------------------------------------------------------
4897
Eric Laurentddb78e72009-07-28 08:44:33 -07004898int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004899 uint32_t *pSamplingRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004900 audio_format_t *pFormat,
Eric Laurenta553c252009-07-17 12:17:14 -07004901 uint32_t *pChannels,
4902 uint32_t *pLatencyMs,
4903 uint32_t flags)
4904{
4905 status_t status;
4906 PlaybackThread *thread = NULL;
4907 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4908 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004909 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta553c252009-07-17 12:17:14 -07004910 uint32_t channels = pChannels ? *pChannels : 0;
4911 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004912 audio_stream_out_t *outStream;
4913 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004914
Steve Block71f2cf12011-10-20 11:56:00 +01004915 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07004916 pDevices ? *pDevices : 0,
4917 samplingRate,
4918 format,
4919 channels,
4920 flags);
4921
4922 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004923 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004924 }
Dima Zavin31f188892011-04-18 16:57:27 -07004925
Eric Laurenta553c252009-07-17 12:17:14 -07004926 Mutex::Autolock _l(mLock);
4927
Dima Zavin31f188892011-04-18 16:57:27 -07004928 outHwDev = findSuitableHwDev_l(*pDevices);
4929 if (outHwDev == NULL)
4930 return 0;
4931
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004932 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07004933 &channels, &samplingRate, &outStream);
Steve Block71f2cf12011-10-20 11:56:00 +01004934 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004935 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004936 samplingRate,
4937 format,
4938 channels,
4939 status);
4940
4941 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004942 if (outStream != NULL) {
4943 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent464d5b32011-06-17 21:29:58 -07004944 int id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004945
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004946 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4947 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4948 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004949 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004950 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004951 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004952 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004953 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004954 }
Eric Laurent65b65452010-06-01 23:49:17 -07004955 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004956
Glenn Kasten3694ec12012-01-27 16:47:15 -08004957 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4958 if (pFormat != NULL) *pFormat = format;
4959 if (pChannels != NULL) *pChannels = channels;
4960 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004961
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004962 // notify client processes of the new output creation
4963 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004964 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004965 }
4966
Eric Laurent9cc489a22009-12-05 05:20:01 -08004967 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004968}
4969
Eric Laurentddb78e72009-07-28 08:44:33 -07004970int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004971{
4972 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004973 MixerThread *thread1 = checkMixerThread_l(output1);
4974 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004975
Eric Laurentddb78e72009-07-28 08:44:33 -07004976 if (thread1 == NULL || thread2 == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00004977 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004978 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004979 }
4980
Eric Laurent464d5b32011-06-17 21:29:58 -07004981 int id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004982 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004983 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004984 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004985 // notify client processes of the new output creation
4986 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004987 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004988}
4989
Eric Laurentddb78e72009-07-28 08:44:33 -07004990status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004991{
Eric Laurent49018a52009-08-04 08:37:05 -07004992 // keep strong reference on the playback thread so that
4993 // it is not destroyed while exit() is executed
4994 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004995 {
4996 Mutex::Autolock _l(mLock);
4997 thread = checkPlaybackThread_l(output);
4998 if (thread == NULL) {
4999 return BAD_VALUE;
5000 }
5001
Steve Block71f2cf12011-10-20 11:56:00 +01005002 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005003
Eric Laurent464d5b32011-06-17 21:29:58 -07005004 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07005005 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005006 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005007 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07005008 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07005009 }
5010 }
5011 }
Glenn Kasten3694ec12012-01-27 16:47:15 -08005012 void *param2 = NULL;
Eric Laurent49f02be2009-11-19 09:00:56 -08005013 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005014 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07005015 }
5016 thread->exit();
5017
Eric Laurent464d5b32011-06-17 21:29:58 -07005018 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07005019 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005020 assert(out != NULL);
Eric Laurent828b9772011-08-07 16:32:26 -07005021 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005022 out->hwDev->close_output_stream(out->hwDev, out->stream);
5023 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005024 }
Eric Laurenta553c252009-07-17 12:17:14 -07005025 return NO_ERROR;
5026}
5027
Eric Laurentddb78e72009-07-28 08:44:33 -07005028status_t AudioFlinger::suspendOutput(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("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005038 thread->suspend();
5039
5040 return NO_ERROR;
5041}
5042
Eric Laurentddb78e72009-07-28 08:44:33 -07005043status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005044{
5045 Mutex::Autolock _l(mLock);
5046 PlaybackThread *thread = checkPlaybackThread_l(output);
5047
5048 if (thread == NULL) {
5049 return BAD_VALUE;
5050 }
5051
Steve Block71f2cf12011-10-20 11:56:00 +01005052 ALOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005053
5054 thread->restore();
5055
5056 return NO_ERROR;
5057}
5058
Eric Laurentddb78e72009-07-28 08:44:33 -07005059int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005060 uint32_t *pSamplingRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005061 audio_format_t *pFormat,
Eric Laurenta553c252009-07-17 12:17:14 -07005062 uint32_t *pChannels,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005063 audio_in_acoustics_t acoustics)
Eric Laurenta553c252009-07-17 12:17:14 -07005064{
5065 status_t status;
5066 RecordThread *thread = NULL;
5067 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005068 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta553c252009-07-17 12:17:14 -07005069 uint32_t channels = pChannels ? *pChannels : 0;
5070 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005071 audio_format_t reqFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -07005072 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005073 audio_stream_in_t *inStream;
5074 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005075
5076 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005077 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005078 }
Dima Zavin31f188892011-04-18 16:57:27 -07005079
Eric Laurenta553c252009-07-17 12:17:14 -07005080 Mutex::Autolock _l(mLock);
5081
Dima Zavin31f188892011-04-18 16:57:27 -07005082 inHwDev = findSuitableHwDev_l(*pDevices);
5083 if (inHwDev == NULL)
5084 return 0;
5085
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005086 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07005087 &channels, &samplingRate,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005088 acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005089 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005090 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005091 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005092 samplingRate,
5093 format,
5094 channels,
5095 acoustics,
5096 status);
5097
5098 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5099 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5100 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005101 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005102 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005103 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005104 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005105 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005106 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07005107 &channels, &samplingRate,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005108 acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005109 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005110 }
5111
Dima Zavin31f188892011-04-18 16:57:27 -07005112 if (inStream != NULL) {
5113 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5114
Eric Laurent464d5b32011-06-17 21:29:58 -07005115 int id = nextUniqueId();
5116 // Start record thread
5117 // RecorThread require both input and output device indication to forward to audio
5118 // pre processing modules
5119 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5120 thread = new RecordThread(this,
5121 input,
5122 reqSamplingRate,
5123 reqChannels,
5124 id,
5125 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005126 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005127 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kasten3694ec12012-01-27 16:47:15 -08005128 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5129 if (pFormat != NULL) *pFormat = format;
5130 if (pChannels != NULL) *pChannels = reqChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07005131
Dima Zavin31f188892011-04-18 16:57:27 -07005132 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005133
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005134 // notify client processes of the new input creation
5135 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005136 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005137 }
5138
Eric Laurent9cc489a22009-12-05 05:20:01 -08005139 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005140}
5141
Eric Laurentddb78e72009-07-28 08:44:33 -07005142status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07005143{
Eric Laurent49018a52009-08-04 08:37:05 -07005144 // keep strong reference on the record thread so that
5145 // it is not destroyed while exit() is executed
5146 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005147 {
5148 Mutex::Autolock _l(mLock);
5149 thread = checkRecordThread_l(input);
5150 if (thread == NULL) {
5151 return BAD_VALUE;
5152 }
5153
Steve Block71f2cf12011-10-20 11:56:00 +01005154 ALOGV("closeInput() %d", input);
Glenn Kasten3694ec12012-01-27 16:47:15 -08005155 void *param2 = NULL;
Eric Laurent49f02be2009-11-19 09:00:56 -08005156 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005157 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005158 }
5159 thread->exit();
5160
Eric Laurent828b9772011-08-07 16:32:26 -07005161 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005162 assert(in != NULL);
Eric Laurent828b9772011-08-07 16:32:26 -07005163 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005164 in->hwDev->close_input_stream(in->hwDev, in->stream);
5165 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005166
Eric Laurenta553c252009-07-17 12:17:14 -07005167 return NO_ERROR;
5168}
5169
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08005170status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005171{
5172 Mutex::Autolock _l(mLock);
5173 MixerThread *dstThread = checkMixerThread_l(output);
5174 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005175 ALOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005176 return BAD_VALUE;
5177 }
5178
Steve Block71f2cf12011-10-20 11:56:00 +01005179 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005180 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005181
Eric Laurent05ce0942011-08-30 10:18:54 -07005182 dstThread->setStreamValid(stream, true);
5183
Eric Laurenta553c252009-07-17 12:17:14 -07005184 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005185 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005186 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005187 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005188 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005189 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005190 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005191 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005192 }
Eric Laurentd069f322009-09-01 05:56:26 -07005193
Eric Laurenta553c252009-07-17 12:17:14 -07005194 return NO_ERROR;
5195}
5196
Eric Laurent65b65452010-06-01 23:49:17 -07005197
5198int AudioFlinger::newAudioSessionId()
5199{
Eric Laurent464d5b32011-06-17 21:29:58 -07005200 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005201}
5202
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005203void AudioFlinger::acquireAudioSessionId(int audioSession)
5204{
5205 Mutex::Autolock _l(mLock);
5206 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005207 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005208 int num = mAudioSessionRefs.size();
5209 for (int i = 0; i< num; i++) {
5210 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5211 if (ref->sessionid == audioSession && ref->pid == caller) {
5212 ref->cnt++;
Steve Block71f2cf12011-10-20 11:56:00 +01005213 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005214 return;
5215 }
5216 }
Glenn Kastendc3ac852012-01-25 15:28:08 -08005217 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5218 ALOGV(" added new entry for %d", audioSession);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005219}
5220
5221void AudioFlinger::releaseAudioSessionId(int audioSession)
5222{
5223 Mutex::Autolock _l(mLock);
5224 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005225 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005226 int num = mAudioSessionRefs.size();
5227 for (int i = 0; i< num; i++) {
5228 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5229 if (ref->sessionid == audioSession && ref->pid == caller) {
5230 ref->cnt--;
Steve Block71f2cf12011-10-20 11:56:00 +01005231 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005232 if (ref->cnt == 0) {
5233 mAudioSessionRefs.removeAt(i);
5234 delete ref;
5235 purgeStaleEffects_l();
5236 }
5237 return;
5238 }
5239 }
Steve Block8564c8d2012-01-05 23:22:43 +00005240 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005241}
5242
5243void AudioFlinger::purgeStaleEffects_l() {
5244
Steve Block71f2cf12011-10-20 11:56:00 +01005245 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005246
5247 Vector< sp<EffectChain> > chains;
5248
5249 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5250 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5251 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5252 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005253 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5254 chains.push(ec);
5255 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005256 }
5257 }
5258 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5259 sp<RecordThread> t = mRecordThreads.valueAt(i);
5260 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5261 sp<EffectChain> ec = t->mEffectChains[j];
5262 chains.push(ec);
5263 }
5264 }
5265
5266 for (size_t i = 0; i < chains.size(); i++) {
5267 sp<EffectChain> ec = chains[i];
5268 int sessionid = ec->sessionId();
5269 sp<ThreadBase> t = ec->mThread.promote();
5270 if (t == 0) {
5271 continue;
5272 }
5273 size_t numsessionrefs = mAudioSessionRefs.size();
5274 bool found = false;
5275 for (size_t k = 0; k < numsessionrefs; k++) {
5276 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5277 if (ref->sessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005278 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005279 sessionid, ref->pid, ref->cnt);
5280 found = true;
5281 break;
5282 }
5283 }
5284 if (!found) {
5285 // remove all effects from the chain
5286 while (ec->mEffects.size()) {
5287 sp<EffectModule> effect = ec->mEffects[0];
5288 effect->unPin();
5289 Mutex::Autolock _l (t->mLock);
5290 t->removeEffect_l(effect);
5291 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5292 sp<EffectHandle> handle = effect->mHandles[j].promote();
5293 if (handle != 0) {
5294 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005295 if (handle->mHasControl && handle->mEnabled) {
5296 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5297 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005298 }
5299 }
5300 AudioSystem::unregisterEffect(effect->id());
5301 }
5302 }
5303 }
5304 return;
5305}
5306
Eric Laurenta553c252009-07-17 12:17:14 -07005307// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005308AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005309{
5310 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005311 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5312 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005313 }
Eric Laurenta553c252009-07-17 12:17:14 -07005314 return thread;
5315}
5316
5317// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005318AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005319{
5320 PlaybackThread *thread = checkPlaybackThread_l(output);
5321 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005322 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005323 thread = NULL;
5324 }
5325 }
5326 return (MixerThread *)thread;
5327}
5328
5329// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005330AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005331{
5332 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005333 if (mRecordThreads.indexOfKey(input) >= 0) {
5334 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005335 }
Eric Laurenta553c252009-07-17 12:17:14 -07005336 return thread;
5337}
5338
Eric Laurent464d5b32011-06-17 21:29:58 -07005339uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005340{
Eric Laurent464d5b32011-06-17 21:29:58 -07005341 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005342}
5343
Eric Laurent464d5b32011-06-17 21:29:58 -07005344AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5345{
5346 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5347 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005348 AudioStreamOut *output = thread->getOutput();
5349 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005350 return thread;
5351 }
5352 }
5353 return NULL;
5354}
5355
5356uint32_t AudioFlinger::primaryOutputDevice_l()
5357{
5358 PlaybackThread *thread = primaryPlaybackThread_l();
5359
5360 if (thread == NULL) {
5361 return 0;
5362 }
5363
5364 return thread->device();
5365}
5366
5367
Eric Laurent65b65452010-06-01 23:49:17 -07005368// ----------------------------------------------------------------------------
5369// Effect management
5370// ----------------------------------------------------------------------------
5371
5372
Eric Laurent65b65452010-06-01 23:49:17 -07005373status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5374{
5375 Mutex::Autolock _l(mLock);
5376 return EffectQueryNumberEffects(numEffects);
5377}
5378
Eric Laurent53334cd2010-06-23 17:38:20 -07005379status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07005380{
5381 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005382 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005383}
5384
5385status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5386{
5387 Mutex::Autolock _l(mLock);
5388 return EffectGetDescriptor(pUuid, descriptor);
5389}
5390
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005391
Eric Laurent65b65452010-06-01 23:49:17 -07005392sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5393 effect_descriptor_t *pDesc,
5394 const sp<IEffectClient>& effectClient,
5395 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005396 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005397 int sessionId,
5398 status_t *status,
5399 int *id,
5400 int *enabled)
5401{
5402 status_t lStatus = NO_ERROR;
5403 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005404 effect_descriptor_t desc;
5405 sp<Client> client;
5406 wp<Client> wclient;
5407
Steve Block71f2cf12011-10-20 11:56:00 +01005408 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005409 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005410
5411 if (pDesc == NULL) {
5412 lStatus = BAD_VALUE;
5413 goto Exit;
5414 }
5415
Eric Laurent98c92592010-09-23 16:10:16 -07005416 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005417 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005418 lStatus = PERMISSION_DENIED;
5419 goto Exit;
5420 }
5421
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005422 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005423 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005424 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005425 lStatus = PERMISSION_DENIED;
5426 goto Exit;
5427 }
5428
Eric Laurent464d5b32011-06-17 21:29:58 -07005429 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005430 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005431 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005432 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005433 lStatus = BAD_VALUE;
5434 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005435 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005436 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005437 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005438 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005439 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005440 }
5441 }
5442
Eric Laurent65b65452010-06-01 23:49:17 -07005443 {
5444 Mutex::Autolock _l(mLock);
5445
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005446
Eric Laurent65b65452010-06-01 23:49:17 -07005447 if (!EffectIsNullUuid(&pDesc->uuid)) {
5448 // if uuid is specified, request effect descriptor
5449 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5450 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005451 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005452 goto Exit;
5453 }
5454 } else {
5455 // if uuid is not specified, look for an available implementation
5456 // of the required type in effect factory
5457 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005458 ALOGW("createEffect() no effect type");
Eric Laurent65b65452010-06-01 23:49:17 -07005459 lStatus = BAD_VALUE;
5460 goto Exit;
5461 }
5462 uint32_t numEffects = 0;
5463 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005464 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005465 bool found = false;
5466
5467 lStatus = EffectQueryNumberEffects(&numEffects);
5468 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005469 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005470 goto Exit;
5471 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005472 for (uint32_t i = 0; i < numEffects; i++) {
5473 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005474 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005475 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005476 continue;
5477 }
5478 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5479 // If matching type found save effect descriptor. If the session is
5480 // 0 and the effect is not auxiliary, continue enumeration in case
5481 // an auxiliary version of this effect type is available
5482 found = true;
5483 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005484 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005485 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5486 break;
5487 }
5488 }
5489 }
5490 if (!found) {
5491 lStatus = BAD_VALUE;
Steve Block8564c8d2012-01-05 23:22:43 +00005492 ALOGW("createEffect() effect not found");
Eric Laurent65b65452010-06-01 23:49:17 -07005493 goto Exit;
5494 }
5495 // For same effect type, chose auxiliary version over insert version if
5496 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005497 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005498 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5499 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5500 }
5501 }
5502
5503 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005504 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005505 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5506 lStatus = INVALID_OPERATION;
5507 goto Exit;
5508 }
5509
Eric Laurentf82fccd2011-07-27 19:49:51 -07005510 // check recording permission for visualizer
5511 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5512 !recordingAllowed()) {
5513 lStatus = PERMISSION_DENIED;
5514 goto Exit;
5515 }
5516
Eric Laurent65b65452010-06-01 23:49:17 -07005517 // return effect descriptor
5518 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5519
5520 // If output is not specified try to find a matching audio session ID in one of the
5521 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005522 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5523 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005524 // Note: io is never 0 when creating an effect on an input
5525 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005526 // look for the thread where the specified audio session is present
5527 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5528 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005529 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005530 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005531 }
Eric Laurent65b65452010-06-01 23:49:17 -07005532 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005533 if (io == 0) {
5534 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5535 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5536 io = mRecordThreads.keyAt(i);
5537 break;
5538 }
5539 }
5540 }
Eric Laurent98c92592010-09-23 16:10:16 -07005541 // If no output thread contains the requested session ID, default to
5542 // first output. The effect chain will be moved to the correct output
5543 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005544 if (io == 0 && mPlaybackThreads.size()) {
5545 io = mPlaybackThreads.keyAt(0);
5546 }
Steve Block71f2cf12011-10-20 11:56:00 +01005547 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005548 }
5549 ThreadBase *thread = checkRecordThread_l(io);
5550 if (thread == NULL) {
5551 thread = checkPlaybackThread_l(io);
5552 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +00005553 ALOGE("createEffect() unknown output thread");
Eric Laurent464d5b32011-06-17 21:29:58 -07005554 lStatus = BAD_VALUE;
5555 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005556 }
Eric Laurent65b65452010-06-01 23:49:17 -07005557 }
Eric Laurent98c92592010-09-23 16:10:16 -07005558
Eric Laurent65b65452010-06-01 23:49:17 -07005559 wclient = mClients.valueFor(pid);
5560
5561 if (wclient != NULL) {
5562 client = wclient.promote();
5563 } else {
5564 client = new Client(this, pid);
5565 mClients.add(pid, client);
5566 }
5567
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005568 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005569 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5570 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005571 if (handle != 0 && id != NULL) {
5572 *id = handle->id();
5573 }
5574 }
5575
5576Exit:
5577 if(status) {
5578 *status = lStatus;
5579 }
5580 return handle;
5581}
5582
Eric Laurentf82fccd2011-07-27 19:49:51 -07005583status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005584{
Steve Block71f2cf12011-10-20 11:56:00 +01005585 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005586 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005587 Mutex::Autolock _l(mLock);
5588 if (srcOutput == dstOutput) {
Steve Block8564c8d2012-01-05 23:22:43 +00005589 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005590 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005591 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005592 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5593 if (srcThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005594 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005595 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005596 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005597 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5598 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005599 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005600 return BAD_VALUE;
5601 }
5602
5603 Mutex::Autolock _dl(dstThread->mLock);
5604 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005605 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005606
Eric Laurent53334cd2010-06-23 17:38:20 -07005607 return NO_ERROR;
5608}
5609
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005610// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005611status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005612 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005613 AudioFlinger::PlaybackThread *dstThread,
5614 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005615{
Steve Block71f2cf12011-10-20 11:56:00 +01005616 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005617 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005618
Eric Laurentf82fccd2011-07-27 19:49:51 -07005619 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005620 if (chain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005621 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005622 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005623 return INVALID_OPERATION;
5624 }
5625
Eric Laurent493941b2010-07-28 01:32:47 -07005626 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005627 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005628 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005629 // removed.
5630 srcThread->removeEffectChain_l(chain);
5631
5632 // transfer all effects one by one so that new effect chain is created on new thread with
5633 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005634 int dstOutput = dstThread->id();
5635 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005636 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005637 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5638 while (effect != 0) {
5639 srcThread->removeEffect_l(effect);
5640 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005641 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5642 if (effect->state() == EffectModule::ACTIVE ||
5643 effect->state() == EffectModule::STOPPING) {
5644 effect->start();
5645 }
Eric Laurent493941b2010-07-28 01:32:47 -07005646 // if the move request is not received from audio policy manager, the effect must be
5647 // re-registered with the new strategy and output
5648 if (dstChain == 0) {
5649 dstChain = effect->chain().promote();
5650 if (dstChain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005651 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent493941b2010-07-28 01:32:47 -07005652 srcThread->addEffect_l(effect);
5653 return NO_INIT;
5654 }
5655 strategy = dstChain->strategy();
5656 }
5657 if (reRegister) {
5658 AudioSystem::unregisterEffect(effect->id());
5659 AudioSystem::registerEffect(&effect->desc(),
5660 dstOutput,
5661 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005662 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005663 effect->id());
5664 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005665 effect = chain->getEffectFromId_l(0);
5666 }
5667
5668 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005669}
5670
Eric Laurent464d5b32011-06-17 21:29:58 -07005671
Eric Laurent65b65452010-06-01 23:49:17 -07005672// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005673sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005674 const sp<AudioFlinger::Client>& client,
5675 const sp<IEffectClient>& effectClient,
5676 int32_t priority,
5677 int sessionId,
5678 effect_descriptor_t *desc,
5679 int *enabled,
5680 status_t *status
5681 )
5682{
5683 sp<EffectModule> effect;
5684 sp<EffectHandle> handle;
5685 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005686 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005687 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005688 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005689 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005690
Eric Laurent464d5b32011-06-17 21:29:58 -07005691 lStatus = initCheck();
5692 if (lStatus != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00005693 ALOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005694 goto Exit;
5695 }
5696
5697 // Do not allow effects with session ID 0 on direct output or duplicating threads
5698 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005699 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block8564c8d2012-01-05 23:22:43 +00005700 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005701 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005702 lStatus = BAD_VALUE;
5703 goto Exit;
5704 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005705 // Only Pre processor effects are allowed on input threads and only on input threads
5706 if ((mType == RECORD &&
5707 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5708 (mType != RECORD &&
5709 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005710 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005711 desc->name, desc->flags, mType);
5712 lStatus = BAD_VALUE;
5713 goto Exit;
5714 }
Eric Laurent65b65452010-06-01 23:49:17 -07005715
Steve Block71f2cf12011-10-20 11:56:00 +01005716 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005717
5718 { // scope for mLock
5719 Mutex::Autolock _l(mLock);
5720
5721 // check for existing effect chain with the requested audio session
5722 chain = getEffectChain_l(sessionId);
5723 if (chain == 0) {
5724 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005725 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005726 chain = new EffectChain(this, sessionId);
5727 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005728 chain->setStrategy(getStrategyForSession_l(sessionId));
5729 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005730 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005731 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005732 }
5733
Glenn Kasten70ed6b72012-01-10 10:46:34 -08005734 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005735
5736 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005737 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005738 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005739 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005740 if (lStatus != NO_ERROR) {
5741 goto Exit;
5742 }
5743 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005744 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005745 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005746 lStatus = effect->status();
5747 if (lStatus != NO_ERROR) {
5748 goto Exit;
5749 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005750 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005751 if (lStatus != NO_ERROR) {
5752 goto Exit;
5753 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005754 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005755
5756 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005757 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005758 }
5759 // create effect handle and connect it to effect module
5760 handle = new EffectHandle(effect, client, effectClient, priority);
5761 lStatus = effect->addHandle(handle);
Glenn Kasten3694ec12012-01-27 16:47:15 -08005762 if (enabled != NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005763 *enabled = (int)effect->isEnabled();
5764 }
5765 }
5766
5767Exit:
5768 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005769 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005770 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005771 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005772 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005773 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005774 AudioSystem::unregisterEffect(effect->id());
5775 }
5776 if (chainCreated) {
5777 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005778 }
Eric Laurent65b65452010-06-01 23:49:17 -07005779 handle.clear();
5780 }
5781
5782 if(status) {
5783 *status = lStatus;
5784 }
5785 return handle;
5786}
5787
Eric Laurent464d5b32011-06-17 21:29:58 -07005788sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5789{
5790 sp<EffectModule> effect;
5791
5792 sp<EffectChain> chain = getEffectChain_l(sessionId);
5793 if (chain != 0) {
5794 effect = chain->getEffectFromId_l(effectId);
5795 }
5796 return effect;
5797}
5798
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005799// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5800// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005801status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005802{
5803 // check for existing effect chain with the requested audio session
5804 int sessionId = effect->sessionId();
5805 sp<EffectChain> chain = getEffectChain_l(sessionId);
5806 bool chainCreated = false;
5807
5808 if (chain == 0) {
5809 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005810 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005811 chain = new EffectChain(this, sessionId);
5812 addEffectChain_l(chain);
5813 chain->setStrategy(getStrategyForSession_l(sessionId));
5814 chainCreated = true;
5815 }
Steve Block71f2cf12011-10-20 11:56:00 +01005816 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005817
5818 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005819 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005820 this, effect->desc().name, chain.get());
5821 return BAD_VALUE;
5822 }
5823
5824 status_t status = chain->addEffect_l(effect);
5825 if (status != NO_ERROR) {
5826 if (chainCreated) {
5827 removeEffectChain_l(chain);
5828 }
5829 return status;
5830 }
5831
5832 effect->setDevice(mDevice);
5833 effect->setMode(mAudioFlinger->getMode());
5834 return NO_ERROR;
5835}
5836
Eric Laurent464d5b32011-06-17 21:29:58 -07005837void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005838
Steve Block71f2cf12011-10-20 11:56:00 +01005839 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005840 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005841 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5842 detachAuxEffect_l(effect->id());
5843 }
5844
5845 sp<EffectChain> chain = effect->chain().promote();
5846 if (chain != 0) {
5847 // remove effect chain if removing last effect
5848 if (chain->removeEffect_l(effect) == 0) {
5849 removeEffectChain_l(chain);
5850 }
5851 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00005852 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005853 }
5854}
5855
Eric Laurent464d5b32011-06-17 21:29:58 -07005856void AudioFlinger::ThreadBase::lockEffectChains_l(
5857 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5858{
5859 effectChains = mEffectChains;
5860 for (size_t i = 0; i < mEffectChains.size(); i++) {
5861 mEffectChains[i]->lock();
5862 }
5863}
5864
5865void AudioFlinger::ThreadBase::unlockEffectChains(
5866 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5867{
5868 for (size_t i = 0; i < effectChains.size(); i++) {
5869 effectChains[i]->unlock();
5870 }
5871}
5872
5873sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5874{
5875 Mutex::Autolock _l(mLock);
5876 return getEffectChain_l(sessionId);
5877}
5878
5879sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5880{
5881 sp<EffectChain> chain;
5882
5883 size_t size = mEffectChains.size();
5884 for (size_t i = 0; i < size; i++) {
5885 if (mEffectChains[i]->sessionId() == sessionId) {
5886 chain = mEffectChains[i];
5887 break;
5888 }
5889 }
5890 return chain;
5891}
5892
Glenn Kastenaccb1142012-01-04 11:00:47 -08005893void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent464d5b32011-06-17 21:29:58 -07005894{
5895 Mutex::Autolock _l(mLock);
5896 size_t size = mEffectChains.size();
5897 for (size_t i = 0; i < size; i++) {
5898 mEffectChains[i]->setMode_l(mode);
5899 }
5900}
5901
5902void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005903 const wp<EffectHandle>& handle,
5904 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005905
Eric Laurent53334cd2010-06-23 17:38:20 -07005906 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01005907 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005908 // delete the effect module if removing last handle on it
5909 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005910 if (!effect->isPinned() || unpiniflast) {
5911 removeEffect_l(effect);
5912 AudioSystem::unregisterEffect(effect->id());
5913 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005914 }
5915}
5916
Eric Laurent65b65452010-06-01 23:49:17 -07005917status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5918{
5919 int session = chain->sessionId();
5920 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005921 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005922
Steve Block71f2cf12011-10-20 11:56:00 +01005923 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005924 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005925 // Only one effect chain can be present in direct output thread and it uses
5926 // the mix buffer as input
5927 if (mType != DIRECT) {
5928 size_t numSamples = mFrameCount * mChannelCount;
5929 buffer = new int16_t[numSamples];
5930 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01005931 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005932 ownsBuffer = true;
5933 }
Eric Laurent65b65452010-06-01 23:49:17 -07005934
Eric Laurent53334cd2010-06-23 17:38:20 -07005935 // Attach all tracks with same session ID to this chain.
5936 for (size_t i = 0; i < mTracks.size(); ++i) {
5937 sp<Track> track = mTracks[i];
5938 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005939 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07005940 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005941 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005942 }
5943 }
5944
5945 // indicate all active tracks in the chain
5946 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5947 sp<Track> track = mActiveTracks[i].promote();
5948 if (track == 0) continue;
5949 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005950 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005951 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005952 }
Eric Laurent65b65452010-06-01 23:49:17 -07005953 }
5954 }
5955
Eric Laurent53334cd2010-06-23 17:38:20 -07005956 chain->setInBuffer(buffer, ownsBuffer);
5957 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005958 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005959 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005960 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5961 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005962 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005963 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5964 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005965 // Effect chain for other sessions are inserted at beginning of effect
5966 // chains list to be processed before output mix effects. Relative order between other
5967 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005968 size_t size = mEffectChains.size();
5969 size_t i = 0;
5970 for (i = 0; i < size; i++) {
5971 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005972 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005973 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005974 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005975
5976 return NO_ERROR;
5977}
5978
5979size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5980{
5981 int session = chain->sessionId();
5982
Steve Block71f2cf12011-10-20 11:56:00 +01005983 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005984
5985 for (size_t i = 0; i < mEffectChains.size(); i++) {
5986 if (chain == mEffectChains[i]) {
5987 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005988 // detach all active tracks from the chain
5989 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5990 sp<Track> track = mActiveTracks[i].promote();
5991 if (track == 0) continue;
5992 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005993 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07005994 chain.get(), session);
5995 chain->decActiveTrackCnt();
5996 }
5997 }
5998
Eric Laurent65b65452010-06-01 23:49:17 -07005999 // detach all tracks with same session ID from this chain
6000 for (size_t i = 0; i < mTracks.size(); ++i) {
6001 sp<Track> track = mTracks[i];
6002 if (session == track->sessionId()) {
6003 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07006004 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07006005 }
6006 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006007 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006008 }
6009 }
6010 return mEffectChains.size();
6011}
6012
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006013status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6014 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006015{
6016 Mutex::Autolock _l(mLock);
6017 return attachAuxEffect_l(track, EffectId);
6018}
6019
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006020status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6021 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006022{
6023 status_t status = NO_ERROR;
6024
6025 if (EffectId == 0) {
6026 track->setAuxBuffer(0, NULL);
6027 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006028 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6029 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006030 if (effect != 0) {
6031 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6032 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6033 } else {
6034 status = INVALID_OPERATION;
6035 }
6036 } else {
6037 status = BAD_VALUE;
6038 }
6039 }
6040 return status;
6041}
6042
6043void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6044{
6045 for (size_t i = 0; i < mTracks.size(); ++i) {
6046 sp<Track> track = mTracks[i];
6047 if (track->auxEffectId() == effectId) {
6048 attachAuxEffect_l(track, 0);
6049 }
6050 }
6051}
6052
Eric Laurent464d5b32011-06-17 21:29:58 -07006053status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6054{
6055 // only one chain per input thread
6056 if (mEffectChains.size() != 0) {
6057 return INVALID_OPERATION;
6058 }
Steve Block71f2cf12011-10-20 11:56:00 +01006059 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006060
6061 chain->setInBuffer(NULL);
6062 chain->setOutBuffer(NULL);
6063
Eric Laurentf82fccd2011-07-27 19:49:51 -07006064 checkSuspendOnAddEffectChain_l(chain);
6065
Eric Laurent464d5b32011-06-17 21:29:58 -07006066 mEffectChains.add(chain);
6067
6068 return NO_ERROR;
6069}
6070
6071size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6072{
Steve Block71f2cf12011-10-20 11:56:00 +01006073 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block8564c8d2012-01-05 23:22:43 +00006074 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent464d5b32011-06-17 21:29:58 -07006075 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6076 chain.get(), mEffectChains.size(), this);
6077 if (mEffectChains.size() == 1) {
6078 mEffectChains.removeAt(0);
6079 }
6080 return 0;
6081}
6082
Eric Laurent65b65452010-06-01 23:49:17 -07006083// ----------------------------------------------------------------------------
6084// EffectModule implementation
6085// ----------------------------------------------------------------------------
6086
6087#undef LOG_TAG
6088#define LOG_TAG "AudioFlinger::EffectModule"
6089
6090AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6091 const wp<AudioFlinger::EffectChain>& chain,
6092 effect_descriptor_t *desc,
6093 int id,
6094 int sessionId)
6095 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006096 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006097{
Steve Block71f2cf12011-10-20 11:56:00 +01006098 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006099 int lStatus;
6100 sp<ThreadBase> thread = mThread.promote();
6101 if (thread == 0) {
6102 return;
6103 }
Eric Laurent65b65452010-06-01 23:49:17 -07006104
6105 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6106
6107 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006108 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006109
Eric Laurent65b65452010-06-01 23:49:17 -07006110 if (mStatus != NO_ERROR) {
6111 return;
6112 }
6113 lStatus = init();
6114 if (lStatus < 0) {
6115 mStatus = lStatus;
6116 goto Error;
6117 }
6118
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006119 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6120 mPinned = true;
6121 }
Steve Block71f2cf12011-10-20 11:56:00 +01006122 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006123 return;
6124Error:
6125 EffectRelease(mEffectInterface);
6126 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006127 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006128}
6129
6130AudioFlinger::EffectModule::~EffectModule()
6131{
Steve Block71f2cf12011-10-20 11:56:00 +01006132 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006133 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006134 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6135 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6136 sp<ThreadBase> thread = mThread.promote();
6137 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006138 audio_stream_t *stream = thread->stream();
6139 if (stream != NULL) {
6140 stream->remove_audio_effect(stream, mEffectInterface);
6141 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006142 }
6143 }
Eric Laurent65b65452010-06-01 23:49:17 -07006144 // release effect engine
6145 EffectRelease(mEffectInterface);
6146 }
6147}
6148
Glenn Kasten1f812f72012-01-30 10:15:48 -08006149status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Eric Laurent65b65452010-06-01 23:49:17 -07006150{
6151 status_t status;
6152
6153 Mutex::Autolock _l(mLock);
6154 // First handle in mHandles has highest priority and controls the effect module
6155 int priority = handle->priority();
6156 size_t size = mHandles.size();
6157 sp<EffectHandle> h;
6158 size_t i;
6159 for (i = 0; i < size; i++) {
6160 h = mHandles[i].promote();
6161 if (h == 0) continue;
6162 if (h->priority() <= priority) break;
6163 }
6164 // if inserted in first place, move effect control from previous owner to this handle
6165 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006166 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006167 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006168 enabled = h->enabled();
6169 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006170 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006171 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006172 status = NO_ERROR;
6173 } else {
6174 status = ALREADY_EXISTS;
6175 }
Steve Block71f2cf12011-10-20 11:56:00 +01006176 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006177 mHandles.insertAt(handle, i);
6178 return status;
6179}
6180
6181size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6182{
6183 Mutex::Autolock _l(mLock);
6184 size_t size = mHandles.size();
6185 size_t i;
6186 for (i = 0; i < size; i++) {
6187 if (mHandles[i] == handle) break;
6188 }
6189 if (i == size) {
6190 return size;
6191 }
Steve Block71f2cf12011-10-20 11:56:00 +01006192 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006193
6194 bool enabled = false;
6195 EffectHandle *hdl = handle.unsafe_get();
Glenn Kasten3694ec12012-01-27 16:47:15 -08006196 if (hdl != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01006197 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006198 enabled = hdl->enabled();
6199 }
Eric Laurent65b65452010-06-01 23:49:17 -07006200 mHandles.removeAt(i);
6201 size = mHandles.size();
6202 // if removed from first place, move effect control from this handle to next in line
6203 if (i == 0 && size != 0) {
6204 sp<EffectHandle> h = mHandles[0].promote();
6205 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006206 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006207 }
6208 }
6209
Eric Laurent21b5c472011-07-26 20:54:46 -07006210 // Prevent calls to process() and other functions on effect interface from now on.
6211 // The effect engine will be released by the destructor when the last strong reference on
6212 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006213 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006214 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006215 }
6216
Eric Laurent65b65452010-06-01 23:49:17 -07006217 return size;
6218}
6219
Eric Laurentf82fccd2011-07-27 19:49:51 -07006220sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6221{
6222 Mutex::Autolock _l(mLock);
6223 sp<EffectHandle> handle;
6224 if (mHandles.size() != 0) {
6225 handle = mHandles[0].promote();
6226 }
6227 return handle;
6228}
6229
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006230void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006231{
Steve Block71f2cf12011-10-20 11:56:00 +01006232 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006233 // keep a strong reference on this EffectModule to avoid calling the
6234 // destructor before we exit
6235 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006236 {
6237 sp<ThreadBase> thread = mThread.promote();
6238 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006239 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006240 }
6241 }
6242}
6243
Eric Laurent7d850f22010-07-09 13:34:17 -07006244void AudioFlinger::EffectModule::updateState() {
6245 Mutex::Autolock _l(mLock);
6246
6247 switch (mState) {
6248 case RESTART:
6249 reset_l();
6250 // FALL THROUGH
6251
6252 case STARTING:
6253 // clear auxiliary effect input buffer for next accumulation
6254 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6255 memset(mConfig.inputCfg.buffer.raw,
6256 0,
6257 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6258 }
6259 start_l();
6260 mState = ACTIVE;
6261 break;
6262 case STOPPING:
6263 stop_l();
6264 mDisableWaitCnt = mMaxDisableWaitCnt;
6265 mState = STOPPED;
6266 break;
6267 case STOPPED:
6268 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6269 // turn off sequence.
6270 if (--mDisableWaitCnt == 0) {
6271 reset_l();
6272 mState = IDLE;
6273 }
6274 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006275 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006276 break;
6277 }
6278}
6279
Eric Laurent65b65452010-06-01 23:49:17 -07006280void AudioFlinger::EffectModule::process()
6281{
6282 Mutex::Autolock _l(mLock);
6283
Eric Laurent21b5c472011-07-26 20:54:46 -07006284 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006285 mConfig.inputCfg.buffer.raw == NULL ||
6286 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006287 return;
6288 }
6289
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006290 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006291 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6292 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten490909d2011-12-15 09:52:39 -08006293 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Eric Laurent65b65452010-06-01 23:49:17 -07006294 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006295 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006296 }
6297
Eric Laurent65b65452010-06-01 23:49:17 -07006298 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006299 int ret = (*mEffectInterface)->process(mEffectInterface,
6300 &mConfig.inputCfg.buffer,
6301 &mConfig.outputCfg.buffer);
6302
6303 // force transition to IDLE state when engine is ready
6304 if (mState == STOPPED && ret == -ENODATA) {
6305 mDisableWaitCnt = 1;
6306 }
Eric Laurent65b65452010-06-01 23:49:17 -07006307
6308 // clear auxiliary effect input buffer for next accumulation
6309 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006310 memset(mConfig.inputCfg.buffer.raw, 0,
6311 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006312 }
6313 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006314 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6315 // If an insert effect is idle and input buffer is different from output buffer,
6316 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006317 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006318 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006319 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6320 int16_t *in = mConfig.inputCfg.buffer.s16;
6321 int16_t *out = mConfig.outputCfg.buffer.s16;
6322 for (size_t i = 0; i < frameCnt; i++) {
6323 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006324 }
Eric Laurent65b65452010-06-01 23:49:17 -07006325 }
6326 }
6327}
6328
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006329void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006330{
6331 if (mEffectInterface == NULL) {
6332 return;
6333 }
6334 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6335}
6336
6337status_t AudioFlinger::EffectModule::configure()
6338{
6339 uint32_t channels;
6340 if (mEffectInterface == NULL) {
6341 return NO_INIT;
6342 }
6343
6344 sp<ThreadBase> thread = mThread.promote();
6345 if (thread == 0) {
6346 return DEAD_OBJECT;
6347 }
6348
6349 // TODO: handle configuration of effects replacing track process
6350 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006351 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006352 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006353 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006354 }
6355
6356 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006357 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006358 } else {
6359 mConfig.inputCfg.channels = channels;
6360 }
6361 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006362 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6363 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006364 mConfig.inputCfg.samplingRate = thread->sampleRate();
6365 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6366 mConfig.inputCfg.bufferProvider.cookie = NULL;
6367 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6368 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6369 mConfig.outputCfg.bufferProvider.cookie = NULL;
6370 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6371 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6372 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6373 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006374 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006375 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006376 // - in other sessions:
6377 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6378 // other effect: overwrites output buffer: input buffer == output buffer
6379 // Auxiliary effect:
6380 // accumulates in output buffer: input buffer != output buffer
6381 // Therefore: accumulate <=> input buffer != output buffer
6382 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6383 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6384 } else {
6385 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6386 }
6387 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6388 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6389 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6390 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6391
Steve Block71f2cf12011-10-20 11:56:00 +01006392 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006393 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6394
Eric Laurent65b65452010-06-01 23:49:17 -07006395 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006396 uint32_t size = sizeof(int);
6397 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent4abf8822011-12-16 15:30:36 -08006398 EFFECT_CMD_SET_CONFIG,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006399 sizeof(effect_config_t),
6400 &mConfig,
6401 &size,
6402 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006403 if (status == 0) {
6404 status = cmdStatus;
6405 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006406
6407 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6408 (1000 * mConfig.outputCfg.buffer.frameCount);
6409
Eric Laurent65b65452010-06-01 23:49:17 -07006410 return status;
6411}
6412
6413status_t AudioFlinger::EffectModule::init()
6414{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006415 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006416 if (mEffectInterface == NULL) {
6417 return NO_INIT;
6418 }
6419 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006420 uint32_t size = sizeof(status_t);
6421 status_t status = (*mEffectInterface)->command(mEffectInterface,
6422 EFFECT_CMD_INIT,
6423 0,
6424 NULL,
6425 &size,
6426 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006427 if (status == 0) {
6428 status = cmdStatus;
6429 }
6430 return status;
6431}
6432
Eric Laurent6fccbd02011-10-05 17:42:25 -07006433status_t AudioFlinger::EffectModule::start()
6434{
6435 Mutex::Autolock _l(mLock);
6436 return start_l();
6437}
6438
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006439status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006440{
6441 if (mEffectInterface == NULL) {
6442 return NO_INIT;
6443 }
6444 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006445 uint32_t size = sizeof(status_t);
6446 status_t status = (*mEffectInterface)->command(mEffectInterface,
6447 EFFECT_CMD_ENABLE,
6448 0,
6449 NULL,
6450 &size,
6451 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006452 if (status == 0) {
6453 status = cmdStatus;
6454 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006455 if (status == 0 &&
6456 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6457 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6458 sp<ThreadBase> thread = mThread.promote();
6459 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006460 audio_stream_t *stream = thread->stream();
6461 if (stream != NULL) {
6462 stream->add_audio_effect(stream, mEffectInterface);
6463 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006464 }
6465 }
Eric Laurent65b65452010-06-01 23:49:17 -07006466 return status;
6467}
6468
Eric Laurent21b5c472011-07-26 20:54:46 -07006469status_t AudioFlinger::EffectModule::stop()
6470{
6471 Mutex::Autolock _l(mLock);
6472 return stop_l();
6473}
6474
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006475status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006476{
6477 if (mEffectInterface == NULL) {
6478 return NO_INIT;
6479 }
6480 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006481 uint32_t size = sizeof(status_t);
6482 status_t status = (*mEffectInterface)->command(mEffectInterface,
6483 EFFECT_CMD_DISABLE,
6484 0,
6485 NULL,
6486 &size,
6487 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006488 if (status == 0) {
6489 status = cmdStatus;
6490 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006491 if (status == 0 &&
6492 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6493 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6494 sp<ThreadBase> thread = mThread.promote();
6495 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006496 audio_stream_t *stream = thread->stream();
6497 if (stream != NULL) {
6498 stream->remove_audio_effect(stream, mEffectInterface);
6499 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006500 }
6501 }
Eric Laurent65b65452010-06-01 23:49:17 -07006502 return status;
6503}
6504
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006505status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6506 uint32_t cmdSize,
6507 void *pCmdData,
6508 uint32_t *replySize,
6509 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006510{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006511 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006512// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006513
Eric Laurent21b5c472011-07-26 20:54:46 -07006514 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006515 return NO_INIT;
6516 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006517 status_t status = (*mEffectInterface)->command(mEffectInterface,
6518 cmdCode,
6519 cmdSize,
6520 pCmdData,
6521 replySize,
6522 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006523 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006524 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006525 for (size_t i = 1; i < mHandles.size(); i++) {
6526 sp<EffectHandle> h = mHandles[i].promote();
6527 if (h != 0) {
6528 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6529 }
6530 }
6531 }
6532 return status;
6533}
6534
6535status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6536{
Eric Laurent6752ec82011-08-10 10:37:50 -07006537
Eric Laurent65b65452010-06-01 23:49:17 -07006538 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006539 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006540
6541 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006542 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6543 if (enabled && status != NO_ERROR) {
6544 return status;
6545 }
6546
Eric Laurent65b65452010-06-01 23:49:17 -07006547 switch (mState) {
6548 // going from disabled to enabled
6549 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006550 mState = STARTING;
6551 break;
6552 case STOPPED:
6553 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006554 break;
6555 case STOPPING:
6556 mState = ACTIVE;
6557 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006558
6559 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006560 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006561 mState = STOPPED;
6562 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006563 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006564 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006565 break;
6566 case ACTIVE:
6567 mState = STOPPING;
6568 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006569 case DESTROYED:
6570 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006571 }
6572 for (size_t i = 1; i < mHandles.size(); i++) {
6573 sp<EffectHandle> h = mHandles[i].promote();
6574 if (h != 0) {
6575 h->setEnabled(enabled);
6576 }
6577 }
6578 }
6579 return NO_ERROR;
6580}
6581
Glenn Kasteneabd94a2012-02-02 14:06:11 -08006582bool AudioFlinger::EffectModule::isEnabled() const
Eric Laurent65b65452010-06-01 23:49:17 -07006583{
6584 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006585 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006586 case STARTING:
6587 case ACTIVE:
6588 return true;
6589 case IDLE:
6590 case STOPPING:
6591 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006592 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006593 default:
6594 return false;
6595 }
6596}
6597
Glenn Kasteneabd94a2012-02-02 14:06:11 -08006598bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006599{
6600 switch (mState) {
6601 case RESTART:
6602 case ACTIVE:
6603 case STOPPING:
6604 case STOPPED:
6605 return true;
6606 case IDLE:
6607 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006608 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006609 default:
6610 return false;
6611 }
6612}
6613
Eric Laurent65b65452010-06-01 23:49:17 -07006614status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6615{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006616 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006617 status_t status = NO_ERROR;
6618
6619 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6620 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006621 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006622 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6623 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006624 status_t cmdStatus;
6625 uint32_t volume[2];
6626 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006627 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006628 volume[0] = *left;
6629 volume[1] = *right;
6630 if (controller) {
6631 pVolume = volume;
6632 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006633 status = (*mEffectInterface)->command(mEffectInterface,
6634 EFFECT_CMD_SET_VOLUME,
6635 size,
6636 volume,
6637 &size,
6638 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006639 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6640 *left = volume[0];
6641 *right = volume[1];
6642 }
6643 }
6644 return status;
6645}
6646
6647status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6648{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006649 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006650 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006651 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6652 // audio pre processing modules on RecordThread can receive both output and
6653 // input device indication in the same call
6654 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6655 if (dev) {
6656 status_t cmdStatus;
6657 uint32_t size = sizeof(status_t);
6658
6659 status = (*mEffectInterface)->command(mEffectInterface,
6660 EFFECT_CMD_SET_DEVICE,
6661 sizeof(uint32_t),
6662 &dev,
6663 &size,
6664 &cmdStatus);
6665 if (status == NO_ERROR) {
6666 status = cmdStatus;
6667 }
6668 }
6669 dev = device & AUDIO_DEVICE_IN_ALL;
6670 if (dev) {
6671 status_t cmdStatus;
6672 uint32_t size = sizeof(status_t);
6673
6674 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6675 EFFECT_CMD_SET_INPUT_DEVICE,
6676 sizeof(uint32_t),
6677 &dev,
6678 &size,
6679 &cmdStatus);
6680 if (status2 == NO_ERROR) {
6681 status2 = cmdStatus;
6682 }
6683 if (status == NO_ERROR) {
6684 status = status2;
6685 }
Eric Laurent65b65452010-06-01 23:49:17 -07006686 }
6687 }
6688 return status;
6689}
6690
Glenn Kastenaccb1142012-01-04 11:00:47 -08006691status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006692{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006693 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006694 status_t status = NO_ERROR;
6695 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006696 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006697 uint32_t size = sizeof(status_t);
6698 status = (*mEffectInterface)->command(mEffectInterface,
6699 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenaccb1142012-01-04 11:00:47 -08006700 sizeof(audio_mode_t),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006701 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006702 &size,
6703 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006704 if (status == NO_ERROR) {
6705 status = cmdStatus;
6706 }
6707 }
6708 return status;
6709}
6710
Eric Laurentf82fccd2011-07-27 19:49:51 -07006711void AudioFlinger::EffectModule::setSuspended(bool suspended)
6712{
6713 Mutex::Autolock _l(mLock);
6714 mSuspended = suspended;
6715}
Glenn Kasten1dce8412012-01-04 11:01:11 -08006716
6717bool AudioFlinger::EffectModule::suspended() const
Eric Laurentf82fccd2011-07-27 19:49:51 -07006718{
6719 Mutex::Autolock _l(mLock);
6720 return mSuspended;
6721}
6722
Eric Laurent65b65452010-06-01 23:49:17 -07006723status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6724{
6725 const size_t SIZE = 256;
6726 char buffer[SIZE];
6727 String8 result;
6728
6729 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6730 result.append(buffer);
6731
6732 bool locked = tryLock(mLock);
6733 // failed to lock - AudioFlinger is probably deadlocked
6734 if (!locked) {
6735 result.append("\t\tCould not lock Fx mutex:\n");
6736 }
6737
6738 result.append("\t\tSession Status State Engine:\n");
6739 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6740 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6741 result.append(buffer);
6742
6743 result.append("\t\tDescriptor:\n");
6744 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6745 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6746 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6747 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6748 result.append(buffer);
6749 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6750 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6751 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6752 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6753 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006754 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006755 mDescriptor.apiVersion,
6756 mDescriptor.flags);
6757 result.append(buffer);
6758 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6759 mDescriptor.name);
6760 result.append(buffer);
6761 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6762 mDescriptor.implementor);
6763 result.append(buffer);
6764
6765 result.append("\t\t- Input configuration:\n");
6766 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6767 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6768 (uint32_t)mConfig.inputCfg.buffer.raw,
6769 mConfig.inputCfg.buffer.frameCount,
6770 mConfig.inputCfg.samplingRate,
6771 mConfig.inputCfg.channels,
6772 mConfig.inputCfg.format);
6773 result.append(buffer);
6774
6775 result.append("\t\t- Output configuration:\n");
6776 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6777 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6778 (uint32_t)mConfig.outputCfg.buffer.raw,
6779 mConfig.outputCfg.buffer.frameCount,
6780 mConfig.outputCfg.samplingRate,
6781 mConfig.outputCfg.channels,
6782 mConfig.outputCfg.format);
6783 result.append(buffer);
6784
6785 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6786 result.append(buffer);
6787 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6788 for (size_t i = 0; i < mHandles.size(); ++i) {
6789 sp<EffectHandle> handle = mHandles[i].promote();
6790 if (handle != 0) {
6791 handle->dump(buffer, SIZE);
6792 result.append(buffer);
6793 }
6794 }
6795
6796 result.append("\n");
6797
6798 write(fd, result.string(), result.length());
6799
6800 if (locked) {
6801 mLock.unlock();
6802 }
6803
6804 return NO_ERROR;
6805}
6806
6807// ----------------------------------------------------------------------------
6808// EffectHandle implementation
6809// ----------------------------------------------------------------------------
6810
6811#undef LOG_TAG
6812#define LOG_TAG "AudioFlinger::EffectHandle"
6813
6814AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6815 const sp<AudioFlinger::Client>& client,
6816 const sp<IEffectClient>& effectClient,
6817 int32_t priority)
6818 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006819 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006820 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006821{
Steve Block71f2cf12011-10-20 11:56:00 +01006822 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006823
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006824 if (client == 0) {
6825 return;
6826 }
Eric Laurent65b65452010-06-01 23:49:17 -07006827 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6828 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6829 if (mCblkMemory != 0) {
6830 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6831
Glenn Kasten3694ec12012-01-27 16:47:15 -08006832 if (mCblk != NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006833 new(mCblk) effect_param_cblk_t();
6834 mBuffer = (uint8_t *)mCblk + bufOffset;
6835 }
6836 } else {
Steve Block3762c312012-01-06 19:20:56 +00006837 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006838 return;
6839 }
6840}
6841
6842AudioFlinger::EffectHandle::~EffectHandle()
6843{
Steve Block71f2cf12011-10-20 11:56:00 +01006844 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006845 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01006846 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006847}
6848
6849status_t AudioFlinger::EffectHandle::enable()
6850{
Steve Block71f2cf12011-10-20 11:56:00 +01006851 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006852 if (!mHasControl) return INVALID_OPERATION;
6853 if (mEffect == 0) return DEAD_OBJECT;
6854
Eric Laurent6752ec82011-08-10 10:37:50 -07006855 if (mEnabled) {
6856 return NO_ERROR;
6857 }
6858
Eric Laurentf82fccd2011-07-27 19:49:51 -07006859 mEnabled = true;
6860
6861 sp<ThreadBase> thread = mEffect->thread().promote();
6862 if (thread != 0) {
6863 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6864 }
6865
6866 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6867 if (mEffect->suspended()) {
6868 return NO_ERROR;
6869 }
6870
Eric Laurent6752ec82011-08-10 10:37:50 -07006871 status_t status = mEffect->setEnabled(true);
6872 if (status != NO_ERROR) {
6873 if (thread != 0) {
6874 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6875 }
6876 mEnabled = false;
6877 }
6878 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006879}
6880
6881status_t AudioFlinger::EffectHandle::disable()
6882{
Steve Block71f2cf12011-10-20 11:56:00 +01006883 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006884 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006885 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006886
Eric Laurent6752ec82011-08-10 10:37:50 -07006887 if (!mEnabled) {
6888 return NO_ERROR;
6889 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006890 mEnabled = false;
6891
6892 if (mEffect->suspended()) {
6893 return NO_ERROR;
6894 }
6895
6896 status_t status = mEffect->setEnabled(false);
6897
6898 sp<ThreadBase> thread = mEffect->thread().promote();
6899 if (thread != 0) {
6900 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6901 }
6902
6903 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006904}
6905
6906void AudioFlinger::EffectHandle::disconnect()
6907{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006908 disconnect(true);
6909}
6910
6911void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6912{
Steve Block71f2cf12011-10-20 11:56:00 +01006913 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006914 if (mEffect == 0) {
6915 return;
6916 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006917 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006918
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006919 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006920 sp<ThreadBase> thread = mEffect->thread().promote();
6921 if (thread != 0) {
6922 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6923 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006924 }
6925
Eric Laurent65b65452010-06-01 23:49:17 -07006926 // release sp on module => module destructor can be called now
6927 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006928 if (mClient != 0) {
Glenn Kasten3694ec12012-01-27 16:47:15 -08006929 if (mCblk != NULL) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006930 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6931 }
6932 mCblkMemory.clear(); // and free the shared memory
Eric Laurent65b65452010-06-01 23:49:17 -07006933 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6934 mClient.clear();
6935 }
6936}
6937
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006938status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6939 uint32_t cmdSize,
6940 void *pCmdData,
6941 uint32_t *replySize,
6942 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006943{
Steve Block71f2cf12011-10-20 11:56:00 +01006944// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006945// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006946
6947 // only get parameter command is permitted for applications not controlling the effect
6948 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6949 return INVALID_OPERATION;
6950 }
6951 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006952 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006953
6954 // handle commands that are not forwarded transparently to effect engine
6955 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6956 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6957 // no risk to block the whole media server process or mixer threads is we are stuck here
6958 Mutex::Autolock _l(mCblk->lock);
6959 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6960 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6961 mCblk->serverIndex = 0;
6962 mCblk->clientIndex = 0;
6963 return BAD_VALUE;
6964 }
6965 status_t status = NO_ERROR;
6966 while (mCblk->serverIndex < mCblk->clientIndex) {
6967 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006968 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006969 int *p = (int *)(mBuffer + mCblk->serverIndex);
6970 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006971 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block8564c8d2012-01-05 23:22:43 +00006972 ALOGW("command(): invalid parameter block size");
Eric Laurent53334cd2010-06-23 17:38:20 -07006973 break;
6974 }
Eric Laurent65b65452010-06-01 23:49:17 -07006975 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006976 if (param->psize == 0 || param->vsize == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006977 ALOGW("command(): null parameter or value size");
Eric Laurent53334cd2010-06-23 17:38:20 -07006978 mCblk->serverIndex += size;
6979 continue;
6980 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006981 uint32_t psize = sizeof(effect_param_t) +
6982 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6983 param->vsize;
6984 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6985 psize,
6986 p,
6987 &rsize,
6988 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006989 // stop at first error encountered
6990 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006991 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006992 *(int *)pReplyData = reply;
6993 break;
6994 } else if (reply != NO_ERROR) {
6995 *(int *)pReplyData = reply;
6996 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006997 }
6998 mCblk->serverIndex += size;
6999 }
7000 mCblk->serverIndex = 0;
7001 mCblk->clientIndex = 0;
7002 return status;
7003 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07007004 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007005 return enable();
7006 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07007007 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007008 return disable();
7009 }
7010
7011 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7012}
7013
Eric Laurentf82fccd2011-07-27 19:49:51 -07007014void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07007015{
Steve Block71f2cf12011-10-20 11:56:00 +01007016 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07007017
7018 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007019 mEnabled = enabled;
7020
Eric Laurent65b65452010-06-01 23:49:17 -07007021 if (signal && mEffectClient != 0) {
7022 mEffectClient->controlStatusChanged(hasControl);
7023 }
7024}
7025
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007026void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7027 uint32_t cmdSize,
7028 void *pCmdData,
7029 uint32_t replySize,
7030 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007031{
7032 if (mEffectClient != 0) {
7033 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7034 }
7035}
7036
7037
7038
7039void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7040{
7041 if (mEffectClient != 0) {
7042 mEffectClient->enableStatusChanged(enabled);
7043 }
7044}
7045
7046status_t AudioFlinger::EffectHandle::onTransact(
7047 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7048{
7049 return BnEffect::onTransact(code, data, reply, flags);
7050}
7051
7052
7053void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7054{
Glenn Kasten3694ec12012-01-27 16:47:15 -08007055 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Eric Laurent65b65452010-06-01 23:49:17 -07007056
7057 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7058 (mClient == NULL) ? getpid() : mClient->pid(),
7059 mPriority,
7060 mHasControl,
7061 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007062 mCblk ? mCblk->clientIndex : 0,
7063 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007064 );
7065
7066 if (locked) {
7067 mCblk->lock.unlock();
7068 }
7069}
7070
7071#undef LOG_TAG
7072#define LOG_TAG "AudioFlinger::EffectChain"
7073
7074AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7075 int sessionId)
Eric Laurentf9c361d2011-11-11 15:42:52 -08007076 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007077 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7078 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007079{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007080 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007081 sp<ThreadBase> thread = mThread.promote();
7082 if (thread == 0) {
7083 return;
7084 }
7085 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7086 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007087}
7088
7089AudioFlinger::EffectChain::~EffectChain()
7090{
7091 if (mOwnInBuffer) {
7092 delete mInBuffer;
7093 }
7094
7095}
7096
Eric Laurentf82fccd2011-07-27 19:49:51 -07007097// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007098sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007099{
7100 sp<EffectModule> effect;
7101 size_t size = mEffects.size();
7102
7103 for (size_t i = 0; i < size; i++) {
7104 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7105 effect = mEffects[i];
7106 break;
7107 }
7108 }
7109 return effect;
7110}
7111
Eric Laurentf82fccd2011-07-27 19:49:51 -07007112// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007113sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007114{
7115 sp<EffectModule> effect;
7116 size_t size = mEffects.size();
7117
7118 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007119 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7120 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07007121 effect = mEffects[i];
7122 break;
7123 }
7124 }
7125 return effect;
7126}
7127
Eric Laurentf82fccd2011-07-27 19:49:51 -07007128// getEffectFromType_l() must be called with ThreadBase::mLock held
7129sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7130 const effect_uuid_t *type)
7131{
7132 sp<EffectModule> effect;
7133 size_t size = mEffects.size();
7134
7135 for (size_t i = 0; i < size; i++) {
7136 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7137 effect = mEffects[i];
7138 break;
7139 }
7140 }
7141 return effect;
7142}
7143
Eric Laurent65b65452010-06-01 23:49:17 -07007144// Must be called with EffectChain::mLock locked
7145void AudioFlinger::EffectChain::process_l()
7146{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007147 sp<ThreadBase> thread = mThread.promote();
7148 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007149 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007150 return;
7151 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007152 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7153 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007154 // always process effects unless no more tracks are on the session and the effect tail
7155 // has been rendered
7156 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007157 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007158 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007159
Eric Laurentf9c361d2011-11-11 15:42:52 -08007160 if (!tracksOnSession && mTailBufferCount == 0) {
7161 doProcess = false;
7162 }
7163
7164 if (activeTrackCnt() == 0) {
7165 // if no track is active and the effect tail has not been rendered,
7166 // the input buffer must be cleared here as the mixer process will not do it
7167 if (tracksOnSession || mTailBufferCount > 0) {
7168 size_t numSamples = thread->frameCount() * thread->channelCount();
7169 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7170 if (mTailBufferCount > 0) {
7171 mTailBufferCount--;
7172 }
7173 }
7174 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007175 }
7176
Eric Laurent65b65452010-06-01 23:49:17 -07007177 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007178 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007179 for (size_t i = 0; i < size; i++) {
7180 mEffects[i]->process();
7181 }
Eric Laurent65b65452010-06-01 23:49:17 -07007182 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007183 for (size_t i = 0; i < size; i++) {
7184 mEffects[i]->updateState();
7185 }
Eric Laurent65b65452010-06-01 23:49:17 -07007186}
7187
Eric Laurent76c40f72010-07-15 12:50:15 -07007188// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007189status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007190{
7191 effect_descriptor_t desc = effect->desc();
7192 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7193
7194 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007195 effect->setChain(this);
7196 sp<ThreadBase> thread = mThread.promote();
7197 if (thread == 0) {
7198 return NO_INIT;
7199 }
7200 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007201
7202 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7203 // Auxiliary effects are inserted at the beginning of mEffects vector as
7204 // they are processed first and accumulated in chain input buffer
7205 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007206
Eric Laurent65b65452010-06-01 23:49:17 -07007207 // the input buffer for auxiliary effect contains mono samples in
7208 // 32 bit format. This is to avoid saturation in AudoMixer
7209 // accumulation stage. Saturation is done in EffectModule::process() before
7210 // calling the process in effect engine
7211 size_t numSamples = thread->frameCount();
7212 int32_t *buffer = new int32_t[numSamples];
7213 memset(buffer, 0, numSamples * sizeof(int32_t));
7214 effect->setInBuffer((int16_t *)buffer);
7215 // auxiliary effects output samples to chain input buffer for further processing
7216 // by insert effects
7217 effect->setOutBuffer(mInBuffer);
7218 } else {
7219 // Insert effects are inserted at the end of mEffects vector as they are processed
7220 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007221 // Insert effect order as a function of indicated preference:
7222 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7223 // another effect is present
7224 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7225 // last effect claiming first position
7226 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7227 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007228 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007229 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7230 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007231
7232 int size = (int)mEffects.size();
7233 int idx_insert = size;
7234 int idx_insert_first = -1;
7235 int idx_insert_last = -1;
7236
7237 for (int i = 0; i < size; i++) {
7238 effect_descriptor_t d = mEffects[i]->desc();
7239 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7240 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7241 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7242 // check invalid effect chaining combinations
7243 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007244 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block8564c8d2012-01-05 23:22:43 +00007245 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007246 return INVALID_OPERATION;
7247 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007248 // remember position of first insert effect and by default
7249 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007250 if (idx_insert == size) {
7251 idx_insert = i;
7252 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007253 // remember position of last insert effect claiming
7254 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007255 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7256 idx_insert_first = i;
7257 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007258 // remember position of first insert effect claiming
7259 // last position
7260 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7261 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007262 idx_insert_last = i;
7263 }
7264 }
7265 }
7266
Eric Laurent53334cd2010-06-23 17:38:20 -07007267 // modify idx_insert from first position if needed
7268 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7269 if (idx_insert_last != -1) {
7270 idx_insert = idx_insert_last;
7271 } else {
7272 idx_insert = size;
7273 }
7274 } else {
7275 if (idx_insert_first != -1) {
7276 idx_insert = idx_insert_first + 1;
7277 }
Eric Laurent65b65452010-06-01 23:49:17 -07007278 }
7279
7280 // always read samples from chain input buffer
7281 effect->setInBuffer(mInBuffer);
7282
7283 // if last effect in the chain, output samples to chain
7284 // output buffer, otherwise to chain input buffer
7285 if (idx_insert == size) {
7286 if (idx_insert != 0) {
7287 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7288 mEffects[idx_insert-1]->configure();
7289 }
7290 effect->setOutBuffer(mOutBuffer);
7291 } else {
7292 effect->setOutBuffer(mInBuffer);
7293 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007294 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007295
Steve Block71f2cf12011-10-20 11:56:00 +01007296 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007297 }
7298 effect->configure();
7299 return NO_ERROR;
7300}
7301
Eric Laurent76c40f72010-07-15 12:50:15 -07007302// removeEffect_l() must be called with PlaybackThread::mLock held
7303size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007304{
7305 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007306 int size = (int)mEffects.size();
7307 int i;
7308 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7309
7310 for (i = 0; i < size; i++) {
7311 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007312 // calling stop here will remove pre-processing effect from the audio HAL.
7313 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7314 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007315 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7316 mEffects[i]->state() == EffectModule::STOPPING) {
7317 mEffects[i]->stop();
7318 }
Eric Laurent65b65452010-06-01 23:49:17 -07007319 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7320 delete[] effect->inBuffer();
7321 } else {
7322 if (i == size - 1 && i != 0) {
7323 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7324 mEffects[i - 1]->configure();
7325 }
7326 }
7327 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007328 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007329 break;
7330 }
7331 }
Eric Laurent65b65452010-06-01 23:49:17 -07007332
7333 return mEffects.size();
7334}
7335
Eric Laurent76c40f72010-07-15 12:50:15 -07007336// setDevice_l() must be called with PlaybackThread::mLock held
7337void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007338{
7339 size_t size = mEffects.size();
7340 for (size_t i = 0; i < size; i++) {
7341 mEffects[i]->setDevice(device);
7342 }
7343}
7344
Eric Laurent76c40f72010-07-15 12:50:15 -07007345// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenaccb1142012-01-04 11:00:47 -08007346void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007347{
7348 size_t size = mEffects.size();
7349 for (size_t i = 0; i < size; i++) {
7350 mEffects[i]->setMode(mode);
7351 }
7352}
7353
Eric Laurent76c40f72010-07-15 12:50:15 -07007354// setVolume_l() must be called with PlaybackThread::mLock held
7355bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007356{
7357 uint32_t newLeft = *left;
7358 uint32_t newRight = *right;
7359 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007360 int ctrlIdx = -1;
7361 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007362
Eric Laurent76c40f72010-07-15 12:50:15 -07007363 // first update volume controller
7364 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007365 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007366 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7367 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007368 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007369 break;
7370 }
7371 }
7372
7373 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007374 if (hasControl) {
7375 *left = mNewLeftVolume;
7376 *right = mNewRightVolume;
7377 }
7378 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007379 }
7380
7381 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007382 mLeftVolume = newLeft;
7383 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007384
7385 // second get volume update from volume controller
7386 if (ctrlIdx >= 0) {
7387 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007388 mNewLeftVolume = newLeft;
7389 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007390 }
7391 // then indicate volume to all other effects in chain.
7392 // Pass altered volume to effects before volume controller
7393 // and requested volume to effects after controller
7394 uint32_t lVol = newLeft;
7395 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007396
Eric Laurent65b65452010-06-01 23:49:17 -07007397 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007398 if ((int)i == ctrlIdx) continue;
7399 // this also works for ctrlIdx == -1 when there is no volume controller
7400 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007401 lVol = *left;
7402 rVol = *right;
7403 }
7404 mEffects[i]->setVolume(&lVol, &rVol, false);
7405 }
7406 *left = newLeft;
7407 *right = newRight;
7408
7409 return hasControl;
7410}
7411
Eric Laurent65b65452010-06-01 23:49:17 -07007412status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7413{
7414 const size_t SIZE = 256;
7415 char buffer[SIZE];
7416 String8 result;
7417
7418 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7419 result.append(buffer);
7420
7421 bool locked = tryLock(mLock);
7422 // failed to lock - AudioFlinger is probably deadlocked
7423 if (!locked) {
7424 result.append("\tCould not lock mutex:\n");
7425 }
7426
Eric Laurent76c40f72010-07-15 12:50:15 -07007427 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7428 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007429 mEffects.size(),
7430 (uint32_t)mInBuffer,
7431 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007432 mActiveTrackCnt);
7433 result.append(buffer);
7434 write(fd, result.string(), result.size());
7435
7436 for (size_t i = 0; i < mEffects.size(); ++i) {
7437 sp<EffectModule> effect = mEffects[i];
7438 if (effect != 0) {
7439 effect->dump(fd, args);
7440 }
7441 }
7442
7443 if (locked) {
7444 mLock.unlock();
7445 }
7446
7447 return NO_ERROR;
7448}
7449
Eric Laurentf82fccd2011-07-27 19:49:51 -07007450// must be called with ThreadBase::mLock held
7451void AudioFlinger::EffectChain::setEffectSuspended_l(
7452 const effect_uuid_t *type, bool suspend)
7453{
7454 sp<SuspendedEffectDesc> desc;
7455 // use effect type UUID timelow as key as there is no real risk of identical
7456 // timeLow fields among effect type UUIDs.
7457 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7458 if (suspend) {
7459 if (index >= 0) {
7460 desc = mSuspendedEffects.valueAt(index);
7461 } else {
7462 desc = new SuspendedEffectDesc();
7463 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7464 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007465 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007466 }
7467 if (desc->mRefCount++ == 0) {
7468 sp<EffectModule> effect = getEffectIfEnabled(type);
7469 if (effect != 0) {
7470 desc->mEffect = effect;
7471 effect->setSuspended(true);
7472 effect->setEnabled(false);
7473 }
7474 }
7475 } else {
7476 if (index < 0) {
7477 return;
7478 }
7479 desc = mSuspendedEffects.valueAt(index);
7480 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007481 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007482 desc->mRefCount = 1;
7483 }
7484 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007485 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007486 if (desc->mEffect != 0) {
7487 sp<EffectModule> effect = desc->mEffect.promote();
7488 if (effect != 0) {
7489 effect->setSuspended(false);
7490 sp<EffectHandle> handle = effect->controlHandle();
7491 if (handle != 0) {
7492 effect->setEnabled(handle->enabled());
7493 }
7494 }
7495 desc->mEffect.clear();
7496 }
7497 mSuspendedEffects.removeItemsAt(index);
7498 }
7499 }
7500}
7501
7502// must be called with ThreadBase::mLock held
7503void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7504{
7505 sp<SuspendedEffectDesc> desc;
7506
7507 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7508 if (suspend) {
7509 if (index >= 0) {
7510 desc = mSuspendedEffects.valueAt(index);
7511 } else {
7512 desc = new SuspendedEffectDesc();
7513 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007514 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007515 }
7516 if (desc->mRefCount++ == 0) {
Glenn Kasten97040262012-01-30 12:56:03 -08007517 Vector< sp<EffectModule> > effects;
7518 getSuspendEligibleEffects(effects);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007519 for (size_t i = 0; i < effects.size(); i++) {
7520 setEffectSuspended_l(&effects[i]->desc().type, true);
7521 }
7522 }
7523 } else {
7524 if (index < 0) {
7525 return;
7526 }
7527 desc = mSuspendedEffects.valueAt(index);
7528 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007529 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007530 desc->mRefCount = 1;
7531 }
7532 if (--desc->mRefCount == 0) {
7533 Vector<const effect_uuid_t *> types;
7534 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7535 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7536 continue;
7537 }
7538 types.add(&mSuspendedEffects.valueAt(i)->mType);
7539 }
7540 for (size_t i = 0; i < types.size(); i++) {
7541 setEffectSuspended_l(types[i], false);
7542 }
Steve Block71f2cf12011-10-20 11:56:00 +01007543 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007544 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7545 }
7546 }
7547}
7548
Eric Laurent5e7acae2011-09-23 08:40:41 -07007549
7550// The volume effect is used for automated tests only
7551#ifndef OPENSL_ES_H_
7552static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7553 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7554const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7555#endif //OPENSL_ES_H_
7556
Eric Laurent6752ec82011-08-10 10:37:50 -07007557bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7558{
7559 // auxiliary effects and visualizer are never suspended on output mix
7560 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7561 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007562 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7563 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007564 return false;
7565 }
7566 return true;
7567}
7568
Glenn Kasten97040262012-01-30 12:56:03 -08007569void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurentf82fccd2011-07-27 19:49:51 -07007570{
Glenn Kasten97040262012-01-30 12:56:03 -08007571 effects.clear();
Eric Laurentf82fccd2011-07-27 19:49:51 -07007572 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kasten97040262012-01-30 12:56:03 -08007573 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7574 effects.add(mEffects[i]);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007575 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007576 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007577}
7578
7579sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7580 const effect_uuid_t *type)
7581{
7582 sp<EffectModule> effect;
7583 effect = getEffectFromType_l(type);
7584 if (effect != 0 && !effect->isEnabled()) {
7585 effect.clear();
7586 }
7587 return effect;
7588}
7589
7590void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7591 bool enabled)
7592{
7593 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7594 if (enabled) {
7595 if (index < 0) {
7596 // if the effect is not suspend check if all effects are suspended
7597 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7598 if (index < 0) {
7599 return;
7600 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007601 if (!isEffectEligibleForSuspend(effect->desc())) {
7602 return;
7603 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007604 setEffectSuspended_l(&effect->desc().type, enabled);
7605 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007606 if (index < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007607 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurent6752ec82011-08-10 10:37:50 -07007608 return;
7609 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007610 }
Steve Block71f2cf12011-10-20 11:56:00 +01007611 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007612 effect->desc().type.timeLow);
7613 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7614 // if effect is requested to suspended but was not yet enabled, supend it now.
7615 if (desc->mEffect == 0) {
7616 desc->mEffect = effect;
7617 effect->setEnabled(false);
7618 effect->setSuspended(true);
7619 }
7620 } else {
7621 if (index < 0) {
7622 return;
7623 }
Steve Block71f2cf12011-10-20 11:56:00 +01007624 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007625 effect->desc().type.timeLow);
7626 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7627 desc->mEffect.clear();
7628 effect->setSuspended(false);
7629 }
7630}
7631
Eric Laurent65b65452010-06-01 23:49:17 -07007632#undef LOG_TAG
7633#define LOG_TAG "AudioFlinger"
7634
Eric Laurenta553c252009-07-17 12:17:14 -07007635// ----------------------------------------------------------------------------
7636
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007637status_t AudioFlinger::onTransact(
7638 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7639{
7640 return BnAudioFlinger::onTransact(code, data, reply, flags);
7641}
7642
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007643}; // namespace android