blob: 43b724537fd86a5e8d03d39052cee4c2b425c03d [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 }
Glenn Kasten706b6182012-01-20 13:44:40 -0800812 if (thread != 0) {
813 return thread->setParameters(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700814 }
Eric Laurenta553c252009-07-17 12:17:14 -0700815 return BAD_VALUE;
816}
817
Glenn Kasten3f6d83a2012-01-26 16:25:10 -0800818String8 AudioFlinger::getParameters(int ioHandle, const String8& keys) const
Eric Laurenta553c252009-07-17 12:17:14 -0700819{
Steve Block71f2cf12011-10-20 11:56:00 +0100820// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700821// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
822
823 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700824 String8 out_s8;
825
Dima Zavin31f188892011-04-18 16:57:27 -0700826 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
827 audio_hw_device_t *dev = mAudioHwDevs[i];
828 char *s = dev->get_parameters(dev, keys.string());
829 out_s8 += String8(s);
830 free(s);
831 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700832 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700833 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700834
835 Mutex::Autolock _l(mLock);
836
Eric Laurenta553c252009-07-17 12:17:14 -0700837 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
838 if (playbackThread != NULL) {
839 return playbackThread->getParameters(keys);
840 }
841 RecordThread *recordThread = checkRecordThread_l(ioHandle);
842 if (recordThread != NULL) {
843 return recordThread->getParameters(keys);
844 }
845 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700846}
847
Glenn Kasten3f6d83a2012-01-26 16:25:10 -0800848size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700850 status_t ret = initCheck();
851 if (ret != NO_ERROR) {
852 return 0;
853 }
854
Dima Zavin31f188892011-04-18 16:57:27 -0700855 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856}
857
Glenn Kasten3f6d83a2012-01-26 16:25:10 -0800858unsigned int AudioFlinger::getInputFramesLost(int ioHandle) const
Eric Laurent47d0a922010-02-26 02:47:27 -0800859{
860 if (ioHandle == 0) {
861 return 0;
862 }
863
864 Mutex::Autolock _l(mLock);
865
866 RecordThread *recordThread = checkRecordThread_l(ioHandle);
867 if (recordThread != NULL) {
868 return recordThread->getInputFramesLost();
869 }
870 return 0;
871}
872
Eric Laurent415f3e22009-10-21 08:14:22 -0700873status_t AudioFlinger::setVoiceVolume(float value)
874{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700875 status_t ret = initCheck();
876 if (ret != NO_ERROR) {
877 return ret;
878 }
879
Eric Laurent415f3e22009-10-21 08:14:22 -0700880 // check calling permissions
881 if (!settingsAllowed()) {
882 return PERMISSION_DENIED;
883 }
884
885 AutoMutex lock(mHardwareLock);
886 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700887 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700888 mHardwareStatus = AUDIO_HW_IDLE;
889
890 return ret;
891}
892
Glenn Kasten3f6d83a2012-01-26 16:25:10 -0800893status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output) const
Eric Laurent0986e792010-01-19 17:37:09 -0800894{
895 status_t status;
896
897 Mutex::Autolock _l(mLock);
898
899 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
900 if (playbackThread != NULL) {
901 return playbackThread->getRenderPosition(halFrames, dspFrames);
902 }
903
904 return BAD_VALUE;
905}
906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
908{
Eric Laurenta553c252009-07-17 12:17:14 -0700909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 Mutex::Autolock _l(mLock);
911
Glenn Kastend153b1f2012-02-03 11:10:26 -0800912 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700913 if (mNotificationClients.indexOfKey(pid) < 0) {
914 sp<NotificationClient> notificationClient = new NotificationClient(this,
915 client,
916 pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100917 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700918
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700919 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700920
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700921 sp<IBinder> binder = client->asBinder();
922 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700924 // the config change is always sent from playback or record threads to avoid deadlock
925 // with AudioSystem::gLock
926 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
927 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
928 }
Eric Laurenta553c252009-07-17 12:17:14 -0700929
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700930 for (size_t i = 0; i < mRecordThreads.size(); i++) {
931 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 }
933 }
934}
935
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700936void AudioFlinger::removeNotificationClient(pid_t pid)
937{
938 Mutex::Autolock _l(mLock);
939
940 int index = mNotificationClients.indexOfKey(pid);
941 if (index >= 0) {
942 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100943 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700944 mNotificationClients.removeItem(pid);
945 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700946
Steve Block71f2cf12011-10-20 11:56:00 +0100947 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700948 int num = mAudioSessionRefs.size();
949 bool removed = false;
950 for (int i = 0; i< num; i++) {
951 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +0100952 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700953 if (ref->pid == pid) {
Steve Block71f2cf12011-10-20 11:56:00 +0100954 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700955 mAudioSessionRefs.removeAt(i);
956 delete ref;
957 removed = true;
958 i--;
959 num--;
960 }
961 }
962 if (removed) {
963 purgeStaleEffects_l();
964 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700965}
966
Eric Laurent296a0ec2009-09-15 07:10:12 -0700967// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700968void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
969{
Eric Laurent49f02be2009-11-19 09:00:56 -0800970 size_t size = mNotificationClients.size();
971 for (size_t i = 0; i < size; i++) {
Glenn Kastendc3ac852012-01-25 15:28:08 -0800972 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
973 param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700974 }
975}
976
Eric Laurentb9481d82009-09-17 05:12:56 -0700977// removeClient_l() must be called with AudioFlinger::mLock held
978void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700979{
Steve Block71f2cf12011-10-20 11:56:00 +0100980 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700981 mClients.removeItem(pid);
982}
983
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700984
Eric Laurenta553c252009-07-17 12:17:14 -0700985// ----------------------------------------------------------------------------
986
Glenn Kastenefd511a2012-01-26 10:38:26 -0800987AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device,
988 type_t type)
Eric Laurenta553c252009-07-17 12:17:14 -0700989 : Thread(false),
Glenn Kastenefd511a2012-01-26 10:38:26 -0800990 mType(type),
Glenn Kastendc3ac852012-01-25 15:28:08 -0800991 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
992 // mChannelMask
993 mChannelCount(0),
994 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
995 mParamStatus(NO_ERROR),
996 mStandby(false), mId(id), mExiting(false),
997 mDevice(device),
998 mDeathRecipient(new PMDeathRecipient(this))
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700999{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000}
1001
Eric Laurenta553c252009-07-17 12:17:14 -07001002AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001004 mParamCond.broadcast();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001005 // do not lock the mutex in destructor
1006 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -07001007 if (mPowerManager != 0) {
1008 sp<IBinder> binder = mPowerManager->asBinder();
1009 binder->unlinkToDeath(mDeathRecipient);
1010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011}
1012
Eric Laurenta553c252009-07-17 12:17:14 -07001013void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001014{
Glenn Kastene5fb2632011-12-14 10:28:06 -08001015 // keep a strong ref on ourself so that we won't get
Eric Laurenta553c252009-07-17 12:17:14 -07001016 // destroyed in the middle of requestExitAndWait()
1017 sp <ThreadBase> strongMe = this;
1018
Steve Block71f2cf12011-10-20 11:56:00 +01001019 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001020 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08001021 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001022 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001023 requestExit();
1024 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001025 }
Eric Laurenta553c252009-07-17 12:17:14 -07001026 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001027}
Eric Laurenta553c252009-07-17 12:17:14 -07001028
Eric Laurenta553c252009-07-17 12:17:14 -07001029status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1030{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001031 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001032
Steve Block71f2cf12011-10-20 11:56:00 +01001033 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001034 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001035
Eric Laurent8fce46a2009-08-04 09:45:33 -07001036 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001037 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001038 // wait condition with timeout in case the thread loop has exited
1039 // before the request could be processed
Glenn Kastencbfe2e12011-12-13 11:04:14 -08001040 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001041 status = mParamStatus;
1042 mWaitWorkCV.signal();
1043 } else {
1044 status = TIMED_OUT;
1045 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001046 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001047}
1048
1049void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1050{
1051 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001052 sendConfigEvent_l(event, param);
1053}
1054
1055// sendConfigEvent_l() must be called with ThreadBase::mLock held
1056void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1057{
Glenn Kasten4b220f02011-12-13 11:50:00 -08001058 ConfigEvent configEvent;
1059 configEvent.mEvent = event;
1060 configEvent.mParam = param;
Eric Laurenta553c252009-07-17 12:17:14 -07001061 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001062 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001063 mWaitWorkCV.signal();
1064}
1065
1066void AudioFlinger::ThreadBase::processConfigEvents()
1067{
1068 mLock.lock();
1069 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001070 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kasten4b220f02011-12-13 11:50:00 -08001071 ConfigEvent configEvent = mConfigEvents[0];
Eric Laurenta553c252009-07-17 12:17:14 -07001072 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001073 // release mLock before locking AudioFlinger mLock: lock order is always
1074 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001075 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001076 mAudioFlinger->mLock.lock();
Glenn Kasten4b220f02011-12-13 11:50:00 -08001077 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001078 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001079 mLock.lock();
1080 }
1081 mLock.unlock();
1082}
1083
Eric Laurent3fdb1262009-11-07 00:01:32 -08001084status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1085{
1086 const size_t SIZE = 256;
1087 char buffer[SIZE];
1088 String8 result;
1089
1090 bool locked = tryLock(mLock);
1091 if (!locked) {
1092 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1093 write(fd, buffer, strlen(buffer));
1094 }
1095
1096 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1097 result.append(buffer);
1098 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1099 result.append(buffer);
1100 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1101 result.append(buffer);
1102 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1103 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001104 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1105 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001106 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1107 result.append(buffer);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001108 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001109 result.append(buffer);
1110
1111 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1112 result.append(buffer);
1113 result.append(" Index Command");
1114 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1115 snprintf(buffer, SIZE, "\n %02d ", i);
1116 result.append(buffer);
1117 result.append(mNewParameters[i]);
1118 }
1119
1120 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1121 result.append(buffer);
1122 snprintf(buffer, SIZE, " Index event param\n");
1123 result.append(buffer);
1124 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kasten4b220f02011-12-13 11:50:00 -08001125 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001126 result.append(buffer);
1127 }
1128 result.append("\n");
1129
1130 write(fd, result.string(), result.size());
1131
1132 if (locked) {
1133 mLock.unlock();
1134 }
1135 return NO_ERROR;
1136}
1137
Eric Laurent1345d332011-07-24 17:49:51 -07001138status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1139{
1140 const size_t SIZE = 256;
1141 char buffer[SIZE];
1142 String8 result;
1143
1144 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1145 write(fd, buffer, strlen(buffer));
1146
1147 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1148 sp<EffectChain> chain = mEffectChains[i];
1149 if (chain != 0) {
1150 chain->dump(fd, args);
1151 }
1152 }
1153 return NO_ERROR;
1154}
1155
Eric Laurent6dbdc402011-07-22 09:04:31 -07001156void AudioFlinger::ThreadBase::acquireWakeLock()
1157{
1158 Mutex::Autolock _l(mLock);
1159 acquireWakeLock_l();
1160}
1161
1162void AudioFlinger::ThreadBase::acquireWakeLock_l()
1163{
1164 if (mPowerManager == 0) {
1165 // use checkService() to avoid blocking if power service is not up yet
1166 sp<IBinder> binder =
1167 defaultServiceManager()->checkService(String16("power"));
1168 if (binder == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00001169 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001170 } else {
1171 mPowerManager = interface_cast<IPowerManager>(binder);
1172 binder->linkToDeath(mDeathRecipient);
1173 }
1174 }
1175 if (mPowerManager != 0) {
1176 sp<IBinder> binder = new BBinder();
1177 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1178 binder,
1179 String16(mName));
1180 if (status == NO_ERROR) {
1181 mWakeLockToken = binder;
1182 }
Steve Block71f2cf12011-10-20 11:56:00 +01001183 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001184 }
1185}
1186
1187void AudioFlinger::ThreadBase::releaseWakeLock()
1188{
1189 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001190 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001191}
1192
1193void AudioFlinger::ThreadBase::releaseWakeLock_l()
1194{
1195 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001196 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001197 if (mPowerManager != 0) {
1198 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1199 }
1200 mWakeLockToken.clear();
1201 }
1202}
1203
1204void AudioFlinger::ThreadBase::clearPowerManager()
1205{
1206 Mutex::Autolock _l(mLock);
1207 releaseWakeLock_l();
1208 mPowerManager.clear();
1209}
1210
1211void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1212{
1213 sp<ThreadBase> thread = mThread.promote();
1214 if (thread != 0) {
1215 thread->clearPowerManager();
1216 }
Steve Block8564c8d2012-01-05 23:22:43 +00001217 ALOGW("power manager service died !!!");
Eric Laurent6dbdc402011-07-22 09:04:31 -07001218}
Eric Laurent1345d332011-07-24 17:49:51 -07001219
Eric Laurentf82fccd2011-07-27 19:49:51 -07001220void AudioFlinger::ThreadBase::setEffectSuspended(
1221 const effect_uuid_t *type, bool suspend, int sessionId)
1222{
1223 Mutex::Autolock _l(mLock);
1224 setEffectSuspended_l(type, suspend, sessionId);
1225}
1226
1227void AudioFlinger::ThreadBase::setEffectSuspended_l(
1228 const effect_uuid_t *type, bool suspend, int sessionId)
1229{
Glenn Kastenc64a6f02012-01-30 13:00:02 -08001230 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001231 if (chain != 0) {
1232 if (type != NULL) {
1233 chain->setEffectSuspended_l(type, suspend);
1234 } else {
1235 chain->setEffectSuspendedAll_l(suspend);
1236 }
1237 }
1238
1239 updateSuspendedSessions_l(type, suspend, sessionId);
1240}
1241
1242void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1243{
1244 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1245 if (index < 0) {
1246 return;
1247 }
1248
1249 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1250 mSuspendedSessions.editValueAt(index);
1251
1252 for (size_t i = 0; i < sessionEffects.size(); i++) {
1253 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1254 for (int j = 0; j < desc->mRefCount; j++) {
1255 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1256 chain->setEffectSuspendedAll_l(true);
1257 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001258 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001259 desc->mType.timeLow);
1260 chain->setEffectSuspended_l(&desc->mType, true);
1261 }
1262 }
1263 }
1264}
1265
Eric Laurentf82fccd2011-07-27 19:49:51 -07001266void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1267 bool suspend,
1268 int sessionId)
1269{
1270 int index = mSuspendedSessions.indexOfKey(sessionId);
1271
1272 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1273
1274 if (suspend) {
1275 if (index >= 0) {
1276 sessionEffects = mSuspendedSessions.editValueAt(index);
1277 } else {
1278 mSuspendedSessions.add(sessionId, sessionEffects);
1279 }
1280 } else {
1281 if (index < 0) {
1282 return;
1283 }
1284 sessionEffects = mSuspendedSessions.editValueAt(index);
1285 }
1286
1287
1288 int key = EffectChain::kKeyForSuspendAll;
1289 if (type != NULL) {
1290 key = type->timeLow;
1291 }
1292 index = sessionEffects.indexOfKey(key);
1293
1294 sp <SuspendedSessionDesc> desc;
1295 if (suspend) {
1296 if (index >= 0) {
1297 desc = sessionEffects.valueAt(index);
1298 } else {
1299 desc = new SuspendedSessionDesc();
1300 if (type != NULL) {
1301 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1302 }
1303 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001304 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001305 }
1306 desc->mRefCount++;
1307 } else {
1308 if (index < 0) {
1309 return;
1310 }
1311 desc = sessionEffects.valueAt(index);
1312 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001313 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001314 sessionEffects.removeItemsAt(index);
1315 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001316 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001317 sessionId);
1318 mSuspendedSessions.removeItem(sessionId);
1319 }
1320 }
1321 }
1322 if (!sessionEffects.isEmpty()) {
1323 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1324 }
1325}
1326
1327void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1328 bool enabled,
1329 int sessionId)
1330{
1331 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001332 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1333}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001334
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001335void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1336 bool enabled,
1337 int sessionId)
1338{
Eric Laurent6752ec82011-08-10 10:37:50 -07001339 if (mType != RECORD) {
1340 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1341 // another session. This gives the priority to well behaved effect control panels
1342 // and applications not using global effects.
1343 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1344 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1345 }
1346 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001347
1348 sp<EffectChain> chain = getEffectChain_l(sessionId);
1349 if (chain != 0) {
1350 chain->checkSuspendOnEffectEnabled(effect, enabled);
1351 }
1352}
1353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354// ----------------------------------------------------------------------------
1355
Eric Laurent464d5b32011-06-17 21:29:58 -07001356AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1357 AudioStreamOut* output,
1358 int id,
Glenn Kastenefd511a2012-01-26 10:38:26 -08001359 uint32_t device,
1360 type_t type)
1361 : ThreadBase(audioFlinger, id, device, type),
Glenn Kastendc3ac852012-01-25 15:28:08 -08001362 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1363 // Assumes constructor is called by AudioFlinger with it's mLock held,
1364 // but it would be safer to explicitly pass initial masterMute as parameter
1365 mMasterMute(audioFlinger->masterMute_l()),
1366 // mStreamTypes[] initialized in constructor body
1367 mOutput(output),
1368 // Assumes constructor is called by AudioFlinger with it's mLock held,
1369 // but it would be safer to explicitly pass initial masterVolume as parameter
1370 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent464d5b32011-06-17 21:29:58 -07001371 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001373 snprintf(mName, kNameLength, "AudioOut_%d", id);
1374
Eric Laurenta553c252009-07-17 12:17:14 -07001375 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376
Glenn Kasten6e987a42012-01-06 08:40:01 -08001377 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001378 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1379 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1380 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001381 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1382 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten6e987a42012-01-06 08:40:01 -08001383 // initialized by stream_type_t default constructor
1384 // mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386}
1387
Eric Laurenta553c252009-07-17 12:17:14 -07001388AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389{
1390 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391}
1392
Eric Laurenta553c252009-07-17 12:17:14 -07001393status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394{
1395 dumpInternals(fd, args);
1396 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001397 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 return NO_ERROR;
1399}
1400
Eric Laurenta553c252009-07-17 12:17:14 -07001401status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402{
1403 const size_t SIZE = 256;
1404 char buffer[SIZE];
1405 String8 result;
1406
Eric Laurenta553c252009-07-17 12:17:14 -07001407 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001409 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 -08001410 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001411 sp<Track> track = mTracks[i];
1412 if (track != 0) {
1413 track->dump(buffer, SIZE);
1414 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 }
1416 }
1417
Eric Laurenta553c252009-07-17 12:17:14 -07001418 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001420 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 -08001421 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kastene4787422012-01-25 14:27:41 -08001422 sp<Track> track = mActiveTracks[i].promote();
1423 if (track != 0) {
1424 track->dump(buffer, SIZE);
1425 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
1427 }
1428 write(fd, result.string(), result.size());
1429 return NO_ERROR;
1430}
1431
Eric Laurenta553c252009-07-17 12:17:14 -07001432status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433{
1434 const size_t SIZE = 256;
1435 char buffer[SIZE];
1436 String8 result;
1437
Eric Laurent3fdb1262009-11-07 00:01:32 -08001438 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 result.append(buffer);
1440 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1441 result.append(buffer);
1442 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1443 result.append(buffer);
1444 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1445 result.append(buffer);
1446 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1447 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001448 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1449 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001450 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1451 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001453
1454 dumpBase(fd, args);
1455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 return NO_ERROR;
1457}
1458
1459// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001460status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461{
Eric Laurent828b9772011-08-07 16:32:26 -07001462 status_t status = initCheck();
1463 if (status == NO_ERROR) {
Steve Block6215d3f2012-01-04 20:05:49 +00001464 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurent828b9772011-08-07 16:32:26 -07001465 } else {
Steve Block3762c312012-01-06 19:20:56 +00001466 ALOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
Eric Laurent828b9772011-08-07 16:32:26 -07001468 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469}
1470
Eric Laurenta553c252009-07-17 12:17:14 -07001471void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001473 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474}
1475
Eric Laurenta553c252009-07-17 12:17:14 -07001476// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1477sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 const sp<AudioFlinger::Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001479 audio_stream_type_t streamType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08001481 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001482 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 int frameCount,
1484 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001485 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 status_t *status)
1487{
1488 sp<Track> track;
1489 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001490
1491 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001492 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1493 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block3762c312012-01-06 19:20:56 +00001494 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001495 "for output %p with format %d",
1496 sampleRate, format, channelMask, mOutput, mFormat);
1497 lStatus = BAD_VALUE;
1498 goto Exit;
1499 }
Eric Laurenta553c252009-07-17 12:17:14 -07001500 }
1501 } else {
1502 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1503 if (sampleRate > mSampleRate*2) {
Steve Block3762c312012-01-06 19:20:56 +00001504 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Eric Laurenta553c252009-07-17 12:17:14 -07001505 lStatus = BAD_VALUE;
1506 goto Exit;
1507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 }
1509
Eric Laurent464d5b32011-06-17 21:29:58 -07001510 lStatus = initCheck();
1511 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00001512 ALOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001513 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
1515
Eric Laurenta553c252009-07-17 12:17:14 -07001516 { // scope for mLock
1517 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001518
1519 // all tracks in same audio session must share the same routing strategy otherwise
1520 // conflicts will happen when tracks are moved from one output to another by audio policy
1521 // manager
1522 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001523 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001524 for (size_t i = 0; i < mTracks.size(); ++i) {
1525 sp<Track> t = mTracks[i];
1526 if (t != 0) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001527 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1528 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block3762c312012-01-06 19:20:56 +00001529 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001530 strategy, actual);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001531 lStatus = BAD_VALUE;
1532 goto Exit;
1533 }
1534 }
1535 }
1536
Eric Laurenta553c252009-07-17 12:17:14 -07001537 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001538 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001539 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001540 lStatus = NO_MEMORY;
1541 goto Exit;
1542 }
1543 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001544
1545 sp<EffectChain> chain = getEffectChain_l(sessionId);
1546 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001547 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001548 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001549 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001550 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001551 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001552
1553 // invalidate track immediately if the stream type was moved to another thread since
1554 // createTrack() was called by the client process.
1555 if (!mStreamTypes[streamType].valid) {
Steve Block8564c8d2012-01-05 23:22:43 +00001556 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07001557 this, streamType);
1558 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1559 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001560 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001561 lStatus = NO_ERROR;
1562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563Exit:
1564 if(status) {
1565 *status = lStatus;
1566 }
1567 return track;
1568}
1569
Eric Laurenta553c252009-07-17 12:17:14 -07001570uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571{
Eric Laurent828b9772011-08-07 16:32:26 -07001572 Mutex::Autolock _l(mLock);
1573 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001574 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001575 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 return 0;
1577 }
1578}
1579
Eric Laurenta553c252009-07-17 12:17:14 -07001580status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581{
1582 mMasterVolume = value;
1583 return NO_ERROR;
1584}
1585
Eric Laurenta553c252009-07-17 12:17:14 -07001586status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587{
1588 mMasterMute = muted;
1589 return NO_ERROR;
1590}
1591
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001592status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593{
1594 mStreamTypes[stream].volume = value;
1595 return NO_ERROR;
1596}
1597
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001598status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599{
1600 mStreamTypes[stream].mute = muted;
1601 return NO_ERROR;
1602}
1603
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001604float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605{
1606 return mStreamTypes[stream].volume;
1607}
1608
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001609bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610{
1611 return mStreamTypes[stream].mute;
1612}
1613
Eric Laurenta553c252009-07-17 12:17:14 -07001614// addTrack_l() must be called with ThreadBase::mLock held
1615status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616{
1617 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001618
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001619 // set retry count for buffer fill
1620 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001621 if (mActiveTracks.indexOf(track) < 0) {
1622 // the track is newly added, make sure it fills up all its
1623 // buffers before playing. This is to ensure the client will
1624 // effectively get the latency it requested.
1625 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001626 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001627 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001628 if (track->mainBuffer() != mMixBuffer) {
1629 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1630 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001631 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001632 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001633 }
1634 }
1635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001637 }
Eric Laurenta553c252009-07-17 12:17:14 -07001638
Steve Block71f2cf12011-10-20 11:56:00 +01001639 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001640 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641
1642 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001643}
1644
Eric Laurenta553c252009-07-17 12:17:14 -07001645// destroyTrack_l() must be called with ThreadBase::mLock held
1646void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001647{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001648 track->mState = TrackBase::TERMINATED;
1649 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001650 removeTrack_l(track);
1651 }
1652}
1653
1654void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1655{
1656 mTracks.remove(track);
1657 deleteTrackName_l(track->name());
1658 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1659 if (chain != 0) {
1660 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001661 }
1662}
1663
Eric Laurenta553c252009-07-17 12:17:14 -07001664String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001665{
Eric Laurent828b9772011-08-07 16:32:26 -07001666 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001667 char *s;
1668
Eric Laurent828b9772011-08-07 16:32:26 -07001669 Mutex::Autolock _l(mLock);
1670 if (initCheck() != NO_ERROR) {
1671 return out_s8;
1672 }
1673
Dima Zavin31f188892011-04-18 16:57:27 -07001674 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001675 out_s8 = String8(s);
1676 free(s);
1677 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001678}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001679
Eric Laurent828b9772011-08-07 16:32:26 -07001680// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001681void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001682 AudioSystem::OutputDescriptor desc;
Glenn Kasten3694ec12012-01-27 16:47:15 -08001683 void *param2 = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07001684
Steve Block71f2cf12011-10-20 11:56:00 +01001685 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001686
1687 switch (event) {
1688 case AudioSystem::OUTPUT_OPENED:
1689 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001690 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001691 desc.samplingRate = mSampleRate;
1692 desc.format = mFormat;
1693 desc.frameCount = mFrameCount;
1694 desc.latency = latency();
1695 param2 = &desc;
1696 break;
1697
1698 case AudioSystem::STREAM_CONFIG_CHANGED:
1699 param2 = &param;
1700 case AudioSystem::OUTPUT_CLOSED:
1701 default:
1702 break;
1703 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001704 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001705}
1706
1707void AudioFlinger::PlaybackThread::readOutputParameters()
1708{
Dima Zavin31f188892011-04-18 16:57:27 -07001709 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001710 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1711 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001712 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001713 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin31f188892011-04-18 16:57:27 -07001714 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001715
Eric Laurenta553c252009-07-17 12:17:14 -07001716 // FIXME - Current mixer implementation only supports stereo output: Always
1717 // Allocate a stereo buffer even if HW output is mono.
Glenn Kasten2589cf92012-01-27 18:08:45 -08001718 delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001719 mMixBuffer = new int16_t[mFrameCount * 2];
1720 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001721
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001722 // force reconfiguration of effect chains and engines to take new buffer size and audio
1723 // parameters into account
1724 // Note that mLock is not held when readOutputParameters() is called from the constructor
1725 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1726 // matter.
1727 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1728 Vector< sp<EffectChain> > effectChains = mEffectChains;
1729 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001730 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001731 }
Eric Laurenta553c252009-07-17 12:17:14 -07001732}
1733
Eric Laurent0986e792010-01-19 17:37:09 -08001734status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1735{
Glenn Kasten3694ec12012-01-27 16:47:15 -08001736 if (halFrames == NULL || dspFrames == NULL) {
Eric Laurent0986e792010-01-19 17:37:09 -08001737 return BAD_VALUE;
1738 }
Eric Laurent828b9772011-08-07 16:32:26 -07001739 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001740 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001741 return INVALID_OPERATION;
1742 }
Dima Zavin31f188892011-04-18 16:57:27 -07001743 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001744
Dima Zavin31f188892011-04-18 16:57:27 -07001745 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001746}
1747
Eric Laurent493941b2010-07-28 01:32:47 -07001748uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001749{
1750 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001751 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001752 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001753 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001754 }
1755
1756 for (size_t i = 0; i < mTracks.size(); ++i) {
1757 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001758 if (sessionId == track->sessionId() &&
1759 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001760 result |= TRACK_SESSION;
1761 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001762 }
1763 }
1764
Eric Laurent493941b2010-07-28 01:32:47 -07001765 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001766}
1767
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001768uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1769{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001770 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001771 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001772 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1773 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001774 }
1775 for (size_t i = 0; i < mTracks.size(); i++) {
1776 sp<Track> track = mTracks[i];
1777 if (sessionId == track->sessionId() &&
1778 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001779 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001780 }
1781 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001782 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001783}
1784
Eric Laurent53334cd2010-06-23 17:38:20 -07001785
Glenn Kasten5b0135e2012-01-26 09:46:34 -08001786AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent828b9772011-08-07 16:32:26 -07001787{
1788 Mutex::Autolock _l(mLock);
1789 return mOutput;
1790}
1791
1792AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1793{
1794 Mutex::Autolock _l(mLock);
1795 AudioStreamOut *output = mOutput;
1796 mOutput = NULL;
1797 return output;
1798}
1799
1800// this method must always be called either with ThreadBase mLock held or inside the thread loop
1801audio_stream_t* AudioFlinger::PlaybackThread::stream()
1802{
1803 if (mOutput == NULL) {
1804 return NULL;
1805 }
1806 return &mOutput->stream->common;
1807}
1808
Eric Laurent44331692011-12-05 09:47:19 -08001809uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1810{
1811 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1812 // decoding and transfer time. So sleeping for half of the latency would likely cause
1813 // underruns
1814 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1815 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1816 } else {
1817 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1818 }
1819}
1820
Eric Laurenta553c252009-07-17 12:17:14 -07001821// ----------------------------------------------------------------------------
1822
Glenn Kastenefd511a2012-01-26 10:38:26 -08001823AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1824 int id, uint32_t device, type_t type)
1825 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kastendc3ac852012-01-25 15:28:08 -08001826 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1827 mPrevMixerStatus(MIXER_IDLE)
Eric Laurenta553c252009-07-17 12:17:14 -07001828{
Eric Laurenta553c252009-07-17 12:17:14 -07001829 // FIXME - Current mixer implementation only supports stereo output
1830 if (mChannelCount == 1) {
Steve Block3762c312012-01-06 19:20:56 +00001831 ALOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001833}
1834
Eric Laurenta553c252009-07-17 12:17:14 -07001835AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001836{
Eric Laurenta553c252009-07-17 12:17:14 -07001837 delete mAudioMixer;
1838}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839
Eric Laurenta553c252009-07-17 12:17:14 -07001840bool AudioFlinger::MixerThread::threadLoop()
1841{
Eric Laurenta553c252009-07-17 12:17:14 -07001842 Vector< sp<Track> > tracksToRemove;
Glenn Kasten789fef12012-01-26 13:37:52 -08001843 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001844 nsecs_t standbyTime = systemTime();
1845 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001846 // FIXME: Relaxed timing because of a certain device that can't meet latency
1847 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001848 // increase threshold again due to low power audio mode. The way this warning threshold is
1849 // calculated and its usefulness should be reconsidered anyway.
1850 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001851 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001852 bool longStandbyExit = false;
1853 uint32_t activeSleepTime = activeSleepTimeUs();
1854 uint32_t idleSleepTime = idleSleepTimeUs();
1855 uint32_t sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001856 uint32_t sleepTimeShift = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001857 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001858#ifdef DEBUG_CPU_USAGE
1859 ThreadCpuUsage cpu;
1860 const CentralTendencyStatistics& stats = cpu.statistics();
1861#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862
Eric Laurent6dbdc402011-07-22 09:04:31 -07001863 acquireWakeLock();
1864
Eric Laurenta553c252009-07-17 12:17:14 -07001865 while (!exitPending())
1866 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001867#ifdef DEBUG_CPU_USAGE
1868 cpu.sampleAndEnable();
1869 unsigned n = stats.n();
1870 // cpu.elapsed() is expensive, so don't call it every loop
1871 if ((n & 127) == 1) {
1872 long long elapsed = cpu.elapsed();
1873 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1874 double perLoop = elapsed / (double) n;
1875 double perLoop100 = perLoop * 0.01;
1876 double mean = stats.mean();
1877 double stddev = stats.stddev();
1878 double minimum = stats.minimum();
1879 double maximum = stats.maximum();
1880 cpu.resetStatistics();
Steve Block6215d3f2012-01-04 20:05:49 +00001881 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 -07001882 elapsed * .000000001, n, perLoop * .000001,
1883 mean * .001,
1884 stddev * .001,
1885 minimum * .001,
1886 maximum * .001,
1887 mean / perLoop100,
1888 stddev / perLoop100,
1889 minimum / perLoop100,
1890 maximum / perLoop100);
1891 }
1892 }
1893#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001894 processConfigEvents();
1895
Eric Laurent059b4be2009-11-09 23:32:22 -08001896 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001897 { // scope for mLock
1898
1899 Mutex::Autolock _l(mLock);
1900
1901 if (checkForNewParameters_l()) {
1902 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001903 // FIXME: Relaxed timing because of a certain device that can't meet latency
1904 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001905 // increase threshold again due to low power audio mode. The way this warning
1906 // threshold is calculated and its usefulness should be reconsidered anyway.
1907 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001908 activeSleepTime = activeSleepTimeUs();
1909 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001910 }
1911
1912 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1913
1914 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001915 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1916 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001917 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01001918 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001919 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001920 mStandby = true;
1921 mBytesWritten = 0;
1922 }
1923
1924 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1925 // we're about to wait, flush the binder command buffer
1926 IPCThreadState::self()->flushCommands();
1927
1928 if (exitPending()) break;
1929
Eric Laurent6dbdc402011-07-22 09:04:31 -07001930 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001931 // wait until we have something to do...
Steve Block71f2cf12011-10-20 11:56:00 +01001932 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07001933 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01001934 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001935 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001936
Eric Laurent71c44962012-01-17 19:20:12 -08001937 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenb737dbb2012-01-13 15:54:24 -08001938 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07001939 char value[PROPERTY_VALUE_MAX];
1940 property_get("ro.audio.silent", value, "0");
1941 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00001942 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07001943 setMasterMute(true);
1944 }
1945 }
1946
1947 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001948 sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001949 sleepTimeShift = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001950 continue;
1951 }
1952 }
1953
Eric Laurent059b4be2009-11-09 23:32:22 -08001954 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001955
1956 // prevent any changes in effect chain list and in each effect chain
1957 // during mixing and effect process as the audio buffers could be deleted
1958 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001959 lockEffectChains_l(effectChains);
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08001960 }
Eric Laurenta553c252009-07-17 12:17:14 -07001961
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001962 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001963 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001964 mAudioMixer->process();
Eric Laurent06092312012-01-23 18:56:59 -08001965 // increase sleep time progressively when application underrun condition clears.
1966 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1967 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1968 // such that we would underrun the audio HAL.
1969 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001970 sleepTimeShift--;
1971 }
Eric Laurent06092312012-01-23 18:56:59 -08001972 sleepTime = 0;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001973 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001974 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001975 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001976 // If no tracks are ready, sleep once for the duration of an output
1977 // buffer size, then write 0s to the output
1978 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001979 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001980 sleepTime = activeSleepTime >> sleepTimeShift;
1981 if (sleepTime < kMinThreadSleepTimeUs) {
1982 sleepTime = kMinThreadSleepTimeUs;
1983 }
1984 // reduce sleep time in case of consecutive application underruns to avoid
1985 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1986 // duration we would end up writing less data than needed by the audio HAL if
1987 // the condition persists.
1988 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1989 sleepTimeShift++;
1990 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001991 } else {
1992 sleepTime = idleSleepTime;
1993 }
1994 } else if (mBytesWritten != 0 ||
1995 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001996 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001997 sleepTime = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01001998 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001999 }
Eric Laurent65b65452010-06-01 23:49:17 -07002000 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07002001 }
2002
2003 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002004 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002005 }
2006 // sleepTime == 0 means we must write to audio hardware
2007 if (sleepTime == 0) {
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08002008 for (size_t i = 0; i < effectChains.size(); i ++) {
2009 effectChains[i]->process_l();
2010 }
2011 // enable changes in effect chain
2012 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002013 mLastWriteTime = systemTime();
2014 mInWrite = true;
2015 mBytesWritten += mixBufferSize;
2016
Dima Zavin31f188892011-04-18 16:57:27 -07002017 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002018 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002019 mNumWrites++;
2020 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002021 nsecs_t now = systemTime();
2022 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07002023 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002024 mNumDelayedWrites++;
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002025 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00002026 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002027 ns2ms(delta), mNumDelayedWrites, this);
2028 lastWarning = now;
2029 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002030 if (mStandby) {
2031 longStandbyExit = true;
2032 }
Eric Laurenta553c252009-07-17 12:17:14 -07002033 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002034 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002035 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002036 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002037 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002038 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002039 }
2040
2041 // finally let go of all our tracks, without the lock held
2042 // since we can't guarantee the destructors won't acquire that
2043 // same lock.
2044 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002045
2046 // Effect chains will be actually deleted here if they were removed from
2047 // mEffectChains list during mixing or effects processing
2048 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002049 }
2050
2051 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002052 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002053 }
Eric Laurenta553c252009-07-17 12:17:14 -07002054
Eric Laurent6dbdc402011-07-22 09:04:31 -07002055 releaseWakeLock();
2056
Steve Block71f2cf12011-10-20 11:56:00 +01002057 ALOGV("MixerThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002058 return false;
2059}
2060
2061// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten789fef12012-01-26 13:37:52 -08002062AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2063 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002064{
2065
Glenn Kasten789fef12012-01-26 13:37:52 -08002066 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002067 // find out which tracks need to be processed
2068 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002069 size_t mixedTracks = 0;
2070 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002071
2072 float masterVolume = mMasterVolume;
2073 bool masterMute = mMasterMute;
2074
Eric Laurent8cc93b92010-08-11 05:20:11 -07002075 if (masterMute) {
2076 masterVolume = 0;
2077 }
Eric Laurent65b65452010-06-01 23:49:17 -07002078 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002079 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002080 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002081 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002082 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002083 masterVolume = (float)((v + (1 << 23)) >> 24);
2084 chain.clear();
2085 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002086
Eric Laurenta553c252009-07-17 12:17:14 -07002087 for (size_t i=0 ; i<count ; i++) {
2088 sp<Track> t = activeTracks[i].promote();
2089 if (t == 0) continue;
2090
Glenn Kasten68deb152011-12-19 15:06:39 -08002091 // this const just means the local variable doesn't change
Eric Laurenta553c252009-07-17 12:17:14 -07002092 Track* const track = t.get();
2093 audio_track_cblk_t* cblk = track->cblk();
2094
2095 // The first time a track is added we wait
2096 // for all its buffers to be filled before processing it
Glenn Kasten68deb152011-12-19 15:06:39 -08002097 int name = track->name();
Eric Laurent8a04fe02011-11-08 18:10:16 -08002098 // make sure that we have enough frames to mix one full buffer.
2099 // enforce this condition only once to enable draining the buffer in case the client
2100 // app does not call stop() and relies on underrun to stop:
Eric Laurent71c44962012-01-17 19:20:12 -08002101 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurent8a04fe02011-11-08 18:10:16 -08002102 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002103 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002104 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent71c44962012-01-17 19:20:12 -08002105 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002106 if (t->sampleRate() == (int)mSampleRate) {
2107 minFrames = mFrameCount;
2108 } else {
Eric Laurent72dafb22011-12-22 16:08:41 -08002109 // +1 for rounding and +1 for additional sample needed for interpolation
2110 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2111 // add frames already consumed but not yet released by the resampler
2112 // because cblk->framesReady() will include these frames
2113 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2114 // the minimum track buffer size is normally twice the number of frames necessary
2115 // to fill one buffer and the resampler should not leave more than one buffer worth
2116 // of unreleased frames after each pass, but just in case...
Steve Blockec193de2012-01-09 18:35:44 +00002117 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002118 }
2119 }
2120 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002121 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002122 {
Glenn Kasten68deb152011-12-19 15:06:39 -08002123 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002124
Eric Laurent65b65452010-06-01 23:49:17 -07002125 mixedTracks++;
2126
2127 // track->mainBuffer() != mMixBuffer means there is an effect chain
2128 // connected to the track
2129 chain.clear();
2130 if (track->mainBuffer() != mMixBuffer) {
2131 chain = getEffectChain_l(track->sessionId());
2132 // Delegate volume control to effect in track effect chain if needed
2133 if (chain != 0) {
2134 tracksWithEffect++;
2135 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00002136 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten68deb152011-12-19 15:06:39 -08002137 name, track->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002138 }
2139 }
2140
2141
2142 int param = AudioMixer::VOLUME;
2143 if (track->mFillingUpStatus == Track::FS_FILLED) {
2144 // no ramp for the first volume setting
2145 track->mFillingUpStatus = Track::FS_ACTIVE;
2146 if (track->mState == TrackBase::RESUMING) {
2147 track->mState = TrackBase::ACTIVE;
2148 param = AudioMixer::RAMP_VOLUME;
2149 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002150 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002151 } else if (cblk->server != 0) {
2152 // If the track is stopped before the first frame was mixed,
2153 // do not apply ramp
2154 param = AudioMixer::RAMP_VOLUME;
2155 }
2156
Eric Laurenta553c252009-07-17 12:17:14 -07002157 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002158 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002159 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002160 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002161 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002162 if (track->isPausing()) {
2163 track->setPaused();
2164 }
2165 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002166
Glenn Kasten871c16c2010-03-05 12:18:01 -08002167 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002168 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002169 float v = masterVolume * typeVolume;
Glenn Kastenbc4de882012-01-17 14:39:34 -08002170 uint32_t vlr = cblk->getVolumeLR();
Glenn Kasten0632bad2012-01-17 12:20:54 -08002171 vl = vlr & 0xFFFF;
2172 vr = vlr >> 16;
2173 // track volumes come from shared memory, so can't be trusted and must be clamped
2174 if (vl > MAX_GAIN_INT) {
2175 ALOGV("Track left volume out of range: %04X", vl);
2176 vl = MAX_GAIN_INT;
2177 }
2178 if (vr > MAX_GAIN_INT) {
2179 ALOGV("Track right volume out of range: %04X", vr);
2180 vr = MAX_GAIN_INT;
2181 }
2182 // now apply the master volume and stream type volume
2183 vl = (uint32_t)(v * vl) << 12;
2184 vr = (uint32_t)(v * vr) << 12;
2185 // assuming master volume and stream type volume each go up to 1.0,
2186 // vl and vr are now in 8.24 format
Eric Laurenta553c252009-07-17 12:17:14 -07002187
Glenn Kasten4790bd82012-01-03 14:22:33 -08002188 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2189 // send level comes from shared memory and so may be corrupt
Glenn Kasten0632bad2012-01-17 12:20:54 -08002190 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten4790bd82012-01-03 14:22:33 -08002191 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kasten0632bad2012-01-17 12:20:54 -08002192 sendLevel = MAX_GAIN_INT;
Glenn Kasten4790bd82012-01-03 14:22:33 -08002193 }
2194 va = (uint32_t)(v * sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002195 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002196 // Delegate volume control to effect in track effect chain if needed
2197 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2198 // Do not ramp volume if volume is controlled by effect
2199 param = AudioMixer::VOLUME;
2200 track->mHasVolumeController = true;
2201 } else {
2202 // force no volume ramp when volume controller was just disabled or removed
2203 // from effect chain to avoid volume spike
2204 if (track->mHasVolumeController) {
2205 param = AudioMixer::VOLUME;
2206 }
2207 track->mHasVolumeController = false;
2208 }
2209
2210 // Convert volumes from 8.24 to 4.12 format
2211 int16_t left, right, aux;
Glenn Kasten0632bad2012-01-17 12:20:54 -08002212 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002213 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2214 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2215 left = int16_t(v_clamped);
2216 v_clamped = (vr + (1 << 11)) >> 12;
2217 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2218 right = int16_t(v_clamped);
2219
2220 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2221 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002222
Eric Laurent65b65452010-06-01 23:49:17 -07002223 // XXX: these things DON'T need to be done each time
Glenn Kasten68deb152011-12-19 15:06:39 -08002224 mAudioMixer->setBufferProvider(name, track);
2225 mAudioMixer->enable(name);
Eric Laurent65b65452010-06-01 23:49:17 -07002226
Glenn Kasten68deb152011-12-19 15:06:39 -08002227 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2228 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2229 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002230 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002231 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002232 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002233 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002234 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002235 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002236 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002237 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002238 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002239 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002240 AudioMixer::RESAMPLE,
2241 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002242 (void *)(cblk->sampleRate));
2243 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002244 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002245 AudioMixer::TRACK,
2246 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2247 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002248 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002249 AudioMixer::TRACK,
2250 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002251
2252 // reset retry count
2253 track->mRetryCount = kMaxTrackRetries;
Eric Laurent71c44962012-01-17 19:20:12 -08002254 // If one track is ready, set the mixer ready if:
2255 // - the mixer was not ready during previous round OR
2256 // - no other track is not ready
2257 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2258 mixerStatus != MIXER_TRACKS_ENABLED) {
2259 mixerStatus = MIXER_TRACKS_READY;
2260 }
Eric Laurenta553c252009-07-17 12:17:14 -07002261 } else {
Glenn Kasten68deb152011-12-19 15:06:39 -08002262 //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 -07002263 if (track->isStopped()) {
2264 track->reset();
2265 }
2266 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2267 // We have consumed all the buffers of this track.
2268 // Remove it from the list of active tracks.
2269 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002270 } else {
2271 // No buffers for this track. Give it a few chances to
2272 // fill a buffer, then remove it from active list.
2273 if (--(track->mRetryCount) <= 0) {
Glenn Kasten68deb152011-12-19 15:06:39 -08002274 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002275 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002276 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002277 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent71c44962012-01-17 19:20:12 -08002278 // If one track is not ready, mark the mixer also not ready if:
2279 // - the mixer was ready during previous round OR
2280 // - no other track is ready
2281 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2282 mixerStatus != MIXER_TRACKS_READY) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002283 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002284 }
Eric Laurenta553c252009-07-17 12:17:14 -07002285 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002286 mAudioMixer->disable(name);
Eric Laurenta553c252009-07-17 12:17:14 -07002287 }
2288 }
2289
2290 // remove all the tracks that need to be...
2291 count = tracksToRemove->size();
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002292 if (CC_UNLIKELY(count)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002293 for (size_t i=0 ; i<count ; i++) {
2294 const sp<Track>& track = tracksToRemove->itemAt(i);
2295 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002296 if (track->mainBuffer() != mMixBuffer) {
2297 chain = getEffectChain_l(track->sessionId());
2298 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002299 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002300 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002301 }
2302 }
Eric Laurenta553c252009-07-17 12:17:14 -07002303 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002304 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002305 }
2306 }
2307 }
2308
Eric Laurent65b65452010-06-01 23:49:17 -07002309 // mix buffer must be cleared if all tracks are connected to an
2310 // effect chain as in this case the mixer will not write to
2311 // mix buffer and track effects will accumulate into it
2312 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2313 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2314 }
2315
Eric Laurent71c44962012-01-17 19:20:12 -08002316 mPrevMixerStatus = mixerStatus;
Eric Laurent059b4be2009-11-09 23:32:22 -08002317 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002318}
2319
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002320void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002321{
Steve Block71f2cf12011-10-20 11:56:00 +01002322 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002323 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002324 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002325
Eric Laurenta553c252009-07-17 12:17:14 -07002326 size_t size = mTracks.size();
2327 for (size_t i = 0; i < size; i++) {
2328 sp<Track> t = mTracks[i];
2329 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002330 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002331 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002332 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002333 }
2334}
Eric Laurenta553c252009-07-17 12:17:14 -07002335
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002336void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent05ce0942011-08-30 10:18:54 -07002337{
Steve Block71f2cf12011-10-20 11:56:00 +01002338 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002339 this, streamType, valid);
2340 Mutex::Autolock _l(mLock);
2341
2342 mStreamTypes[streamType].valid = valid;
2343}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344
Eric Laurenta553c252009-07-17 12:17:14 -07002345// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002346int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347{
2348 return mAudioMixer->getTrackName();
2349}
2350
Eric Laurenta553c252009-07-17 12:17:14 -07002351// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002352void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353{
Steve Block71f2cf12011-10-20 11:56:00 +01002354 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 mAudioMixer->deleteTrackName(name);
2356}
2357
Eric Laurenta553c252009-07-17 12:17:14 -07002358// checkForNewParameters_l() must be called with ThreadBase::mLock held
2359bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360{
Eric Laurenta553c252009-07-17 12:17:14 -07002361 bool reconfig = false;
2362
Eric Laurent8fce46a2009-08-04 09:45:33 -07002363 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002364 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002365 String8 keyValuePair = mNewParameters[0];
2366 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002367 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002368
Eric Laurenta553c252009-07-17 12:17:14 -07002369 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2370 reconfig = true;
2371 }
2372 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08002373 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002374 status = BAD_VALUE;
2375 } else {
2376 reconfig = true;
2377 }
2378 }
2379 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002380 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002381 status = BAD_VALUE;
2382 } else {
2383 reconfig = true;
2384 }
2385 }
2386 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2387 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastene5fb2632011-12-14 10:28:06 -08002388 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07002389 // if frame count is changed after track creation
2390 if (!mTracks.isEmpty()) {
2391 status = INVALID_OPERATION;
2392 } else {
2393 reconfig = true;
2394 }
2395 }
Eric Laurent65b65452010-06-01 23:49:17 -07002396 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002397 // when changing the audio output device, call addBatteryData to notify
2398 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002399 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002400 uint32_t params = 0;
2401 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002402 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002403 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2404 }
2405
2406 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002407 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002408 // check if any other device (except speaker) is on
2409 if (value & deviceWithoutSpeaker ) {
2410 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2411 }
2412
2413 if (params != 0) {
2414 addBatteryData(params);
2415 }
2416 }
2417
Eric Laurent65b65452010-06-01 23:49:17 -07002418 // forward device change to effects that have requested to be
2419 // aware of attached audio device.
2420 mDevice = (uint32_t)value;
2421 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002422 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002423 }
2424 }
2425
Eric Laurenta553c252009-07-17 12:17:14 -07002426 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002427 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002428 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002429 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002430 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002431 mStandby = true;
2432 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002433 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002434 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002435 }
2436 if (status == NO_ERROR && reconfig) {
2437 delete mAudioMixer;
Glenn Kasten2589cf92012-01-27 18:08:45 -08002438 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2439 mAudioMixer = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07002440 readOutputParameters();
2441 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2442 for (size_t i = 0; i < mTracks.size() ; i++) {
2443 int name = getTrackName_l();
2444 if (name < 0) break;
2445 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002446 // limit track sample rate to 2 x new output sample rate
2447 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2448 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2449 }
Eric Laurenta553c252009-07-17 12:17:14 -07002450 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002451 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002452 }
2453 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002454
2455 mNewParameters.removeAt(0);
2456
Eric Laurenta553c252009-07-17 12:17:14 -07002457 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002458 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002459 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2460 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002461 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002462 }
2463 return reconfig;
2464}
2465
2466status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2467{
2468 const size_t SIZE = 256;
2469 char buffer[SIZE];
2470 String8 result;
2471
2472 PlaybackThread::dumpInternals(fd, args);
2473
2474 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2475 result.append(buffer);
2476 write(fd, result.string(), result.size());
2477 return NO_ERROR;
2478}
2479
Eric Laurent059b4be2009-11-09 23:32:22 -08002480uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2481{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002482 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002483}
2484
Eric Laurent8448a792010-08-18 18:13:17 -07002485uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2486{
2487 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2488}
2489
Eric Laurenta553c252009-07-17 12:17:14 -07002490// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002491AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Glenn Kastenefd511a2012-01-26 10:38:26 -08002492 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kastendc3ac852012-01-25 15:28:08 -08002493 // mLeftVolFloat, mRightVolFloat
2494 // mLeftVolShort, mRightVolShort
Eric Laurenta553c252009-07-17 12:17:14 -07002495{
Eric Laurenta553c252009-07-17 12:17:14 -07002496}
2497
2498AudioFlinger::DirectOutputThread::~DirectOutputThread()
2499{
2500}
2501
Eric Laurent65b65452010-06-01 23:49:17 -07002502static inline
2503int32_t mul(int16_t in, int16_t v)
2504{
2505#if defined(__arm__) && !defined(__thumb__)
2506 int32_t out;
2507 asm( "smulbb %[out], %[in], %[v] \n"
2508 : [out]"=r"(out)
2509 : [in]"%r"(in), [v]"r"(v)
2510 : );
2511 return out;
2512#else
2513 return in * int32_t(v);
2514#endif
2515}
2516
2517void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2518{
2519 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002520 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002521 return;
2522 }
2523
2524 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002525 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002526 size_t count = mFrameCount * mChannelCount;
2527 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2528 int16_t *dst = mMixBuffer + count-1;
2529 while(count--) {
2530 *dst-- = (int16_t)(*src--^0x80) << 8;
2531 }
2532 }
2533
2534 size_t frameCount = mFrameCount;
2535 int16_t *out = mMixBuffer;
2536 if (ramp) {
2537 if (mChannelCount == 1) {
2538 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2539 int32_t vlInc = d / (int32_t)frameCount;
2540 int32_t vl = ((int32_t)mLeftVolShort << 16);
2541 do {
2542 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2543 out++;
2544 vl += vlInc;
2545 } while (--frameCount);
2546
2547 } else {
2548 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2549 int32_t vlInc = d / (int32_t)frameCount;
2550 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2551 int32_t vrInc = d / (int32_t)frameCount;
2552 int32_t vl = ((int32_t)mLeftVolShort << 16);
2553 int32_t vr = ((int32_t)mRightVolShort << 16);
2554 do {
2555 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2556 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2557 out += 2;
2558 vl += vlInc;
2559 vr += vrInc;
2560 } while (--frameCount);
2561 }
2562 } else {
2563 if (mChannelCount == 1) {
2564 do {
2565 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2566 out++;
2567 } while (--frameCount);
2568 } else {
2569 do {
2570 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2571 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2572 out += 2;
2573 } while (--frameCount);
2574 }
2575 }
2576
2577 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002578 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002579 size_t count = mFrameCount * mChannelCount;
2580 int16_t *src = mMixBuffer;
2581 uint8_t *dst = (uint8_t *)mMixBuffer;
2582 while(count--) {
2583 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2584 }
2585 }
2586
2587 mLeftVolShort = leftVol;
2588 mRightVolShort = rightVol;
2589}
2590
Eric Laurenta553c252009-07-17 12:17:14 -07002591bool AudioFlinger::DirectOutputThread::threadLoop()
2592{
Glenn Kasten789fef12012-01-26 13:37:52 -08002593 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002594 sp<Track> trackToRemove;
2595 sp<Track> activeTrack;
2596 nsecs_t standbyTime = systemTime();
2597 int8_t *curBuf;
2598 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002599 uint32_t activeSleepTime = activeSleepTimeUs();
2600 uint32_t idleSleepTime = idleSleepTimeUs();
2601 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002602 // use shorter standby delay as on normal output to release
2603 // hardware resources as soon as possible
2604 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002605
Eric Laurent6dbdc402011-07-22 09:04:31 -07002606 acquireWakeLock();
2607
Eric Laurenta553c252009-07-17 12:17:14 -07002608 while (!exitPending())
2609 {
Eric Laurent65b65452010-06-01 23:49:17 -07002610 bool rampVolume;
2611 uint16_t leftVol;
2612 uint16_t rightVol;
2613 Vector< sp<EffectChain> > effectChains;
2614
Eric Laurenta553c252009-07-17 12:17:14 -07002615 processConfigEvents();
2616
Eric Laurent059b4be2009-11-09 23:32:22 -08002617 mixerStatus = MIXER_IDLE;
2618
Eric Laurenta553c252009-07-17 12:17:14 -07002619 { // scope for the mLock
2620
2621 Mutex::Autolock _l(mLock);
2622
2623 if (checkForNewParameters_l()) {
2624 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002625 activeSleepTime = activeSleepTimeUs();
2626 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002627 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002628 }
2629
2630 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002631 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2632 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002633 // wait until we have something to do...
2634 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01002635 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002636 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002637 mStandby = true;
2638 mBytesWritten = 0;
2639 }
2640
2641 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2642 // we're about to wait, flush the binder command buffer
2643 IPCThreadState::self()->flushCommands();
2644
2645 if (exitPending()) break;
2646
Eric Laurent6dbdc402011-07-22 09:04:31 -07002647 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002648 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002649 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002650 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002651 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002652
Glenn Kastenb737dbb2012-01-13 15:54:24 -08002653 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07002654 char value[PROPERTY_VALUE_MAX];
2655 property_get("ro.audio.silent", value, "0");
2656 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00002657 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07002658 setMasterMute(true);
2659 }
2660 }
2661
Eric Laurentef9500f2010-03-11 14:47:00 -08002662 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002663 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002664 continue;
2665 }
2666 }
2667
Eric Laurent65b65452010-06-01 23:49:17 -07002668 effectChains = mEffectChains;
2669
Eric Laurenta553c252009-07-17 12:17:14 -07002670 // find out which tracks need to be processed
2671 if (mActiveTracks.size() != 0) {
2672 sp<Track> t = mActiveTracks[0].promote();
2673 if (t == 0) continue;
2674
2675 Track* const track = t.get();
2676 audio_track_cblk_t* cblk = track->cblk();
2677
2678 // The first time a track is added we wait
2679 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002680 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002681 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002682 {
Steve Block71f2cf12011-10-20 11:56:00 +01002683 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002684
Eric Laurent65b65452010-06-01 23:49:17 -07002685 if (track->mFillingUpStatus == Track::FS_FILLED) {
2686 track->mFillingUpStatus = Track::FS_ACTIVE;
2687 mLeftVolFloat = mRightVolFloat = 0;
2688 mLeftVolShort = mRightVolShort = 0;
2689 if (track->mState == TrackBase::RESUMING) {
2690 track->mState = TrackBase::ACTIVE;
2691 rampVolume = true;
2692 }
2693 } else if (cblk->server != 0) {
2694 // If the track is stopped before the first frame was mixed,
2695 // do not apply ramp
2696 rampVolume = true;
2697 }
Eric Laurenta553c252009-07-17 12:17:14 -07002698 // compute volume for this track
2699 float left, right;
2700 if (track->isMuted() || mMasterMute || track->isPausing() ||
2701 mStreamTypes[track->type()].mute) {
2702 left = right = 0;
2703 if (track->isPausing()) {
2704 track->setPaused();
2705 }
2706 } else {
2707 float typeVolume = mStreamTypes[track->type()].volume;
2708 float v = mMasterVolume * typeVolume;
Glenn Kastenbc4de882012-01-17 14:39:34 -08002709 uint32_t vlr = cblk->getVolumeLR();
Glenn Kasten0632bad2012-01-17 12:20:54 -08002710 float v_clamped = v * (vlr & 0xFFFF);
Eric Laurenta553c252009-07-17 12:17:14 -07002711 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2712 left = v_clamped/MAX_GAIN;
Glenn Kasten0632bad2012-01-17 12:20:54 -08002713 v_clamped = v * (vlr >> 16);
Eric Laurenta553c252009-07-17 12:17:14 -07002714 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2715 right = v_clamped/MAX_GAIN;
2716 }
2717
Eric Laurent65b65452010-06-01 23:49:17 -07002718 if (left != mLeftVolFloat || right != mRightVolFloat) {
2719 mLeftVolFloat = left;
2720 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002721
Eric Laurent65b65452010-06-01 23:49:17 -07002722 // If audio HAL implements volume control,
2723 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002724 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002725 left = 1.0f;
2726 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002727 }
Eric Laurent65b65452010-06-01 23:49:17 -07002728
2729 // Convert volumes from float to 8.24
2730 uint32_t vl = (uint32_t)(left * (1 << 24));
2731 uint32_t vr = (uint32_t)(right * (1 << 24));
2732
2733 // Delegate volume control to effect in track effect chain if needed
2734 // only one effect chain can be present on DirectOutputThread, so if
2735 // there is one, the track is connected to it
2736 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002737 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002738 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002739 rampVolume = false;
2740 }
2741 }
2742
2743 // Convert volumes from 8.24 to 4.12 format
2744 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2745 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2746 leftVol = (uint16_t)v_clamped;
2747 v_clamped = (vr + (1 << 11)) >> 12;
2748 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2749 rightVol = (uint16_t)v_clamped;
2750 } else {
2751 leftVol = mLeftVolShort;
2752 rightVol = mRightVolShort;
2753 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002754 }
2755
2756 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002757 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002758 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002759 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002760 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002761 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002762 if (track->isStopped()) {
2763 track->reset();
2764 }
2765 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2766 // We have consumed all the buffers of this track.
2767 // Remove it from the list of active tracks.
2768 trackToRemove = track;
2769 } else {
2770 // No buffers for this track. Give it a few chances to
2771 // fill a buffer, then remove it from active list.
2772 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002773 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurenta553c252009-07-17 12:17:14 -07002774 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002775 } else {
2776 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002777 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002778 }
Eric Laurenta553c252009-07-17 12:17:14 -07002779 }
2780 }
2781
2782 // remove all the tracks that need to be...
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002783 if (CC_UNLIKELY(trackToRemove != 0)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002784 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002785 if (!effectChains.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01002786 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002787 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002788 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002789 }
Eric Laurenta553c252009-07-17 12:17:14 -07002790 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002791 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002792 }
2793 }
Eric Laurent65b65452010-06-01 23:49:17 -07002794
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002795 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002796 }
2797
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002798 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002799 AudioBufferProvider::Buffer buffer;
2800 size_t frameCount = mFrameCount;
2801 curBuf = (int8_t *)mMixBuffer;
2802 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002803 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002804 buffer.frameCount = frameCount;
2805 activeTrack->getNextBuffer(&buffer);
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002806 if (CC_UNLIKELY(buffer.raw == NULL)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002807 memset(curBuf, 0, frameCount * mFrameSize);
2808 break;
2809 }
2810 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2811 frameCount -= buffer.frameCount;
2812 curBuf += buffer.frameCount * mFrameSize;
2813 activeTrack->releaseBuffer(&buffer);
2814 }
2815 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002816 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002817 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002818 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002819 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2820 sleepTime = activeSleepTime;
2821 } else {
2822 sleepTime = idleSleepTime;
2823 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002824 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002825 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002826 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002827 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002828 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002829
Eric Laurentf69a3f82009-09-22 00:35:48 -07002830 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002831 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002832 }
2833 // sleepTime == 0 means we must write to audio hardware
2834 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002835 if (mixerStatus == MIXER_TRACKS_READY) {
2836 applyVolume(leftVol, rightVol, rampVolume);
2837 }
2838 for (size_t i = 0; i < effectChains.size(); i ++) {
2839 effectChains[i]->process_l();
2840 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002841 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002842
Eric Laurentf69a3f82009-09-22 00:35:48 -07002843 mLastWriteTime = systemTime();
2844 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002845 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002846 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002847 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002848 mNumWrites++;
2849 mInWrite = false;
2850 mStandby = false;
2851 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002852 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002853 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002854 }
2855
2856 // finally let go of removed track, without the lock held
2857 // since we can't guarantee the destructors won't acquire that
2858 // same lock.
2859 trackToRemove.clear();
2860 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002861
2862 // Effect chains will be actually deleted here if they were removed from
2863 // mEffectChains list during mixing or effects processing
2864 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002865 }
2866
2867 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002868 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002869 }
Eric Laurenta553c252009-07-17 12:17:14 -07002870
Eric Laurent6dbdc402011-07-22 09:04:31 -07002871 releaseWakeLock();
2872
Steve Block71f2cf12011-10-20 11:56:00 +01002873 ALOGV("DirectOutputThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002874 return false;
2875}
2876
2877// getTrackName_l() must be called with ThreadBase::mLock held
2878int AudioFlinger::DirectOutputThread::getTrackName_l()
2879{
2880 return 0;
2881}
2882
2883// deleteTrackName_l() must be called with ThreadBase::mLock held
2884void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2885{
2886}
2887
2888// checkForNewParameters_l() must be called with ThreadBase::mLock held
2889bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2890{
2891 bool reconfig = false;
2892
Eric Laurent8fce46a2009-08-04 09:45:33 -07002893 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002894 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002895 String8 keyValuePair = mNewParameters[0];
2896 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002897 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002898
Eric Laurenta553c252009-07-17 12:17:14 -07002899 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2900 // do not accept frame count changes if tracks are open as the track buffer
2901 // size depends on frame count and correct behavior would not be garantied
2902 // if frame count is changed after track creation
2903 if (!mTracks.isEmpty()) {
2904 status = INVALID_OPERATION;
2905 } else {
2906 reconfig = true;
2907 }
2908 }
2909 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002910 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002911 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002912 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002913 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002914 mStandby = true;
2915 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002916 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002917 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002918 }
2919 if (status == NO_ERROR && reconfig) {
2920 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002921 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002922 }
2923 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002924
2925 mNewParameters.removeAt(0);
2926
Eric Laurenta553c252009-07-17 12:17:14 -07002927 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002928 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002929 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2930 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002931 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002932 }
2933 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002934}
2935
Eric Laurent059b4be2009-11-09 23:32:22 -08002936uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002937{
2938 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002939 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08002940 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08002941 } else {
2942 time = 10000;
2943 }
2944 return time;
2945}
2946
2947uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2948{
2949 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002950 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002951 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002952 } else {
2953 time = 10000;
2954 }
2955 return time;
2956}
2957
Eric Laurent8448a792010-08-18 18:13:17 -07002958uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2959{
2960 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002961 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002962 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2963 } else {
2964 time = 10000;
2965 }
2966 return time;
2967}
2968
2969
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002970// ----------------------------------------------------------------------------
2971
Glenn Kastenefd511a2012-01-26 10:38:26 -08002972AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
2973 AudioFlinger::MixerThread* mainThread, int id)
2974 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2975 mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002976{
Eric Laurenta553c252009-07-17 12:17:14 -07002977 addOutputTrack(mainThread);
2978}
2979
2980AudioFlinger::DuplicatingThread::~DuplicatingThread()
2981{
Eric Laurent0a080292009-12-07 10:53:10 -08002982 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2983 mOutputTracks[i]->destroy();
2984 }
Eric Laurenta553c252009-07-17 12:17:14 -07002985 mOutputTracks.clear();
2986}
2987
2988bool AudioFlinger::DuplicatingThread::threadLoop()
2989{
Eric Laurenta553c252009-07-17 12:17:14 -07002990 Vector< sp<Track> > tracksToRemove;
Glenn Kasten789fef12012-01-26 13:37:52 -08002991 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002992 nsecs_t standbyTime = systemTime();
2993 size_t mixBufferSize = mFrameCount*mFrameSize;
2994 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002995 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002996 uint32_t activeSleepTime = activeSleepTimeUs();
2997 uint32_t idleSleepTime = idleSleepTimeUs();
2998 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002999 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07003000
Eric Laurent6dbdc402011-07-22 09:04:31 -07003001 acquireWakeLock();
3002
Eric Laurenta553c252009-07-17 12:17:14 -07003003 while (!exitPending())
3004 {
3005 processConfigEvents();
3006
Eric Laurent059b4be2009-11-09 23:32:22 -08003007 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07003008 { // scope for the mLock
3009
3010 Mutex::Autolock _l(mLock);
3011
3012 if (checkForNewParameters_l()) {
3013 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003014 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08003015 activeSleepTime = activeSleepTimeUs();
3016 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07003017 }
3018
3019 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3020
3021 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3022 outputTracks.add(mOutputTracks[i]);
3023 }
3024
3025 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003026 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3027 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003028 if (!mStandby) {
3029 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07003030 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07003031 }
3032 mStandby = true;
3033 mBytesWritten = 0;
3034 }
3035
3036 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3037 // we're about to wait, flush the binder command buffer
3038 IPCThreadState::self()->flushCommands();
3039 outputTracks.clear();
3040
3041 if (exitPending()) break;
3042
Eric Laurent6dbdc402011-07-22 09:04:31 -07003043 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01003044 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07003045 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01003046 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07003047 acquireWakeLock_l();
3048
Eric Laurent71c44962012-01-17 19:20:12 -08003049 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenb737dbb2012-01-13 15:54:24 -08003050 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07003051 char value[PROPERTY_VALUE_MAX];
3052 property_get("ro.audio.silent", value, "0");
3053 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00003054 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07003055 setMasterMute(true);
3056 }
3057 }
3058
3059 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08003060 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07003061 continue;
3062 }
3063 }
3064
Eric Laurent059b4be2009-11-09 23:32:22 -08003065 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07003066
3067 // prevent any changes in effect chain list and in each effect chain
3068 // during mixing and effect process as the audio buffers could be deleted
3069 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003070 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003071 }
Eric Laurenta553c252009-07-17 12:17:14 -07003072
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003073 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003074 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003075 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003076 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003077 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003078 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003079 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003080 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003081 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003082 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003083 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003084 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3085 sleepTime = activeSleepTime;
3086 } else {
3087 sleepTime = idleSleepTime;
3088 }
Eric Laurent62443f52009-10-05 20:29:18 -07003089 } else if (mBytesWritten != 0) {
3090 // flush remaining overflow buffers in output tracks
3091 for (size_t i = 0; i < outputTracks.size(); i++) {
3092 if (outputTracks[i]->isActive()) {
3093 sleepTime = 0;
3094 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003095 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003096 break;
3097 }
3098 }
Eric Laurenta553c252009-07-17 12:17:14 -07003099 }
3100 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003101
3102 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003103 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003104 }
3105 // sleepTime == 0 means we must write to audio hardware
3106 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003107 for (size_t i = 0; i < effectChains.size(); i ++) {
3108 effectChains[i]->process_l();
3109 }
3110 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003111 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003112
Eric Laurent62443f52009-10-05 20:29:18 -07003113 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003114 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003115 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003116 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003117 mStandby = false;
3118 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003119 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003120 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003121 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003122 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003123 }
3124
3125 // finally let go of all our tracks, without the lock held
3126 // since we can't guarantee the destructors won't acquire that
3127 // same lock.
3128 tracksToRemove.clear();
3129 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003130
3131 // Effect chains will be actually deleted here if they were removed from
3132 // mEffectChains list during mixing or effects processing
3133 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003134 }
3135
Eric Laurent6dbdc402011-07-22 09:04:31 -07003136 releaseWakeLock();
3137
Eric Laurenta553c252009-07-17 12:17:14 -07003138 return false;
3139}
3140
3141void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3142{
3143 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3144 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003145 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003146 mSampleRate,
3147 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003148 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003149 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003150 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003151 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003152 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003153 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003154 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003155 }
Eric Laurenta553c252009-07-17 12:17:14 -07003156}
3157
3158void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3159{
3160 Mutex::Autolock _l(mLock);
3161 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3162 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003163 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003164 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003165 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003166 return;
3167 }
3168 }
Steve Block71f2cf12011-10-20 11:56:00 +01003169 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003170}
3171
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003172void AudioFlinger::DuplicatingThread::updateWaitTime()
3173{
3174 mWaitTimeMs = UINT_MAX;
3175 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3176 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten706b6182012-01-20 13:44:40 -08003177 if (strong != 0) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003178 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3179 if (waitTimeMs < mWaitTimeMs) {
3180 mWaitTimeMs = waitTimeMs;
3181 }
3182 }
3183 }
3184}
3185
3186
3187bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3188{
3189 for (size_t i = 0; i < outputTracks.size(); i++) {
3190 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3191 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003192 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003193 return false;
3194 }
3195 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3196 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003197 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003198 return false;
3199 }
3200 }
3201 return true;
3202}
3203
3204uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3205{
3206 return (mWaitTimeMs * 1000) / 2;
3207}
3208
Eric Laurenta553c252009-07-17 12:17:14 -07003209// ----------------------------------------------------------------------------
3210
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003211// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003212AudioFlinger::ThreadBase::TrackBase::TrackBase(
3213 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003214 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003215 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003216 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003217 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003218 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003220 const sp<IMemory>& sharedBuffer,
3221 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003222 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003223 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003224 mClient(client),
Glenn Kastendc3ac852012-01-25 15:28:08 -08003225 mCblk(NULL),
3226 // mBuffer
3227 // mBufferEnd
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003228 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003229 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003230 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003231 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3232 mSessionId(sessionId)
Glenn Kastendc3ac852012-01-25 15:28:08 -08003233 // mChannelCount
3234 // mChannelMask
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003235{
Steve Block71f2cf12011-10-20 11:56:00 +01003236 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003237
Steve Block5baa3a62011-12-20 16:23:08 +00003238 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003239 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003240 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003241 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3242 if (sharedBuffer == 0) {
3243 size += bufferSize;
3244 }
3245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 if (client != NULL) {
3247 mCblkMemory = client->heap()->allocate(size);
3248 if (mCblkMemory != 0) {
3249 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kasten3694ec12012-01-27 16:47:15 -08003250 if (mCblk != NULL) { // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 new(mCblk) audio_track_cblk_t();
3252 // clear all buffers
3253 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003254 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003255 mChannelCount = channelCount;
3256 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 if (sharedBuffer == 0) {
3258 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3259 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3260 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003261 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003262 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 } else {
3264 mBuffer = sharedBuffer->pointer();
3265 }
3266 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 } else {
Steve Block3762c312012-01-06 19:20:56 +00003269 ALOGE("not enough memory for AudioTrack size=%u", size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 client->heap()->dump("AudioTrack");
3271 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 } else {
3274 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenc95ca2c2012-01-06 15:03:11 -08003275 // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 new(mCblk) audio_track_cblk_t();
3277 // clear all buffers
3278 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003279 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003280 mChannelCount = channelCount;
3281 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3283 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3284 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003285 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003286 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003289}
3290
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003291AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003292{
Glenn Kasten3694ec12012-01-27 16:47:15 -08003293 if (mCblk != NULL) {
Glenn Kastend9d68dc2012-02-03 10:24:48 -08003294 if (mClient == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003295 delete mCblk;
Glenn Kastend9d68dc2012-02-03 10:24:48 -08003296 } else {
3297 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Eric Laurenta553c252009-07-17 12:17:14 -07003298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003300 mCblkMemory.clear(); // and free the shared memory
Glenn Kasten706b6182012-01-20 13:44:40 -08003301 if (mClient != 0) {
Glenn Kastendc3ac852012-01-25 15:28:08 -08003302 // Client destructor must run with AudioFlinger mutex locked
Eric Laurentb9481d82009-09-17 05:12:56 -07003303 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten706b6182012-01-20 13:44:40 -08003304 // If the client's reference count drops to zero, the associated destructor
3305 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3306 // relying on the automatic clear() at end of scope.
Eric Laurentb9481d82009-09-17 05:12:56 -07003307 mClient.clear();
3308 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003309}
3310
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003311void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003312{
Glenn Kastenc434c902011-12-13 11:53:26 -08003313 buffer->raw = NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003314 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003315 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003316 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003317}
3318
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003319bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003320 bool result;
3321 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003322
3323 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003324 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003325 ALOGV("stepServer failed acquiring cblk mutex");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003326 mFlags |= STEPSERVER_FAILED;
3327 }
3328 return result;
3329}
3330
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003331void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003332 audio_track_cblk_t* cblk = this->cblk();
3333
3334 cblk->user = 0;
3335 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003336 cblk->userBase = 0;
3337 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block71f2cf12011-10-20 11:56:00 +01003339 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003340}
3341
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003342int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003343 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003344}
3345
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003346void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003347 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003348 size_t frameSize = cblk->frameSize;
3349 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3350 int8_t *bufferEnd = bufferStart + frames * frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003351
3352 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003353 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003354 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block3762c312012-01-06 19:20:56 +00003355 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 -07003356 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003357 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003358 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kasten3694ec12012-01-27 16:47:15 -08003359 return NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003360 }
3361
3362 return bufferStart;
3363}
3364
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003365// ----------------------------------------------------------------------------
3366
Eric Laurenta553c252009-07-17 12:17:14 -07003367// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3368AudioFlinger::PlaybackThread::Track::Track(
3369 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003370 const sp<Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08003371 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003372 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003373 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003374 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003375 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003376 const sp<IMemory>& sharedBuffer,
3377 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003378 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003379 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3380 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003381{
Eric Laurent8a77a992009-09-09 05:16:08 -07003382 if (mCblk != NULL) {
3383 sp<ThreadBase> baseThread = thread.promote();
3384 if (baseThread != 0) {
3385 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3386 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003387 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003388 }
Steve Block71f2cf12011-10-20 11:56:00 +01003389 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003390 if (mName < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003391 ALOGE("no more track names available");
Eric Laurent8a77a992009-09-09 05:16:08 -07003392 }
Eric Laurent8a77a992009-09-09 05:16:08 -07003393 mStreamType = streamType;
3394 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3395 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003396 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003397 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003398}
3399
Eric Laurenta553c252009-07-17 12:17:14 -07003400AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003401{
Steve Block71f2cf12011-10-20 11:56:00 +01003402 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003403 sp<ThreadBase> thread = mThread.promote();
3404 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003405 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003406 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003407 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003408}
3409
Eric Laurenta553c252009-07-17 12:17:14 -07003410void AudioFlinger::PlaybackThread::Track::destroy()
3411{
3412 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3413 // by removing it from mTracks vector, so there is a risk that this Tracks's
3414 // desctructor is called. As the destructor needs to lock mLock,
3415 // we must acquire a strong reference on this Track before locking mLock
3416 // here so that the destructor is called only when exiting this function.
3417 // On the other hand, as long as Track::destroy() is only called by
3418 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3419 // this Track with its member mTrack.
3420 sp<Track> keep(this);
3421 { // scope for mLock
3422 sp<ThreadBase> thread = mThread.promote();
3423 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003424 if (!isOutputTrack()) {
3425 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003426 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003427 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003428 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003429
3430 // to track the speaker usage
3431 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003432 }
3433 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003434 }
Eric Laurenta553c252009-07-17 12:17:14 -07003435 Mutex::Autolock _l(thread->mLock);
3436 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3437 playbackThread->destroyTrack_l(this);
3438 }
3439 }
3440}
3441
3442void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003443{
Glenn Kastenbc4de882012-01-17 14:39:34 -08003444 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003445 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 -07003446 mName - AudioMixer::TRACK0,
Glenn Kasten706b6182012-01-20 13:44:40 -08003447 (mClient == 0) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003448 mStreamType,
3449 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003450 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003451 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003452 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003453 mState,
3454 mMute,
3455 mFillingUpStatus,
3456 mCblk->sampleRate,
Glenn Kasten0632bad2012-01-17 12:20:54 -08003457 vlr & 0xFFFF,
3458 vlr >> 16,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003459 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003460 mCblk->user,
3461 (int)mMainBuffer,
3462 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003463}
3464
Eric Laurenta553c252009-07-17 12:17:14 -07003465status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003466{
3467 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003468 uint32_t framesReady;
3469 uint32_t framesReq = buffer->frameCount;
3470
3471 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003472 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3473 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003474 ALOGV("stepServer recovered");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003475 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3476 }
3477
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003478 framesReady = cblk->framesReady();
3479
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003480 if (CC_LIKELY(framesReady)) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003481 uint32_t s = cblk->server;
3482 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3483
3484 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3485 if (framesReq > framesReady) {
3486 framesReq = framesReady;
3487 }
3488 if (s + framesReq > bufferEnd) {
3489 framesReq = bufferEnd - s;
3490 }
3491
3492 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003493 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003494
3495 buffer->frameCount = framesReq;
3496 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003497 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003498
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003499getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003500 buffer->raw = NULL;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003501 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003502 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 -07003503 return NOT_ENOUGH_DATA;
3504}
3505
Eric Laurenta553c252009-07-17 12:17:14 -07003506bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003507 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003508
3509 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003510 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003511 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003512 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003513 return true;
3514 }
3515 return false;
3516}
3517
Eric Laurenta553c252009-07-17 12:17:14 -07003518status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003519{
Eric Laurent49f02be2009-11-19 09:00:56 -08003520 status_t status = NO_ERROR;
Steve Block71f2cf12011-10-20 11:56:00 +01003521 ALOGV("start(%d), calling thread %d session %d",
Eric Laurent0d7e0482010-07-19 06:24:46 -07003522 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003523 sp<ThreadBase> thread = mThread.promote();
3524 if (thread != 0) {
3525 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003526 track_state state = mState;
Eric Laurent49f02be2009-11-19 09:00:56 -08003527 // here the track could be either new, or restarted
3528 // in both cases "unstop" the track
3529 if (mState == PAUSED) {
3530 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003531 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003532 } else {
3533 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003534 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003535 }
3536
3537 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3538 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003539 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003540 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003541 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003542 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003543
3544 // to track the speaker usage
3545 if (status == NO_ERROR) {
3546 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3547 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003548 }
3549 if (status == NO_ERROR) {
3550 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3551 playbackThread->addTrack_l(this);
3552 } else {
3553 mState = state;
3554 }
3555 } else {
3556 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003557 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003558 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003559}
3560
Eric Laurenta553c252009-07-17 12:17:14 -07003561void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003562{
Steve Block71f2cf12011-10-20 11:56:00 +01003563 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003564 sp<ThreadBase> thread = mThread.promote();
3565 if (thread != 0) {
3566 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003567 track_state state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003568 if (mState > STOPPED) {
3569 mState = STOPPED;
3570 // If the track is not active (PAUSED and buffers full), flush buffers
3571 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3572 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3573 reset();
3574 }
Steve Block71f2cf12011-10-20 11:56:00 +01003575 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003576 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003577 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3578 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003579 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003580 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003581 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003582 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003583
3584 // to track the speaker usage
3585 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003586 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003587 }
3588}
3589
Eric Laurenta553c252009-07-17 12:17:14 -07003590void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003591{
Steve Block71f2cf12011-10-20 11:56:00 +01003592 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003593 sp<ThreadBase> thread = mThread.promote();
3594 if (thread != 0) {
3595 Mutex::Autolock _l(thread->mLock);
3596 if (mState == ACTIVE || mState == RESUMING) {
3597 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003598 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003599 if (!isOutputTrack()) {
3600 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003601 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003602 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003603 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003604 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003605
3606 // to track the speaker usage
3607 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003608 }
Eric Laurenta553c252009-07-17 12:17:14 -07003609 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003610 }
3611}
3612
Eric Laurenta553c252009-07-17 12:17:14 -07003613void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003614{
Steve Block71f2cf12011-10-20 11:56:00 +01003615 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003616 sp<ThreadBase> thread = mThread.promote();
3617 if (thread != 0) {
3618 Mutex::Autolock _l(thread->mLock);
3619 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3620 return;
3621 }
3622 // No point remaining in PAUSED state after a flush => go to
3623 // STOPPED state
3624 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003625
Eric Laurentae29b762011-03-28 18:37:07 -07003626 // do not reset the track if it is still in the process of being stopped or paused.
3627 // this will be done by prepareTracks_l() when the track is stopped.
3628 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3629 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3630 reset();
3631 }
Eric Laurenta553c252009-07-17 12:17:14 -07003632 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003633}
3634
Eric Laurenta553c252009-07-17 12:17:14 -07003635void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003636{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003637 // Do not reset twice to avoid discarding data written just after a flush and before
3638 // the audioflinger thread detects the track is stopped.
3639 if (!mResetDone) {
3640 TrackBase::reset();
3641 // Force underrun condition to avoid false underrun callback until first data is
3642 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003643 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3644 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003645 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003646 mResetDone = true;
3647 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003648}
3649
Eric Laurenta553c252009-07-17 12:17:14 -07003650void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003651{
3652 mMute = muted;
3653}
3654
Eric Laurent65b65452010-06-01 23:49:17 -07003655status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3656{
3657 status_t status = DEAD_OBJECT;
3658 sp<ThreadBase> thread = mThread.promote();
3659 if (thread != 0) {
3660 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3661 status = playbackThread->attachAuxEffect(this, EffectId);
3662 }
3663 return status;
3664}
3665
3666void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3667{
3668 mAuxEffectId = EffectId;
3669 mAuxBuffer = buffer;
3670}
3671
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003672// ----------------------------------------------------------------------------
3673
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003674// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003675AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3676 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003679 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003680 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003682 uint32_t flags,
3683 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003684 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003685 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003686 mOverflow(false)
3687{
Eric Laurent8a77a992009-09-09 05:16:08 -07003688 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003689 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003690 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003691 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003692 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003693 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003694 } else {
3695 mCblk->frameSize = sizeof(int8_t);
3696 }
3697 }
Eric Laurenta553c252009-07-17 12:17:14 -07003698}
3699
3700AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701{
Eric Laurent49f02be2009-11-19 09:00:56 -08003702 sp<ThreadBase> thread = mThread.promote();
3703 if (thread != 0) {
3704 AudioSystem::releaseInput(thread->id());
3705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003706}
3707
Eric Laurenta553c252009-07-17 12:17:14 -07003708status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709{
3710 audio_track_cblk_t* cblk = this->cblk();
3711 uint32_t framesAvail;
3712 uint32_t framesReq = buffer->frameCount;
3713
3714 // Check if last stepServer failed, try to step now
3715 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3716 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003717 ALOGV("stepServer recovered");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3719 }
3720
3721 framesAvail = cblk->framesAvailable_l();
3722
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003723 if (CC_LIKELY(framesAvail)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 uint32_t s = cblk->server;
3725 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3726
3727 if (framesReq > framesAvail) {
3728 framesReq = framesAvail;
3729 }
3730 if (s + framesReq > bufferEnd) {
3731 framesReq = bufferEnd - s;
3732 }
3733
3734 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003735 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736
3737 buffer->frameCount = framesReq;
3738 return NO_ERROR;
3739 }
3740
3741getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003742 buffer->raw = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 buffer->frameCount = 0;
3744 return NOT_ENOUGH_DATA;
3745}
3746
Eric Laurenta553c252009-07-17 12:17:14 -07003747status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748{
Eric Laurenta553c252009-07-17 12:17:14 -07003749 sp<ThreadBase> thread = mThread.promote();
3750 if (thread != 0) {
3751 RecordThread *recordThread = (RecordThread *)thread.get();
3752 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003753 } else {
3754 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756}
3757
Eric Laurenta553c252009-07-17 12:17:14 -07003758void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759{
Eric Laurenta553c252009-07-17 12:17:14 -07003760 sp<ThreadBase> thread = mThread.promote();
3761 if (thread != 0) {
3762 RecordThread *recordThread = (RecordThread *)thread.get();
3763 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003764 TrackBase::reset();
3765 // Force overerrun condition to avoid false overrun callback until first data is
3766 // read from buffer
3767 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769}
3770
Eric Laurent3fdb1262009-11-07 00:01:32 -08003771void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3772{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003773 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten706b6182012-01-20 13:44:40 -08003774 (mClient == 0) ? getpid() : mClient->pid(),
Eric Laurent3fdb1262009-11-07 00:01:32 -08003775 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003776 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003777 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003778 mFrameCount,
3779 mState,
3780 mCblk->sampleRate,
3781 mCblk->server,
3782 mCblk->user);
3783}
3784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785
3786// ----------------------------------------------------------------------------
3787
Eric Laurenta553c252009-07-17 12:17:14 -07003788AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3789 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003790 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003792 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003793 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003795 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003796 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797{
Eric Laurenta553c252009-07-17 12:17:14 -07003798
3799 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003800 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003801 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003802 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Eric Laurent6c30a712009-08-10 23:22:32 -07003803 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003804 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01003805 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003806 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3807 mCblk, mBuffer, mCblk->buffers,
3808 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003809 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003810 ALOGW("Error creating output track on thread %p", playbackThread);
Eric Laurent6c30a712009-08-10 23:22:32 -07003811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812}
3813
Eric Laurenta553c252009-07-17 12:17:14 -07003814AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815{
Eric Laurent6c30a712009-08-10 23:22:32 -07003816 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817}
3818
Eric Laurenta553c252009-07-17 12:17:14 -07003819status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820{
3821 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003822 if (status != NO_ERROR) {
3823 return status;
3824 }
3825
3826 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 mRetryCount = 127;
3828 return status;
3829}
3830
Eric Laurenta553c252009-07-17 12:17:14 -07003831void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832{
3833 Track::stop();
3834 clearBufferQueue();
3835 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003836 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837}
3838
Eric Laurenta553c252009-07-17 12:17:14 -07003839bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840{
3841 Buffer *pInBuffer;
3842 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003843 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003844 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003845 inBuffer.frameCount = frames;
3846 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003847
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003848 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003849
Eric Laurent62443f52009-10-05 20:29:18 -07003850 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003851 start();
3852 sp<ThreadBase> thread = mThread.promote();
3853 if (thread != 0) {
3854 MixerThread *mixerThread = (MixerThread *)thread.get();
3855 if (mCblk->frameCount > frames){
3856 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3857 uint32_t startFrames = (mCblk->frameCount - frames);
3858 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003859 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003860 pInBuffer->frameCount = startFrames;
3861 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003862 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003863 mBufferQueue.add(pInBuffer);
3864 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003865 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurenta553c252009-07-17 12:17:14 -07003866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 }
Eric Laurenta553c252009-07-17 12:17:14 -07003868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 }
3870
Eric Laurenta553c252009-07-17 12:17:14 -07003871 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 // First write pending buffers, then new data
3873 if (mBufferQueue.size()) {
3874 pInBuffer = mBufferQueue.itemAt(0);
3875 } else {
3876 pInBuffer = &inBuffer;
3877 }
Eric Laurenta553c252009-07-17 12:17:14 -07003878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 if (pInBuffer->frameCount == 0) {
3880 break;
3881 }
Eric Laurenta553c252009-07-17 12:17:14 -07003882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 if (mOutBuffer.frameCount == 0) {
3884 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003885 nsecs_t startTime = systemTime();
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003886 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01003887 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003888 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 break;
3890 }
Eric Laurenta553c252009-07-17 12:17:14 -07003891 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003892 if (waitTimeLeftMs >= waitTimeMs) {
3893 waitTimeLeftMs -= waitTimeMs;
3894 } else {
3895 waitTimeLeftMs = 0;
3896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 }
Eric Laurenta553c252009-07-17 12:17:14 -07003898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003900 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 mCblk->stepUser(outFrames);
3902 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003903 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003905 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 if (pInBuffer->frameCount == 0) {
3908 if (mBufferQueue.size()) {
3909 mBufferQueue.removeAt(0);
3910 delete [] pInBuffer->mBuffer;
3911 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01003912 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 -08003913 } else {
3914 break;
3915 }
3916 }
3917 }
Eric Laurenta553c252009-07-17 12:17:14 -07003918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 // If we could not write all frames, allocate a buffer and queue it for next time.
3920 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003921 sp<ThreadBase> thread = mThread.promote();
3922 if (thread != 0 && !thread->standby()) {
3923 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3924 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003925 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003926 pInBuffer->frameCount = inBuffer.frameCount;
3927 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003928 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003929 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01003930 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003931 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003932 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 }
3935 }
Eric Laurenta553c252009-07-17 12:17:14 -07003936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003938 // 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 -08003939 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003940 if (frames == 0 && mBufferQueue.size() == 0) {
3941 if (mCblk->user < mCblk->frameCount) {
3942 frames = mCblk->frameCount - mCblk->user;
3943 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003944 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003945 pInBuffer->frameCount = frames;
3946 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003947 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003948 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003949 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003950 stop();
3951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 }
3953
Eric Laurenta553c252009-07-17 12:17:14 -07003954 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955}
3956
Eric Laurenta553c252009-07-17 12:17:14 -07003957status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958{
3959 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 status_t result;
3961 audio_track_cblk_t* cblk = mCblk;
3962 uint32_t framesReq = buffer->frameCount;
3963
Steve Block71f2cf12011-10-20 11:56:00 +01003964// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 uint32_t framesAvail = cblk->framesAvailable();
3968
Eric Laurenta553c252009-07-17 12:17:14 -07003969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003971 Mutex::Autolock _l(cblk->lock);
3972 goto start_loop_here;
3973 while (framesAvail == 0) {
3974 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003975 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01003976 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003977 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07003978 }
3979 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3980 if (result != NO_ERROR) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003981 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07003982 }
3983 // read the server count again
3984 start_loop_here:
3985 framesAvail = cblk->framesAvailable_l();
3986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 }
3988
Eric Laurenta553c252009-07-17 12:17:14 -07003989// if (framesAvail < framesReq) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003990// return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07003991// }
3992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 if (framesReq > framesAvail) {
3994 framesReq = framesAvail;
3995 }
3996
3997 uint32_t u = cblk->user;
3998 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3999
4000 if (u + framesReq > bufferEnd) {
4001 framesReq = bufferEnd - u;
4002 }
4003
4004 buffer->frameCount = framesReq;
4005 buffer->raw = (void *)cblk->buffer(u);
4006 return NO_ERROR;
4007}
4008
4009
Eric Laurenta553c252009-07-17 12:17:14 -07004010void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011{
4012 size_t size = mBufferQueue.size();
4013 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 for (size_t i = 0; i < size; i++) {
4016 pBuffer = mBufferQueue.itemAt(i);
4017 delete [] pBuffer->mBuffer;
4018 delete pBuffer;
4019 }
4020 mBufferQueue.clear();
4021}
4022
4023// ----------------------------------------------------------------------------
4024
4025AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4026 : RefBase(),
4027 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08004028 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 mPid(pid)
4030{
4031 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4032}
4033
Eric Laurentb9481d82009-09-17 05:12:56 -07004034// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035AudioFlinger::Client::~Client()
4036{
Eric Laurentb9481d82009-09-17 05:12:56 -07004037 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038}
4039
Glenn Kasten1f812f72012-01-30 10:15:48 -08004040sp<MemoryDealer> AudioFlinger::Client::heap() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041{
4042 return mMemoryDealer;
4043}
4044
4045// ----------------------------------------------------------------------------
4046
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004047AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4048 const sp<IAudioFlingerClient>& client,
4049 pid_t pid)
Glenn Kastendc3ac852012-01-25 15:28:08 -08004050 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004051{
4052}
4053
4054AudioFlinger::NotificationClient::~NotificationClient()
4055{
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004056}
4057
4058void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4059{
4060 sp<NotificationClient> keep(this);
4061 {
4062 mAudioFlinger->removeNotificationClient(mPid);
4063 }
4064}
4065
4066// ----------------------------------------------------------------------------
4067
Eric Laurenta553c252009-07-17 12:17:14 -07004068AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004069 : BnAudioTrack(),
4070 mTrack(track)
4071{
4072}
4073
4074AudioFlinger::TrackHandle::~TrackHandle() {
4075 // just stop the track on deletion, associated resources
4076 // will be freed from the main thread once all pending buffers have
4077 // been played. Unless it's not in the active track list, in which
4078 // case we free everything now...
4079 mTrack->destroy();
4080}
4081
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004082sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4083 return mTrack->getCblk();
4084}
4085
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004086status_t AudioFlinger::TrackHandle::start() {
4087 return mTrack->start();
4088}
4089
4090void AudioFlinger::TrackHandle::stop() {
4091 mTrack->stop();
4092}
4093
4094void AudioFlinger::TrackHandle::flush() {
4095 mTrack->flush();
4096}
4097
4098void AudioFlinger::TrackHandle::mute(bool e) {
4099 mTrack->mute(e);
4100}
4101
4102void AudioFlinger::TrackHandle::pause() {
4103 mTrack->pause();
4104}
4105
Eric Laurent65b65452010-06-01 23:49:17 -07004106status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4107{
4108 return mTrack->attachAuxEffect(EffectId);
4109}
4110
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004111status_t AudioFlinger::TrackHandle::onTransact(
4112 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4113{
4114 return BnAudioTrack::onTransact(code, data, reply, flags);
4115}
4116
4117// ----------------------------------------------------------------------------
4118
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004119sp<IAudioRecord> AudioFlinger::openRecord(
4120 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07004121 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004122 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004123 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004124 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004125 int frameCount,
4126 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004127 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004128 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004129{
Eric Laurenta553c252009-07-17 12:17:14 -07004130 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004131 sp<RecordHandle> recordHandle;
4132 sp<Client> client;
4133 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004134 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004135 RecordThread *thread;
4136 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004137 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004138
4139 // check calling permissions
4140 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004141 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004142 goto Exit;
4143 }
4144
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004145 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004146 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004147 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004148 thread = checkRecordThread_l(input);
4149 if (thread == NULL) {
4150 lStatus = BAD_VALUE;
4151 goto Exit;
4152 }
4153
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004154 wclient = mClients.valueFor(pid);
4155 if (wclient != NULL) {
4156 client = wclient.promote();
4157 } else {
4158 client = new Client(this, pid);
4159 mClients.add(pid, client);
4160 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004161
Eric Laurent65b65452010-06-01 23:49:17 -07004162 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004163 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004164 lSessionId = *sessionId;
4165 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004166 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004167 if (sessionId != NULL) {
4168 *sessionId = lSessionId;
4169 }
4170 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004171 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004172 recordTrack = thread->createRecordTrack_l(client,
4173 sampleRate,
4174 format,
4175 channelMask,
4176 frameCount,
4177 flags,
4178 lSessionId,
4179 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004180 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004181 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004182 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4183 // destructor is called by the TrackBase destructor with mLock held
4184 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004185 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 goto Exit;
4187 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004188
4189 // return to handle to client
4190 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004191 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004192
4193Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004194 if (status) {
4195 *status = lStatus;
4196 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004197 return recordHandle;
4198}
4199
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004200// ----------------------------------------------------------------------------
4201
Eric Laurenta553c252009-07-17 12:17:14 -07004202AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004203 : BnAudioRecord(),
4204 mRecordTrack(recordTrack)
4205{
4206}
4207
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004208AudioFlinger::RecordHandle::~RecordHandle() {
4209 stop();
4210}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004211
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004212sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4213 return mRecordTrack->getCblk();
4214}
4215
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004216status_t AudioFlinger::RecordHandle::start() {
Steve Block71f2cf12011-10-20 11:56:00 +01004217 ALOGV("RecordHandle::start()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004218 return mRecordTrack->start();
4219}
4220
4221void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004222 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004223 mRecordTrack->stop();
4224}
4225
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004226status_t AudioFlinger::RecordHandle::onTransact(
4227 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4228{
4229 return BnAudioRecord::onTransact(code, data, reply, flags);
4230}
4231
4232// ----------------------------------------------------------------------------
4233
Eric Laurent464d5b32011-06-17 21:29:58 -07004234AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4235 AudioStreamIn *input,
4236 uint32_t sampleRate,
4237 uint32_t channels,
4238 int id,
4239 uint32_t device) :
Glenn Kastenefd511a2012-01-26 10:38:26 -08004240 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kastendc3ac852012-01-25 15:28:08 -08004241 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4242 // mRsmpInIndex and mInputBytes set by readInputParameters()
4243 mReqChannelCount(popcount(channels)),
4244 mReqSampleRate(sampleRate)
4245 // mBytesRead is only meaningful while active, and so is cleared in start()
4246 // (but might be better to also clear here for dump?)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004247{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004248 snprintf(mName, kNameLength, "AudioIn_%d", id);
4249
Eric Laurenta553c252009-07-17 12:17:14 -07004250 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004251}
4252
Eric Laurenta553c252009-07-17 12:17:14 -07004253
4254AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004255{
Eric Laurenta553c252009-07-17 12:17:14 -07004256 delete[] mRsmpInBuffer;
Glenn Kasten2589cf92012-01-27 18:08:45 -08004257 delete mResampler;
4258 delete[] mRsmpOutBuffer;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004259}
4260
Eric Laurenta553c252009-07-17 12:17:14 -07004261void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004262{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004263 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004264}
Eric Laurent49f02be2009-11-19 09:00:56 -08004265
Eric Laurent828b9772011-08-07 16:32:26 -07004266status_t AudioFlinger::RecordThread::readyToRun()
4267{
4268 status_t status = initCheck();
Steve Block8564c8d2012-01-05 23:22:43 +00004269 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurent828b9772011-08-07 16:32:26 -07004270 return status;
4271}
4272
Eric Laurenta553c252009-07-17 12:17:14 -07004273bool AudioFlinger::RecordThread::threadLoop()
4274{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004275 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004276 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004277 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004278
Eric Laurent4712baa2010-09-30 16:12:31 -07004279 nsecs_t lastWarning = 0;
4280
Eric Laurent6dbdc402011-07-22 09:04:31 -07004281 acquireWakeLock();
4282
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004283 // start recording
4284 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004285
Eric Laurenta553c252009-07-17 12:17:14 -07004286 processConfigEvents();
4287
4288 { // scope for mLock
4289 Mutex::Autolock _l(mLock);
4290 checkForNewParameters_l();
4291 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4292 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004293 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004294 mStandby = true;
4295 }
4296
4297 if (exitPending()) break;
4298
Eric Laurent6dbdc402011-07-22 09:04:31 -07004299 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004300 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004301 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004302 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004303 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004304 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004305 continue;
4306 }
4307 if (mActiveTrack != 0) {
4308 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004309 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004310 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004311 mStandby = true;
4312 }
Eric Laurenta553c252009-07-17 12:17:14 -07004313 mActiveTrack.clear();
4314 mStartStopCond.broadcast();
4315 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004316 if (mReqChannelCount != mActiveTrack->channelCount()) {
4317 mActiveTrack.clear();
Eric Laurent9cc489a2009-12-05 05:20:01 -08004318 mStartStopCond.broadcast();
4319 } else if (mBytesRead != 0) {
4320 // record start succeeds only if first read from audio input
4321 // succeeds
4322 if (mBytesRead > 0) {
4323 mActiveTrack->mState = TrackBase::ACTIVE;
4324 } else {
4325 mActiveTrack.clear();
4326 }
4327 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004328 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004329 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004330 }
Eric Laurenta553c252009-07-17 12:17:14 -07004331 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004332 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004333 }
4334
4335 if (mActiveTrack != 0) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004336 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4337 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004338 unlockEffectChains(effectChains);
4339 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004340 continue;
4341 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004342 for (size_t i = 0; i < effectChains.size(); i ++) {
4343 effectChains[i]->process_l();
4344 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004345
Eric Laurenta553c252009-07-17 12:17:14 -07004346 buffer.frameCount = mFrameCount;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004347 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004348 size_t framesOut = buffer.frameCount;
Glenn Kastenc434c902011-12-13 11:53:26 -08004349 if (mResampler == NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004350 // no resampling
4351 while (framesOut) {
4352 size_t framesIn = mFrameCount - mRsmpInIndex;
4353 if (framesIn) {
4354 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4355 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4356 if (framesIn > framesOut)
4357 framesIn = framesOut;
4358 mRsmpInIndex += framesIn;
4359 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004360 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004361 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004362 memcpy(dst, src, framesIn * mFrameSize);
4363 } else {
4364 int16_t *src16 = (int16_t *)src;
4365 int16_t *dst16 = (int16_t *)dst;
4366 if (mChannelCount == 1) {
4367 while (framesIn--) {
4368 *dst16++ = *src16;
4369 *dst16++ = *src16++;
4370 }
4371 } else {
4372 while (framesIn--) {
4373 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4374 src16 += 2;
4375 }
4376 }
4377 }
4378 }
4379 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004380 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004381 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004382 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004383 framesOut = 0;
4384 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004385 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004386 mRsmpInIndex = 0;
4387 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004388 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004389 ALOGE("Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08004390 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004391 // Force input into standby so that it tries to
4392 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004393 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004394 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004395 }
Eric Laurenta553c252009-07-17 12:17:14 -07004396 mRsmpInIndex = mFrameCount;
4397 framesOut = 0;
4398 buffer.frameCount = 0;
4399 }
4400 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004401 }
4402 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004403 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004404
Eric Laurenta553c252009-07-17 12:17:14 -07004405 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4406 // alter output frame count as if we were expecting stereo samples
4407 if (mChannelCount == 1 && mReqChannelCount == 1) {
4408 framesOut >>= 1;
4409 }
4410 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4411 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4412 // are 32 bit aligned which should be always true.
4413 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten490909d2011-12-15 09:52:39 -08004414 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004415 // the resampler always outputs stereo samples: do post stereo to mono conversion
4416 int16_t *src = (int16_t *)mRsmpOutBuffer;
4417 int16_t *dst = buffer.i16;
4418 while (framesOut--) {
4419 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4420 src += 2;
4421 }
4422 } else {
Glenn Kasten490909d2011-12-15 09:52:39 -08004423 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004424 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004425
Eric Laurenta553c252009-07-17 12:17:14 -07004426 }
4427 mActiveTrack->releaseBuffer(&buffer);
4428 mActiveTrack->overflow();
4429 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004430 // client isn't retrieving buffers fast enough
4431 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004432 if (!mActiveTrack->setOverflow()) {
4433 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004434 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00004435 ALOGW("RecordThread: buffer overflow");
Eric Laurent4712baa2010-09-30 16:12:31 -07004436 lastWarning = now;
4437 }
4438 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004439 // Release the processor for a while before asking for a new buffer.
4440 // This will give the application more chance to read from the buffer and
4441 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004442 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004443 }
4444 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004445 // enable changes in effect chain
4446 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004447 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004448 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004449
Eric Laurenta553c252009-07-17 12:17:14 -07004450 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004451 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004452 }
Eric Laurenta553c252009-07-17 12:17:14 -07004453 mActiveTrack.clear();
4454
Eric Laurent49f02be2009-11-19 09:00:56 -08004455 mStartStopCond.broadcast();
4456
Eric Laurent6dbdc402011-07-22 09:04:31 -07004457 releaseWakeLock();
4458
Steve Block71f2cf12011-10-20 11:56:00 +01004459 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004460 return false;
4461}
4462
Eric Laurent464d5b32011-06-17 21:29:58 -07004463
4464sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4465 const sp<AudioFlinger::Client>& client,
4466 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004467 audio_format_t format,
Eric Laurent464d5b32011-06-17 21:29:58 -07004468 int channelMask,
4469 int frameCount,
4470 uint32_t flags,
4471 int sessionId,
4472 status_t *status)
4473{
4474 sp<RecordTrack> track;
4475 status_t lStatus;
4476
4477 lStatus = initCheck();
4478 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00004479 ALOGE("Audio driver not initialized.");
Eric Laurent464d5b32011-06-17 21:29:58 -07004480 goto Exit;
4481 }
4482
4483 { // scope for mLock
4484 Mutex::Autolock _l(mLock);
4485
4486 track = new RecordTrack(this, client, sampleRate,
4487 format, channelMask, frameCount, flags, sessionId);
4488
Glenn Kasten706b6182012-01-20 13:44:40 -08004489 if (track->getCblk() == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004490 lStatus = NO_MEMORY;
4491 goto Exit;
4492 }
4493
4494 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004495 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4496 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004497 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004498 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4499 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004500 }
4501 lStatus = NO_ERROR;
4502
4503Exit:
4504 if (status) {
4505 *status = lStatus;
4506 }
4507 return track;
4508}
4509
Eric Laurenta553c252009-07-17 12:17:14 -07004510status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004511{
Steve Block71f2cf12011-10-20 11:56:00 +01004512 ALOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004513 sp <ThreadBase> strongMe = this;
4514 status_t status = NO_ERROR;
4515 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004516 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004517 if (mActiveTrack != 0) {
4518 if (recordTrack != mActiveTrack.get()) {
4519 status = -EBUSY;
4520 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004521 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004522 }
4523 return status;
4524 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004525
Eric Laurent49f02be2009-11-19 09:00:56 -08004526 recordTrack->mState = TrackBase::IDLE;
4527 mActiveTrack = recordTrack;
4528 mLock.unlock();
4529 status_t status = AudioSystem::startInput(mId);
4530 mLock.lock();
4531 if (status != NO_ERROR) {
4532 mActiveTrack.clear();
4533 return status;
4534 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004535 mRsmpInIndex = mFrameCount;
4536 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004537 if (mResampler != NULL) {
4538 mResampler->reset();
4539 }
4540 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004541 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004542 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004543 mWaitWorkCV.signal();
4544 // do not wait for mStartStopCond if exiting
4545 if (mExiting) {
4546 mActiveTrack.clear();
4547 status = INVALID_OPERATION;
4548 goto startError;
4549 }
4550 mStartStopCond.wait(mLock);
4551 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01004552 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004553 status = BAD_VALUE;
4554 goto startError;
4555 }
Steve Block71f2cf12011-10-20 11:56:00 +01004556 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004557 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004558 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004559startError:
4560 AudioSystem::stopInput(mId);
4561 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004562}
4563
Eric Laurenta553c252009-07-17 12:17:14 -07004564void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01004565 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004566 sp <ThreadBase> strongMe = this;
4567 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004568 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004569 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4570 mActiveTrack->mState = TrackBase::PAUSING;
4571 // do not wait for mStartStopCond if exiting
4572 if (mExiting) {
4573 return;
4574 }
4575 mStartStopCond.wait(mLock);
4576 // if we have been restarted, recordTrack == mActiveTrack.get() here
4577 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4578 mLock.unlock();
4579 AudioSystem::stopInput(mId);
4580 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01004581 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004582 }
4583 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004584 }
4585}
4586
Eric Laurenta553c252009-07-17 12:17:14 -07004587status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588{
4589 const size_t SIZE = 256;
4590 char buffer[SIZE];
4591 String8 result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592
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 Laurent9cc489a2009-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 Laurent9cc489a2009-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 Laurent9cc489a2009-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 Laurent9cc489a2009-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 Laurent9cc489a2009-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 Laurent9cc489a2009-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 Laurent9cc489a2009-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);
Glenn Kastend153b1f2012-02-03 11:10:26 -08005206 pid_t 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);
Glenn Kastend153b1f2012-02-03 11:10:26 -08005224 pid_t 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
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005373status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Eric Laurent65b65452010-06-01 23:49:17 -07005374{
5375 Mutex::Autolock _l(mLock);
5376 return EffectQueryNumberEffects(numEffects);
5377}
5378
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005379status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
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
Glenn Kasten67313332012-01-30 07:40:52 -08005385status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005386 effect_descriptor_t *descriptor) const
Eric Laurent65b65452010-06-01 23:49:17 -07005387{
5388 Mutex::Autolock _l(mLock);
5389 return EffectGetDescriptor(pUuid, descriptor);
5390}
5391
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005392
Eric Laurent65b65452010-06-01 23:49:17 -07005393sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5394 effect_descriptor_t *pDesc,
5395 const sp<IEffectClient>& effectClient,
5396 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005397 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005398 int sessionId,
5399 status_t *status,
5400 int *id,
5401 int *enabled)
5402{
5403 status_t lStatus = NO_ERROR;
5404 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005405 effect_descriptor_t desc;
5406 sp<Client> client;
5407 wp<Client> wclient;
5408
Steve Block71f2cf12011-10-20 11:56:00 +01005409 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005410 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005411
5412 if (pDesc == NULL) {
5413 lStatus = BAD_VALUE;
5414 goto Exit;
5415 }
5416
Eric Laurent98c92592010-09-23 16:10:16 -07005417 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005418 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005419 lStatus = PERMISSION_DENIED;
5420 goto Exit;
5421 }
5422
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005423 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005424 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005425 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005426 lStatus = PERMISSION_DENIED;
5427 goto Exit;
5428 }
5429
Eric Laurent464d5b32011-06-17 21:29:58 -07005430 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005431 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005432 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005433 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005434 lStatus = BAD_VALUE;
5435 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005436 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005437 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005438 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005439 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005440 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005441 }
5442 }
5443
Eric Laurent65b65452010-06-01 23:49:17 -07005444 {
5445 Mutex::Autolock _l(mLock);
5446
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005447
Eric Laurent65b65452010-06-01 23:49:17 -07005448 if (!EffectIsNullUuid(&pDesc->uuid)) {
5449 // if uuid is specified, request effect descriptor
5450 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5451 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005452 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005453 goto Exit;
5454 }
5455 } else {
5456 // if uuid is not specified, look for an available implementation
5457 // of the required type in effect factory
5458 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005459 ALOGW("createEffect() no effect type");
Eric Laurent65b65452010-06-01 23:49:17 -07005460 lStatus = BAD_VALUE;
5461 goto Exit;
5462 }
5463 uint32_t numEffects = 0;
5464 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005465 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005466 bool found = false;
5467
5468 lStatus = EffectQueryNumberEffects(&numEffects);
5469 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005470 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005471 goto Exit;
5472 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005473 for (uint32_t i = 0; i < numEffects; i++) {
5474 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005475 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005476 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005477 continue;
5478 }
5479 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5480 // If matching type found save effect descriptor. If the session is
5481 // 0 and the effect is not auxiliary, continue enumeration in case
5482 // an auxiliary version of this effect type is available
5483 found = true;
5484 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005485 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005486 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5487 break;
5488 }
5489 }
5490 }
5491 if (!found) {
5492 lStatus = BAD_VALUE;
Steve Block8564c8d2012-01-05 23:22:43 +00005493 ALOGW("createEffect() effect not found");
Eric Laurent65b65452010-06-01 23:49:17 -07005494 goto Exit;
5495 }
5496 // For same effect type, chose auxiliary version over insert version if
5497 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005498 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005499 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5500 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5501 }
5502 }
5503
5504 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005505 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005506 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5507 lStatus = INVALID_OPERATION;
5508 goto Exit;
5509 }
5510
Eric Laurentf82fccd2011-07-27 19:49:51 -07005511 // check recording permission for visualizer
5512 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5513 !recordingAllowed()) {
5514 lStatus = PERMISSION_DENIED;
5515 goto Exit;
5516 }
5517
Eric Laurent65b65452010-06-01 23:49:17 -07005518 // return effect descriptor
5519 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5520
5521 // If output is not specified try to find a matching audio session ID in one of the
5522 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005523 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5524 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005525 // Note: io is never 0 when creating an effect on an input
5526 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005527 // look for the thread where the specified audio session is present
5528 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5529 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005530 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005531 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005532 }
Eric Laurent65b65452010-06-01 23:49:17 -07005533 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005534 if (io == 0) {
5535 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5536 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5537 io = mRecordThreads.keyAt(i);
5538 break;
5539 }
5540 }
5541 }
Eric Laurent98c92592010-09-23 16:10:16 -07005542 // If no output thread contains the requested session ID, default to
5543 // first output. The effect chain will be moved to the correct output
5544 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005545 if (io == 0 && mPlaybackThreads.size()) {
5546 io = mPlaybackThreads.keyAt(0);
5547 }
Steve Block71f2cf12011-10-20 11:56:00 +01005548 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005549 }
5550 ThreadBase *thread = checkRecordThread_l(io);
5551 if (thread == NULL) {
5552 thread = checkPlaybackThread_l(io);
5553 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +00005554 ALOGE("createEffect() unknown output thread");
Eric Laurent464d5b32011-06-17 21:29:58 -07005555 lStatus = BAD_VALUE;
5556 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005557 }
Eric Laurent65b65452010-06-01 23:49:17 -07005558 }
Eric Laurent98c92592010-09-23 16:10:16 -07005559
Eric Laurent65b65452010-06-01 23:49:17 -07005560 wclient = mClients.valueFor(pid);
5561
5562 if (wclient != NULL) {
5563 client = wclient.promote();
5564 } else {
5565 client = new Client(this, pid);
5566 mClients.add(pid, client);
5567 }
5568
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005569 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005570 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5571 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005572 if (handle != 0 && id != NULL) {
5573 *id = handle->id();
5574 }
5575 }
5576
5577Exit:
5578 if(status) {
5579 *status = lStatus;
5580 }
5581 return handle;
5582}
5583
Eric Laurentf82fccd2011-07-27 19:49:51 -07005584status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005585{
Steve Block71f2cf12011-10-20 11:56:00 +01005586 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005587 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005588 Mutex::Autolock _l(mLock);
5589 if (srcOutput == dstOutput) {
Steve Block8564c8d2012-01-05 23:22:43 +00005590 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005591 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005592 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005593 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5594 if (srcThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005595 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005596 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005597 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005598 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5599 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005600 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005601 return BAD_VALUE;
5602 }
5603
5604 Mutex::Autolock _dl(dstThread->mLock);
5605 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005606 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005607
Eric Laurent53334cd2010-06-23 17:38:20 -07005608 return NO_ERROR;
5609}
5610
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005611// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005612status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005613 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005614 AudioFlinger::PlaybackThread *dstThread,
5615 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005616{
Steve Block71f2cf12011-10-20 11:56:00 +01005617 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005618 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005619
Eric Laurentf82fccd2011-07-27 19:49:51 -07005620 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005621 if (chain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005622 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005623 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005624 return INVALID_OPERATION;
5625 }
5626
Eric Laurent493941b2010-07-28 01:32:47 -07005627 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005628 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005629 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005630 // removed.
5631 srcThread->removeEffectChain_l(chain);
5632
5633 // transfer all effects one by one so that new effect chain is created on new thread with
5634 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005635 int dstOutput = dstThread->id();
5636 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005637 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005638 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5639 while (effect != 0) {
5640 srcThread->removeEffect_l(effect);
5641 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005642 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5643 if (effect->state() == EffectModule::ACTIVE ||
5644 effect->state() == EffectModule::STOPPING) {
5645 effect->start();
5646 }
Eric Laurent493941b2010-07-28 01:32:47 -07005647 // if the move request is not received from audio policy manager, the effect must be
5648 // re-registered with the new strategy and output
5649 if (dstChain == 0) {
5650 dstChain = effect->chain().promote();
5651 if (dstChain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005652 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent493941b2010-07-28 01:32:47 -07005653 srcThread->addEffect_l(effect);
5654 return NO_INIT;
5655 }
5656 strategy = dstChain->strategy();
5657 }
5658 if (reRegister) {
5659 AudioSystem::unregisterEffect(effect->id());
5660 AudioSystem::registerEffect(&effect->desc(),
5661 dstOutput,
5662 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005663 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005664 effect->id());
5665 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005666 effect = chain->getEffectFromId_l(0);
5667 }
5668
5669 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005670}
5671
Eric Laurent464d5b32011-06-17 21:29:58 -07005672
Eric Laurent65b65452010-06-01 23:49:17 -07005673// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005674sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005675 const sp<AudioFlinger::Client>& client,
5676 const sp<IEffectClient>& effectClient,
5677 int32_t priority,
5678 int sessionId,
5679 effect_descriptor_t *desc,
5680 int *enabled,
5681 status_t *status
5682 )
5683{
5684 sp<EffectModule> effect;
5685 sp<EffectHandle> handle;
5686 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005687 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005688 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005689 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005690 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005691
Eric Laurent464d5b32011-06-17 21:29:58 -07005692 lStatus = initCheck();
5693 if (lStatus != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00005694 ALOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005695 goto Exit;
5696 }
5697
5698 // Do not allow effects with session ID 0 on direct output or duplicating threads
5699 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005700 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block8564c8d2012-01-05 23:22:43 +00005701 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005702 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005703 lStatus = BAD_VALUE;
5704 goto Exit;
5705 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005706 // Only Pre processor effects are allowed on input threads and only on input threads
5707 if ((mType == RECORD &&
5708 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5709 (mType != RECORD &&
5710 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005711 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005712 desc->name, desc->flags, mType);
5713 lStatus = BAD_VALUE;
5714 goto Exit;
5715 }
Eric Laurent65b65452010-06-01 23:49:17 -07005716
Steve Block71f2cf12011-10-20 11:56:00 +01005717 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005718
5719 { // scope for mLock
5720 Mutex::Autolock _l(mLock);
5721
5722 // check for existing effect chain with the requested audio session
5723 chain = getEffectChain_l(sessionId);
5724 if (chain == 0) {
5725 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005726 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005727 chain = new EffectChain(this, sessionId);
5728 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005729 chain->setStrategy(getStrategyForSession_l(sessionId));
5730 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005731 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005732 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005733 }
5734
Glenn Kasten70ed6b72012-01-10 10:46:34 -08005735 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005736
5737 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005738 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005739 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005740 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005741 if (lStatus != NO_ERROR) {
5742 goto Exit;
5743 }
5744 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005745 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005746 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005747 lStatus = effect->status();
5748 if (lStatus != NO_ERROR) {
5749 goto Exit;
5750 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005751 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005752 if (lStatus != NO_ERROR) {
5753 goto Exit;
5754 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005755 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005756
5757 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005758 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005759 }
5760 // create effect handle and connect it to effect module
5761 handle = new EffectHandle(effect, client, effectClient, priority);
5762 lStatus = effect->addHandle(handle);
Glenn Kasten3694ec12012-01-27 16:47:15 -08005763 if (enabled != NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005764 *enabled = (int)effect->isEnabled();
5765 }
5766 }
5767
5768Exit:
5769 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005770 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005771 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005772 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005773 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005774 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005775 AudioSystem::unregisterEffect(effect->id());
5776 }
5777 if (chainCreated) {
5778 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005779 }
Eric Laurent65b65452010-06-01 23:49:17 -07005780 handle.clear();
5781 }
5782
5783 if(status) {
5784 *status = lStatus;
5785 }
5786 return handle;
5787}
5788
Eric Laurent464d5b32011-06-17 21:29:58 -07005789sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5790{
Eric Laurent464d5b32011-06-17 21:29:58 -07005791 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kastenc64a6f02012-01-30 13:00:02 -08005792 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent464d5b32011-06-17 21:29:58 -07005793}
5794
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005795// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5796// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005797status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005798{
5799 // check for existing effect chain with the requested audio session
5800 int sessionId = effect->sessionId();
5801 sp<EffectChain> chain = getEffectChain_l(sessionId);
5802 bool chainCreated = false;
5803
5804 if (chain == 0) {
5805 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005806 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005807 chain = new EffectChain(this, sessionId);
5808 addEffectChain_l(chain);
5809 chain->setStrategy(getStrategyForSession_l(sessionId));
5810 chainCreated = true;
5811 }
Steve Block71f2cf12011-10-20 11:56:00 +01005812 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005813
5814 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005815 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005816 this, effect->desc().name, chain.get());
5817 return BAD_VALUE;
5818 }
5819
5820 status_t status = chain->addEffect_l(effect);
5821 if (status != NO_ERROR) {
5822 if (chainCreated) {
5823 removeEffectChain_l(chain);
5824 }
5825 return status;
5826 }
5827
5828 effect->setDevice(mDevice);
5829 effect->setMode(mAudioFlinger->getMode());
5830 return NO_ERROR;
5831}
5832
Eric Laurent464d5b32011-06-17 21:29:58 -07005833void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005834
Steve Block71f2cf12011-10-20 11:56:00 +01005835 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005836 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005837 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5838 detachAuxEffect_l(effect->id());
5839 }
5840
5841 sp<EffectChain> chain = effect->chain().promote();
5842 if (chain != 0) {
5843 // remove effect chain if removing last effect
5844 if (chain->removeEffect_l(effect) == 0) {
5845 removeEffectChain_l(chain);
5846 }
5847 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00005848 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005849 }
5850}
5851
Eric Laurent464d5b32011-06-17 21:29:58 -07005852void AudioFlinger::ThreadBase::lockEffectChains_l(
5853 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5854{
5855 effectChains = mEffectChains;
5856 for (size_t i = 0; i < mEffectChains.size(); i++) {
5857 mEffectChains[i]->lock();
5858 }
5859}
5860
5861void AudioFlinger::ThreadBase::unlockEffectChains(
5862 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5863{
5864 for (size_t i = 0; i < effectChains.size(); i++) {
5865 effectChains[i]->unlock();
5866 }
5867}
5868
5869sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5870{
5871 Mutex::Autolock _l(mLock);
5872 return getEffectChain_l(sessionId);
5873}
5874
5875sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5876{
Eric Laurent464d5b32011-06-17 21:29:58 -07005877 size_t size = mEffectChains.size();
5878 for (size_t i = 0; i < size; i++) {
5879 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08005880 return mEffectChains[i];
Eric Laurent464d5b32011-06-17 21:29:58 -07005881 }
5882 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08005883 return 0;
Eric Laurent464d5b32011-06-17 21:29:58 -07005884}
5885
Glenn Kastenaccb1142012-01-04 11:00:47 -08005886void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent464d5b32011-06-17 21:29:58 -07005887{
5888 Mutex::Autolock _l(mLock);
5889 size_t size = mEffectChains.size();
5890 for (size_t i = 0; i < size; i++) {
5891 mEffectChains[i]->setMode_l(mode);
5892 }
5893}
5894
5895void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005896 const wp<EffectHandle>& handle,
5897 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005898
Eric Laurent53334cd2010-06-23 17:38:20 -07005899 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01005900 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005901 // delete the effect module if removing last handle on it
5902 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005903 if (!effect->isPinned() || unpiniflast) {
5904 removeEffect_l(effect);
5905 AudioSystem::unregisterEffect(effect->id());
5906 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005907 }
5908}
5909
Eric Laurent65b65452010-06-01 23:49:17 -07005910status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5911{
5912 int session = chain->sessionId();
5913 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005914 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005915
Steve Block71f2cf12011-10-20 11:56:00 +01005916 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005917 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005918 // Only one effect chain can be present in direct output thread and it uses
5919 // the mix buffer as input
5920 if (mType != DIRECT) {
5921 size_t numSamples = mFrameCount * mChannelCount;
5922 buffer = new int16_t[numSamples];
5923 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01005924 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005925 ownsBuffer = true;
5926 }
Eric Laurent65b65452010-06-01 23:49:17 -07005927
Eric Laurent53334cd2010-06-23 17:38:20 -07005928 // Attach all tracks with same session ID to this chain.
5929 for (size_t i = 0; i < mTracks.size(); ++i) {
5930 sp<Track> track = mTracks[i];
5931 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005932 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07005933 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005934 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005935 }
5936 }
5937
5938 // indicate all active tracks in the chain
5939 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5940 sp<Track> track = mActiveTracks[i].promote();
5941 if (track == 0) continue;
5942 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005943 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005944 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005945 }
Eric Laurent65b65452010-06-01 23:49:17 -07005946 }
5947 }
5948
Eric Laurent53334cd2010-06-23 17:38:20 -07005949 chain->setInBuffer(buffer, ownsBuffer);
5950 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005951 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005952 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005953 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5954 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005955 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005956 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5957 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005958 // Effect chain for other sessions are inserted at beginning of effect
5959 // chains list to be processed before output mix effects. Relative order between other
5960 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005961 size_t size = mEffectChains.size();
5962 size_t i = 0;
5963 for (i = 0; i < size; i++) {
5964 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005965 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005966 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005967 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005968
5969 return NO_ERROR;
5970}
5971
5972size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5973{
5974 int session = chain->sessionId();
5975
Steve Block71f2cf12011-10-20 11:56:00 +01005976 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005977
5978 for (size_t i = 0; i < mEffectChains.size(); i++) {
5979 if (chain == mEffectChains[i]) {
5980 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005981 // detach all active tracks from the chain
5982 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5983 sp<Track> track = mActiveTracks[i].promote();
5984 if (track == 0) continue;
5985 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005986 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07005987 chain.get(), session);
5988 chain->decActiveTrackCnt();
5989 }
5990 }
5991
Eric Laurent65b65452010-06-01 23:49:17 -07005992 // detach all tracks with same session ID from this chain
5993 for (size_t i = 0; i < mTracks.size(); ++i) {
5994 sp<Track> track = mTracks[i];
5995 if (session == track->sessionId()) {
5996 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005997 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005998 }
5999 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006000 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006001 }
6002 }
6003 return mEffectChains.size();
6004}
6005
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006006status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6007 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006008{
6009 Mutex::Autolock _l(mLock);
6010 return attachAuxEffect_l(track, EffectId);
6011}
6012
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006013status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6014 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006015{
6016 status_t status = NO_ERROR;
6017
6018 if (EffectId == 0) {
6019 track->setAuxBuffer(0, NULL);
6020 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006021 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6022 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006023 if (effect != 0) {
6024 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6025 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6026 } else {
6027 status = INVALID_OPERATION;
6028 }
6029 } else {
6030 status = BAD_VALUE;
6031 }
6032 }
6033 return status;
6034}
6035
6036void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6037{
6038 for (size_t i = 0; i < mTracks.size(); ++i) {
6039 sp<Track> track = mTracks[i];
6040 if (track->auxEffectId() == effectId) {
6041 attachAuxEffect_l(track, 0);
6042 }
6043 }
6044}
6045
Eric Laurent464d5b32011-06-17 21:29:58 -07006046status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6047{
6048 // only one chain per input thread
6049 if (mEffectChains.size() != 0) {
6050 return INVALID_OPERATION;
6051 }
Steve Block71f2cf12011-10-20 11:56:00 +01006052 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006053
6054 chain->setInBuffer(NULL);
6055 chain->setOutBuffer(NULL);
6056
Eric Laurentf82fccd2011-07-27 19:49:51 -07006057 checkSuspendOnAddEffectChain_l(chain);
6058
Eric Laurent464d5b32011-06-17 21:29:58 -07006059 mEffectChains.add(chain);
6060
6061 return NO_ERROR;
6062}
6063
6064size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6065{
Steve Block71f2cf12011-10-20 11:56:00 +01006066 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block8564c8d2012-01-05 23:22:43 +00006067 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent464d5b32011-06-17 21:29:58 -07006068 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6069 chain.get(), mEffectChains.size(), this);
6070 if (mEffectChains.size() == 1) {
6071 mEffectChains.removeAt(0);
6072 }
6073 return 0;
6074}
6075
Eric Laurent65b65452010-06-01 23:49:17 -07006076// ----------------------------------------------------------------------------
6077// EffectModule implementation
6078// ----------------------------------------------------------------------------
6079
6080#undef LOG_TAG
6081#define LOG_TAG "AudioFlinger::EffectModule"
6082
6083AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6084 const wp<AudioFlinger::EffectChain>& chain,
6085 effect_descriptor_t *desc,
6086 int id,
6087 int sessionId)
6088 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006089 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006090{
Steve Block71f2cf12011-10-20 11:56:00 +01006091 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006092 int lStatus;
6093 sp<ThreadBase> thread = mThread.promote();
6094 if (thread == 0) {
6095 return;
6096 }
Eric Laurent65b65452010-06-01 23:49:17 -07006097
6098 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6099
6100 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006101 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006102
Eric Laurent65b65452010-06-01 23:49:17 -07006103 if (mStatus != NO_ERROR) {
6104 return;
6105 }
6106 lStatus = init();
6107 if (lStatus < 0) {
6108 mStatus = lStatus;
6109 goto Error;
6110 }
6111
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006112 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6113 mPinned = true;
6114 }
Steve Block71f2cf12011-10-20 11:56:00 +01006115 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006116 return;
6117Error:
6118 EffectRelease(mEffectInterface);
6119 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006120 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006121}
6122
6123AudioFlinger::EffectModule::~EffectModule()
6124{
Steve Block71f2cf12011-10-20 11:56:00 +01006125 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006126 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006127 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6128 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6129 sp<ThreadBase> thread = mThread.promote();
6130 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006131 audio_stream_t *stream = thread->stream();
6132 if (stream != NULL) {
6133 stream->remove_audio_effect(stream, mEffectInterface);
6134 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006135 }
6136 }
Eric Laurent65b65452010-06-01 23:49:17 -07006137 // release effect engine
6138 EffectRelease(mEffectInterface);
6139 }
6140}
6141
Glenn Kasten1f812f72012-01-30 10:15:48 -08006142status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Eric Laurent65b65452010-06-01 23:49:17 -07006143{
6144 status_t status;
6145
6146 Mutex::Autolock _l(mLock);
6147 // First handle in mHandles has highest priority and controls the effect module
6148 int priority = handle->priority();
6149 size_t size = mHandles.size();
6150 sp<EffectHandle> h;
6151 size_t i;
6152 for (i = 0; i < size; i++) {
6153 h = mHandles[i].promote();
6154 if (h == 0) continue;
6155 if (h->priority() <= priority) break;
6156 }
6157 // if inserted in first place, move effect control from previous owner to this handle
6158 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006159 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006160 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006161 enabled = h->enabled();
6162 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006163 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006164 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006165 status = NO_ERROR;
6166 } else {
6167 status = ALREADY_EXISTS;
6168 }
Steve Block71f2cf12011-10-20 11:56:00 +01006169 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006170 mHandles.insertAt(handle, i);
6171 return status;
6172}
6173
6174size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6175{
6176 Mutex::Autolock _l(mLock);
6177 size_t size = mHandles.size();
6178 size_t i;
6179 for (i = 0; i < size; i++) {
6180 if (mHandles[i] == handle) break;
6181 }
6182 if (i == size) {
6183 return size;
6184 }
Steve Block71f2cf12011-10-20 11:56:00 +01006185 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006186
6187 bool enabled = false;
6188 EffectHandle *hdl = handle.unsafe_get();
Glenn Kasten3694ec12012-01-27 16:47:15 -08006189 if (hdl != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01006190 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006191 enabled = hdl->enabled();
6192 }
Eric Laurent65b65452010-06-01 23:49:17 -07006193 mHandles.removeAt(i);
6194 size = mHandles.size();
6195 // if removed from first place, move effect control from this handle to next in line
6196 if (i == 0 && size != 0) {
6197 sp<EffectHandle> h = mHandles[0].promote();
6198 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006199 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006200 }
6201 }
6202
Eric Laurent21b5c472011-07-26 20:54:46 -07006203 // Prevent calls to process() and other functions on effect interface from now on.
6204 // The effect engine will be released by the destructor when the last strong reference on
6205 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006206 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006207 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006208 }
6209
Eric Laurent65b65452010-06-01 23:49:17 -07006210 return size;
6211}
6212
Eric Laurentf82fccd2011-07-27 19:49:51 -07006213sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6214{
6215 Mutex::Autolock _l(mLock);
Glenn Kastenc64a6f02012-01-30 13:00:02 -08006216 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006217}
6218
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006219void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006220{
Steve Block71f2cf12011-10-20 11:56:00 +01006221 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006222 // keep a strong reference on this EffectModule to avoid calling the
6223 // destructor before we exit
6224 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006225 {
6226 sp<ThreadBase> thread = mThread.promote();
6227 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006228 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006229 }
6230 }
6231}
6232
Eric Laurent7d850f22010-07-09 13:34:17 -07006233void AudioFlinger::EffectModule::updateState() {
6234 Mutex::Autolock _l(mLock);
6235
6236 switch (mState) {
6237 case RESTART:
6238 reset_l();
6239 // FALL THROUGH
6240
6241 case STARTING:
6242 // clear auxiliary effect input buffer for next accumulation
6243 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6244 memset(mConfig.inputCfg.buffer.raw,
6245 0,
6246 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6247 }
6248 start_l();
6249 mState = ACTIVE;
6250 break;
6251 case STOPPING:
6252 stop_l();
6253 mDisableWaitCnt = mMaxDisableWaitCnt;
6254 mState = STOPPED;
6255 break;
6256 case STOPPED:
6257 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6258 // turn off sequence.
6259 if (--mDisableWaitCnt == 0) {
6260 reset_l();
6261 mState = IDLE;
6262 }
6263 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006264 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006265 break;
6266 }
6267}
6268
Eric Laurent65b65452010-06-01 23:49:17 -07006269void AudioFlinger::EffectModule::process()
6270{
6271 Mutex::Autolock _l(mLock);
6272
Eric Laurent21b5c472011-07-26 20:54:46 -07006273 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006274 mConfig.inputCfg.buffer.raw == NULL ||
6275 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006276 return;
6277 }
6278
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006279 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006280 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6281 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten490909d2011-12-15 09:52:39 -08006282 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Eric Laurent65b65452010-06-01 23:49:17 -07006283 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006284 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006285 }
6286
Eric Laurent65b65452010-06-01 23:49:17 -07006287 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006288 int ret = (*mEffectInterface)->process(mEffectInterface,
6289 &mConfig.inputCfg.buffer,
6290 &mConfig.outputCfg.buffer);
6291
6292 // force transition to IDLE state when engine is ready
6293 if (mState == STOPPED && ret == -ENODATA) {
6294 mDisableWaitCnt = 1;
6295 }
Eric Laurent65b65452010-06-01 23:49:17 -07006296
6297 // clear auxiliary effect input buffer for next accumulation
6298 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006299 memset(mConfig.inputCfg.buffer.raw, 0,
6300 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006301 }
6302 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006303 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6304 // If an insert effect is idle and input buffer is different from output buffer,
6305 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006306 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006307 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006308 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6309 int16_t *in = mConfig.inputCfg.buffer.s16;
6310 int16_t *out = mConfig.outputCfg.buffer.s16;
6311 for (size_t i = 0; i < frameCnt; i++) {
6312 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006313 }
Eric Laurent65b65452010-06-01 23:49:17 -07006314 }
6315 }
6316}
6317
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006318void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006319{
6320 if (mEffectInterface == NULL) {
6321 return;
6322 }
6323 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6324}
6325
6326status_t AudioFlinger::EffectModule::configure()
6327{
6328 uint32_t channels;
6329 if (mEffectInterface == NULL) {
6330 return NO_INIT;
6331 }
6332
6333 sp<ThreadBase> thread = mThread.promote();
6334 if (thread == 0) {
6335 return DEAD_OBJECT;
6336 }
6337
6338 // TODO: handle configuration of effects replacing track process
6339 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006340 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006341 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006342 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006343 }
6344
6345 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006346 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006347 } else {
6348 mConfig.inputCfg.channels = channels;
6349 }
6350 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006351 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6352 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006353 mConfig.inputCfg.samplingRate = thread->sampleRate();
6354 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6355 mConfig.inputCfg.bufferProvider.cookie = NULL;
6356 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6357 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6358 mConfig.outputCfg.bufferProvider.cookie = NULL;
6359 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6360 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6361 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6362 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006363 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006364 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006365 // - in other sessions:
6366 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6367 // other effect: overwrites output buffer: input buffer == output buffer
6368 // Auxiliary effect:
6369 // accumulates in output buffer: input buffer != output buffer
6370 // Therefore: accumulate <=> input buffer != output buffer
6371 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6372 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6373 } else {
6374 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6375 }
6376 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6377 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6378 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6379 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6380
Steve Block71f2cf12011-10-20 11:56:00 +01006381 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006382 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6383
Eric Laurent65b65452010-06-01 23:49:17 -07006384 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006385 uint32_t size = sizeof(int);
6386 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent4abf8822011-12-16 15:30:36 -08006387 EFFECT_CMD_SET_CONFIG,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006388 sizeof(effect_config_t),
6389 &mConfig,
6390 &size,
6391 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006392 if (status == 0) {
6393 status = cmdStatus;
6394 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006395
6396 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6397 (1000 * mConfig.outputCfg.buffer.frameCount);
6398
Eric Laurent65b65452010-06-01 23:49:17 -07006399 return status;
6400}
6401
6402status_t AudioFlinger::EffectModule::init()
6403{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006404 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006405 if (mEffectInterface == NULL) {
6406 return NO_INIT;
6407 }
6408 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006409 uint32_t size = sizeof(status_t);
6410 status_t status = (*mEffectInterface)->command(mEffectInterface,
6411 EFFECT_CMD_INIT,
6412 0,
6413 NULL,
6414 &size,
6415 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006416 if (status == 0) {
6417 status = cmdStatus;
6418 }
6419 return status;
6420}
6421
Eric Laurent6fccbd02011-10-05 17:42:25 -07006422status_t AudioFlinger::EffectModule::start()
6423{
6424 Mutex::Autolock _l(mLock);
6425 return start_l();
6426}
6427
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006428status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006429{
6430 if (mEffectInterface == NULL) {
6431 return NO_INIT;
6432 }
6433 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006434 uint32_t size = sizeof(status_t);
6435 status_t status = (*mEffectInterface)->command(mEffectInterface,
6436 EFFECT_CMD_ENABLE,
6437 0,
6438 NULL,
6439 &size,
6440 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006441 if (status == 0) {
6442 status = cmdStatus;
6443 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006444 if (status == 0 &&
6445 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6446 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6447 sp<ThreadBase> thread = mThread.promote();
6448 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006449 audio_stream_t *stream = thread->stream();
6450 if (stream != NULL) {
6451 stream->add_audio_effect(stream, mEffectInterface);
6452 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006453 }
6454 }
Eric Laurent65b65452010-06-01 23:49:17 -07006455 return status;
6456}
6457
Eric Laurent21b5c472011-07-26 20:54:46 -07006458status_t AudioFlinger::EffectModule::stop()
6459{
6460 Mutex::Autolock _l(mLock);
6461 return stop_l();
6462}
6463
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006464status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006465{
6466 if (mEffectInterface == NULL) {
6467 return NO_INIT;
6468 }
6469 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006470 uint32_t size = sizeof(status_t);
6471 status_t status = (*mEffectInterface)->command(mEffectInterface,
6472 EFFECT_CMD_DISABLE,
6473 0,
6474 NULL,
6475 &size,
6476 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006477 if (status == 0) {
6478 status = cmdStatus;
6479 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006480 if (status == 0 &&
6481 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6482 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6483 sp<ThreadBase> thread = mThread.promote();
6484 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006485 audio_stream_t *stream = thread->stream();
6486 if (stream != NULL) {
6487 stream->remove_audio_effect(stream, mEffectInterface);
6488 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006489 }
6490 }
Eric Laurent65b65452010-06-01 23:49:17 -07006491 return status;
6492}
6493
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006494status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6495 uint32_t cmdSize,
6496 void *pCmdData,
6497 uint32_t *replySize,
6498 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006499{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006500 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006501// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006502
Eric Laurent21b5c472011-07-26 20:54:46 -07006503 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006504 return NO_INIT;
6505 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006506 status_t status = (*mEffectInterface)->command(mEffectInterface,
6507 cmdCode,
6508 cmdSize,
6509 pCmdData,
6510 replySize,
6511 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006512 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006513 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006514 for (size_t i = 1; i < mHandles.size(); i++) {
6515 sp<EffectHandle> h = mHandles[i].promote();
6516 if (h != 0) {
6517 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6518 }
6519 }
6520 }
6521 return status;
6522}
6523
6524status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6525{
Eric Laurent6752ec82011-08-10 10:37:50 -07006526
Eric Laurent65b65452010-06-01 23:49:17 -07006527 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006528 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006529
6530 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006531 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6532 if (enabled && status != NO_ERROR) {
6533 return status;
6534 }
6535
Eric Laurent65b65452010-06-01 23:49:17 -07006536 switch (mState) {
6537 // going from disabled to enabled
6538 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006539 mState = STARTING;
6540 break;
6541 case STOPPED:
6542 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006543 break;
6544 case STOPPING:
6545 mState = ACTIVE;
6546 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006547
6548 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006549 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006550 mState = STOPPED;
6551 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006552 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006553 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006554 break;
6555 case ACTIVE:
6556 mState = STOPPING;
6557 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006558 case DESTROYED:
6559 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006560 }
6561 for (size_t i = 1; i < mHandles.size(); i++) {
6562 sp<EffectHandle> h = mHandles[i].promote();
6563 if (h != 0) {
6564 h->setEnabled(enabled);
6565 }
6566 }
6567 }
6568 return NO_ERROR;
6569}
6570
Glenn Kasteneabd94a2012-02-02 14:06:11 -08006571bool AudioFlinger::EffectModule::isEnabled() const
Eric Laurent65b65452010-06-01 23:49:17 -07006572{
6573 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006574 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006575 case STARTING:
6576 case ACTIVE:
6577 return true;
6578 case IDLE:
6579 case STOPPING:
6580 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006581 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006582 default:
6583 return false;
6584 }
6585}
6586
Glenn Kasteneabd94a2012-02-02 14:06:11 -08006587bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006588{
6589 switch (mState) {
6590 case RESTART:
6591 case ACTIVE:
6592 case STOPPING:
6593 case STOPPED:
6594 return true;
6595 case IDLE:
6596 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006597 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006598 default:
6599 return false;
6600 }
6601}
6602
Eric Laurent65b65452010-06-01 23:49:17 -07006603status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6604{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006605 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006606 status_t status = NO_ERROR;
6607
6608 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6609 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006610 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006611 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6612 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006613 status_t cmdStatus;
6614 uint32_t volume[2];
6615 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006616 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006617 volume[0] = *left;
6618 volume[1] = *right;
6619 if (controller) {
6620 pVolume = volume;
6621 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006622 status = (*mEffectInterface)->command(mEffectInterface,
6623 EFFECT_CMD_SET_VOLUME,
6624 size,
6625 volume,
6626 &size,
6627 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006628 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6629 *left = volume[0];
6630 *right = volume[1];
6631 }
6632 }
6633 return status;
6634}
6635
6636status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6637{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006638 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006639 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006640 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6641 // audio pre processing modules on RecordThread can receive both output and
6642 // input device indication in the same call
6643 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6644 if (dev) {
6645 status_t cmdStatus;
6646 uint32_t size = sizeof(status_t);
6647
6648 status = (*mEffectInterface)->command(mEffectInterface,
6649 EFFECT_CMD_SET_DEVICE,
6650 sizeof(uint32_t),
6651 &dev,
6652 &size,
6653 &cmdStatus);
6654 if (status == NO_ERROR) {
6655 status = cmdStatus;
6656 }
6657 }
6658 dev = device & AUDIO_DEVICE_IN_ALL;
6659 if (dev) {
6660 status_t cmdStatus;
6661 uint32_t size = sizeof(status_t);
6662
6663 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6664 EFFECT_CMD_SET_INPUT_DEVICE,
6665 sizeof(uint32_t),
6666 &dev,
6667 &size,
6668 &cmdStatus);
6669 if (status2 == NO_ERROR) {
6670 status2 = cmdStatus;
6671 }
6672 if (status == NO_ERROR) {
6673 status = status2;
6674 }
Eric Laurent65b65452010-06-01 23:49:17 -07006675 }
6676 }
6677 return status;
6678}
6679
Glenn Kastenaccb1142012-01-04 11:00:47 -08006680status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006681{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006682 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006683 status_t status = NO_ERROR;
6684 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006685 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006686 uint32_t size = sizeof(status_t);
6687 status = (*mEffectInterface)->command(mEffectInterface,
6688 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenaccb1142012-01-04 11:00:47 -08006689 sizeof(audio_mode_t),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006690 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006691 &size,
6692 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006693 if (status == NO_ERROR) {
6694 status = cmdStatus;
6695 }
6696 }
6697 return status;
6698}
6699
Eric Laurentf82fccd2011-07-27 19:49:51 -07006700void AudioFlinger::EffectModule::setSuspended(bool suspended)
6701{
6702 Mutex::Autolock _l(mLock);
6703 mSuspended = suspended;
6704}
Glenn Kasten1dce8412012-01-04 11:01:11 -08006705
6706bool AudioFlinger::EffectModule::suspended() const
Eric Laurentf82fccd2011-07-27 19:49:51 -07006707{
6708 Mutex::Autolock _l(mLock);
6709 return mSuspended;
6710}
6711
Eric Laurent65b65452010-06-01 23:49:17 -07006712status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6713{
6714 const size_t SIZE = 256;
6715 char buffer[SIZE];
6716 String8 result;
6717
6718 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6719 result.append(buffer);
6720
6721 bool locked = tryLock(mLock);
6722 // failed to lock - AudioFlinger is probably deadlocked
6723 if (!locked) {
6724 result.append("\t\tCould not lock Fx mutex:\n");
6725 }
6726
6727 result.append("\t\tSession Status State Engine:\n");
6728 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6729 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6730 result.append(buffer);
6731
6732 result.append("\t\tDescriptor:\n");
6733 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6734 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6735 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6736 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6737 result.append(buffer);
6738 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6739 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6740 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6741 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6742 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006743 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006744 mDescriptor.apiVersion,
6745 mDescriptor.flags);
6746 result.append(buffer);
6747 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6748 mDescriptor.name);
6749 result.append(buffer);
6750 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6751 mDescriptor.implementor);
6752 result.append(buffer);
6753
6754 result.append("\t\t- Input configuration:\n");
6755 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6756 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6757 (uint32_t)mConfig.inputCfg.buffer.raw,
6758 mConfig.inputCfg.buffer.frameCount,
6759 mConfig.inputCfg.samplingRate,
6760 mConfig.inputCfg.channels,
6761 mConfig.inputCfg.format);
6762 result.append(buffer);
6763
6764 result.append("\t\t- Output configuration:\n");
6765 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6766 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6767 (uint32_t)mConfig.outputCfg.buffer.raw,
6768 mConfig.outputCfg.buffer.frameCount,
6769 mConfig.outputCfg.samplingRate,
6770 mConfig.outputCfg.channels,
6771 mConfig.outputCfg.format);
6772 result.append(buffer);
6773
6774 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6775 result.append(buffer);
6776 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6777 for (size_t i = 0; i < mHandles.size(); ++i) {
6778 sp<EffectHandle> handle = mHandles[i].promote();
6779 if (handle != 0) {
6780 handle->dump(buffer, SIZE);
6781 result.append(buffer);
6782 }
6783 }
6784
6785 result.append("\n");
6786
6787 write(fd, result.string(), result.length());
6788
6789 if (locked) {
6790 mLock.unlock();
6791 }
6792
6793 return NO_ERROR;
6794}
6795
6796// ----------------------------------------------------------------------------
6797// EffectHandle implementation
6798// ----------------------------------------------------------------------------
6799
6800#undef LOG_TAG
6801#define LOG_TAG "AudioFlinger::EffectHandle"
6802
6803AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6804 const sp<AudioFlinger::Client>& client,
6805 const sp<IEffectClient>& effectClient,
6806 int32_t priority)
6807 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006808 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006809 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006810{
Steve Block71f2cf12011-10-20 11:56:00 +01006811 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006812
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006813 if (client == 0) {
6814 return;
6815 }
Eric Laurent65b65452010-06-01 23:49:17 -07006816 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6817 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6818 if (mCblkMemory != 0) {
6819 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6820
Glenn Kasten3694ec12012-01-27 16:47:15 -08006821 if (mCblk != NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006822 new(mCblk) effect_param_cblk_t();
6823 mBuffer = (uint8_t *)mCblk + bufOffset;
6824 }
6825 } else {
Steve Block3762c312012-01-06 19:20:56 +00006826 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006827 return;
6828 }
6829}
6830
6831AudioFlinger::EffectHandle::~EffectHandle()
6832{
Steve Block71f2cf12011-10-20 11:56:00 +01006833 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006834 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01006835 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006836}
6837
6838status_t AudioFlinger::EffectHandle::enable()
6839{
Steve Block71f2cf12011-10-20 11:56:00 +01006840 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006841 if (!mHasControl) return INVALID_OPERATION;
6842 if (mEffect == 0) return DEAD_OBJECT;
6843
Eric Laurent6752ec82011-08-10 10:37:50 -07006844 if (mEnabled) {
6845 return NO_ERROR;
6846 }
6847
Eric Laurentf82fccd2011-07-27 19:49:51 -07006848 mEnabled = true;
6849
6850 sp<ThreadBase> thread = mEffect->thread().promote();
6851 if (thread != 0) {
6852 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6853 }
6854
6855 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6856 if (mEffect->suspended()) {
6857 return NO_ERROR;
6858 }
6859
Eric Laurent6752ec82011-08-10 10:37:50 -07006860 status_t status = mEffect->setEnabled(true);
6861 if (status != NO_ERROR) {
6862 if (thread != 0) {
6863 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6864 }
6865 mEnabled = false;
6866 }
6867 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006868}
6869
6870status_t AudioFlinger::EffectHandle::disable()
6871{
Steve Block71f2cf12011-10-20 11:56:00 +01006872 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006873 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006874 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006875
Eric Laurent6752ec82011-08-10 10:37:50 -07006876 if (!mEnabled) {
6877 return NO_ERROR;
6878 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006879 mEnabled = false;
6880
6881 if (mEffect->suspended()) {
6882 return NO_ERROR;
6883 }
6884
6885 status_t status = mEffect->setEnabled(false);
6886
6887 sp<ThreadBase> thread = mEffect->thread().promote();
6888 if (thread != 0) {
6889 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6890 }
6891
6892 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006893}
6894
6895void AudioFlinger::EffectHandle::disconnect()
6896{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006897 disconnect(true);
6898}
6899
6900void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6901{
Steve Block71f2cf12011-10-20 11:56:00 +01006902 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006903 if (mEffect == 0) {
6904 return;
6905 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006906 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006907
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006908 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006909 sp<ThreadBase> thread = mEffect->thread().promote();
6910 if (thread != 0) {
6911 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6912 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006913 }
6914
Eric Laurent65b65452010-06-01 23:49:17 -07006915 // release sp on module => module destructor can be called now
6916 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006917 if (mClient != 0) {
Glenn Kasten3694ec12012-01-27 16:47:15 -08006918 if (mCblk != NULL) {
Glenn Kastend9d68dc2012-02-03 10:24:48 -08006919 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006920 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6921 }
6922 mCblkMemory.clear(); // and free the shared memory
Eric Laurent65b65452010-06-01 23:49:17 -07006923 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6924 mClient.clear();
6925 }
6926}
6927
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006928status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6929 uint32_t cmdSize,
6930 void *pCmdData,
6931 uint32_t *replySize,
6932 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006933{
Steve Block71f2cf12011-10-20 11:56:00 +01006934// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006935// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006936
6937 // only get parameter command is permitted for applications not controlling the effect
6938 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6939 return INVALID_OPERATION;
6940 }
6941 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006942 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006943
6944 // handle commands that are not forwarded transparently to effect engine
6945 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6946 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6947 // no risk to block the whole media server process or mixer threads is we are stuck here
6948 Mutex::Autolock _l(mCblk->lock);
6949 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6950 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6951 mCblk->serverIndex = 0;
6952 mCblk->clientIndex = 0;
6953 return BAD_VALUE;
6954 }
6955 status_t status = NO_ERROR;
6956 while (mCblk->serverIndex < mCblk->clientIndex) {
6957 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006958 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006959 int *p = (int *)(mBuffer + mCblk->serverIndex);
6960 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006961 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block8564c8d2012-01-05 23:22:43 +00006962 ALOGW("command(): invalid parameter block size");
Eric Laurent53334cd2010-06-23 17:38:20 -07006963 break;
6964 }
Eric Laurent65b65452010-06-01 23:49:17 -07006965 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006966 if (param->psize == 0 || param->vsize == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006967 ALOGW("command(): null parameter or value size");
Eric Laurent53334cd2010-06-23 17:38:20 -07006968 mCblk->serverIndex += size;
6969 continue;
6970 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006971 uint32_t psize = sizeof(effect_param_t) +
6972 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6973 param->vsize;
6974 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6975 psize,
6976 p,
6977 &rsize,
6978 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006979 // stop at first error encountered
6980 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006981 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006982 *(int *)pReplyData = reply;
6983 break;
6984 } else if (reply != NO_ERROR) {
6985 *(int *)pReplyData = reply;
6986 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006987 }
6988 mCblk->serverIndex += size;
6989 }
6990 mCblk->serverIndex = 0;
6991 mCblk->clientIndex = 0;
6992 return status;
6993 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006994 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006995 return enable();
6996 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006997 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006998 return disable();
6999 }
7000
7001 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7002}
7003
Eric Laurentf82fccd2011-07-27 19:49:51 -07007004void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07007005{
Steve Block71f2cf12011-10-20 11:56:00 +01007006 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07007007
7008 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007009 mEnabled = enabled;
7010
Eric Laurent65b65452010-06-01 23:49:17 -07007011 if (signal && mEffectClient != 0) {
7012 mEffectClient->controlStatusChanged(hasControl);
7013 }
7014}
7015
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007016void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7017 uint32_t cmdSize,
7018 void *pCmdData,
7019 uint32_t replySize,
7020 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007021{
7022 if (mEffectClient != 0) {
7023 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7024 }
7025}
7026
7027
7028
7029void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7030{
7031 if (mEffectClient != 0) {
7032 mEffectClient->enableStatusChanged(enabled);
7033 }
7034}
7035
7036status_t AudioFlinger::EffectHandle::onTransact(
7037 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7038{
7039 return BnEffect::onTransact(code, data, reply, flags);
7040}
7041
7042
7043void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7044{
Glenn Kasten3694ec12012-01-27 16:47:15 -08007045 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Eric Laurent65b65452010-06-01 23:49:17 -07007046
7047 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten706b6182012-01-20 13:44:40 -08007048 (mClient == 0) ? getpid() : mClient->pid(),
Eric Laurent65b65452010-06-01 23:49:17 -07007049 mPriority,
7050 mHasControl,
7051 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007052 mCblk ? mCblk->clientIndex : 0,
7053 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007054 );
7055
7056 if (locked) {
7057 mCblk->lock.unlock();
7058 }
7059}
7060
7061#undef LOG_TAG
7062#define LOG_TAG "AudioFlinger::EffectChain"
7063
7064AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7065 int sessionId)
Eric Laurentf9c361d2011-11-11 15:42:52 -08007066 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007067 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7068 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007069{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007070 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007071 sp<ThreadBase> thread = mThread.promote();
7072 if (thread == 0) {
7073 return;
7074 }
7075 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7076 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007077}
7078
7079AudioFlinger::EffectChain::~EffectChain()
7080{
7081 if (mOwnInBuffer) {
7082 delete mInBuffer;
7083 }
7084
7085}
7086
Eric Laurentf82fccd2011-07-27 19:49:51 -07007087// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007088sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007089{
Eric Laurent65b65452010-06-01 23:49:17 -07007090 size_t size = mEffects.size();
7091
7092 for (size_t i = 0; i < size; i++) {
7093 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007094 return mEffects[i];
Eric Laurent65b65452010-06-01 23:49:17 -07007095 }
7096 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007097 return 0;
Eric Laurent65b65452010-06-01 23:49:17 -07007098}
7099
Eric Laurentf82fccd2011-07-27 19:49:51 -07007100// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007101sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007102{
Eric Laurent65b65452010-06-01 23:49:17 -07007103 size_t size = mEffects.size();
7104
7105 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007106 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7107 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007108 return mEffects[i];
Eric Laurent65b65452010-06-01 23:49:17 -07007109 }
7110 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007111 return 0;
Eric Laurent65b65452010-06-01 23:49:17 -07007112}
7113
Eric Laurentf82fccd2011-07-27 19:49:51 -07007114// getEffectFromType_l() must be called with ThreadBase::mLock held
7115sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7116 const effect_uuid_t *type)
7117{
Eric Laurentf82fccd2011-07-27 19:49:51 -07007118 size_t size = mEffects.size();
7119
7120 for (size_t i = 0; i < size; i++) {
7121 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007122 return mEffects[i];
Eric Laurentf82fccd2011-07-27 19:49:51 -07007123 }
7124 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007125 return 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007126}
7127
Eric Laurent65b65452010-06-01 23:49:17 -07007128// Must be called with EffectChain::mLock locked
7129void AudioFlinger::EffectChain::process_l()
7130{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007131 sp<ThreadBase> thread = mThread.promote();
7132 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007133 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007134 return;
7135 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007136 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7137 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007138 // always process effects unless no more tracks are on the session and the effect tail
7139 // has been rendered
7140 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007141 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007142 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007143
Eric Laurentf9c361d2011-11-11 15:42:52 -08007144 if (!tracksOnSession && mTailBufferCount == 0) {
7145 doProcess = false;
7146 }
7147
7148 if (activeTrackCnt() == 0) {
7149 // if no track is active and the effect tail has not been rendered,
7150 // the input buffer must be cleared here as the mixer process will not do it
7151 if (tracksOnSession || mTailBufferCount > 0) {
7152 size_t numSamples = thread->frameCount() * thread->channelCount();
7153 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7154 if (mTailBufferCount > 0) {
7155 mTailBufferCount--;
7156 }
7157 }
7158 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007159 }
7160
Eric Laurent65b65452010-06-01 23:49:17 -07007161 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007162 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007163 for (size_t i = 0; i < size; i++) {
7164 mEffects[i]->process();
7165 }
Eric Laurent65b65452010-06-01 23:49:17 -07007166 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007167 for (size_t i = 0; i < size; i++) {
7168 mEffects[i]->updateState();
7169 }
Eric Laurent65b65452010-06-01 23:49:17 -07007170}
7171
Eric Laurent76c40f72010-07-15 12:50:15 -07007172// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007173status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007174{
7175 effect_descriptor_t desc = effect->desc();
7176 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7177
7178 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007179 effect->setChain(this);
7180 sp<ThreadBase> thread = mThread.promote();
7181 if (thread == 0) {
7182 return NO_INIT;
7183 }
7184 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007185
7186 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7187 // Auxiliary effects are inserted at the beginning of mEffects vector as
7188 // they are processed first and accumulated in chain input buffer
7189 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007190
Eric Laurent65b65452010-06-01 23:49:17 -07007191 // the input buffer for auxiliary effect contains mono samples in
7192 // 32 bit format. This is to avoid saturation in AudoMixer
7193 // accumulation stage. Saturation is done in EffectModule::process() before
7194 // calling the process in effect engine
7195 size_t numSamples = thread->frameCount();
7196 int32_t *buffer = new int32_t[numSamples];
7197 memset(buffer, 0, numSamples * sizeof(int32_t));
7198 effect->setInBuffer((int16_t *)buffer);
7199 // auxiliary effects output samples to chain input buffer for further processing
7200 // by insert effects
7201 effect->setOutBuffer(mInBuffer);
7202 } else {
7203 // Insert effects are inserted at the end of mEffects vector as they are processed
7204 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007205 // Insert effect order as a function of indicated preference:
7206 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7207 // another effect is present
7208 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7209 // last effect claiming first position
7210 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7211 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007212 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007213 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7214 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007215
7216 int size = (int)mEffects.size();
7217 int idx_insert = size;
7218 int idx_insert_first = -1;
7219 int idx_insert_last = -1;
7220
7221 for (int i = 0; i < size; i++) {
7222 effect_descriptor_t d = mEffects[i]->desc();
7223 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7224 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7225 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7226 // check invalid effect chaining combinations
7227 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007228 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block8564c8d2012-01-05 23:22:43 +00007229 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007230 return INVALID_OPERATION;
7231 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007232 // remember position of first insert effect and by default
7233 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007234 if (idx_insert == size) {
7235 idx_insert = i;
7236 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007237 // remember position of last insert effect claiming
7238 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007239 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7240 idx_insert_first = i;
7241 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007242 // remember position of first insert effect claiming
7243 // last position
7244 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7245 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007246 idx_insert_last = i;
7247 }
7248 }
7249 }
7250
Eric Laurent53334cd2010-06-23 17:38:20 -07007251 // modify idx_insert from first position if needed
7252 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7253 if (idx_insert_last != -1) {
7254 idx_insert = idx_insert_last;
7255 } else {
7256 idx_insert = size;
7257 }
7258 } else {
7259 if (idx_insert_first != -1) {
7260 idx_insert = idx_insert_first + 1;
7261 }
Eric Laurent65b65452010-06-01 23:49:17 -07007262 }
7263
7264 // always read samples from chain input buffer
7265 effect->setInBuffer(mInBuffer);
7266
7267 // if last effect in the chain, output samples to chain
7268 // output buffer, otherwise to chain input buffer
7269 if (idx_insert == size) {
7270 if (idx_insert != 0) {
7271 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7272 mEffects[idx_insert-1]->configure();
7273 }
7274 effect->setOutBuffer(mOutBuffer);
7275 } else {
7276 effect->setOutBuffer(mInBuffer);
7277 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007278 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007279
Steve Block71f2cf12011-10-20 11:56:00 +01007280 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007281 }
7282 effect->configure();
7283 return NO_ERROR;
7284}
7285
Eric Laurent76c40f72010-07-15 12:50:15 -07007286// removeEffect_l() must be called with PlaybackThread::mLock held
7287size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007288{
7289 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007290 int size = (int)mEffects.size();
7291 int i;
7292 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7293
7294 for (i = 0; i < size; i++) {
7295 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007296 // calling stop here will remove pre-processing effect from the audio HAL.
7297 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7298 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007299 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7300 mEffects[i]->state() == EffectModule::STOPPING) {
7301 mEffects[i]->stop();
7302 }
Eric Laurent65b65452010-06-01 23:49:17 -07007303 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7304 delete[] effect->inBuffer();
7305 } else {
7306 if (i == size - 1 && i != 0) {
7307 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7308 mEffects[i - 1]->configure();
7309 }
7310 }
7311 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007312 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007313 break;
7314 }
7315 }
Eric Laurent65b65452010-06-01 23:49:17 -07007316
7317 return mEffects.size();
7318}
7319
Eric Laurent76c40f72010-07-15 12:50:15 -07007320// setDevice_l() must be called with PlaybackThread::mLock held
7321void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007322{
7323 size_t size = mEffects.size();
7324 for (size_t i = 0; i < size; i++) {
7325 mEffects[i]->setDevice(device);
7326 }
7327}
7328
Eric Laurent76c40f72010-07-15 12:50:15 -07007329// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenaccb1142012-01-04 11:00:47 -08007330void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007331{
7332 size_t size = mEffects.size();
7333 for (size_t i = 0; i < size; i++) {
7334 mEffects[i]->setMode(mode);
7335 }
7336}
7337
Eric Laurent76c40f72010-07-15 12:50:15 -07007338// setVolume_l() must be called with PlaybackThread::mLock held
7339bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007340{
7341 uint32_t newLeft = *left;
7342 uint32_t newRight = *right;
7343 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007344 int ctrlIdx = -1;
7345 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007346
Eric Laurent76c40f72010-07-15 12:50:15 -07007347 // first update volume controller
7348 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007349 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007350 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7351 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007352 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007353 break;
7354 }
7355 }
7356
7357 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007358 if (hasControl) {
7359 *left = mNewLeftVolume;
7360 *right = mNewRightVolume;
7361 }
7362 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007363 }
7364
7365 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007366 mLeftVolume = newLeft;
7367 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007368
7369 // second get volume update from volume controller
7370 if (ctrlIdx >= 0) {
7371 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007372 mNewLeftVolume = newLeft;
7373 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007374 }
7375 // then indicate volume to all other effects in chain.
7376 // Pass altered volume to effects before volume controller
7377 // and requested volume to effects after controller
7378 uint32_t lVol = newLeft;
7379 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007380
Eric Laurent65b65452010-06-01 23:49:17 -07007381 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007382 if ((int)i == ctrlIdx) continue;
7383 // this also works for ctrlIdx == -1 when there is no volume controller
7384 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007385 lVol = *left;
7386 rVol = *right;
7387 }
7388 mEffects[i]->setVolume(&lVol, &rVol, false);
7389 }
7390 *left = newLeft;
7391 *right = newRight;
7392
7393 return hasControl;
7394}
7395
Eric Laurent65b65452010-06-01 23:49:17 -07007396status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7397{
7398 const size_t SIZE = 256;
7399 char buffer[SIZE];
7400 String8 result;
7401
7402 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7403 result.append(buffer);
7404
7405 bool locked = tryLock(mLock);
7406 // failed to lock - AudioFlinger is probably deadlocked
7407 if (!locked) {
7408 result.append("\tCould not lock mutex:\n");
7409 }
7410
Eric Laurent76c40f72010-07-15 12:50:15 -07007411 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7412 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007413 mEffects.size(),
7414 (uint32_t)mInBuffer,
7415 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007416 mActiveTrackCnt);
7417 result.append(buffer);
7418 write(fd, result.string(), result.size());
7419
7420 for (size_t i = 0; i < mEffects.size(); ++i) {
7421 sp<EffectModule> effect = mEffects[i];
7422 if (effect != 0) {
7423 effect->dump(fd, args);
7424 }
7425 }
7426
7427 if (locked) {
7428 mLock.unlock();
7429 }
7430
7431 return NO_ERROR;
7432}
7433
Eric Laurentf82fccd2011-07-27 19:49:51 -07007434// must be called with ThreadBase::mLock held
7435void AudioFlinger::EffectChain::setEffectSuspended_l(
7436 const effect_uuid_t *type, bool suspend)
7437{
7438 sp<SuspendedEffectDesc> desc;
7439 // use effect type UUID timelow as key as there is no real risk of identical
7440 // timeLow fields among effect type UUIDs.
7441 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7442 if (suspend) {
7443 if (index >= 0) {
7444 desc = mSuspendedEffects.valueAt(index);
7445 } else {
7446 desc = new SuspendedEffectDesc();
7447 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7448 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007449 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007450 }
7451 if (desc->mRefCount++ == 0) {
7452 sp<EffectModule> effect = getEffectIfEnabled(type);
7453 if (effect != 0) {
7454 desc->mEffect = effect;
7455 effect->setSuspended(true);
7456 effect->setEnabled(false);
7457 }
7458 }
7459 } else {
7460 if (index < 0) {
7461 return;
7462 }
7463 desc = mSuspendedEffects.valueAt(index);
7464 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007465 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007466 desc->mRefCount = 1;
7467 }
7468 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007469 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007470 if (desc->mEffect != 0) {
7471 sp<EffectModule> effect = desc->mEffect.promote();
7472 if (effect != 0) {
7473 effect->setSuspended(false);
7474 sp<EffectHandle> handle = effect->controlHandle();
7475 if (handle != 0) {
7476 effect->setEnabled(handle->enabled());
7477 }
7478 }
7479 desc->mEffect.clear();
7480 }
7481 mSuspendedEffects.removeItemsAt(index);
7482 }
7483 }
7484}
7485
7486// must be called with ThreadBase::mLock held
7487void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7488{
7489 sp<SuspendedEffectDesc> desc;
7490
7491 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7492 if (suspend) {
7493 if (index >= 0) {
7494 desc = mSuspendedEffects.valueAt(index);
7495 } else {
7496 desc = new SuspendedEffectDesc();
7497 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007498 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007499 }
7500 if (desc->mRefCount++ == 0) {
Glenn Kasten97040262012-01-30 12:56:03 -08007501 Vector< sp<EffectModule> > effects;
7502 getSuspendEligibleEffects(effects);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007503 for (size_t i = 0; i < effects.size(); i++) {
7504 setEffectSuspended_l(&effects[i]->desc().type, true);
7505 }
7506 }
7507 } else {
7508 if (index < 0) {
7509 return;
7510 }
7511 desc = mSuspendedEffects.valueAt(index);
7512 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007513 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007514 desc->mRefCount = 1;
7515 }
7516 if (--desc->mRefCount == 0) {
7517 Vector<const effect_uuid_t *> types;
7518 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7519 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7520 continue;
7521 }
7522 types.add(&mSuspendedEffects.valueAt(i)->mType);
7523 }
7524 for (size_t i = 0; i < types.size(); i++) {
7525 setEffectSuspended_l(types[i], false);
7526 }
Steve Block71f2cf12011-10-20 11:56:00 +01007527 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007528 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7529 }
7530 }
7531}
7532
Eric Laurent5e7acae2011-09-23 08:40:41 -07007533
7534// The volume effect is used for automated tests only
7535#ifndef OPENSL_ES_H_
7536static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7537 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7538const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7539#endif //OPENSL_ES_H_
7540
Eric Laurent6752ec82011-08-10 10:37:50 -07007541bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7542{
7543 // auxiliary effects and visualizer are never suspended on output mix
7544 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7545 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007546 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7547 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007548 return false;
7549 }
7550 return true;
7551}
7552
Glenn Kasten97040262012-01-30 12:56:03 -08007553void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurentf82fccd2011-07-27 19:49:51 -07007554{
Glenn Kasten97040262012-01-30 12:56:03 -08007555 effects.clear();
Eric Laurentf82fccd2011-07-27 19:49:51 -07007556 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kasten97040262012-01-30 12:56:03 -08007557 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7558 effects.add(mEffects[i]);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007559 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007560 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007561}
7562
7563sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7564 const effect_uuid_t *type)
7565{
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007566 sp<EffectModule> effect = getEffectFromType_l(type);
7567 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007568}
7569
7570void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7571 bool enabled)
7572{
7573 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7574 if (enabled) {
7575 if (index < 0) {
7576 // if the effect is not suspend check if all effects are suspended
7577 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7578 if (index < 0) {
7579 return;
7580 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007581 if (!isEffectEligibleForSuspend(effect->desc())) {
7582 return;
7583 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007584 setEffectSuspended_l(&effect->desc().type, enabled);
7585 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007586 if (index < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007587 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurent6752ec82011-08-10 10:37:50 -07007588 return;
7589 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007590 }
Steve Block71f2cf12011-10-20 11:56:00 +01007591 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007592 effect->desc().type.timeLow);
7593 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7594 // if effect is requested to suspended but was not yet enabled, supend it now.
7595 if (desc->mEffect == 0) {
7596 desc->mEffect = effect;
7597 effect->setEnabled(false);
7598 effect->setSuspended(true);
7599 }
7600 } else {
7601 if (index < 0) {
7602 return;
7603 }
Steve Block71f2cf12011-10-20 11:56:00 +01007604 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007605 effect->desc().type.timeLow);
7606 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7607 desc->mEffect.clear();
7608 effect->setSuspended(false);
7609 }
7610}
7611
Eric Laurent65b65452010-06-01 23:49:17 -07007612#undef LOG_TAG
7613#define LOG_TAG "AudioFlinger"
7614
Eric Laurenta553c252009-07-17 12:17:14 -07007615// ----------------------------------------------------------------------------
7616
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007617status_t AudioFlinger::onTransact(
7618 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7619{
7620 return BnAudioFlinger::onTransact(code, data, reply, flags);
7621}
7622
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007623}; // namespace android