blob: 819a12c12d8bc8d16bcbcd87188fe6c5c1b9348f [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 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800248}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800249
Dima Zavin31f188892011-04-18 16:57:27 -0700250audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
251{
252 /* first matching HW device is returned */
253 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
254 audio_hw_device_t *dev = mAudioHwDevs[i];
255 if ((dev->get_supported_devices(dev) & devices) == devices)
256 return dev;
257 }
258 return NULL;
259}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700260
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700261status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
262{
263 const size_t SIZE = 256;
264 char buffer[SIZE];
265 String8 result;
266
267 result.append("Clients:\n");
268 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kastene4787422012-01-25 14:27:41 -0800269 sp<Client> client = mClients.valueAt(i).promote();
270 if (client != 0) {
271 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
272 result.append(buffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700273 }
274 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700275
276 result.append("Global session refs:\n");
277 result.append(" session pid cnt\n");
278 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
279 AudioSessionRef *r = mAudioSessionRefs[i];
280 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
281 result.append(buffer);
282 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700283 write(fd, result.string(), result.size());
284 return NO_ERROR;
285}
286
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700287
288status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
289{
290 const size_t SIZE = 256;
291 char buffer[SIZE];
292 String8 result;
Glenn Kastena934c2c2012-01-04 11:02:33 -0800293 hardware_call_state hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700294
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700295 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700296 result.append(buffer);
297 write(fd, result.string(), result.size());
298 return NO_ERROR;
299}
300
301status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
302{
303 const size_t SIZE = 256;
304 char buffer[SIZE];
305 String8 result;
306 snprintf(buffer, SIZE, "Permission Denial: "
307 "can't dump AudioFlinger from pid=%d, uid=%d\n",
308 IPCThreadState::self()->getCallingPid(),
309 IPCThreadState::self()->getCallingUid());
310 result.append(buffer);
311 write(fd, result.string(), result.size());
312 return NO_ERROR;
313}
314
The Android Open Source Project10592532009-03-18 17:39:46 -0700315static bool tryLock(Mutex& mutex)
316{
317 bool locked = false;
318 for (int i = 0; i < kDumpLockRetries; ++i) {
319 if (mutex.tryLock() == NO_ERROR) {
320 locked = true;
321 break;
322 }
Glenn Kastencbfe2e12011-12-13 11:04:14 -0800323 usleep(kDumpLockSleepUs);
The Android Open Source Project10592532009-03-18 17:39:46 -0700324 }
325 return locked;
326}
327
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700328status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
329{
Glenn Kastenb737dbb2012-01-13 15:54:24 -0800330 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700331 dumpPermissionDenial(fd, args);
332 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700333 // get state of hardware lock
334 bool hardwareLocked = tryLock(mHardwareLock);
335 if (!hardwareLocked) {
336 String8 result(kHardwareLockedString);
337 write(fd, result.string(), result.size());
338 } else {
339 mHardwareLock.unlock();
340 }
341
342 bool locked = tryLock(mLock);
343
344 // failed to lock - AudioFlinger is probably deadlocked
345 if (!locked) {
346 String8 result(kDeadlockedString);
347 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700348 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700349
350 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700351 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352
Eric Laurenta553c252009-07-17 12:17:14 -0700353 // dump playback threads
354 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700355 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700356 }
357
358 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700359 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700360 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362
Dima Zavin31f188892011-04-18 16:57:27 -0700363 // dump all hardware devs
364 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
365 audio_hw_device_t *dev = mAudioHwDevs[i];
366 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700367 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700368 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700369 }
370 return NO_ERROR;
371}
372
Glenn Kasten803a86a2012-01-25 14:28:29 -0800373sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
374{
375 // If pid is already in the mClients wp<> map, then use that entry
376 // (for which promote() is always != 0), otherwise create a new entry and Client.
377 sp<Client> client = mClients.valueFor(pid).promote();
378 if (client == 0) {
379 client = new Client(this, pid);
380 mClients.add(pid, client);
381 }
382
383 return client;
384}
Eric Laurenta553c252009-07-17 12:17:14 -0700385
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700386// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387
388
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700389sp<IAudioTrack> AudioFlinger::createTrack(
390 pid_t pid,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800391 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700392 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800393 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700394 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800395 int frameCount,
396 uint32_t flags,
397 const sp<IMemory>& sharedBuffer,
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800398 audio_io_handle_t output,
Eric Laurent65b65452010-06-01 23:49:17 -0700399 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800400 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700401{
Eric Laurenta553c252009-07-17 12:17:14 -0700402 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700403 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700404 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800405 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700406 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700407
Glenn Kasten6e987a42012-01-06 08:40:01 -0800408 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
409 // but if someone uses binder directly they could bypass that and cause us to crash
410 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block3762c312012-01-06 19:20:56 +0000411 ALOGE("createTrack() invalid stream type %d", streamType);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800412 lStatus = BAD_VALUE;
413 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700414 }
415
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800416 {
417 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700418 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700419 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700420 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +0000421 ALOGE("unknown output thread");
Eric Laurenta553c252009-07-17 12:17:14 -0700422 lStatus = BAD_VALUE;
423 goto Exit;
424 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800425
Glenn Kasten803a86a2012-01-25 14:28:29 -0800426 client = registerPid_l(pid);
Eric Laurent65b65452010-06-01 23:49:17 -0700427
Steve Block71f2cf12011-10-20 11:56:00 +0100428 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700429 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700430 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700431 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
432 if (mPlaybackThreads.keyAt(i) != output) {
433 // prevent same audio session on different output threads
434 uint32_t sessions = t->hasAudioSession(*sessionId);
435 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block3762c312012-01-06 19:20:56 +0000436 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent493941b2010-07-28 01:32:47 -0700437 lStatus = BAD_VALUE;
438 goto Exit;
439 }
440 // check if an effect with same session ID is waiting for a track to be created
441 if (sessions & PlaybackThread::EFFECT_SESSION) {
442 effectThread = t.get();
443 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700444 }
445 }
Eric Laurent65b65452010-06-01 23:49:17 -0700446 lSessionId = *sessionId;
447 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700448 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700449 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700450 if (sessionId != NULL) {
451 *sessionId = lSessionId;
452 }
453 }
Steve Block71f2cf12011-10-20 11:56:00 +0100454 ALOGV("createTrack() lSessionId: %d", lSessionId);
Eric Laurent65b65452010-06-01 23:49:17 -0700455
Eric Laurenta553c252009-07-17 12:17:14 -0700456 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700457 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700458
459 // move effect chain to this output thread if an effect on same session was waiting
460 // for a track to be created
461 if (lStatus == NO_ERROR && effectThread != NULL) {
462 Mutex::Autolock _dl(thread->mLock);
463 Mutex::Autolock _sl(effectThread->mLock);
464 moveEffectChain_l(lSessionId, effectThread, thread, true);
465 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700466 }
467 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800468 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700469 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700470 // remove local strong reference to Client before deleting the Track so that the Client
471 // destructor is called by the TrackBase destructor with mLock held
472 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700473 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800474 }
475
476Exit:
477 if(status) {
478 *status = lStatus;
479 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700480 return trackHandle;
481}
482
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800483uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700484{
Eric Laurenta553c252009-07-17 12:17:14 -0700485 Mutex::Autolock _l(mLock);
486 PlaybackThread *thread = checkPlaybackThread_l(output);
487 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000488 ALOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700489 return 0;
490 }
491 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700492}
493
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800494int AudioFlinger::channelCount(audio_io_handle_t output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700495{
Eric Laurenta553c252009-07-17 12:17:14 -0700496 Mutex::Autolock _l(mLock);
497 PlaybackThread *thread = checkPlaybackThread_l(output);
498 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000499 ALOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700500 return 0;
501 }
502 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700503}
504
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800505audio_format_t AudioFlinger::format(audio_io_handle_t output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700506{
Eric Laurenta553c252009-07-17 12:17:14 -0700507 Mutex::Autolock _l(mLock);
508 PlaybackThread *thread = checkPlaybackThread_l(output);
509 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000510 ALOGW("format() unknown thread %d", output);
Glenn Kasten0a204ed2012-01-12 12:27:51 -0800511 return AUDIO_FORMAT_INVALID;
Eric Laurenta553c252009-07-17 12:17:14 -0700512 }
513 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700514}
515
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800516size_t AudioFlinger::frameCount(audio_io_handle_t output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700517{
Eric Laurenta553c252009-07-17 12:17:14 -0700518 Mutex::Autolock _l(mLock);
519 PlaybackThread *thread = checkPlaybackThread_l(output);
520 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000521 ALOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700522 return 0;
523 }
524 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700525}
526
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800527uint32_t AudioFlinger::latency(audio_io_handle_t output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800528{
Eric Laurenta553c252009-07-17 12:17:14 -0700529 Mutex::Autolock _l(mLock);
530 PlaybackThread *thread = checkPlaybackThread_l(output);
531 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000532 ALOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700533 return 0;
534 }
535 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800536}
537
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700538status_t AudioFlinger::setMasterVolume(float value)
539{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700540 status_t ret = initCheck();
541 if (ret != NO_ERROR) {
542 return ret;
543 }
544
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700545 // check calling permissions
546 if (!settingsAllowed()) {
547 return PERMISSION_DENIED;
548 }
549
550 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800551 { // scope for the lock
552 AutoMutex lock(mHardwareLock);
553 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700554 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800555 value = 1.0f;
556 }
557 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700558 }
Eric Laurenta553c252009-07-17 12:17:14 -0700559
Eric Laurent01635942011-01-18 18:39:02 -0800560 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700561 mMasterVolume = value;
562 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700563 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700564
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700565 return NO_ERROR;
566}
567
Glenn Kastenaccb1142012-01-04 11:00:47 -0800568status_t AudioFlinger::setMode(audio_mode_t mode)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700569{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700570 status_t ret = initCheck();
571 if (ret != NO_ERROR) {
572 return ret;
573 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700574
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700575 // check calling permissions
576 if (!settingsAllowed()) {
577 return PERMISSION_DENIED;
578 }
Glenn Kasten01aaf2c2012-01-06 16:47:31 -0800579 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block8564c8d2012-01-05 23:22:43 +0000580 ALOGW("Illegal value: setMode(%d)", mode);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700581 return BAD_VALUE;
582 }
583
Eric Laurent53334cd2010-06-23 17:38:20 -0700584 { // scope for the lock
585 AutoMutex lock(mHardwareLock);
586 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700587 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700588 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800589 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700590
591 if (NO_ERROR == ret) {
592 Mutex::Autolock _l(mLock);
593 mMode = mode;
594 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
595 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700596 }
597
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700598 return ret;
599}
600
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700601status_t AudioFlinger::setMicMute(bool state)
602{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700603 status_t ret = initCheck();
604 if (ret != NO_ERROR) {
605 return ret;
606 }
607
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700608 // check calling permissions
609 if (!settingsAllowed()) {
610 return PERMISSION_DENIED;
611 }
612
613 AutoMutex lock(mHardwareLock);
614 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700615 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700616 mHardwareStatus = AUDIO_HW_IDLE;
617 return ret;
618}
619
620bool AudioFlinger::getMicMute() const
621{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700622 status_t ret = initCheck();
623 if (ret != NO_ERROR) {
624 return false;
625 }
626
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700627 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700628 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700629 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700630 mHardwareStatus = AUDIO_HW_IDLE;
631 return state;
632}
633
634status_t AudioFlinger::setMasterMute(bool muted)
635{
636 // check calling permissions
637 if (!settingsAllowed()) {
638 return PERMISSION_DENIED;
639 }
Eric Laurenta553c252009-07-17 12:17:14 -0700640
Eric Laurent01635942011-01-18 18:39:02 -0800641 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700642 mMasterMute = muted;
643 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700644 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700645
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700646 return NO_ERROR;
647}
648
649float AudioFlinger::masterVolume() const
650{
Glenn Kastene6f8a422011-12-13 11:47:54 -0800651 Mutex::Autolock _l(mLock);
652 return masterVolume_l();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700653}
654
655bool AudioFlinger::masterMute() const
656{
Glenn Kastene6f8a422011-12-13 11:47:54 -0800657 Mutex::Autolock _l(mLock);
658 return masterMute_l();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700659}
660
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800661status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
662 audio_io_handle_t output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700663{
664 // check calling permissions
665 if (!settingsAllowed()) {
666 return PERMISSION_DENIED;
667 }
668
Glenn Kasten6e987a42012-01-06 08:40:01 -0800669 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block3762c312012-01-06 19:20:56 +0000670 ALOGE("setStreamVolume() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700671 return BAD_VALUE;
672 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800673
Eric Laurenta553c252009-07-17 12:17:14 -0700674 AutoMutex lock(mLock);
675 PlaybackThread *thread = NULL;
676 if (output) {
677 thread = checkPlaybackThread_l(output);
678 if (thread == NULL) {
679 return BAD_VALUE;
680 }
681 }
682
Eric Laurenta553c252009-07-17 12:17:14 -0700683 mStreamTypes[stream].volume = value;
684
685 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700686 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700687 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700688 }
Eric Laurenta553c252009-07-17 12:17:14 -0700689 } else {
690 thread->setStreamVolume(stream, value);
691 }
Eric Laurentef028272009-04-21 07:56:33 -0700692
Eric Laurent415f3e22009-10-21 08:14:22 -0700693 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700694}
695
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800696status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700697{
698 // check calling permissions
699 if (!settingsAllowed()) {
700 return PERMISSION_DENIED;
701 }
702
Glenn Kasten6e987a42012-01-06 08:40:01 -0800703 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700704 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block3762c312012-01-06 19:20:56 +0000705 ALOGE("setStreamMute() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700706 return BAD_VALUE;
707 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700708
Eric Laurent01635942011-01-18 18:39:02 -0800709 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700710 mStreamTypes[stream].mute = muted;
711 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700712 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700714 return NO_ERROR;
715}
716
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800717float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700718{
Glenn Kasten6e987a42012-01-06 08:40:01 -0800719 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700720 return 0.0f;
721 }
Eric Laurenta553c252009-07-17 12:17:14 -0700722
723 AutoMutex lock(mLock);
724 float volume;
725 if (output) {
726 PlaybackThread *thread = checkPlaybackThread_l(output);
727 if (thread == NULL) {
728 return 0.0f;
729 }
730 volume = thread->streamVolume(stream);
731 } else {
732 volume = mStreamTypes[stream].volume;
733 }
734
Eric Laurentef028272009-04-21 07:56:33 -0700735 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700736}
737
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800738bool AudioFlinger::streamMute(audio_stream_type_t stream) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700739{
Glenn Kasten6e987a42012-01-06 08:40:01 -0800740 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700741 return true;
742 }
Eric Laurenta553c252009-07-17 12:17:14 -0700743
744 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700745}
746
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800747status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700748{
Eric Laurenta553c252009-07-17 12:17:14 -0700749 status_t result;
750
Steve Block71f2cf12011-10-20 11:56:00 +0100751 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700752 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
753 // check calling permissions
754 if (!settingsAllowed()) {
755 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800756 }
Eric Laurenta553c252009-07-17 12:17:14 -0700757
758 // ioHandle == 0 means the parameters are global to the audio hardware interface
759 if (ioHandle == 0) {
760 AutoMutex lock(mHardwareLock);
761 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700762 status_t final_result = NO_ERROR;
763 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
764 audio_hw_device_t *dev = mAudioHwDevs[i];
765 result = dev->set_parameters(dev, keyValuePairs.string());
766 final_result = result ?: final_result;
767 }
Eric Laurenta553c252009-07-17 12:17:14 -0700768 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent6639b552011-08-01 09:52:20 -0700769 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
770 AudioParameter param = AudioParameter(keyValuePairs);
771 String8 value;
772 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
773 Mutex::Autolock _l(mLock);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700774 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
775 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent6639b552011-08-01 09:52:20 -0700776 for (size_t i = 0; i < mRecordThreads.size(); i++) {
777 sp<RecordThread> thread = mRecordThreads.valueAt(i);
778 RecordThread::RecordTrack *track = thread->track();
779 if (track != NULL) {
780 audio_devices_t device = (audio_devices_t)(
781 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700782 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700783 thread->setEffectSuspended(FX_IID_AEC,
784 suspend,
785 track->sessionId());
786 thread->setEffectSuspended(FX_IID_NS,
787 suspend,
788 track->sessionId());
789 }
790 }
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700791 mBtNrecIsOff = btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700792 }
793 }
Dima Zavin31f188892011-04-18 16:57:27 -0700794 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700795 }
796
Eric Laurentb7d94602009-09-29 11:12:57 -0700797 // hold a strong ref on thread in case closeOutput() or closeInput() is called
798 // and the thread is exited once the lock is released
799 sp<ThreadBase> thread;
800 {
801 Mutex::Autolock _l(mLock);
802 thread = checkPlaybackThread_l(ioHandle);
803 if (thread == NULL) {
804 thread = checkRecordThread_l(ioHandle);
Glenn Kasten70ed6b72012-01-10 10:46:34 -0800805 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent464d5b32011-06-17 21:29:58 -0700806 // indicate output device change to all input threads for pre processing
807 AudioParameter param = AudioParameter(keyValuePairs);
808 int value;
809 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
810 for (size_t i = 0; i < mRecordThreads.size(); i++) {
811 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
812 }
813 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700814 }
Eric Laurenta553c252009-07-17 12:17:14 -0700815 }
Glenn Kasten706b6182012-01-20 13:44:40 -0800816 if (thread != 0) {
817 return thread->setParameters(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700818 }
Eric Laurenta553c252009-07-17 12:17:14 -0700819 return BAD_VALUE;
820}
821
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800822String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Eric Laurenta553c252009-07-17 12:17:14 -0700823{
Steve Block71f2cf12011-10-20 11:56:00 +0100824// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700825// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
826
827 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700828 String8 out_s8;
829
Dima Zavin31f188892011-04-18 16:57:27 -0700830 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
831 audio_hw_device_t *dev = mAudioHwDevs[i];
832 char *s = dev->get_parameters(dev, keys.string());
833 out_s8 += String8(s);
834 free(s);
835 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700836 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700837 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700838
839 Mutex::Autolock _l(mLock);
840
Eric Laurenta553c252009-07-17 12:17:14 -0700841 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
842 if (playbackThread != NULL) {
843 return playbackThread->getParameters(keys);
844 }
845 RecordThread *recordThread = checkRecordThread_l(ioHandle);
846 if (recordThread != NULL) {
847 return recordThread->getParameters(keys);
848 }
849 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700850}
851
Glenn Kasten3f6d83a2012-01-26 16:25:10 -0800852size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700854 status_t ret = initCheck();
855 if (ret != NO_ERROR) {
856 return 0;
857 }
858
Dima Zavin31f188892011-04-18 16:57:27 -0700859 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860}
861
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800862unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Eric Laurent47d0a922010-02-26 02:47:27 -0800863{
864 if (ioHandle == 0) {
865 return 0;
866 }
867
868 Mutex::Autolock _l(mLock);
869
870 RecordThread *recordThread = checkRecordThread_l(ioHandle);
871 if (recordThread != NULL) {
872 return recordThread->getInputFramesLost();
873 }
874 return 0;
875}
876
Eric Laurent415f3e22009-10-21 08:14:22 -0700877status_t AudioFlinger::setVoiceVolume(float value)
878{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700879 status_t ret = initCheck();
880 if (ret != NO_ERROR) {
881 return ret;
882 }
883
Eric Laurent415f3e22009-10-21 08:14:22 -0700884 // check calling permissions
885 if (!settingsAllowed()) {
886 return PERMISSION_DENIED;
887 }
888
889 AutoMutex lock(mHardwareLock);
890 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700891 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700892 mHardwareStatus = AUDIO_HW_IDLE;
893
894 return ret;
895}
896
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800897status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
898 audio_io_handle_t output) const
Eric Laurent0986e792010-01-19 17:37:09 -0800899{
900 status_t status;
901
902 Mutex::Autolock _l(mLock);
903
904 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
905 if (playbackThread != NULL) {
906 return playbackThread->getRenderPosition(halFrames, dspFrames);
907 }
908
909 return BAD_VALUE;
910}
911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
913{
Eric Laurenta553c252009-07-17 12:17:14 -0700914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 Mutex::Autolock _l(mLock);
916
Glenn Kastend153b1f2012-02-03 11:10:26 -0800917 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700918 if (mNotificationClients.indexOfKey(pid) < 0) {
919 sp<NotificationClient> notificationClient = new NotificationClient(this,
920 client,
921 pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100922 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700923
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700924 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700925
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700926 sp<IBinder> binder = client->asBinder();
927 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700929 // the config change is always sent from playback or record threads to avoid deadlock
930 // with AudioSystem::gLock
931 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
932 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
933 }
Eric Laurenta553c252009-07-17 12:17:14 -0700934
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700935 for (size_t i = 0; i < mRecordThreads.size(); i++) {
936 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 }
938 }
939}
940
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700941void AudioFlinger::removeNotificationClient(pid_t pid)
942{
943 Mutex::Autolock _l(mLock);
944
945 int index = mNotificationClients.indexOfKey(pid);
946 if (index >= 0) {
947 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100948 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700949 mNotificationClients.removeItem(pid);
950 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700951
Steve Block71f2cf12011-10-20 11:56:00 +0100952 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700953 int num = mAudioSessionRefs.size();
954 bool removed = false;
955 for (int i = 0; i< num; i++) {
956 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +0100957 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700958 if (ref->pid == pid) {
Steve Block71f2cf12011-10-20 11:56:00 +0100959 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700960 mAudioSessionRefs.removeAt(i);
961 delete ref;
962 removed = true;
963 i--;
964 num--;
965 }
966 }
967 if (removed) {
968 purgeStaleEffects_l();
969 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700970}
971
Eric Laurent296a0ec2009-09-15 07:10:12 -0700972// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800973void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700974{
Eric Laurent49f02be2009-11-19 09:00:56 -0800975 size_t size = mNotificationClients.size();
976 for (size_t i = 0; i < size; i++) {
Glenn Kastendc3ac852012-01-25 15:28:08 -0800977 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
978 param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700979 }
980}
981
Eric Laurentb9481d82009-09-17 05:12:56 -0700982// removeClient_l() must be called with AudioFlinger::mLock held
983void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700984{
Steve Block71f2cf12011-10-20 11:56:00 +0100985 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 -0700986 mClients.removeItem(pid);
987}
988
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700989
Eric Laurenta553c252009-07-17 12:17:14 -0700990// ----------------------------------------------------------------------------
991
Glenn Kasten39d00cb2012-01-17 11:09:42 -0800992AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
993 uint32_t device, type_t type)
Eric Laurenta553c252009-07-17 12:17:14 -0700994 : Thread(false),
Glenn Kastenefd511a2012-01-26 10:38:26 -0800995 mType(type),
Glenn Kastendc3ac852012-01-25 15:28:08 -0800996 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
997 // mChannelMask
998 mChannelCount(0),
999 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1000 mParamStatus(NO_ERROR),
1001 mStandby(false), mId(id), mExiting(false),
1002 mDevice(device),
1003 mDeathRecipient(new PMDeathRecipient(this))
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001004{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005}
1006
Eric Laurenta553c252009-07-17 12:17:14 -07001007AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001009 mParamCond.broadcast();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001010 // do not lock the mutex in destructor
1011 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -07001012 if (mPowerManager != 0) {
1013 sp<IBinder> binder = mPowerManager->asBinder();
1014 binder->unlinkToDeath(mDeathRecipient);
1015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016}
1017
Eric Laurenta553c252009-07-17 12:17:14 -07001018void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001019{
Glenn Kastene5fb2632011-12-14 10:28:06 -08001020 // keep a strong ref on ourself so that we won't get
Eric Laurenta553c252009-07-17 12:17:14 -07001021 // destroyed in the middle of requestExitAndWait()
1022 sp <ThreadBase> strongMe = this;
1023
Steve Block71f2cf12011-10-20 11:56:00 +01001024 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001025 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08001026 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001027 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001028 requestExit();
1029 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001030 }
Eric Laurenta553c252009-07-17 12:17:14 -07001031 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001032}
Eric Laurenta553c252009-07-17 12:17:14 -07001033
Eric Laurenta553c252009-07-17 12:17:14 -07001034status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1035{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001036 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001037
Steve Block71f2cf12011-10-20 11:56:00 +01001038 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001039 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001040
Eric Laurent8fce46a2009-08-04 09:45:33 -07001041 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001042 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001043 // wait condition with timeout in case the thread loop has exited
1044 // before the request could be processed
Glenn Kastencbfe2e12011-12-13 11:04:14 -08001045 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001046 status = mParamStatus;
1047 mWaitWorkCV.signal();
1048 } else {
1049 status = TIMED_OUT;
1050 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001051 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001052}
1053
1054void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1055{
1056 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001057 sendConfigEvent_l(event, param);
1058}
1059
1060// sendConfigEvent_l() must be called with ThreadBase::mLock held
1061void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1062{
Glenn Kasten4b220f02011-12-13 11:50:00 -08001063 ConfigEvent configEvent;
1064 configEvent.mEvent = event;
1065 configEvent.mParam = param;
Eric Laurenta553c252009-07-17 12:17:14 -07001066 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001067 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001068 mWaitWorkCV.signal();
1069}
1070
1071void AudioFlinger::ThreadBase::processConfigEvents()
1072{
1073 mLock.lock();
1074 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001075 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kasten4b220f02011-12-13 11:50:00 -08001076 ConfigEvent configEvent = mConfigEvents[0];
Eric Laurenta553c252009-07-17 12:17:14 -07001077 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001078 // release mLock before locking AudioFlinger mLock: lock order is always
1079 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001080 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001081 mAudioFlinger->mLock.lock();
Glenn Kasten4b220f02011-12-13 11:50:00 -08001082 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001083 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001084 mLock.lock();
1085 }
1086 mLock.unlock();
1087}
1088
Eric Laurent3fdb1262009-11-07 00:01:32 -08001089status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1090{
1091 const size_t SIZE = 256;
1092 char buffer[SIZE];
1093 String8 result;
1094
1095 bool locked = tryLock(mLock);
1096 if (!locked) {
1097 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1098 write(fd, buffer, strlen(buffer));
1099 }
1100
1101 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1102 result.append(buffer);
1103 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1104 result.append(buffer);
1105 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1106 result.append(buffer);
1107 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1108 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001109 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1110 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001111 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1112 result.append(buffer);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001113 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001114 result.append(buffer);
1115
1116 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1117 result.append(buffer);
1118 result.append(" Index Command");
1119 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1120 snprintf(buffer, SIZE, "\n %02d ", i);
1121 result.append(buffer);
1122 result.append(mNewParameters[i]);
1123 }
1124
1125 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1126 result.append(buffer);
1127 snprintf(buffer, SIZE, " Index event param\n");
1128 result.append(buffer);
1129 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kasten4b220f02011-12-13 11:50:00 -08001130 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001131 result.append(buffer);
1132 }
1133 result.append("\n");
1134
1135 write(fd, result.string(), result.size());
1136
1137 if (locked) {
1138 mLock.unlock();
1139 }
1140 return NO_ERROR;
1141}
1142
Eric Laurent1345d332011-07-24 17:49:51 -07001143status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1144{
1145 const size_t SIZE = 256;
1146 char buffer[SIZE];
1147 String8 result;
1148
1149 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1150 write(fd, buffer, strlen(buffer));
1151
1152 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1153 sp<EffectChain> chain = mEffectChains[i];
1154 if (chain != 0) {
1155 chain->dump(fd, args);
1156 }
1157 }
1158 return NO_ERROR;
1159}
1160
Eric Laurent6dbdc402011-07-22 09:04:31 -07001161void AudioFlinger::ThreadBase::acquireWakeLock()
1162{
1163 Mutex::Autolock _l(mLock);
1164 acquireWakeLock_l();
1165}
1166
1167void AudioFlinger::ThreadBase::acquireWakeLock_l()
1168{
1169 if (mPowerManager == 0) {
1170 // use checkService() to avoid blocking if power service is not up yet
1171 sp<IBinder> binder =
1172 defaultServiceManager()->checkService(String16("power"));
1173 if (binder == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00001174 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001175 } else {
1176 mPowerManager = interface_cast<IPowerManager>(binder);
1177 binder->linkToDeath(mDeathRecipient);
1178 }
1179 }
1180 if (mPowerManager != 0) {
1181 sp<IBinder> binder = new BBinder();
1182 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1183 binder,
1184 String16(mName));
1185 if (status == NO_ERROR) {
1186 mWakeLockToken = binder;
1187 }
Steve Block71f2cf12011-10-20 11:56:00 +01001188 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001189 }
1190}
1191
1192void AudioFlinger::ThreadBase::releaseWakeLock()
1193{
1194 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001195 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001196}
1197
1198void AudioFlinger::ThreadBase::releaseWakeLock_l()
1199{
1200 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001201 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001202 if (mPowerManager != 0) {
1203 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1204 }
1205 mWakeLockToken.clear();
1206 }
1207}
1208
1209void AudioFlinger::ThreadBase::clearPowerManager()
1210{
1211 Mutex::Autolock _l(mLock);
1212 releaseWakeLock_l();
1213 mPowerManager.clear();
1214}
1215
1216void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1217{
1218 sp<ThreadBase> thread = mThread.promote();
1219 if (thread != 0) {
1220 thread->clearPowerManager();
1221 }
Steve Block8564c8d2012-01-05 23:22:43 +00001222 ALOGW("power manager service died !!!");
Eric Laurent6dbdc402011-07-22 09:04:31 -07001223}
Eric Laurent1345d332011-07-24 17:49:51 -07001224
Eric Laurentf82fccd2011-07-27 19:49:51 -07001225void AudioFlinger::ThreadBase::setEffectSuspended(
1226 const effect_uuid_t *type, bool suspend, int sessionId)
1227{
1228 Mutex::Autolock _l(mLock);
1229 setEffectSuspended_l(type, suspend, sessionId);
1230}
1231
1232void AudioFlinger::ThreadBase::setEffectSuspended_l(
1233 const effect_uuid_t *type, bool suspend, int sessionId)
1234{
Glenn Kastenc64a6f02012-01-30 13:00:02 -08001235 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001236 if (chain != 0) {
1237 if (type != NULL) {
1238 chain->setEffectSuspended_l(type, suspend);
1239 } else {
1240 chain->setEffectSuspendedAll_l(suspend);
1241 }
1242 }
1243
1244 updateSuspendedSessions_l(type, suspend, sessionId);
1245}
1246
1247void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1248{
1249 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1250 if (index < 0) {
1251 return;
1252 }
1253
1254 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1255 mSuspendedSessions.editValueAt(index);
1256
1257 for (size_t i = 0; i < sessionEffects.size(); i++) {
1258 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1259 for (int j = 0; j < desc->mRefCount; j++) {
1260 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1261 chain->setEffectSuspendedAll_l(true);
1262 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001263 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001264 desc->mType.timeLow);
1265 chain->setEffectSuspended_l(&desc->mType, true);
1266 }
1267 }
1268 }
1269}
1270
Eric Laurentf82fccd2011-07-27 19:49:51 -07001271void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1272 bool suspend,
1273 int sessionId)
1274{
1275 int index = mSuspendedSessions.indexOfKey(sessionId);
1276
1277 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1278
1279 if (suspend) {
1280 if (index >= 0) {
1281 sessionEffects = mSuspendedSessions.editValueAt(index);
1282 } else {
1283 mSuspendedSessions.add(sessionId, sessionEffects);
1284 }
1285 } else {
1286 if (index < 0) {
1287 return;
1288 }
1289 sessionEffects = mSuspendedSessions.editValueAt(index);
1290 }
1291
1292
1293 int key = EffectChain::kKeyForSuspendAll;
1294 if (type != NULL) {
1295 key = type->timeLow;
1296 }
1297 index = sessionEffects.indexOfKey(key);
1298
1299 sp <SuspendedSessionDesc> desc;
1300 if (suspend) {
1301 if (index >= 0) {
1302 desc = sessionEffects.valueAt(index);
1303 } else {
1304 desc = new SuspendedSessionDesc();
1305 if (type != NULL) {
1306 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1307 }
1308 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001309 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001310 }
1311 desc->mRefCount++;
1312 } else {
1313 if (index < 0) {
1314 return;
1315 }
1316 desc = sessionEffects.valueAt(index);
1317 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001318 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001319 sessionEffects.removeItemsAt(index);
1320 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001321 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001322 sessionId);
1323 mSuspendedSessions.removeItem(sessionId);
1324 }
1325 }
1326 }
1327 if (!sessionEffects.isEmpty()) {
1328 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1329 }
1330}
1331
1332void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1333 bool enabled,
1334 int sessionId)
1335{
1336 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001337 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1338}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001339
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001340void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1341 bool enabled,
1342 int sessionId)
1343{
Eric Laurent6752ec82011-08-10 10:37:50 -07001344 if (mType != RECORD) {
1345 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1346 // another session. This gives the priority to well behaved effect control panels
1347 // and applications not using global effects.
1348 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1349 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1350 }
1351 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001352
1353 sp<EffectChain> chain = getEffectChain_l(sessionId);
1354 if (chain != 0) {
1355 chain->checkSuspendOnEffectEnabled(effect, enabled);
1356 }
1357}
1358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359// ----------------------------------------------------------------------------
1360
Eric Laurent464d5b32011-06-17 21:29:58 -07001361AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1362 AudioStreamOut* output,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08001363 audio_io_handle_t id,
Glenn Kastenefd511a2012-01-26 10:38:26 -08001364 uint32_t device,
1365 type_t type)
1366 : ThreadBase(audioFlinger, id, device, type),
Glenn Kastendc3ac852012-01-25 15:28:08 -08001367 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1368 // Assumes constructor is called by AudioFlinger with it's mLock held,
1369 // but it would be safer to explicitly pass initial masterMute as parameter
1370 mMasterMute(audioFlinger->masterMute_l()),
1371 // mStreamTypes[] initialized in constructor body
1372 mOutput(output),
1373 // Assumes constructor is called by AudioFlinger with it's mLock held,
1374 // but it would be safer to explicitly pass initial masterVolume as parameter
1375 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent464d5b32011-06-17 21:29:58 -07001376 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001378 snprintf(mName, kNameLength, "AudioOut_%d", id);
1379
Eric Laurenta553c252009-07-17 12:17:14 -07001380 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381
Glenn Kasten6e987a42012-01-06 08:40:01 -08001382 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001383 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1384 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1385 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001386 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1387 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten6e987a42012-01-06 08:40:01 -08001388 // initialized by stream_type_t default constructor
1389 // mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391}
1392
Eric Laurenta553c252009-07-17 12:17:14 -07001393AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394{
1395 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396}
1397
Eric Laurenta553c252009-07-17 12:17:14 -07001398status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399{
1400 dumpInternals(fd, args);
1401 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001402 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 return NO_ERROR;
1404}
1405
Eric Laurenta553c252009-07-17 12:17:14 -07001406status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407{
1408 const size_t SIZE = 256;
1409 char buffer[SIZE];
1410 String8 result;
1411
Eric Laurenta553c252009-07-17 12:17:14 -07001412 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001414 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001416 sp<Track> track = mTracks[i];
1417 if (track != 0) {
1418 track->dump(buffer, SIZE);
1419 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421 }
1422
Eric Laurenta553c252009-07-17 12:17:14 -07001423 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001425 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kastene4787422012-01-25 14:27:41 -08001427 sp<Track> track = mActiveTracks[i].promote();
1428 if (track != 0) {
1429 track->dump(buffer, SIZE);
1430 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 }
1432 }
1433 write(fd, result.string(), result.size());
1434 return NO_ERROR;
1435}
1436
Eric Laurenta553c252009-07-17 12:17:14 -07001437status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438{
1439 const size_t SIZE = 256;
1440 char buffer[SIZE];
1441 String8 result;
1442
Eric Laurent3fdb1262009-11-07 00:01:32 -08001443 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 result.append(buffer);
1445 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1446 result.append(buffer);
1447 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1448 result.append(buffer);
1449 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1450 result.append(buffer);
1451 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1452 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001453 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1454 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001455 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1456 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001458
1459 dumpBase(fd, args);
1460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 return NO_ERROR;
1462}
1463
1464// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001465status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466{
Eric Laurent828b9772011-08-07 16:32:26 -07001467 status_t status = initCheck();
1468 if (status == NO_ERROR) {
Steve Block6215d3f2012-01-04 20:05:49 +00001469 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurent828b9772011-08-07 16:32:26 -07001470 } else {
Steve Block3762c312012-01-06 19:20:56 +00001471 ALOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 }
Eric Laurent828b9772011-08-07 16:32:26 -07001473 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474}
1475
Eric Laurenta553c252009-07-17 12:17:14 -07001476void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001478 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479}
1480
Eric Laurenta553c252009-07-17 12:17:14 -07001481// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1482sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 const sp<AudioFlinger::Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001484 audio_stream_type_t streamType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08001486 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001487 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 int frameCount,
1489 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001490 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 status_t *status)
1492{
1493 sp<Track> track;
1494 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001495
1496 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001497 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1498 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block3762c312012-01-06 19:20:56 +00001499 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001500 "for output %p with format %d",
1501 sampleRate, format, channelMask, mOutput, mFormat);
1502 lStatus = BAD_VALUE;
1503 goto Exit;
1504 }
Eric Laurenta553c252009-07-17 12:17:14 -07001505 }
1506 } else {
1507 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1508 if (sampleRate > mSampleRate*2) {
Steve Block3762c312012-01-06 19:20:56 +00001509 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Eric Laurenta553c252009-07-17 12:17:14 -07001510 lStatus = BAD_VALUE;
1511 goto Exit;
1512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 }
1514
Eric Laurent464d5b32011-06-17 21:29:58 -07001515 lStatus = initCheck();
1516 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00001517 ALOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001518 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 }
1520
Eric Laurenta553c252009-07-17 12:17:14 -07001521 { // scope for mLock
1522 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001523
1524 // all tracks in same audio session must share the same routing strategy otherwise
1525 // conflicts will happen when tracks are moved from one output to another by audio policy
1526 // manager
Glenn Kastenaae26c82012-02-08 12:35:35 -08001527 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001528 for (size_t i = 0; i < mTracks.size(); ++i) {
1529 sp<Track> t = mTracks[i];
1530 if (t != 0) {
Glenn Kastenaae26c82012-02-08 12:35:35 -08001531 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001532 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block3762c312012-01-06 19:20:56 +00001533 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001534 strategy, actual);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001535 lStatus = BAD_VALUE;
1536 goto Exit;
1537 }
1538 }
1539 }
1540
Eric Laurenta553c252009-07-17 12:17:14 -07001541 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001542 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001543 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001544 lStatus = NO_MEMORY;
1545 goto Exit;
1546 }
1547 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001548
1549 sp<EffectChain> chain = getEffectChain_l(sessionId);
1550 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001551 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001552 track->setMainBuffer(chain->inBuffer());
Glenn Kastenaae26c82012-02-08 12:35:35 -08001553 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurent90681d62011-05-09 12:09:06 -07001554 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001555 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001556
1557 // invalidate track immediately if the stream type was moved to another thread since
1558 // createTrack() was called by the client process.
1559 if (!mStreamTypes[streamType].valid) {
Steve Block8564c8d2012-01-05 23:22:43 +00001560 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07001561 this, streamType);
1562 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1563 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001564 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001565 lStatus = NO_ERROR;
1566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567Exit:
1568 if(status) {
1569 *status = lStatus;
1570 }
1571 return track;
1572}
1573
Eric Laurenta553c252009-07-17 12:17:14 -07001574uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575{
Eric Laurent828b9772011-08-07 16:32:26 -07001576 Mutex::Autolock _l(mLock);
1577 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001578 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001579 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 return 0;
1581 }
1582}
1583
Eric Laurenta553c252009-07-17 12:17:14 -07001584status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585{
1586 mMasterVolume = value;
1587 return NO_ERROR;
1588}
1589
Eric Laurenta553c252009-07-17 12:17:14 -07001590status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591{
1592 mMasterMute = muted;
1593 return NO_ERROR;
1594}
1595
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001596status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597{
1598 mStreamTypes[stream].volume = value;
1599 return NO_ERROR;
1600}
1601
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001602status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603{
1604 mStreamTypes[stream].mute = muted;
1605 return NO_ERROR;
1606}
1607
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001608float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609{
1610 return mStreamTypes[stream].volume;
1611}
1612
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001613bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614{
1615 return mStreamTypes[stream].mute;
1616}
1617
Eric Laurenta553c252009-07-17 12:17:14 -07001618// addTrack_l() must be called with ThreadBase::mLock held
1619status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620{
1621 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001622
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001623 // set retry count for buffer fill
1624 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001625 if (mActiveTracks.indexOf(track) < 0) {
1626 // the track is newly added, make sure it fills up all its
1627 // buffers before playing. This is to ensure the client will
1628 // effectively get the latency it requested.
1629 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001630 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001631 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001632 if (track->mainBuffer() != mMixBuffer) {
1633 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1634 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001635 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001636 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001637 }
1638 }
1639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001641 }
Eric Laurenta553c252009-07-17 12:17:14 -07001642
Steve Block71f2cf12011-10-20 11:56:00 +01001643 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001644 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645
1646 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001647}
1648
Eric Laurenta553c252009-07-17 12:17:14 -07001649// destroyTrack_l() must be called with ThreadBase::mLock held
1650void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001651{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001652 track->mState = TrackBase::TERMINATED;
1653 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001654 removeTrack_l(track);
1655 }
1656}
1657
1658void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1659{
1660 mTracks.remove(track);
1661 deleteTrackName_l(track->name());
1662 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1663 if (chain != 0) {
1664 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001665 }
1666}
1667
Eric Laurenta553c252009-07-17 12:17:14 -07001668String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001669{
Eric Laurent828b9772011-08-07 16:32:26 -07001670 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001671 char *s;
1672
Eric Laurent828b9772011-08-07 16:32:26 -07001673 Mutex::Autolock _l(mLock);
1674 if (initCheck() != NO_ERROR) {
1675 return out_s8;
1676 }
1677
Dima Zavin31f188892011-04-18 16:57:27 -07001678 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001679 out_s8 = String8(s);
1680 free(s);
1681 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001682}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001683
Eric Laurent828b9772011-08-07 16:32:26 -07001684// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001685void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001686 AudioSystem::OutputDescriptor desc;
Glenn Kasten3694ec12012-01-27 16:47:15 -08001687 void *param2 = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07001688
Steve Block71f2cf12011-10-20 11:56:00 +01001689 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001690
1691 switch (event) {
1692 case AudioSystem::OUTPUT_OPENED:
1693 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001694 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001695 desc.samplingRate = mSampleRate;
1696 desc.format = mFormat;
1697 desc.frameCount = mFrameCount;
1698 desc.latency = latency();
1699 param2 = &desc;
1700 break;
1701
1702 case AudioSystem::STREAM_CONFIG_CHANGED:
1703 param2 = &param;
1704 case AudioSystem::OUTPUT_CLOSED:
1705 default:
1706 break;
1707 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001708 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001709}
1710
1711void AudioFlinger::PlaybackThread::readOutputParameters()
1712{
Dima Zavin31f188892011-04-18 16:57:27 -07001713 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001714 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1715 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001716 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001717 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin31f188892011-04-18 16:57:27 -07001718 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001719
Eric Laurenta553c252009-07-17 12:17:14 -07001720 // FIXME - Current mixer implementation only supports stereo output: Always
1721 // Allocate a stereo buffer even if HW output is mono.
Glenn Kasten2589cf92012-01-27 18:08:45 -08001722 delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001723 mMixBuffer = new int16_t[mFrameCount * 2];
1724 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001725
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001726 // force reconfiguration of effect chains and engines to take new buffer size and audio
1727 // parameters into account
1728 // Note that mLock is not held when readOutputParameters() is called from the constructor
1729 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1730 // matter.
1731 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1732 Vector< sp<EffectChain> > effectChains = mEffectChains;
1733 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001734 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001735 }
Eric Laurenta553c252009-07-17 12:17:14 -07001736}
1737
Eric Laurent0986e792010-01-19 17:37:09 -08001738status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1739{
Glenn Kasten3694ec12012-01-27 16:47:15 -08001740 if (halFrames == NULL || dspFrames == NULL) {
Eric Laurent0986e792010-01-19 17:37:09 -08001741 return BAD_VALUE;
1742 }
Eric Laurent828b9772011-08-07 16:32:26 -07001743 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001744 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001745 return INVALID_OPERATION;
1746 }
Dima Zavin31f188892011-04-18 16:57:27 -07001747 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001748
Dima Zavin31f188892011-04-18 16:57:27 -07001749 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001750}
1751
Eric Laurent493941b2010-07-28 01:32:47 -07001752uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001753{
1754 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001755 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001756 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001757 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001758 }
1759
1760 for (size_t i = 0; i < mTracks.size(); ++i) {
1761 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001762 if (sessionId == track->sessionId() &&
1763 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001764 result |= TRACK_SESSION;
1765 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001766 }
1767 }
1768
Eric Laurent493941b2010-07-28 01:32:47 -07001769 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001770}
1771
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001772uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1773{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001774 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001775 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001776 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1777 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001778 }
1779 for (size_t i = 0; i < mTracks.size(); i++) {
1780 sp<Track> track = mTracks[i];
1781 if (sessionId == track->sessionId() &&
1782 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kastenaae26c82012-02-08 12:35:35 -08001783 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001784 }
1785 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001786 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001787}
1788
Eric Laurent53334cd2010-06-23 17:38:20 -07001789
Glenn Kasten5b0135e2012-01-26 09:46:34 -08001790AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent828b9772011-08-07 16:32:26 -07001791{
1792 Mutex::Autolock _l(mLock);
1793 return mOutput;
1794}
1795
1796AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1797{
1798 Mutex::Autolock _l(mLock);
1799 AudioStreamOut *output = mOutput;
1800 mOutput = NULL;
1801 return output;
1802}
1803
1804// this method must always be called either with ThreadBase mLock held or inside the thread loop
1805audio_stream_t* AudioFlinger::PlaybackThread::stream()
1806{
1807 if (mOutput == NULL) {
1808 return NULL;
1809 }
1810 return &mOutput->stream->common;
1811}
1812
Eric Laurent44331692011-12-05 09:47:19 -08001813uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1814{
1815 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1816 // decoding and transfer time. So sleeping for half of the latency would likely cause
1817 // underruns
1818 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1819 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1820 } else {
1821 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1822 }
1823}
1824
Eric Laurenta553c252009-07-17 12:17:14 -07001825// ----------------------------------------------------------------------------
1826
Glenn Kastenefd511a2012-01-26 10:38:26 -08001827AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08001828 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kastenefd511a2012-01-26 10:38:26 -08001829 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kastendc3ac852012-01-25 15:28:08 -08001830 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1831 mPrevMixerStatus(MIXER_IDLE)
Eric Laurenta553c252009-07-17 12:17:14 -07001832{
Eric Laurenta553c252009-07-17 12:17:14 -07001833 // FIXME - Current mixer implementation only supports stereo output
1834 if (mChannelCount == 1) {
Steve Block3762c312012-01-06 19:20:56 +00001835 ALOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001837}
1838
Eric Laurenta553c252009-07-17 12:17:14 -07001839AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001840{
Eric Laurenta553c252009-07-17 12:17:14 -07001841 delete mAudioMixer;
1842}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843
Eric Laurenta553c252009-07-17 12:17:14 -07001844bool AudioFlinger::MixerThread::threadLoop()
1845{
Eric Laurenta553c252009-07-17 12:17:14 -07001846 Vector< sp<Track> > tracksToRemove;
Glenn Kasten789fef12012-01-26 13:37:52 -08001847 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001848 nsecs_t standbyTime = systemTime();
1849 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001850 // FIXME: Relaxed timing because of a certain device that can't meet latency
1851 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001852 // increase threshold again due to low power audio mode. The way this warning threshold is
1853 // calculated and its usefulness should be reconsidered anyway.
1854 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001855 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001856 bool longStandbyExit = false;
1857 uint32_t activeSleepTime = activeSleepTimeUs();
1858 uint32_t idleSleepTime = idleSleepTimeUs();
1859 uint32_t sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001860 uint32_t sleepTimeShift = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001861 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001862#ifdef DEBUG_CPU_USAGE
1863 ThreadCpuUsage cpu;
1864 const CentralTendencyStatistics& stats = cpu.statistics();
1865#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866
Eric Laurent6dbdc402011-07-22 09:04:31 -07001867 acquireWakeLock();
1868
Eric Laurenta553c252009-07-17 12:17:14 -07001869 while (!exitPending())
1870 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001871#ifdef DEBUG_CPU_USAGE
1872 cpu.sampleAndEnable();
1873 unsigned n = stats.n();
1874 // cpu.elapsed() is expensive, so don't call it every loop
1875 if ((n & 127) == 1) {
1876 long long elapsed = cpu.elapsed();
1877 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1878 double perLoop = elapsed / (double) n;
1879 double perLoop100 = perLoop * 0.01;
1880 double mean = stats.mean();
1881 double stddev = stats.stddev();
1882 double minimum = stats.minimum();
1883 double maximum = stats.maximum();
1884 cpu.resetStatistics();
Steve Block6215d3f2012-01-04 20:05:49 +00001885 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 -07001886 elapsed * .000000001, n, perLoop * .000001,
1887 mean * .001,
1888 stddev * .001,
1889 minimum * .001,
1890 maximum * .001,
1891 mean / perLoop100,
1892 stddev / perLoop100,
1893 minimum / perLoop100,
1894 maximum / perLoop100);
1895 }
1896 }
1897#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001898 processConfigEvents();
1899
Eric Laurent059b4be2009-11-09 23:32:22 -08001900 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001901 { // scope for mLock
1902
1903 Mutex::Autolock _l(mLock);
1904
1905 if (checkForNewParameters_l()) {
1906 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001907 // FIXME: Relaxed timing because of a certain device that can't meet latency
1908 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001909 // increase threshold again due to low power audio mode. The way this warning
1910 // threshold is calculated and its usefulness should be reconsidered anyway.
1911 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001912 activeSleepTime = activeSleepTimeUs();
1913 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001914 }
1915
1916 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1917
1918 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001919 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1920 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001921 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01001922 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001923 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001924 mStandby = true;
1925 mBytesWritten = 0;
1926 }
1927
1928 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1929 // we're about to wait, flush the binder command buffer
1930 IPCThreadState::self()->flushCommands();
1931
1932 if (exitPending()) break;
1933
Eric Laurent6dbdc402011-07-22 09:04:31 -07001934 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001935 // wait until we have something to do...
Steve Block71f2cf12011-10-20 11:56:00 +01001936 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07001937 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01001938 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001939 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001940
Eric Laurent71c44962012-01-17 19:20:12 -08001941 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenb737dbb2012-01-13 15:54:24 -08001942 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07001943 char value[PROPERTY_VALUE_MAX];
1944 property_get("ro.audio.silent", value, "0");
1945 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00001946 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07001947 setMasterMute(true);
1948 }
1949 }
1950
1951 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001952 sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001953 sleepTimeShift = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001954 continue;
1955 }
1956 }
1957
Eric Laurent059b4be2009-11-09 23:32:22 -08001958 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001959
1960 // prevent any changes in effect chain list and in each effect chain
1961 // during mixing and effect process as the audio buffers could be deleted
1962 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001963 lockEffectChains_l(effectChains);
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08001964 }
Eric Laurenta553c252009-07-17 12:17:14 -07001965
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001966 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001967 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001968 mAudioMixer->process();
Eric Laurent06092312012-01-23 18:56:59 -08001969 // increase sleep time progressively when application underrun condition clears.
1970 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1971 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1972 // such that we would underrun the audio HAL.
1973 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001974 sleepTimeShift--;
1975 }
Eric Laurent06092312012-01-23 18:56:59 -08001976 sleepTime = 0;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001977 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001978 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001979 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001980 // If no tracks are ready, sleep once for the duration of an output
1981 // buffer size, then write 0s to the output
1982 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001983 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001984 sleepTime = activeSleepTime >> sleepTimeShift;
1985 if (sleepTime < kMinThreadSleepTimeUs) {
1986 sleepTime = kMinThreadSleepTimeUs;
1987 }
1988 // reduce sleep time in case of consecutive application underruns to avoid
1989 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1990 // duration we would end up writing less data than needed by the audio HAL if
1991 // the condition persists.
1992 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1993 sleepTimeShift++;
1994 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001995 } else {
1996 sleepTime = idleSleepTime;
1997 }
1998 } else if (mBytesWritten != 0 ||
1999 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002000 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002001 sleepTime = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01002002 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07002003 }
Eric Laurent65b65452010-06-01 23:49:17 -07002004 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07002005 }
2006
2007 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002008 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002009 }
2010 // sleepTime == 0 means we must write to audio hardware
2011 if (sleepTime == 0) {
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08002012 for (size_t i = 0; i < effectChains.size(); i ++) {
2013 effectChains[i]->process_l();
2014 }
2015 // enable changes in effect chain
2016 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002017 mLastWriteTime = systemTime();
2018 mInWrite = true;
2019 mBytesWritten += mixBufferSize;
2020
Dima Zavin31f188892011-04-18 16:57:27 -07002021 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002022 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002023 mNumWrites++;
2024 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002025 nsecs_t now = systemTime();
2026 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07002027 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002028 mNumDelayedWrites++;
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002029 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00002030 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002031 ns2ms(delta), mNumDelayedWrites, this);
2032 lastWarning = now;
2033 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002034 if (mStandby) {
2035 longStandbyExit = true;
2036 }
Eric Laurenta553c252009-07-17 12:17:14 -07002037 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002038 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002039 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002040 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002041 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002042 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002043 }
2044
2045 // finally let go of all our tracks, without the lock held
2046 // since we can't guarantee the destructors won't acquire that
2047 // same lock.
2048 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002049
2050 // Effect chains will be actually deleted here if they were removed from
2051 // mEffectChains list during mixing or effects processing
2052 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002053 }
2054
2055 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002056 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002057 }
Eric Laurenta553c252009-07-17 12:17:14 -07002058
Eric Laurent6dbdc402011-07-22 09:04:31 -07002059 releaseWakeLock();
2060
Steve Block71f2cf12011-10-20 11:56:00 +01002061 ALOGV("MixerThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002062 return false;
2063}
2064
2065// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten789fef12012-01-26 13:37:52 -08002066AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2067 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002068{
2069
Glenn Kasten789fef12012-01-26 13:37:52 -08002070 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002071 // find out which tracks need to be processed
2072 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002073 size_t mixedTracks = 0;
2074 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002075
2076 float masterVolume = mMasterVolume;
2077 bool masterMute = mMasterMute;
2078
Eric Laurent8cc93b92010-08-11 05:20:11 -07002079 if (masterMute) {
2080 masterVolume = 0;
2081 }
Eric Laurent65b65452010-06-01 23:49:17 -07002082 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002083 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002084 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002085 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002086 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002087 masterVolume = (float)((v + (1 << 23)) >> 24);
2088 chain.clear();
2089 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002090
Eric Laurenta553c252009-07-17 12:17:14 -07002091 for (size_t i=0 ; i<count ; i++) {
2092 sp<Track> t = activeTracks[i].promote();
2093 if (t == 0) continue;
2094
Glenn Kasten68deb152011-12-19 15:06:39 -08002095 // this const just means the local variable doesn't change
Eric Laurenta553c252009-07-17 12:17:14 -07002096 Track* const track = t.get();
2097 audio_track_cblk_t* cblk = track->cblk();
2098
2099 // The first time a track is added we wait
2100 // for all its buffers to be filled before processing it
Glenn Kasten68deb152011-12-19 15:06:39 -08002101 int name = track->name();
Eric Laurent8a04fe02011-11-08 18:10:16 -08002102 // make sure that we have enough frames to mix one full buffer.
2103 // enforce this condition only once to enable draining the buffer in case the client
2104 // app does not call stop() and relies on underrun to stop:
Eric Laurent71c44962012-01-17 19:20:12 -08002105 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurent8a04fe02011-11-08 18:10:16 -08002106 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002107 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002108 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent71c44962012-01-17 19:20:12 -08002109 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002110 if (t->sampleRate() == (int)mSampleRate) {
2111 minFrames = mFrameCount;
2112 } else {
Eric Laurent72dafb22011-12-22 16:08:41 -08002113 // +1 for rounding and +1 for additional sample needed for interpolation
2114 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2115 // add frames already consumed but not yet released by the resampler
2116 // because cblk->framesReady() will include these frames
2117 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2118 // the minimum track buffer size is normally twice the number of frames necessary
2119 // to fill one buffer and the resampler should not leave more than one buffer worth
2120 // of unreleased frames after each pass, but just in case...
Steve Blockec193de2012-01-09 18:35:44 +00002121 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002122 }
2123 }
2124 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002125 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002126 {
Glenn Kasten68deb152011-12-19 15:06:39 -08002127 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002128
Eric Laurent65b65452010-06-01 23:49:17 -07002129 mixedTracks++;
2130
2131 // track->mainBuffer() != mMixBuffer means there is an effect chain
2132 // connected to the track
2133 chain.clear();
2134 if (track->mainBuffer() != mMixBuffer) {
2135 chain = getEffectChain_l(track->sessionId());
2136 // Delegate volume control to effect in track effect chain if needed
2137 if (chain != 0) {
2138 tracksWithEffect++;
2139 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00002140 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten68deb152011-12-19 15:06:39 -08002141 name, track->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002142 }
2143 }
2144
2145
2146 int param = AudioMixer::VOLUME;
2147 if (track->mFillingUpStatus == Track::FS_FILLED) {
2148 // no ramp for the first volume setting
2149 track->mFillingUpStatus = Track::FS_ACTIVE;
2150 if (track->mState == TrackBase::RESUMING) {
2151 track->mState = TrackBase::ACTIVE;
2152 param = AudioMixer::RAMP_VOLUME;
2153 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002154 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002155 } else if (cblk->server != 0) {
2156 // If the track is stopped before the first frame was mixed,
2157 // do not apply ramp
2158 param = AudioMixer::RAMP_VOLUME;
2159 }
2160
Eric Laurenta553c252009-07-17 12:17:14 -07002161 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002162 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002163 if (track->isMuted() || track->isPausing() ||
Glenn Kastenaae26c82012-02-08 12:35:35 -08002164 mStreamTypes[track->streamType()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002165 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002166 if (track->isPausing()) {
2167 track->setPaused();
2168 }
2169 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002170
Glenn Kasten871c16c2010-03-05 12:18:01 -08002171 // read original volumes with volume control
Glenn Kastenaae26c82012-02-08 12:35:35 -08002172 float typeVolume = mStreamTypes[track->streamType()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002173 float v = masterVolume * typeVolume;
Glenn Kastenbc4de882012-01-17 14:39:34 -08002174 uint32_t vlr = cblk->getVolumeLR();
Glenn Kasten0632bad2012-01-17 12:20:54 -08002175 vl = vlr & 0xFFFF;
2176 vr = vlr >> 16;
2177 // track volumes come from shared memory, so can't be trusted and must be clamped
2178 if (vl > MAX_GAIN_INT) {
2179 ALOGV("Track left volume out of range: %04X", vl);
2180 vl = MAX_GAIN_INT;
2181 }
2182 if (vr > MAX_GAIN_INT) {
2183 ALOGV("Track right volume out of range: %04X", vr);
2184 vr = MAX_GAIN_INT;
2185 }
2186 // now apply the master volume and stream type volume
2187 vl = (uint32_t)(v * vl) << 12;
2188 vr = (uint32_t)(v * vr) << 12;
2189 // assuming master volume and stream type volume each go up to 1.0,
2190 // vl and vr are now in 8.24 format
Eric Laurenta553c252009-07-17 12:17:14 -07002191
Glenn Kasten4790bd82012-01-03 14:22:33 -08002192 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2193 // send level comes from shared memory and so may be corrupt
Glenn Kasten0632bad2012-01-17 12:20:54 -08002194 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten4790bd82012-01-03 14:22:33 -08002195 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kasten0632bad2012-01-17 12:20:54 -08002196 sendLevel = MAX_GAIN_INT;
Glenn Kasten4790bd82012-01-03 14:22:33 -08002197 }
2198 va = (uint32_t)(v * sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002199 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002200 // Delegate volume control to effect in track effect chain if needed
2201 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2202 // Do not ramp volume if volume is controlled by effect
2203 param = AudioMixer::VOLUME;
2204 track->mHasVolumeController = true;
2205 } else {
2206 // force no volume ramp when volume controller was just disabled or removed
2207 // from effect chain to avoid volume spike
2208 if (track->mHasVolumeController) {
2209 param = AudioMixer::VOLUME;
2210 }
2211 track->mHasVolumeController = false;
2212 }
2213
2214 // Convert volumes from 8.24 to 4.12 format
2215 int16_t left, right, aux;
Glenn Kasten0632bad2012-01-17 12:20:54 -08002216 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002217 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2218 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2219 left = int16_t(v_clamped);
2220 v_clamped = (vr + (1 << 11)) >> 12;
2221 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2222 right = int16_t(v_clamped);
2223
2224 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2225 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002226
Eric Laurent65b65452010-06-01 23:49:17 -07002227 // XXX: these things DON'T need to be done each time
Glenn Kasten68deb152011-12-19 15:06:39 -08002228 mAudioMixer->setBufferProvider(name, track);
2229 mAudioMixer->enable(name);
Eric Laurent65b65452010-06-01 23:49:17 -07002230
Glenn Kasten68deb152011-12-19 15:06:39 -08002231 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2232 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2233 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
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,
Eric Laurent65b65452010-06-01 23:49:17 -07002237 AudioMixer::FORMAT, (void *)track->format());
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::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002241 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002242 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002243 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002244 AudioMixer::RESAMPLE,
2245 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002246 (void *)(cblk->sampleRate));
2247 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002248 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002249 AudioMixer::TRACK,
2250 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2251 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002252 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002253 AudioMixer::TRACK,
2254 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002255
2256 // reset retry count
2257 track->mRetryCount = kMaxTrackRetries;
Eric Laurent71c44962012-01-17 19:20:12 -08002258 // If one track is ready, set the mixer ready if:
2259 // - the mixer was not ready during previous round OR
2260 // - no other track is not ready
2261 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2262 mixerStatus != MIXER_TRACKS_ENABLED) {
2263 mixerStatus = MIXER_TRACKS_READY;
2264 }
Eric Laurenta553c252009-07-17 12:17:14 -07002265 } else {
Glenn Kasten68deb152011-12-19 15:06:39 -08002266 //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 -07002267 if (track->isStopped()) {
2268 track->reset();
2269 }
2270 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2271 // We have consumed all the buffers of this track.
2272 // Remove it from the list of active tracks.
2273 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002274 } else {
2275 // No buffers for this track. Give it a few chances to
2276 // fill a buffer, then remove it from active list.
2277 if (--(track->mRetryCount) <= 0) {
Glenn Kasten68deb152011-12-19 15:06:39 -08002278 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002279 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002280 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002281 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent71c44962012-01-17 19:20:12 -08002282 // If one track is not ready, mark the mixer also not ready if:
2283 // - the mixer was ready during previous round OR
2284 // - no other track is ready
2285 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2286 mixerStatus != MIXER_TRACKS_READY) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002287 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002288 }
Eric Laurenta553c252009-07-17 12:17:14 -07002289 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002290 mAudioMixer->disable(name);
Eric Laurenta553c252009-07-17 12:17:14 -07002291 }
2292 }
2293
2294 // remove all the tracks that need to be...
2295 count = tracksToRemove->size();
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002296 if (CC_UNLIKELY(count)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002297 for (size_t i=0 ; i<count ; i++) {
2298 const sp<Track>& track = tracksToRemove->itemAt(i);
2299 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002300 if (track->mainBuffer() != mMixBuffer) {
2301 chain = getEffectChain_l(track->sessionId());
2302 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002303 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002304 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002305 }
2306 }
Eric Laurenta553c252009-07-17 12:17:14 -07002307 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002308 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002309 }
2310 }
2311 }
2312
Eric Laurent65b65452010-06-01 23:49:17 -07002313 // mix buffer must be cleared if all tracks are connected to an
2314 // effect chain as in this case the mixer will not write to
2315 // mix buffer and track effects will accumulate into it
2316 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2317 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2318 }
2319
Eric Laurent71c44962012-01-17 19:20:12 -08002320 mPrevMixerStatus = mixerStatus;
Eric Laurent059b4be2009-11-09 23:32:22 -08002321 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002322}
2323
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002324void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002325{
Steve Block71f2cf12011-10-20 11:56:00 +01002326 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002327 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002328 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002329
Eric Laurenta553c252009-07-17 12:17:14 -07002330 size_t size = mTracks.size();
2331 for (size_t i = 0; i < size; i++) {
2332 sp<Track> t = mTracks[i];
Glenn Kastenaae26c82012-02-08 12:35:35 -08002333 if (t->streamType() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002334 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002335 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002336 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002337 }
2338}
Eric Laurenta553c252009-07-17 12:17:14 -07002339
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002340void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent05ce0942011-08-30 10:18:54 -07002341{
Steve Block71f2cf12011-10-20 11:56:00 +01002342 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002343 this, streamType, valid);
2344 Mutex::Autolock _l(mLock);
2345
2346 mStreamTypes[streamType].valid = valid;
2347}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348
Eric Laurenta553c252009-07-17 12:17:14 -07002349// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002350int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351{
2352 return mAudioMixer->getTrackName();
2353}
2354
Eric Laurenta553c252009-07-17 12:17:14 -07002355// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002356void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357{
Steve Block71f2cf12011-10-20 11:56:00 +01002358 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 mAudioMixer->deleteTrackName(name);
2360}
2361
Eric Laurenta553c252009-07-17 12:17:14 -07002362// checkForNewParameters_l() must be called with ThreadBase::mLock held
2363bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364{
Eric Laurenta553c252009-07-17 12:17:14 -07002365 bool reconfig = false;
2366
Eric Laurent8fce46a2009-08-04 09:45:33 -07002367 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002368 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002369 String8 keyValuePair = mNewParameters[0];
2370 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002371 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002372
Eric Laurenta553c252009-07-17 12:17:14 -07002373 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2374 reconfig = true;
2375 }
2376 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08002377 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002378 status = BAD_VALUE;
2379 } else {
2380 reconfig = true;
2381 }
2382 }
2383 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002384 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002385 status = BAD_VALUE;
2386 } else {
2387 reconfig = true;
2388 }
2389 }
2390 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2391 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastene5fb2632011-12-14 10:28:06 -08002392 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07002393 // if frame count is changed after track creation
2394 if (!mTracks.isEmpty()) {
2395 status = INVALID_OPERATION;
2396 } else {
2397 reconfig = true;
2398 }
2399 }
Eric Laurent65b65452010-06-01 23:49:17 -07002400 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002401 // when changing the audio output device, call addBatteryData to notify
2402 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002403 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002404 uint32_t params = 0;
2405 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002406 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002407 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2408 }
2409
2410 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002411 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002412 // check if any other device (except speaker) is on
2413 if (value & deviceWithoutSpeaker ) {
2414 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2415 }
2416
2417 if (params != 0) {
2418 addBatteryData(params);
2419 }
2420 }
2421
Eric Laurent65b65452010-06-01 23:49:17 -07002422 // forward device change to effects that have requested to be
2423 // aware of attached audio device.
2424 mDevice = (uint32_t)value;
2425 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002426 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002427 }
2428 }
2429
Eric Laurenta553c252009-07-17 12:17:14 -07002430 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002431 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002432 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002433 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002434 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002435 mStandby = true;
2436 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002437 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002438 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002439 }
2440 if (status == NO_ERROR && reconfig) {
2441 delete mAudioMixer;
Glenn Kasten2589cf92012-01-27 18:08:45 -08002442 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2443 mAudioMixer = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07002444 readOutputParameters();
2445 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2446 for (size_t i = 0; i < mTracks.size() ; i++) {
2447 int name = getTrackName_l();
2448 if (name < 0) break;
2449 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002450 // limit track sample rate to 2 x new output sample rate
2451 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2452 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2453 }
Eric Laurenta553c252009-07-17 12:17:14 -07002454 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002455 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002456 }
2457 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002458
2459 mNewParameters.removeAt(0);
2460
Eric Laurenta553c252009-07-17 12:17:14 -07002461 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002462 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002463 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2464 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002465 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002466 }
2467 return reconfig;
2468}
2469
2470status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2471{
2472 const size_t SIZE = 256;
2473 char buffer[SIZE];
2474 String8 result;
2475
2476 PlaybackThread::dumpInternals(fd, args);
2477
2478 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2479 result.append(buffer);
2480 write(fd, result.string(), result.size());
2481 return NO_ERROR;
2482}
2483
Eric Laurent059b4be2009-11-09 23:32:22 -08002484uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2485{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002486 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002487}
2488
Eric Laurent8448a792010-08-18 18:13:17 -07002489uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2490{
2491 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2492}
2493
Eric Laurenta553c252009-07-17 12:17:14 -07002494// ----------------------------------------------------------------------------
Glenn Kasten39d00cb2012-01-17 11:09:42 -08002495AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2496 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kastenefd511a2012-01-26 10:38:26 -08002497 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kastendc3ac852012-01-25 15:28:08 -08002498 // mLeftVolFloat, mRightVolFloat
2499 // mLeftVolShort, mRightVolShort
Eric Laurenta553c252009-07-17 12:17:14 -07002500{
Eric Laurenta553c252009-07-17 12:17:14 -07002501}
2502
2503AudioFlinger::DirectOutputThread::~DirectOutputThread()
2504{
2505}
2506
Eric Laurent65b65452010-06-01 23:49:17 -07002507static inline
2508int32_t mul(int16_t in, int16_t v)
2509{
2510#if defined(__arm__) && !defined(__thumb__)
2511 int32_t out;
2512 asm( "smulbb %[out], %[in], %[v] \n"
2513 : [out]"=r"(out)
2514 : [in]"%r"(in), [v]"r"(v)
2515 : );
2516 return out;
2517#else
2518 return in * int32_t(v);
2519#endif
2520}
2521
2522void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2523{
2524 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002525 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002526 return;
2527 }
2528
2529 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002530 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002531 size_t count = mFrameCount * mChannelCount;
2532 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2533 int16_t *dst = mMixBuffer + count-1;
2534 while(count--) {
2535 *dst-- = (int16_t)(*src--^0x80) << 8;
2536 }
2537 }
2538
2539 size_t frameCount = mFrameCount;
2540 int16_t *out = mMixBuffer;
2541 if (ramp) {
2542 if (mChannelCount == 1) {
2543 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2544 int32_t vlInc = d / (int32_t)frameCount;
2545 int32_t vl = ((int32_t)mLeftVolShort << 16);
2546 do {
2547 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2548 out++;
2549 vl += vlInc;
2550 } while (--frameCount);
2551
2552 } else {
2553 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2554 int32_t vlInc = d / (int32_t)frameCount;
2555 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2556 int32_t vrInc = d / (int32_t)frameCount;
2557 int32_t vl = ((int32_t)mLeftVolShort << 16);
2558 int32_t vr = ((int32_t)mRightVolShort << 16);
2559 do {
2560 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2561 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2562 out += 2;
2563 vl += vlInc;
2564 vr += vrInc;
2565 } while (--frameCount);
2566 }
2567 } else {
2568 if (mChannelCount == 1) {
2569 do {
2570 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2571 out++;
2572 } while (--frameCount);
2573 } else {
2574 do {
2575 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2576 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2577 out += 2;
2578 } while (--frameCount);
2579 }
2580 }
2581
2582 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002583 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002584 size_t count = mFrameCount * mChannelCount;
2585 int16_t *src = mMixBuffer;
2586 uint8_t *dst = (uint8_t *)mMixBuffer;
2587 while(count--) {
2588 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2589 }
2590 }
2591
2592 mLeftVolShort = leftVol;
2593 mRightVolShort = rightVol;
2594}
2595
Eric Laurenta553c252009-07-17 12:17:14 -07002596bool AudioFlinger::DirectOutputThread::threadLoop()
2597{
Glenn Kasten789fef12012-01-26 13:37:52 -08002598 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002599 sp<Track> trackToRemove;
2600 sp<Track> activeTrack;
2601 nsecs_t standbyTime = systemTime();
2602 int8_t *curBuf;
2603 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002604 uint32_t activeSleepTime = activeSleepTimeUs();
2605 uint32_t idleSleepTime = idleSleepTimeUs();
2606 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002607 // use shorter standby delay as on normal output to release
2608 // hardware resources as soon as possible
2609 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002610
Eric Laurent6dbdc402011-07-22 09:04:31 -07002611 acquireWakeLock();
2612
Eric Laurenta553c252009-07-17 12:17:14 -07002613 while (!exitPending())
2614 {
Eric Laurent65b65452010-06-01 23:49:17 -07002615 bool rampVolume;
2616 uint16_t leftVol;
2617 uint16_t rightVol;
2618 Vector< sp<EffectChain> > effectChains;
2619
Eric Laurenta553c252009-07-17 12:17:14 -07002620 processConfigEvents();
2621
Eric Laurent059b4be2009-11-09 23:32:22 -08002622 mixerStatus = MIXER_IDLE;
2623
Eric Laurenta553c252009-07-17 12:17:14 -07002624 { // scope for the mLock
2625
2626 Mutex::Autolock _l(mLock);
2627
2628 if (checkForNewParameters_l()) {
2629 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002630 activeSleepTime = activeSleepTimeUs();
2631 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002632 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002633 }
2634
2635 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002636 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2637 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002638 // wait until we have something to do...
2639 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01002640 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002641 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002642 mStandby = true;
2643 mBytesWritten = 0;
2644 }
2645
2646 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2647 // we're about to wait, flush the binder command buffer
2648 IPCThreadState::self()->flushCommands();
2649
2650 if (exitPending()) break;
2651
Eric Laurent6dbdc402011-07-22 09:04:31 -07002652 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002653 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002654 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002655 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002656 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002657
Glenn Kastenb737dbb2012-01-13 15:54:24 -08002658 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07002659 char value[PROPERTY_VALUE_MAX];
2660 property_get("ro.audio.silent", value, "0");
2661 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00002662 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07002663 setMasterMute(true);
2664 }
2665 }
2666
Eric Laurentef9500f2010-03-11 14:47:00 -08002667 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002668 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002669 continue;
2670 }
2671 }
2672
Eric Laurent65b65452010-06-01 23:49:17 -07002673 effectChains = mEffectChains;
2674
Eric Laurenta553c252009-07-17 12:17:14 -07002675 // find out which tracks need to be processed
2676 if (mActiveTracks.size() != 0) {
2677 sp<Track> t = mActiveTracks[0].promote();
2678 if (t == 0) continue;
2679
2680 Track* const track = t.get();
2681 audio_track_cblk_t* cblk = track->cblk();
2682
2683 // The first time a track is added we wait
2684 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002685 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002686 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002687 {
Steve Block71f2cf12011-10-20 11:56:00 +01002688 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002689
Eric Laurent65b65452010-06-01 23:49:17 -07002690 if (track->mFillingUpStatus == Track::FS_FILLED) {
2691 track->mFillingUpStatus = Track::FS_ACTIVE;
2692 mLeftVolFloat = mRightVolFloat = 0;
2693 mLeftVolShort = mRightVolShort = 0;
2694 if (track->mState == TrackBase::RESUMING) {
2695 track->mState = TrackBase::ACTIVE;
2696 rampVolume = true;
2697 }
2698 } else if (cblk->server != 0) {
2699 // If the track is stopped before the first frame was mixed,
2700 // do not apply ramp
2701 rampVolume = true;
2702 }
Eric Laurenta553c252009-07-17 12:17:14 -07002703 // compute volume for this track
2704 float left, right;
2705 if (track->isMuted() || mMasterMute || track->isPausing() ||
Glenn Kastenaae26c82012-02-08 12:35:35 -08002706 mStreamTypes[track->streamType()].mute) {
Eric Laurenta553c252009-07-17 12:17:14 -07002707 left = right = 0;
2708 if (track->isPausing()) {
2709 track->setPaused();
2710 }
2711 } else {
Glenn Kastenaae26c82012-02-08 12:35:35 -08002712 float typeVolume = mStreamTypes[track->streamType()].volume;
Eric Laurenta553c252009-07-17 12:17:14 -07002713 float v = mMasterVolume * typeVolume;
Glenn Kastenbc4de882012-01-17 14:39:34 -08002714 uint32_t vlr = cblk->getVolumeLR();
Glenn Kasten0632bad2012-01-17 12:20:54 -08002715 float v_clamped = v * (vlr & 0xFFFF);
Eric Laurenta553c252009-07-17 12:17:14 -07002716 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2717 left = v_clamped/MAX_GAIN;
Glenn Kasten0632bad2012-01-17 12:20:54 -08002718 v_clamped = v * (vlr >> 16);
Eric Laurenta553c252009-07-17 12:17:14 -07002719 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2720 right = v_clamped/MAX_GAIN;
2721 }
2722
Eric Laurent65b65452010-06-01 23:49:17 -07002723 if (left != mLeftVolFloat || right != mRightVolFloat) {
2724 mLeftVolFloat = left;
2725 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002726
Eric Laurent65b65452010-06-01 23:49:17 -07002727 // If audio HAL implements volume control,
2728 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002729 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002730 left = 1.0f;
2731 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002732 }
Eric Laurent65b65452010-06-01 23:49:17 -07002733
2734 // Convert volumes from float to 8.24
2735 uint32_t vl = (uint32_t)(left * (1 << 24));
2736 uint32_t vr = (uint32_t)(right * (1 << 24));
2737
2738 // Delegate volume control to effect in track effect chain if needed
2739 // only one effect chain can be present on DirectOutputThread, so if
2740 // there is one, the track is connected to it
2741 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002742 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002743 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002744 rampVolume = false;
2745 }
2746 }
2747
2748 // Convert volumes from 8.24 to 4.12 format
2749 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2750 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2751 leftVol = (uint16_t)v_clamped;
2752 v_clamped = (vr + (1 << 11)) >> 12;
2753 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2754 rightVol = (uint16_t)v_clamped;
2755 } else {
2756 leftVol = mLeftVolShort;
2757 rightVol = mRightVolShort;
2758 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002759 }
2760
2761 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002762 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002763 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002764 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002765 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002766 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002767 if (track->isStopped()) {
2768 track->reset();
2769 }
2770 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2771 // We have consumed all the buffers of this track.
2772 // Remove it from the list of active tracks.
2773 trackToRemove = track;
2774 } else {
2775 // No buffers for this track. Give it a few chances to
2776 // fill a buffer, then remove it from active list.
2777 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002778 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurenta553c252009-07-17 12:17:14 -07002779 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002780 } else {
2781 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002782 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002783 }
Eric Laurenta553c252009-07-17 12:17:14 -07002784 }
2785 }
2786
2787 // remove all the tracks that need to be...
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002788 if (CC_UNLIKELY(trackToRemove != 0)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002789 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002790 if (!effectChains.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01002791 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002792 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002793 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002794 }
Eric Laurenta553c252009-07-17 12:17:14 -07002795 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002796 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002797 }
2798 }
Eric Laurent65b65452010-06-01 23:49:17 -07002799
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002800 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002801 }
2802
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002803 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002804 AudioBufferProvider::Buffer buffer;
2805 size_t frameCount = mFrameCount;
2806 curBuf = (int8_t *)mMixBuffer;
2807 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002808 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002809 buffer.frameCount = frameCount;
2810 activeTrack->getNextBuffer(&buffer);
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002811 if (CC_UNLIKELY(buffer.raw == NULL)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002812 memset(curBuf, 0, frameCount * mFrameSize);
2813 break;
2814 }
2815 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2816 frameCount -= buffer.frameCount;
2817 curBuf += buffer.frameCount * mFrameSize;
2818 activeTrack->releaseBuffer(&buffer);
2819 }
2820 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002821 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002822 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002823 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002824 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2825 sleepTime = activeSleepTime;
2826 } else {
2827 sleepTime = idleSleepTime;
2828 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002829 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002830 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002831 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002832 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002833 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002834
Eric Laurentf69a3f82009-09-22 00:35:48 -07002835 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002836 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002837 }
2838 // sleepTime == 0 means we must write to audio hardware
2839 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002840 if (mixerStatus == MIXER_TRACKS_READY) {
2841 applyVolume(leftVol, rightVol, rampVolume);
2842 }
2843 for (size_t i = 0; i < effectChains.size(); i ++) {
2844 effectChains[i]->process_l();
2845 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002846 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002847
Eric Laurentf69a3f82009-09-22 00:35:48 -07002848 mLastWriteTime = systemTime();
2849 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002850 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002851 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002852 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002853 mNumWrites++;
2854 mInWrite = false;
2855 mStandby = false;
2856 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002857 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002858 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002859 }
2860
2861 // finally let go of removed track, without the lock held
2862 // since we can't guarantee the destructors won't acquire that
2863 // same lock.
2864 trackToRemove.clear();
2865 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002866
2867 // Effect chains will be actually deleted here if they were removed from
2868 // mEffectChains list during mixing or effects processing
2869 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002870 }
2871
2872 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002873 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002874 }
Eric Laurenta553c252009-07-17 12:17:14 -07002875
Eric Laurent6dbdc402011-07-22 09:04:31 -07002876 releaseWakeLock();
2877
Steve Block71f2cf12011-10-20 11:56:00 +01002878 ALOGV("DirectOutputThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002879 return false;
2880}
2881
2882// getTrackName_l() must be called with ThreadBase::mLock held
2883int AudioFlinger::DirectOutputThread::getTrackName_l()
2884{
2885 return 0;
2886}
2887
2888// deleteTrackName_l() must be called with ThreadBase::mLock held
2889void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2890{
2891}
2892
2893// checkForNewParameters_l() must be called with ThreadBase::mLock held
2894bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2895{
2896 bool reconfig = false;
2897
Eric Laurent8fce46a2009-08-04 09:45:33 -07002898 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002899 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002900 String8 keyValuePair = mNewParameters[0];
2901 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002902 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002903
Eric Laurenta553c252009-07-17 12:17:14 -07002904 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2905 // do not accept frame count changes if tracks are open as the track buffer
2906 // size depends on frame count and correct behavior would not be garantied
2907 // if frame count is changed after track creation
2908 if (!mTracks.isEmpty()) {
2909 status = INVALID_OPERATION;
2910 } else {
2911 reconfig = true;
2912 }
2913 }
2914 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002915 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002916 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002917 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002918 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002919 mStandby = true;
2920 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002921 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002922 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002923 }
2924 if (status == NO_ERROR && reconfig) {
2925 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002926 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002927 }
2928 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002929
2930 mNewParameters.removeAt(0);
2931
Eric Laurenta553c252009-07-17 12:17:14 -07002932 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002933 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002934 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2935 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002936 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002937 }
2938 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002939}
2940
Eric Laurent059b4be2009-11-09 23:32:22 -08002941uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002942{
2943 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002944 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08002945 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08002946 } else {
2947 time = 10000;
2948 }
2949 return time;
2950}
2951
2952uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2953{
2954 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002955 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002956 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002957 } else {
2958 time = 10000;
2959 }
2960 return time;
2961}
2962
Eric Laurent8448a792010-08-18 18:13:17 -07002963uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2964{
2965 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002966 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002967 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2968 } else {
2969 time = 10000;
2970 }
2971 return time;
2972}
2973
2974
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002975// ----------------------------------------------------------------------------
2976
Glenn Kastenefd511a2012-01-26 10:38:26 -08002977AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08002978 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kastenefd511a2012-01-26 10:38:26 -08002979 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2980 mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002981{
Eric Laurenta553c252009-07-17 12:17:14 -07002982 addOutputTrack(mainThread);
2983}
2984
2985AudioFlinger::DuplicatingThread::~DuplicatingThread()
2986{
Eric Laurent0a080292009-12-07 10:53:10 -08002987 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2988 mOutputTracks[i]->destroy();
2989 }
Eric Laurenta553c252009-07-17 12:17:14 -07002990}
2991
2992bool AudioFlinger::DuplicatingThread::threadLoop()
2993{
Eric Laurenta553c252009-07-17 12:17:14 -07002994 Vector< sp<Track> > tracksToRemove;
Glenn Kasten789fef12012-01-26 13:37:52 -08002995 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002996 nsecs_t standbyTime = systemTime();
2997 size_t mixBufferSize = mFrameCount*mFrameSize;
2998 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002999 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08003000 uint32_t activeSleepTime = activeSleepTimeUs();
3001 uint32_t idleSleepTime = idleSleepTimeUs();
3002 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07003003 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07003004
Eric Laurent6dbdc402011-07-22 09:04:31 -07003005 acquireWakeLock();
3006
Eric Laurenta553c252009-07-17 12:17:14 -07003007 while (!exitPending())
3008 {
3009 processConfigEvents();
3010
Eric Laurent059b4be2009-11-09 23:32:22 -08003011 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07003012 { // scope for the mLock
3013
3014 Mutex::Autolock _l(mLock);
3015
3016 if (checkForNewParameters_l()) {
3017 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003018 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08003019 activeSleepTime = activeSleepTimeUs();
3020 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07003021 }
3022
3023 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3024
3025 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3026 outputTracks.add(mOutputTracks[i]);
3027 }
3028
3029 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003030 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3031 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003032 if (!mStandby) {
3033 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07003034 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07003035 }
3036 mStandby = true;
3037 mBytesWritten = 0;
3038 }
3039
3040 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3041 // we're about to wait, flush the binder command buffer
3042 IPCThreadState::self()->flushCommands();
3043 outputTracks.clear();
3044
3045 if (exitPending()) break;
3046
Eric Laurent6dbdc402011-07-22 09:04:31 -07003047 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01003048 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07003049 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01003050 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07003051 acquireWakeLock_l();
3052
Eric Laurent71c44962012-01-17 19:20:12 -08003053 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenb737dbb2012-01-13 15:54:24 -08003054 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07003055 char value[PROPERTY_VALUE_MAX];
3056 property_get("ro.audio.silent", value, "0");
3057 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00003058 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07003059 setMasterMute(true);
3060 }
3061 }
3062
3063 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08003064 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07003065 continue;
3066 }
3067 }
3068
Eric Laurent059b4be2009-11-09 23:32:22 -08003069 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07003070
3071 // prevent any changes in effect chain list and in each effect chain
3072 // during mixing and effect process as the audio buffers could be deleted
3073 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003074 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003075 }
Eric Laurenta553c252009-07-17 12:17:14 -07003076
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003077 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003078 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003079 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003080 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003081 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003082 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003083 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003084 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003085 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003086 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003087 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003088 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3089 sleepTime = activeSleepTime;
3090 } else {
3091 sleepTime = idleSleepTime;
3092 }
Eric Laurent62443f52009-10-05 20:29:18 -07003093 } else if (mBytesWritten != 0) {
3094 // flush remaining overflow buffers in output tracks
3095 for (size_t i = 0; i < outputTracks.size(); i++) {
3096 if (outputTracks[i]->isActive()) {
3097 sleepTime = 0;
3098 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003099 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003100 break;
3101 }
3102 }
Eric Laurenta553c252009-07-17 12:17:14 -07003103 }
3104 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003105
3106 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003107 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003108 }
3109 // sleepTime == 0 means we must write to audio hardware
3110 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003111 for (size_t i = 0; i < effectChains.size(); i ++) {
3112 effectChains[i]->process_l();
3113 }
3114 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003115 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003116
Eric Laurent62443f52009-10-05 20:29:18 -07003117 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003118 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003119 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003120 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003121 mStandby = false;
3122 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003123 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003124 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003125 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003126 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003127 }
3128
3129 // finally let go of all our tracks, without the lock held
3130 // since we can't guarantee the destructors won't acquire that
3131 // same lock.
3132 tracksToRemove.clear();
3133 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003134
3135 // Effect chains will be actually deleted here if they were removed from
3136 // mEffectChains list during mixing or effects processing
3137 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003138 }
3139
Eric Laurent6dbdc402011-07-22 09:04:31 -07003140 releaseWakeLock();
3141
Eric Laurenta553c252009-07-17 12:17:14 -07003142 return false;
3143}
3144
3145void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3146{
3147 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3148 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003149 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003150 mSampleRate,
3151 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003152 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003153 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003154 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003155 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003156 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003157 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003158 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003159 }
Eric Laurenta553c252009-07-17 12:17:14 -07003160}
3161
3162void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3163{
3164 Mutex::Autolock _l(mLock);
3165 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3166 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003167 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003168 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003169 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003170 return;
3171 }
3172 }
Steve Block71f2cf12011-10-20 11:56:00 +01003173 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003174}
3175
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003176void AudioFlinger::DuplicatingThread::updateWaitTime()
3177{
3178 mWaitTimeMs = UINT_MAX;
3179 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3180 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten706b6182012-01-20 13:44:40 -08003181 if (strong != 0) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003182 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3183 if (waitTimeMs < mWaitTimeMs) {
3184 mWaitTimeMs = waitTimeMs;
3185 }
3186 }
3187 }
3188}
3189
3190
3191bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3192{
3193 for (size_t i = 0; i < outputTracks.size(); i++) {
3194 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3195 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003196 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003197 return false;
3198 }
3199 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3200 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003201 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003202 return false;
3203 }
3204 }
3205 return true;
3206}
3207
3208uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3209{
3210 return (mWaitTimeMs * 1000) / 2;
3211}
3212
Eric Laurenta553c252009-07-17 12:17:14 -07003213// ----------------------------------------------------------------------------
3214
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003215// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003216AudioFlinger::ThreadBase::TrackBase::TrackBase(
3217 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003218 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003219 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003220 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003221 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003222 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003224 const sp<IMemory>& sharedBuffer,
3225 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003226 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003227 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003228 mClient(client),
Glenn Kastendc3ac852012-01-25 15:28:08 -08003229 mCblk(NULL),
3230 // mBuffer
3231 // mBufferEnd
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003232 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003233 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003234 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003235 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3236 mSessionId(sessionId)
Glenn Kastendc3ac852012-01-25 15:28:08 -08003237 // mChannelCount
3238 // mChannelMask
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003239{
Steve Block71f2cf12011-10-20 11:56:00 +01003240 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003241
Steve Block5baa3a62011-12-20 16:23:08 +00003242 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003243 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003244 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003245 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3246 if (sharedBuffer == 0) {
3247 size += bufferSize;
3248 }
3249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 if (client != NULL) {
3251 mCblkMemory = client->heap()->allocate(size);
3252 if (mCblkMemory != 0) {
3253 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kasten3694ec12012-01-27 16:47:15 -08003254 if (mCblk != NULL) { // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 new(mCblk) audio_track_cblk_t();
3256 // clear all buffers
3257 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003258 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003259 mChannelCount = channelCount;
3260 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 if (sharedBuffer == 0) {
3262 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3263 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3264 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003265 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003266 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 } else {
3268 mBuffer = sharedBuffer->pointer();
3269 }
3270 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 } else {
Steve Block3762c312012-01-06 19:20:56 +00003273 ALOGE("not enough memory for AudioTrack size=%u", size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 client->heap()->dump("AudioTrack");
3275 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 } else {
3278 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenc95ca2c2012-01-06 15:03:11 -08003279 // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 new(mCblk) audio_track_cblk_t();
3281 // clear all buffers
3282 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003283 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003284 mChannelCount = channelCount;
3285 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3287 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3288 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003289 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003290 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003293}
3294
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003295AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003296{
Glenn Kasten3694ec12012-01-27 16:47:15 -08003297 if (mCblk != NULL) {
Glenn Kastend9d68dc2012-02-03 10:24:48 -08003298 if (mClient == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003299 delete mCblk;
Glenn Kastend9d68dc2012-02-03 10:24:48 -08003300 } else {
3301 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Eric Laurenta553c252009-07-17 12:17:14 -07003302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 }
Glenn Kastenf31d0502012-01-25 15:27:15 -08003304 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten706b6182012-01-20 13:44:40 -08003305 if (mClient != 0) {
Glenn Kastendc3ac852012-01-25 15:28:08 -08003306 // Client destructor must run with AudioFlinger mutex locked
Eric Laurentb9481d82009-09-17 05:12:56 -07003307 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten706b6182012-01-20 13:44:40 -08003308 // If the client's reference count drops to zero, the associated destructor
3309 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3310 // relying on the automatic clear() at end of scope.
Eric Laurentb9481d82009-09-17 05:12:56 -07003311 mClient.clear();
3312 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003313}
3314
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003315void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003316{
Glenn Kastenc434c902011-12-13 11:53:26 -08003317 buffer->raw = NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003318 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003319 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003320 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003321}
3322
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003323bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003324 bool result;
3325 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003326
3327 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003328 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003329 ALOGV("stepServer failed acquiring cblk mutex");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003330 mFlags |= STEPSERVER_FAILED;
3331 }
3332 return result;
3333}
3334
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003335void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003336 audio_track_cblk_t* cblk = this->cblk();
3337
3338 cblk->user = 0;
3339 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003340 cblk->userBase = 0;
3341 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block71f2cf12011-10-20 11:56:00 +01003343 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003344}
3345
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003346int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003347 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003348}
3349
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003350void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003351 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003352 size_t frameSize = cblk->frameSize;
3353 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3354 int8_t *bufferEnd = bufferStart + frames * frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003355
3356 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003357 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003358 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block3762c312012-01-06 19:20:56 +00003359 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 -07003360 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003361 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003362 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kasten3694ec12012-01-27 16:47:15 -08003363 return NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003364 }
3365
3366 return bufferStart;
3367}
3368
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003369// ----------------------------------------------------------------------------
3370
Eric Laurenta553c252009-07-17 12:17:14 -07003371// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3372AudioFlinger::PlaybackThread::Track::Track(
3373 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003374 const sp<Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08003375 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003376 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003377 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003378 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003379 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003380 const sp<IMemory>& sharedBuffer,
3381 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003382 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003383 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3384 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003385{
Eric Laurent8a77a992009-09-09 05:16:08 -07003386 if (mCblk != NULL) {
3387 sp<ThreadBase> baseThread = thread.promote();
3388 if (baseThread != 0) {
3389 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3390 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003391 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003392 }
Steve Block71f2cf12011-10-20 11:56:00 +01003393 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003394 if (mName < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003395 ALOGE("no more track names available");
Eric Laurent8a77a992009-09-09 05:16:08 -07003396 }
Eric Laurent8a77a992009-09-09 05:16:08 -07003397 mStreamType = streamType;
3398 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3399 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003400 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003401 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003402}
3403
Eric Laurenta553c252009-07-17 12:17:14 -07003404AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003405{
Steve Block71f2cf12011-10-20 11:56:00 +01003406 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003407 sp<ThreadBase> thread = mThread.promote();
3408 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003409 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003410 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003411 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003412}
3413
Eric Laurenta553c252009-07-17 12:17:14 -07003414void AudioFlinger::PlaybackThread::Track::destroy()
3415{
3416 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3417 // by removing it from mTracks vector, so there is a risk that this Tracks's
3418 // desctructor is called. As the destructor needs to lock mLock,
3419 // we must acquire a strong reference on this Track before locking mLock
3420 // here so that the destructor is called only when exiting this function.
3421 // On the other hand, as long as Track::destroy() is only called by
3422 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3423 // this Track with its member mTrack.
3424 sp<Track> keep(this);
3425 { // scope for mLock
3426 sp<ThreadBase> thread = mThread.promote();
3427 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003428 if (!isOutputTrack()) {
3429 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kastenaae26c82012-02-08 12:35:35 -08003430 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003431
3432 // to track the speaker usage
3433 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003434 }
3435 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003436 }
Eric Laurenta553c252009-07-17 12:17:14 -07003437 Mutex::Autolock _l(thread->mLock);
3438 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3439 playbackThread->destroyTrack_l(this);
3440 }
3441 }
3442}
3443
3444void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003445{
Glenn Kastenbc4de882012-01-17 14:39:34 -08003446 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003447 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 -07003448 mName - AudioMixer::TRACK0,
Glenn Kasten706b6182012-01-20 13:44:40 -08003449 (mClient == 0) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003450 mStreamType,
3451 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003452 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003453 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003454 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003455 mState,
3456 mMute,
3457 mFillingUpStatus,
3458 mCblk->sampleRate,
Glenn Kasten0632bad2012-01-17 12:20:54 -08003459 vlr & 0xFFFF,
3460 vlr >> 16,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003461 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003462 mCblk->user,
3463 (int)mMainBuffer,
3464 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003465}
3466
Eric Laurenta553c252009-07-17 12:17:14 -07003467status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003468{
3469 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003470 uint32_t framesReady;
3471 uint32_t framesReq = buffer->frameCount;
3472
3473 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003474 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3475 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003476 ALOGV("stepServer recovered");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003477 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3478 }
3479
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003480 framesReady = cblk->framesReady();
3481
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003482 if (CC_LIKELY(framesReady)) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003483 uint32_t s = cblk->server;
3484 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3485
3486 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3487 if (framesReq > framesReady) {
3488 framesReq = framesReady;
3489 }
3490 if (s + framesReq > bufferEnd) {
3491 framesReq = bufferEnd - s;
3492 }
3493
3494 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003495 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003496
3497 buffer->frameCount = framesReq;
3498 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003499 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003500
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003501getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003502 buffer->raw = NULL;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003503 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003504 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 -07003505 return NOT_ENOUGH_DATA;
3506}
3507
Eric Laurenta553c252009-07-17 12:17:14 -07003508bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003509 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003510
3511 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003512 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003513 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003514 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003515 return true;
3516 }
3517 return false;
3518}
3519
Eric Laurenta553c252009-07-17 12:17:14 -07003520status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003521{
Eric Laurent49f02be2009-11-19 09:00:56 -08003522 status_t status = NO_ERROR;
Steve Block71f2cf12011-10-20 11:56:00 +01003523 ALOGV("start(%d), calling thread %d session %d",
Eric Laurent0d7e0482010-07-19 06:24:46 -07003524 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003525 sp<ThreadBase> thread = mThread.promote();
3526 if (thread != 0) {
3527 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003528 track_state state = mState;
Eric Laurent49f02be2009-11-19 09:00:56 -08003529 // here the track could be either new, or restarted
3530 // in both cases "unstop" the track
3531 if (mState == PAUSED) {
3532 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003533 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003534 } else {
3535 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003536 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003537 }
3538
3539 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3540 thread->mLock.unlock();
Glenn Kastenaae26c82012-02-08 12:35:35 -08003541 status = AudioSystem::startOutput(thread->id(), mStreamType, 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();
Glenn Kastenaae26c82012-02-08 12:35:35 -08003579 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003580 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003581
3582 // to track the speaker usage
3583 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003584 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003585 }
3586}
3587
Eric Laurenta553c252009-07-17 12:17:14 -07003588void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003589{
Steve Block71f2cf12011-10-20 11:56:00 +01003590 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003591 sp<ThreadBase> thread = mThread.promote();
3592 if (thread != 0) {
3593 Mutex::Autolock _l(thread->mLock);
3594 if (mState == ACTIVE || mState == RESUMING) {
3595 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003596 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003597 if (!isOutputTrack()) {
3598 thread->mLock.unlock();
Glenn Kastenaae26c82012-02-08 12:35:35 -08003599 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003600 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003601
3602 // to track the speaker usage
3603 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003604 }
Eric Laurenta553c252009-07-17 12:17:14 -07003605 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003606 }
3607}
3608
Eric Laurenta553c252009-07-17 12:17:14 -07003609void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003610{
Steve Block71f2cf12011-10-20 11:56:00 +01003611 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003612 sp<ThreadBase> thread = mThread.promote();
3613 if (thread != 0) {
3614 Mutex::Autolock _l(thread->mLock);
3615 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3616 return;
3617 }
3618 // No point remaining in PAUSED state after a flush => go to
3619 // STOPPED state
3620 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003621
Eric Laurentae29b762011-03-28 18:37:07 -07003622 // do not reset the track if it is still in the process of being stopped or paused.
3623 // this will be done by prepareTracks_l() when the track is stopped.
3624 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3625 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3626 reset();
3627 }
Eric Laurenta553c252009-07-17 12:17:14 -07003628 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003629}
3630
Eric Laurenta553c252009-07-17 12:17:14 -07003631void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003632{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003633 // Do not reset twice to avoid discarding data written just after a flush and before
3634 // the audioflinger thread detects the track is stopped.
3635 if (!mResetDone) {
3636 TrackBase::reset();
3637 // Force underrun condition to avoid false underrun callback until first data is
3638 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003639 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3640 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003641 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003642 mResetDone = true;
3643 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003644}
3645
Eric Laurenta553c252009-07-17 12:17:14 -07003646void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003647{
3648 mMute = muted;
3649}
3650
Eric Laurent65b65452010-06-01 23:49:17 -07003651status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3652{
3653 status_t status = DEAD_OBJECT;
3654 sp<ThreadBase> thread = mThread.promote();
3655 if (thread != 0) {
3656 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3657 status = playbackThread->attachAuxEffect(this, EffectId);
3658 }
3659 return status;
3660}
3661
3662void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3663{
3664 mAuxEffectId = EffectId;
3665 mAuxBuffer = buffer;
3666}
3667
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003668// ----------------------------------------------------------------------------
3669
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003670// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003671AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3672 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003675 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003676 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003678 uint32_t flags,
3679 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003680 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003681 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003682 mOverflow(false)
3683{
Eric Laurent8a77a992009-09-09 05:16:08 -07003684 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003685 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003686 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003687 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003688 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003689 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003690 } else {
3691 mCblk->frameSize = sizeof(int8_t);
3692 }
3693 }
Eric Laurenta553c252009-07-17 12:17:14 -07003694}
3695
3696AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697{
Eric Laurent49f02be2009-11-19 09:00:56 -08003698 sp<ThreadBase> thread = mThread.promote();
3699 if (thread != 0) {
3700 AudioSystem::releaseInput(thread->id());
3701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702}
3703
Eric Laurenta553c252009-07-17 12:17:14 -07003704status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705{
3706 audio_track_cblk_t* cblk = this->cblk();
3707 uint32_t framesAvail;
3708 uint32_t framesReq = buffer->frameCount;
3709
3710 // Check if last stepServer failed, try to step now
3711 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3712 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003713 ALOGV("stepServer recovered");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3715 }
3716
3717 framesAvail = cblk->framesAvailable_l();
3718
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003719 if (CC_LIKELY(framesAvail)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 uint32_t s = cblk->server;
3721 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3722
3723 if (framesReq > framesAvail) {
3724 framesReq = framesAvail;
3725 }
3726 if (s + framesReq > bufferEnd) {
3727 framesReq = bufferEnd - s;
3728 }
3729
3730 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003731 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732
3733 buffer->frameCount = framesReq;
3734 return NO_ERROR;
3735 }
3736
3737getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003738 buffer->raw = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 buffer->frameCount = 0;
3740 return NOT_ENOUGH_DATA;
3741}
3742
Eric Laurenta553c252009-07-17 12:17:14 -07003743status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744{
Eric Laurenta553c252009-07-17 12:17:14 -07003745 sp<ThreadBase> thread = mThread.promote();
3746 if (thread != 0) {
3747 RecordThread *recordThread = (RecordThread *)thread.get();
3748 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003749 } else {
3750 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752}
3753
Eric Laurenta553c252009-07-17 12:17:14 -07003754void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755{
Eric Laurenta553c252009-07-17 12:17:14 -07003756 sp<ThreadBase> thread = mThread.promote();
3757 if (thread != 0) {
3758 RecordThread *recordThread = (RecordThread *)thread.get();
3759 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003760 TrackBase::reset();
3761 // Force overerrun condition to avoid false overrun callback until first data is
3762 // read from buffer
3763 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765}
3766
Eric Laurent3fdb1262009-11-07 00:01:32 -08003767void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3768{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003769 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten706b6182012-01-20 13:44:40 -08003770 (mClient == 0) ? getpid() : mClient->pid(),
Eric Laurent3fdb1262009-11-07 00:01:32 -08003771 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003772 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003773 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003774 mFrameCount,
3775 mState,
3776 mCblk->sampleRate,
3777 mCblk->server,
3778 mCblk->user);
3779}
3780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781
3782// ----------------------------------------------------------------------------
3783
Eric Laurenta553c252009-07-17 12:17:14 -07003784AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3785 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003786 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003788 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003789 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003791 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003792 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793{
Eric Laurenta553c252009-07-17 12:17:14 -07003794
3795 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003796 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003797 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003798 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Eric Laurent6c30a712009-08-10 23:22:32 -07003799 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003800 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01003801 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003802 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3803 mCblk, mBuffer, mCblk->buffers,
3804 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003805 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003806 ALOGW("Error creating output track on thread %p", playbackThread);
Eric Laurent6c30a712009-08-10 23:22:32 -07003807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808}
3809
Eric Laurenta553c252009-07-17 12:17:14 -07003810AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811{
Eric Laurent6c30a712009-08-10 23:22:32 -07003812 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813}
3814
Eric Laurenta553c252009-07-17 12:17:14 -07003815status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816{
3817 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003818 if (status != NO_ERROR) {
3819 return status;
3820 }
3821
3822 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 mRetryCount = 127;
3824 return status;
3825}
3826
Eric Laurenta553c252009-07-17 12:17:14 -07003827void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828{
3829 Track::stop();
3830 clearBufferQueue();
3831 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003832 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833}
3834
Eric Laurenta553c252009-07-17 12:17:14 -07003835bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836{
3837 Buffer *pInBuffer;
3838 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003839 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003840 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003841 inBuffer.frameCount = frames;
3842 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003843
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003844 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003845
Eric Laurent62443f52009-10-05 20:29:18 -07003846 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003847 start();
3848 sp<ThreadBase> thread = mThread.promote();
3849 if (thread != 0) {
3850 MixerThread *mixerThread = (MixerThread *)thread.get();
3851 if (mCblk->frameCount > frames){
3852 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3853 uint32_t startFrames = (mCblk->frameCount - frames);
3854 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003855 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003856 pInBuffer->frameCount = startFrames;
3857 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003858 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003859 mBufferQueue.add(pInBuffer);
3860 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003861 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurenta553c252009-07-17 12:17:14 -07003862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 }
Eric Laurenta553c252009-07-17 12:17:14 -07003864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 }
3866
Eric Laurenta553c252009-07-17 12:17:14 -07003867 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 // First write pending buffers, then new data
3869 if (mBufferQueue.size()) {
3870 pInBuffer = mBufferQueue.itemAt(0);
3871 } else {
3872 pInBuffer = &inBuffer;
3873 }
Eric Laurenta553c252009-07-17 12:17:14 -07003874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 if (pInBuffer->frameCount == 0) {
3876 break;
3877 }
Eric Laurenta553c252009-07-17 12:17:14 -07003878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 if (mOutBuffer.frameCount == 0) {
3880 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003881 nsecs_t startTime = systemTime();
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003882 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01003883 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003884 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 break;
3886 }
Eric Laurenta553c252009-07-17 12:17:14 -07003887 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003888 if (waitTimeLeftMs >= waitTimeMs) {
3889 waitTimeLeftMs -= waitTimeMs;
3890 } else {
3891 waitTimeLeftMs = 0;
3892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 }
Eric Laurenta553c252009-07-17 12:17:14 -07003894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003896 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 mCblk->stepUser(outFrames);
3898 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003899 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003901 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 if (pInBuffer->frameCount == 0) {
3904 if (mBufferQueue.size()) {
3905 mBufferQueue.removeAt(0);
3906 delete [] pInBuffer->mBuffer;
3907 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01003908 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 -08003909 } else {
3910 break;
3911 }
3912 }
3913 }
Eric Laurenta553c252009-07-17 12:17:14 -07003914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 // If we could not write all frames, allocate a buffer and queue it for next time.
3916 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003917 sp<ThreadBase> thread = mThread.promote();
3918 if (thread != 0 && !thread->standby()) {
3919 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3920 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003921 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003922 pInBuffer->frameCount = inBuffer.frameCount;
3923 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003924 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003925 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01003926 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003927 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003928 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 }
3931 }
Eric Laurenta553c252009-07-17 12:17:14 -07003932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003934 // 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 -08003935 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003936 if (frames == 0 && mBufferQueue.size() == 0) {
3937 if (mCblk->user < mCblk->frameCount) {
3938 frames = mCblk->frameCount - mCblk->user;
3939 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003940 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003941 pInBuffer->frameCount = frames;
3942 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003943 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003944 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003945 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003946 stop();
3947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 }
3949
Eric Laurenta553c252009-07-17 12:17:14 -07003950 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951}
3952
Eric Laurenta553c252009-07-17 12:17:14 -07003953status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954{
3955 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 status_t result;
3957 audio_track_cblk_t* cblk = mCblk;
3958 uint32_t framesReq = buffer->frameCount;
3959
Steve Block71f2cf12011-10-20 11:56:00 +01003960// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 uint32_t framesAvail = cblk->framesAvailable();
3964
Eric Laurenta553c252009-07-17 12:17:14 -07003965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003967 Mutex::Autolock _l(cblk->lock);
3968 goto start_loop_here;
3969 while (framesAvail == 0) {
3970 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003971 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01003972 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003973 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07003974 }
3975 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3976 if (result != NO_ERROR) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003977 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07003978 }
3979 // read the server count again
3980 start_loop_here:
3981 framesAvail = cblk->framesAvailable_l();
3982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 }
3984
Eric Laurenta553c252009-07-17 12:17:14 -07003985// if (framesAvail < framesReq) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003986// return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07003987// }
3988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 if (framesReq > framesAvail) {
3990 framesReq = framesAvail;
3991 }
3992
3993 uint32_t u = cblk->user;
3994 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3995
3996 if (u + framesReq > bufferEnd) {
3997 framesReq = bufferEnd - u;
3998 }
3999
4000 buffer->frameCount = framesReq;
4001 buffer->raw = (void *)cblk->buffer(u);
4002 return NO_ERROR;
4003}
4004
4005
Eric Laurenta553c252009-07-17 12:17:14 -07004006void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007{
4008 size_t size = mBufferQueue.size();
4009 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 for (size_t i = 0; i < size; i++) {
4012 pBuffer = mBufferQueue.itemAt(i);
4013 delete [] pBuffer->mBuffer;
4014 delete pBuffer;
4015 }
4016 mBufferQueue.clear();
4017}
4018
4019// ----------------------------------------------------------------------------
4020
4021AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4022 : RefBase(),
4023 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08004024 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 mPid(pid)
4026{
4027 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4028}
4029
Eric Laurentb9481d82009-09-17 05:12:56 -07004030// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031AudioFlinger::Client::~Client()
4032{
Eric Laurentb9481d82009-09-17 05:12:56 -07004033 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034}
4035
Glenn Kasten1f812f72012-01-30 10:15:48 -08004036sp<MemoryDealer> AudioFlinger::Client::heap() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037{
4038 return mMemoryDealer;
4039}
4040
4041// ----------------------------------------------------------------------------
4042
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004043AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4044 const sp<IAudioFlingerClient>& client,
4045 pid_t pid)
Glenn Kastendc3ac852012-01-25 15:28:08 -08004046 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004047{
4048}
4049
4050AudioFlinger::NotificationClient::~NotificationClient()
4051{
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004052}
4053
4054void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4055{
4056 sp<NotificationClient> keep(this);
4057 {
4058 mAudioFlinger->removeNotificationClient(mPid);
4059 }
4060}
4061
4062// ----------------------------------------------------------------------------
4063
Eric Laurenta553c252009-07-17 12:17:14 -07004064AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004065 : BnAudioTrack(),
4066 mTrack(track)
4067{
4068}
4069
4070AudioFlinger::TrackHandle::~TrackHandle() {
4071 // just stop the track on deletion, associated resources
4072 // will be freed from the main thread once all pending buffers have
4073 // been played. Unless it's not in the active track list, in which
4074 // case we free everything now...
4075 mTrack->destroy();
4076}
4077
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004078sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4079 return mTrack->getCblk();
4080}
4081
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004082status_t AudioFlinger::TrackHandle::start() {
4083 return mTrack->start();
4084}
4085
4086void AudioFlinger::TrackHandle::stop() {
4087 mTrack->stop();
4088}
4089
4090void AudioFlinger::TrackHandle::flush() {
4091 mTrack->flush();
4092}
4093
4094void AudioFlinger::TrackHandle::mute(bool e) {
4095 mTrack->mute(e);
4096}
4097
4098void AudioFlinger::TrackHandle::pause() {
4099 mTrack->pause();
4100}
4101
Eric Laurent65b65452010-06-01 23:49:17 -07004102status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4103{
4104 return mTrack->attachAuxEffect(EffectId);
4105}
4106
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004107status_t AudioFlinger::TrackHandle::onTransact(
4108 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4109{
4110 return BnAudioTrack::onTransact(code, data, reply, flags);
4111}
4112
4113// ----------------------------------------------------------------------------
4114
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004115sp<IAudioRecord> AudioFlinger::openRecord(
4116 pid_t pid,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004117 audio_io_handle_t input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004118 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004119 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004120 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004121 int frameCount,
4122 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004123 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004124 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004125{
Eric Laurenta553c252009-07-17 12:17:14 -07004126 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004127 sp<RecordHandle> recordHandle;
4128 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004129 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004130 RecordThread *thread;
4131 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004132 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004133
4134 // check calling permissions
4135 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004136 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004137 goto Exit;
4138 }
4139
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004140 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004141 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004142 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004143 thread = checkRecordThread_l(input);
4144 if (thread == NULL) {
4145 lStatus = BAD_VALUE;
4146 goto Exit;
4147 }
4148
Glenn Kasten803a86a2012-01-25 14:28:29 -08004149 client = registerPid_l(pid);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004150
Eric Laurent65b65452010-06-01 23:49:17 -07004151 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004152 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004153 lSessionId = *sessionId;
4154 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004155 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004156 if (sessionId != NULL) {
4157 *sessionId = lSessionId;
4158 }
4159 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004160 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004161 recordTrack = thread->createRecordTrack_l(client,
4162 sampleRate,
4163 format,
4164 channelMask,
4165 frameCount,
4166 flags,
4167 lSessionId,
4168 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004169 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004170 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004171 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4172 // destructor is called by the TrackBase destructor with mLock held
4173 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 goto Exit;
4176 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004177
4178 // return to handle to client
4179 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004180 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004181
4182Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004183 if (status) {
4184 *status = lStatus;
4185 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004186 return recordHandle;
4187}
4188
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004189// ----------------------------------------------------------------------------
4190
Eric Laurenta553c252009-07-17 12:17:14 -07004191AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004192 : BnAudioRecord(),
4193 mRecordTrack(recordTrack)
4194{
4195}
4196
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004197AudioFlinger::RecordHandle::~RecordHandle() {
4198 stop();
4199}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004200
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004201sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4202 return mRecordTrack->getCblk();
4203}
4204
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004205status_t AudioFlinger::RecordHandle::start() {
Steve Block71f2cf12011-10-20 11:56:00 +01004206 ALOGV("RecordHandle::start()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004207 return mRecordTrack->start();
4208}
4209
4210void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004211 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004212 mRecordTrack->stop();
4213}
4214
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004215status_t AudioFlinger::RecordHandle::onTransact(
4216 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4217{
4218 return BnAudioRecord::onTransact(code, data, reply, flags);
4219}
4220
4221// ----------------------------------------------------------------------------
4222
Eric Laurent464d5b32011-06-17 21:29:58 -07004223AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4224 AudioStreamIn *input,
4225 uint32_t sampleRate,
4226 uint32_t channels,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004227 audio_io_handle_t id,
Eric Laurent464d5b32011-06-17 21:29:58 -07004228 uint32_t device) :
Glenn Kastenefd511a2012-01-26 10:38:26 -08004229 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kastendc3ac852012-01-25 15:28:08 -08004230 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4231 // mRsmpInIndex and mInputBytes set by readInputParameters()
4232 mReqChannelCount(popcount(channels)),
4233 mReqSampleRate(sampleRate)
4234 // mBytesRead is only meaningful while active, and so is cleared in start()
4235 // (but might be better to also clear here for dump?)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004236{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004237 snprintf(mName, kNameLength, "AudioIn_%d", id);
4238
Eric Laurenta553c252009-07-17 12:17:14 -07004239 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004240}
4241
Eric Laurenta553c252009-07-17 12:17:14 -07004242
4243AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004244{
Eric Laurenta553c252009-07-17 12:17:14 -07004245 delete[] mRsmpInBuffer;
Glenn Kasten2589cf92012-01-27 18:08:45 -08004246 delete mResampler;
4247 delete[] mRsmpOutBuffer;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004248}
4249
Eric Laurenta553c252009-07-17 12:17:14 -07004250void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004251{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004252 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004253}
Eric Laurent49f02be2009-11-19 09:00:56 -08004254
Eric Laurent828b9772011-08-07 16:32:26 -07004255status_t AudioFlinger::RecordThread::readyToRun()
4256{
4257 status_t status = initCheck();
Steve Block8564c8d2012-01-05 23:22:43 +00004258 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurent828b9772011-08-07 16:32:26 -07004259 return status;
4260}
4261
Eric Laurenta553c252009-07-17 12:17:14 -07004262bool AudioFlinger::RecordThread::threadLoop()
4263{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004264 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004265 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004266 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004267
Eric Laurent4712baa2010-09-30 16:12:31 -07004268 nsecs_t lastWarning = 0;
4269
Eric Laurent6dbdc402011-07-22 09:04:31 -07004270 acquireWakeLock();
4271
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004272 // start recording
4273 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004274
Eric Laurenta553c252009-07-17 12:17:14 -07004275 processConfigEvents();
4276
4277 { // scope for mLock
4278 Mutex::Autolock _l(mLock);
4279 checkForNewParameters_l();
4280 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4281 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004282 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004283 mStandby = true;
4284 }
4285
4286 if (exitPending()) break;
4287
Eric Laurent6dbdc402011-07-22 09:04:31 -07004288 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004289 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004290 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004291 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004292 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004293 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004294 continue;
4295 }
4296 if (mActiveTrack != 0) {
4297 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004298 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004299 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004300 mStandby = true;
4301 }
Eric Laurenta553c252009-07-17 12:17:14 -07004302 mActiveTrack.clear();
4303 mStartStopCond.broadcast();
4304 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004305 if (mReqChannelCount != mActiveTrack->channelCount()) {
4306 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004307 mStartStopCond.broadcast();
4308 } else if (mBytesRead != 0) {
4309 // record start succeeds only if first read from audio input
4310 // succeeds
4311 if (mBytesRead > 0) {
4312 mActiveTrack->mState = TrackBase::ACTIVE;
4313 } else {
4314 mActiveTrack.clear();
4315 }
4316 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004317 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004318 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004319 }
Eric Laurenta553c252009-07-17 12:17:14 -07004320 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004321 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004322 }
4323
4324 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004325 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4326 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004327 unlockEffectChains(effectChains);
4328 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004329 continue;
4330 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004331 for (size_t i = 0; i < effectChains.size(); i ++) {
4332 effectChains[i]->process_l();
4333 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004334
Eric Laurenta553c252009-07-17 12:17:14 -07004335 buffer.frameCount = mFrameCount;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004336 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004337 size_t framesOut = buffer.frameCount;
Glenn Kastenc434c902011-12-13 11:53:26 -08004338 if (mResampler == NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004339 // no resampling
4340 while (framesOut) {
4341 size_t framesIn = mFrameCount - mRsmpInIndex;
4342 if (framesIn) {
4343 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4344 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4345 if (framesIn > framesOut)
4346 framesIn = framesOut;
4347 mRsmpInIndex += framesIn;
4348 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004349 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004350 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004351 memcpy(dst, src, framesIn * mFrameSize);
4352 } else {
4353 int16_t *src16 = (int16_t *)src;
4354 int16_t *dst16 = (int16_t *)dst;
4355 if (mChannelCount == 1) {
4356 while (framesIn--) {
4357 *dst16++ = *src16;
4358 *dst16++ = *src16++;
4359 }
4360 } else {
4361 while (framesIn--) {
4362 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4363 src16 += 2;
4364 }
4365 }
4366 }
4367 }
4368 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004369 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004370 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004371 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004372 framesOut = 0;
4373 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004374 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004375 mRsmpInIndex = 0;
4376 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004377 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004378 ALOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004379 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004380 // Force input into standby so that it tries to
4381 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004382 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004383 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004384 }
Eric Laurenta553c252009-07-17 12:17:14 -07004385 mRsmpInIndex = mFrameCount;
4386 framesOut = 0;
4387 buffer.frameCount = 0;
4388 }
4389 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004390 }
4391 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004392 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004393
Eric Laurenta553c252009-07-17 12:17:14 -07004394 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4395 // alter output frame count as if we were expecting stereo samples
4396 if (mChannelCount == 1 && mReqChannelCount == 1) {
4397 framesOut >>= 1;
4398 }
4399 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4400 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4401 // are 32 bit aligned which should be always true.
4402 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten490909d2011-12-15 09:52:39 -08004403 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004404 // the resampler always outputs stereo samples: do post stereo to mono conversion
4405 int16_t *src = (int16_t *)mRsmpOutBuffer;
4406 int16_t *dst = buffer.i16;
4407 while (framesOut--) {
4408 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4409 src += 2;
4410 }
4411 } else {
Glenn Kasten490909d2011-12-15 09:52:39 -08004412 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004413 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004414
Eric Laurenta553c252009-07-17 12:17:14 -07004415 }
4416 mActiveTrack->releaseBuffer(&buffer);
4417 mActiveTrack->overflow();
4418 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004419 // client isn't retrieving buffers fast enough
4420 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004421 if (!mActiveTrack->setOverflow()) {
4422 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004423 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00004424 ALOGW("RecordThread: buffer overflow");
Eric Laurent4712baa2010-09-30 16:12:31 -07004425 lastWarning = now;
4426 }
4427 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004428 // Release the processor for a while before asking for a new buffer.
4429 // This will give the application more chance to read from the buffer and
4430 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004431 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004432 }
4433 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004434 // enable changes in effect chain
4435 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004436 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004437 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004438
Eric Laurenta553c252009-07-17 12:17:14 -07004439 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004440 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004441 }
Eric Laurenta553c252009-07-17 12:17:14 -07004442 mActiveTrack.clear();
4443
Eric Laurent49f02be2009-11-19 09:00:56 -08004444 mStartStopCond.broadcast();
4445
Eric Laurent6dbdc402011-07-22 09:04:31 -07004446 releaseWakeLock();
4447
Steve Block71f2cf12011-10-20 11:56:00 +01004448 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004449 return false;
4450}
4451
Eric Laurent464d5b32011-06-17 21:29:58 -07004452
4453sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4454 const sp<AudioFlinger::Client>& client,
4455 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004456 audio_format_t format,
Eric Laurent464d5b32011-06-17 21:29:58 -07004457 int channelMask,
4458 int frameCount,
4459 uint32_t flags,
4460 int sessionId,
4461 status_t *status)
4462{
4463 sp<RecordTrack> track;
4464 status_t lStatus;
4465
4466 lStatus = initCheck();
4467 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00004468 ALOGE("Audio driver not initialized.");
Eric Laurent464d5b32011-06-17 21:29:58 -07004469 goto Exit;
4470 }
4471
4472 { // scope for mLock
4473 Mutex::Autolock _l(mLock);
4474
4475 track = new RecordTrack(this, client, sampleRate,
4476 format, channelMask, frameCount, flags, sessionId);
4477
Glenn Kasten706b6182012-01-20 13:44:40 -08004478 if (track->getCblk() == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004479 lStatus = NO_MEMORY;
4480 goto Exit;
4481 }
4482
4483 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004484 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4485 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004486 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004487 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4488 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004489 }
4490 lStatus = NO_ERROR;
4491
4492Exit:
4493 if (status) {
4494 *status = lStatus;
4495 }
4496 return track;
4497}
4498
Eric Laurenta553c252009-07-17 12:17:14 -07004499status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004500{
Steve Block71f2cf12011-10-20 11:56:00 +01004501 ALOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004502 sp <ThreadBase> strongMe = this;
4503 status_t status = NO_ERROR;
4504 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004505 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004506 if (mActiveTrack != 0) {
4507 if (recordTrack != mActiveTrack.get()) {
4508 status = -EBUSY;
4509 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004510 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004511 }
4512 return status;
4513 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004514
Eric Laurent49f02be2009-11-19 09:00:56 -08004515 recordTrack->mState = TrackBase::IDLE;
4516 mActiveTrack = recordTrack;
4517 mLock.unlock();
4518 status_t status = AudioSystem::startInput(mId);
4519 mLock.lock();
4520 if (status != NO_ERROR) {
4521 mActiveTrack.clear();
4522 return status;
4523 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004524 mRsmpInIndex = mFrameCount;
4525 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004526 if (mResampler != NULL) {
4527 mResampler->reset();
4528 }
4529 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004530 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004531 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004532 mWaitWorkCV.signal();
4533 // do not wait for mStartStopCond if exiting
4534 if (mExiting) {
4535 mActiveTrack.clear();
4536 status = INVALID_OPERATION;
4537 goto startError;
4538 }
4539 mStartStopCond.wait(mLock);
4540 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01004541 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004542 status = BAD_VALUE;
4543 goto startError;
4544 }
Steve Block71f2cf12011-10-20 11:56:00 +01004545 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004546 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004547 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004548startError:
4549 AudioSystem::stopInput(mId);
4550 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004551}
4552
Eric Laurenta553c252009-07-17 12:17:14 -07004553void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01004554 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004555 sp <ThreadBase> strongMe = this;
4556 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004557 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004558 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4559 mActiveTrack->mState = TrackBase::PAUSING;
4560 // do not wait for mStartStopCond if exiting
4561 if (mExiting) {
4562 return;
4563 }
4564 mStartStopCond.wait(mLock);
4565 // if we have been restarted, recordTrack == mActiveTrack.get() here
4566 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4567 mLock.unlock();
4568 AudioSystem::stopInput(mId);
4569 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01004570 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004571 }
4572 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004573 }
4574}
4575
Eric Laurenta553c252009-07-17 12:17:14 -07004576status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577{
4578 const size_t SIZE = 256;
4579 char buffer[SIZE];
4580 String8 result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004581
Eric Laurent3fdb1262009-11-07 00:01:32 -08004582 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4583 result.append(buffer);
4584
4585 if (mActiveTrack != 0) {
4586 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004587 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004588 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004589 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004590
4591 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4592 result.append(buffer);
4593 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4594 result.append(buffer);
Glenn Kastenc434c902011-12-13 11:53:26 -08004595 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Eric Laurent3fdb1262009-11-07 00:01:32 -08004596 result.append(buffer);
4597 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4598 result.append(buffer);
4599 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4600 result.append(buffer);
4601
4602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004603 } else {
4604 result.append("No record client\n");
4605 }
4606 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004607
4608 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004609 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611 return NO_ERROR;
4612}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004613
Eric Laurenta553c252009-07-17 12:17:14 -07004614status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4615{
4616 size_t framesReq = buffer->frameCount;
4617 size_t framesReady = mFrameCount - mRsmpInIndex;
4618 int channelCount;
4619
4620 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004621 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004622 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004623 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004624 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004625 // Force input into standby so that it tries to
4626 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004627 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004628 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004629 }
Glenn Kastenc434c902011-12-13 11:53:26 -08004630 buffer->raw = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004631 buffer->frameCount = 0;
4632 return NOT_ENOUGH_DATA;
4633 }
4634 mRsmpInIndex = 0;
4635 framesReady = mFrameCount;
4636 }
4637
4638 if (framesReq > framesReady) {
4639 framesReq = framesReady;
4640 }
4641
4642 if (mChannelCount == 1 && mReqChannelCount == 2) {
4643 channelCount = 1;
4644 } else {
4645 channelCount = 2;
4646 }
4647 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4648 buffer->frameCount = framesReq;
4649 return NO_ERROR;
4650}
4651
4652void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4653{
4654 mRsmpInIndex += buffer->frameCount;
4655 buffer->frameCount = 0;
4656}
4657
4658bool AudioFlinger::RecordThread::checkForNewParameters_l()
4659{
4660 bool reconfig = false;
4661
Eric Laurent8fce46a2009-08-04 09:45:33 -07004662 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004663 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004664 String8 keyValuePair = mNewParameters[0];
4665 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004666 int value;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004667 audio_format_t reqFormat = mFormat;
Eric Laurenta553c252009-07-17 12:17:14 -07004668 int reqSamplingRate = mReqSampleRate;
4669 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004670
Eric Laurenta553c252009-07-17 12:17:14 -07004671 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4672 reqSamplingRate = value;
4673 reconfig = true;
4674 }
4675 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004676 reqFormat = (audio_format_t) value;
Eric Laurenta553c252009-07-17 12:17:14 -07004677 reconfig = true;
4678 }
4679 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004680 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004681 reconfig = true;
4682 }
4683 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4684 // do not accept frame count changes if tracks are open as the track buffer
4685 // size depends on frame count and correct behavior would not be garantied
4686 // if frame count is changed after track creation
4687 if (mActiveTrack != 0) {
4688 status = INVALID_OPERATION;
4689 } else {
4690 reconfig = true;
4691 }
4692 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004693 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4694 // forward device change to effects that have requested to be
4695 // aware of attached audio device.
4696 for (size_t i = 0; i < mEffectChains.size(); i++) {
4697 mEffectChains[i]->setDevice_l(value);
4698 }
4699 // store input device and output device but do not forward output device to audio HAL.
4700 // Note that status is ignored by the caller for output device
4701 // (see AudioFlinger::setParameters()
4702 if (value & AUDIO_DEVICE_OUT_ALL) {
4703 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4704 status = BAD_VALUE;
4705 } else {
4706 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004707 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4708 if (mTrack != NULL) {
4709 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004710 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004711 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4712 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4713 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004714 }
4715 mDevice |= (uint32_t)value;
4716 }
Eric Laurenta553c252009-07-17 12:17:14 -07004717 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004718 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004719 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004720 mInput->stream->common.standby(&mInput->stream->common);
4721 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004722 }
4723 if (reconfig) {
4724 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004725 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004726 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004727 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4728 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004729 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004730 status = NO_ERROR;
4731 }
4732 if (status == NO_ERROR) {
4733 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004734 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004735 }
4736 }
4737 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004738
4739 mNewParameters.removeAt(0);
4740
Eric Laurenta553c252009-07-17 12:17:14 -07004741 mParamStatus = status;
4742 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004743 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4744 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004745 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07004746 }
4747 return reconfig;
4748}
4749
4750String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4751{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004752 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004753 String8 out_s8 = String8();
4754
4755 Mutex::Autolock _l(mLock);
4756 if (initCheck() != NO_ERROR) {
4757 return out_s8;
4758 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004759
Dima Zavin31f188892011-04-18 16:57:27 -07004760 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004761 out_s8 = String8(s);
4762 free(s);
4763 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004764}
4765
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004766void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004767 AudioSystem::OutputDescriptor desc;
Glenn Kasten3694ec12012-01-27 16:47:15 -08004768 void *param2 = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004769
4770 switch (event) {
4771 case AudioSystem::INPUT_OPENED:
4772 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004773 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004774 desc.samplingRate = mSampleRate;
4775 desc.format = mFormat;
4776 desc.frameCount = mFrameCount;
4777 desc.latency = 0;
4778 param2 = &desc;
4779 break;
4780
4781 case AudioSystem::INPUT_CLOSED:
4782 default:
4783 break;
4784 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004785 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004786}
4787
4788void AudioFlinger::RecordThread::readInputParameters()
4789{
Glenn Kasten2589cf92012-01-27 18:08:45 -08004790 delete mRsmpInBuffer;
4791 // mRsmpInBuffer is always assigned a new[] below
4792 delete mRsmpOutBuffer;
4793 mRsmpOutBuffer = NULL;
4794 delete mResampler;
Glenn Kastenc434c902011-12-13 11:53:26 -08004795 mResampler = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004796
Dima Zavin31f188892011-04-18 16:57:27 -07004797 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004798 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4799 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004800 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08004801 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin31f188892011-04-18 16:57:27 -07004802 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004803 mFrameCount = mInputBytes / mFrameSize;
4804 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4805
4806 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4807 {
4808 int channelCount;
4809 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4810 // stereo to mono post process as the resampler always outputs stereo.
4811 if (mChannelCount == 1 && mReqChannelCount == 2) {
4812 channelCount = 1;
4813 } else {
4814 channelCount = 2;
4815 }
4816 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4817 mResampler->setSampleRate(mSampleRate);
4818 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4819 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4820
4821 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4822 if (mChannelCount == 1 && mReqChannelCount == 1) {
4823 mFrameCount >>= 1;
4824 }
4825
4826 }
4827 mRsmpInIndex = mFrameCount;
4828}
4829
Eric Laurent47d0a922010-02-26 02:47:27 -08004830unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4831{
Eric Laurent828b9772011-08-07 16:32:26 -07004832 Mutex::Autolock _l(mLock);
4833 if (initCheck() != NO_ERROR) {
4834 return 0;
4835 }
4836
Dima Zavin31f188892011-04-18 16:57:27 -07004837 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004838}
4839
Eric Laurent464d5b32011-06-17 21:29:58 -07004840uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4841{
4842 Mutex::Autolock _l(mLock);
4843 uint32_t result = 0;
4844 if (getEffectChain_l(sessionId) != 0) {
4845 result = EFFECT_SESSION;
4846 }
4847
4848 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4849 result |= TRACK_SESSION;
4850 }
4851
4852 return result;
4853}
4854
Eric Laurent6639b552011-08-01 09:52:20 -07004855AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4856{
4857 Mutex::Autolock _l(mLock);
4858 return mTrack;
4859}
4860
Glenn Kasten5b0135e2012-01-26 09:46:34 -08004861AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurent828b9772011-08-07 16:32:26 -07004862{
4863 Mutex::Autolock _l(mLock);
4864 return mInput;
4865}
4866
4867AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4868{
4869 Mutex::Autolock _l(mLock);
4870 AudioStreamIn *input = mInput;
4871 mInput = NULL;
4872 return input;
4873}
4874
4875// this method must always be called either with ThreadBase mLock held or inside the thread loop
4876audio_stream_t* AudioFlinger::RecordThread::stream()
4877{
4878 if (mInput == NULL) {
4879 return NULL;
4880 }
4881 return &mInput->stream->common;
4882}
4883
4884
Eric Laurenta553c252009-07-17 12:17:14 -07004885// ----------------------------------------------------------------------------
4886
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004887audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004888 uint32_t *pSamplingRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004889 audio_format_t *pFormat,
Eric Laurenta553c252009-07-17 12:17:14 -07004890 uint32_t *pChannels,
4891 uint32_t *pLatencyMs,
4892 uint32_t flags)
4893{
4894 status_t status;
4895 PlaybackThread *thread = NULL;
4896 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4897 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004898 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta553c252009-07-17 12:17:14 -07004899 uint32_t channels = pChannels ? *pChannels : 0;
4900 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004901 audio_stream_out_t *outStream;
4902 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004903
Steve Block71f2cf12011-10-20 11:56:00 +01004904 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07004905 pDevices ? *pDevices : 0,
4906 samplingRate,
4907 format,
4908 channels,
4909 flags);
4910
4911 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004912 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004913 }
Dima Zavin31f188892011-04-18 16:57:27 -07004914
Eric Laurenta553c252009-07-17 12:17:14 -07004915 Mutex::Autolock _l(mLock);
4916
Dima Zavin31f188892011-04-18 16:57:27 -07004917 outHwDev = findSuitableHwDev_l(*pDevices);
4918 if (outHwDev == NULL)
4919 return 0;
4920
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004921 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07004922 &channels, &samplingRate, &outStream);
Steve Block71f2cf12011-10-20 11:56:00 +01004923 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004924 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004925 samplingRate,
4926 format,
4927 channels,
4928 status);
4929
4930 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004931 if (outStream != NULL) {
4932 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004933 audio_io_handle_t id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004934
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004935 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4936 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4937 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004938 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004939 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004940 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004941 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004942 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004943 }
Eric Laurent65b65452010-06-01 23:49:17 -07004944 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004945
Glenn Kasten3694ec12012-01-27 16:47:15 -08004946 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4947 if (pFormat != NULL) *pFormat = format;
4948 if (pChannels != NULL) *pChannels = channels;
4949 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004950
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004951 // notify client processes of the new output creation
4952 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004953 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004954 }
4955
Eric Laurent9cc489a22009-12-05 05:20:01 -08004956 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004957}
4958
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004959audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
4960 audio_io_handle_t output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004961{
4962 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004963 MixerThread *thread1 = checkMixerThread_l(output1);
4964 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004965
Eric Laurentddb78e72009-07-28 08:44:33 -07004966 if (thread1 == NULL || thread2 == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00004967 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004968 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004969 }
4970
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004971 audio_io_handle_t id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004972 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004973 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004974 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004975 // notify client processes of the new output creation
4976 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004977 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004978}
4979
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004980status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07004981{
Eric Laurent49018a52009-08-04 08:37:05 -07004982 // keep strong reference on the playback thread so that
4983 // it is not destroyed while exit() is executed
4984 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004985 {
4986 Mutex::Autolock _l(mLock);
4987 thread = checkPlaybackThread_l(output);
4988 if (thread == NULL) {
4989 return BAD_VALUE;
4990 }
4991
Steve Block71f2cf12011-10-20 11:56:00 +01004992 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004993
Eric Laurent464d5b32011-06-17 21:29:58 -07004994 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07004995 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004996 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004997 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004998 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004999 }
5000 }
5001 }
Glenn Kasten3694ec12012-01-27 16:47:15 -08005002 void *param2 = NULL;
Eric Laurent49f02be2009-11-19 09:00:56 -08005003 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005004 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07005005 }
5006 thread->exit();
5007
Eric Laurent464d5b32011-06-17 21:29:58 -07005008 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07005009 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005010 assert(out != NULL);
Eric Laurent828b9772011-08-07 16:32:26 -07005011 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005012 out->hwDev->close_output_stream(out->hwDev, out->stream);
5013 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005014 }
Eric Laurenta553c252009-07-17 12:17:14 -07005015 return NO_ERROR;
5016}
5017
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005018status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005019{
5020 Mutex::Autolock _l(mLock);
5021 PlaybackThread *thread = checkPlaybackThread_l(output);
5022
5023 if (thread == NULL) {
5024 return BAD_VALUE;
5025 }
5026
Steve Block71f2cf12011-10-20 11:56:00 +01005027 ALOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005028 thread->suspend();
5029
5030 return NO_ERROR;
5031}
5032
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005033status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005034{
5035 Mutex::Autolock _l(mLock);
5036 PlaybackThread *thread = checkPlaybackThread_l(output);
5037
5038 if (thread == NULL) {
5039 return BAD_VALUE;
5040 }
5041
Steve Block71f2cf12011-10-20 11:56:00 +01005042 ALOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005043
5044 thread->restore();
5045
5046 return NO_ERROR;
5047}
5048
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005049audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005050 uint32_t *pSamplingRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005051 audio_format_t *pFormat,
Eric Laurenta553c252009-07-17 12:17:14 -07005052 uint32_t *pChannels,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005053 audio_in_acoustics_t acoustics)
Eric Laurenta553c252009-07-17 12:17:14 -07005054{
5055 status_t status;
5056 RecordThread *thread = NULL;
5057 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005058 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta553c252009-07-17 12:17:14 -07005059 uint32_t channels = pChannels ? *pChannels : 0;
5060 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005061 audio_format_t reqFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -07005062 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005063 audio_stream_in_t *inStream;
5064 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005065
5066 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005067 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005068 }
Dima Zavin31f188892011-04-18 16:57:27 -07005069
Eric Laurenta553c252009-07-17 12:17:14 -07005070 Mutex::Autolock _l(mLock);
5071
Dima Zavin31f188892011-04-18 16:57:27 -07005072 inHwDev = findSuitableHwDev_l(*pDevices);
5073 if (inHwDev == NULL)
5074 return 0;
5075
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005076 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07005077 &channels, &samplingRate,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005078 acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005079 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005080 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005081 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005082 samplingRate,
5083 format,
5084 channels,
5085 acoustics,
5086 status);
5087
5088 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5089 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5090 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005091 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005092 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005093 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005094 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005095 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005096 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07005097 &channels, &samplingRate,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005098 acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005099 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005100 }
5101
Dima Zavin31f188892011-04-18 16:57:27 -07005102 if (inStream != NULL) {
5103 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5104
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005105 audio_io_handle_t id = nextUniqueId();
Eric Laurent464d5b32011-06-17 21:29:58 -07005106 // Start record thread
5107 // RecorThread require both input and output device indication to forward to audio
5108 // pre processing modules
5109 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5110 thread = new RecordThread(this,
5111 input,
5112 reqSamplingRate,
5113 reqChannels,
5114 id,
5115 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005116 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005117 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kasten3694ec12012-01-27 16:47:15 -08005118 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5119 if (pFormat != NULL) *pFormat = format;
5120 if (pChannels != NULL) *pChannels = reqChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07005121
Dima Zavin31f188892011-04-18 16:57:27 -07005122 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005123
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005124 // notify client processes of the new input creation
5125 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005126 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005127 }
5128
Eric Laurent9cc489a22009-12-05 05:20:01 -08005129 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005130}
5131
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005132status_t AudioFlinger::closeInput(audio_io_handle_t input)
Eric Laurenta553c252009-07-17 12:17:14 -07005133{
Eric Laurent49018a52009-08-04 08:37:05 -07005134 // keep strong reference on the record thread so that
5135 // it is not destroyed while exit() is executed
5136 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005137 {
5138 Mutex::Autolock _l(mLock);
5139 thread = checkRecordThread_l(input);
5140 if (thread == NULL) {
5141 return BAD_VALUE;
5142 }
5143
Steve Block71f2cf12011-10-20 11:56:00 +01005144 ALOGV("closeInput() %d", input);
Glenn Kasten3694ec12012-01-27 16:47:15 -08005145 void *param2 = NULL;
Eric Laurent49f02be2009-11-19 09:00:56 -08005146 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005147 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005148 }
5149 thread->exit();
5150
Eric Laurent828b9772011-08-07 16:32:26 -07005151 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005152 assert(in != NULL);
Eric Laurent828b9772011-08-07 16:32:26 -07005153 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005154 in->hwDev->close_input_stream(in->hwDev, in->stream);
5155 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005156
Eric Laurenta553c252009-07-17 12:17:14 -07005157 return NO_ERROR;
5158}
5159
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005160status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005161{
5162 Mutex::Autolock _l(mLock);
5163 MixerThread *dstThread = checkMixerThread_l(output);
5164 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005165 ALOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005166 return BAD_VALUE;
5167 }
5168
Steve Block71f2cf12011-10-20 11:56:00 +01005169 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005170 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005171
Eric Laurent05ce0942011-08-30 10:18:54 -07005172 dstThread->setStreamValid(stream, true);
5173
Eric Laurenta553c252009-07-17 12:17:14 -07005174 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005175 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005176 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005177 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005178 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005179 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005180 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005181 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005182 }
Eric Laurentd069f322009-09-01 05:56:26 -07005183
Eric Laurenta553c252009-07-17 12:17:14 -07005184 return NO_ERROR;
5185}
5186
Eric Laurent65b65452010-06-01 23:49:17 -07005187
5188int AudioFlinger::newAudioSessionId()
5189{
Eric Laurent464d5b32011-06-17 21:29:58 -07005190 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005191}
5192
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005193void AudioFlinger::acquireAudioSessionId(int audioSession)
5194{
5195 Mutex::Autolock _l(mLock);
Glenn Kastend153b1f2012-02-03 11:10:26 -08005196 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005197 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005198 int num = mAudioSessionRefs.size();
5199 for (int i = 0; i< num; i++) {
5200 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5201 if (ref->sessionid == audioSession && ref->pid == caller) {
5202 ref->cnt++;
Steve Block71f2cf12011-10-20 11:56:00 +01005203 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005204 return;
5205 }
5206 }
Glenn Kastendc3ac852012-01-25 15:28:08 -08005207 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5208 ALOGV(" added new entry for %d", audioSession);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005209}
5210
5211void AudioFlinger::releaseAudioSessionId(int audioSession)
5212{
5213 Mutex::Autolock _l(mLock);
Glenn Kastend153b1f2012-02-03 11:10:26 -08005214 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005215 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005216 int num = mAudioSessionRefs.size();
5217 for (int i = 0; i< num; i++) {
5218 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5219 if (ref->sessionid == audioSession && ref->pid == caller) {
5220 ref->cnt--;
Steve Block71f2cf12011-10-20 11:56:00 +01005221 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005222 if (ref->cnt == 0) {
5223 mAudioSessionRefs.removeAt(i);
5224 delete ref;
5225 purgeStaleEffects_l();
5226 }
5227 return;
5228 }
5229 }
Steve Block8564c8d2012-01-05 23:22:43 +00005230 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005231}
5232
5233void AudioFlinger::purgeStaleEffects_l() {
5234
Steve Block71f2cf12011-10-20 11:56:00 +01005235 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005236
5237 Vector< sp<EffectChain> > chains;
5238
5239 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5240 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5241 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5242 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005243 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5244 chains.push(ec);
5245 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005246 }
5247 }
5248 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5249 sp<RecordThread> t = mRecordThreads.valueAt(i);
5250 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5251 sp<EffectChain> ec = t->mEffectChains[j];
5252 chains.push(ec);
5253 }
5254 }
5255
5256 for (size_t i = 0; i < chains.size(); i++) {
5257 sp<EffectChain> ec = chains[i];
5258 int sessionid = ec->sessionId();
5259 sp<ThreadBase> t = ec->mThread.promote();
5260 if (t == 0) {
5261 continue;
5262 }
5263 size_t numsessionrefs = mAudioSessionRefs.size();
5264 bool found = false;
5265 for (size_t k = 0; k < numsessionrefs; k++) {
5266 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5267 if (ref->sessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005268 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005269 sessionid, ref->pid, ref->cnt);
5270 found = true;
5271 break;
5272 }
5273 }
5274 if (!found) {
5275 // remove all effects from the chain
5276 while (ec->mEffects.size()) {
5277 sp<EffectModule> effect = ec->mEffects[0];
5278 effect->unPin();
5279 Mutex::Autolock _l (t->mLock);
5280 t->removeEffect_l(effect);
5281 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5282 sp<EffectHandle> handle = effect->mHandles[j].promote();
5283 if (handle != 0) {
5284 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005285 if (handle->mHasControl && handle->mEnabled) {
5286 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5287 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005288 }
5289 }
5290 AudioSystem::unregisterEffect(effect->id());
5291 }
5292 }
5293 }
5294 return;
5295}
5296
Eric Laurenta553c252009-07-17 12:17:14 -07005297// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005298AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005299{
5300 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005301 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5302 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005303 }
Eric Laurenta553c252009-07-17 12:17:14 -07005304 return thread;
5305}
5306
5307// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005308AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005309{
5310 PlaybackThread *thread = checkPlaybackThread_l(output);
5311 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005312 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005313 thread = NULL;
5314 }
5315 }
5316 return (MixerThread *)thread;
5317}
5318
5319// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005320AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005321{
5322 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005323 if (mRecordThreads.indexOfKey(input) >= 0) {
5324 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005325 }
Eric Laurenta553c252009-07-17 12:17:14 -07005326 return thread;
5327}
5328
Eric Laurent464d5b32011-06-17 21:29:58 -07005329uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005330{
Eric Laurent464d5b32011-06-17 21:29:58 -07005331 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005332}
5333
Eric Laurent464d5b32011-06-17 21:29:58 -07005334AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5335{
5336 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5337 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005338 AudioStreamOut *output = thread->getOutput();
5339 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005340 return thread;
5341 }
5342 }
5343 return NULL;
5344}
5345
5346uint32_t AudioFlinger::primaryOutputDevice_l()
5347{
5348 PlaybackThread *thread = primaryPlaybackThread_l();
5349
5350 if (thread == NULL) {
5351 return 0;
5352 }
5353
5354 return thread->device();
5355}
5356
5357
Eric Laurent65b65452010-06-01 23:49:17 -07005358// ----------------------------------------------------------------------------
5359// Effect management
5360// ----------------------------------------------------------------------------
5361
5362
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005363status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Eric Laurent65b65452010-06-01 23:49:17 -07005364{
5365 Mutex::Autolock _l(mLock);
5366 return EffectQueryNumberEffects(numEffects);
5367}
5368
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005369status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Eric Laurent65b65452010-06-01 23:49:17 -07005370{
5371 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005372 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005373}
5374
Glenn Kasten67313332012-01-30 07:40:52 -08005375status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005376 effect_descriptor_t *descriptor) const
Eric Laurent65b65452010-06-01 23:49:17 -07005377{
5378 Mutex::Autolock _l(mLock);
5379 return EffectGetDescriptor(pUuid, descriptor);
5380}
5381
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005382
Eric Laurent65b65452010-06-01 23:49:17 -07005383sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5384 effect_descriptor_t *pDesc,
5385 const sp<IEffectClient>& effectClient,
5386 int32_t priority,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005387 audio_io_handle_t io,
Eric Laurent65b65452010-06-01 23:49:17 -07005388 int sessionId,
5389 status_t *status,
5390 int *id,
5391 int *enabled)
5392{
5393 status_t lStatus = NO_ERROR;
5394 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005395 effect_descriptor_t desc;
Eric Laurent65b65452010-06-01 23:49:17 -07005396
Glenn Kasten803a86a2012-01-25 14:28:29 -08005397 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005398 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005399
5400 if (pDesc == NULL) {
5401 lStatus = BAD_VALUE;
5402 goto Exit;
5403 }
5404
Eric Laurent98c92592010-09-23 16:10:16 -07005405 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005406 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005407 lStatus = PERMISSION_DENIED;
5408 goto Exit;
5409 }
5410
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005411 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005412 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005413 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005414 lStatus = PERMISSION_DENIED;
5415 goto Exit;
5416 }
5417
Eric Laurent464d5b32011-06-17 21:29:58 -07005418 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005419 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005420 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005421 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005422 lStatus = BAD_VALUE;
5423 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005424 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005425 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005426 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005427 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005428 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005429 }
5430 }
5431
Eric Laurent65b65452010-06-01 23:49:17 -07005432 {
5433 Mutex::Autolock _l(mLock);
5434
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005435
Eric Laurent65b65452010-06-01 23:49:17 -07005436 if (!EffectIsNullUuid(&pDesc->uuid)) {
5437 // if uuid is specified, request effect descriptor
5438 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5439 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005440 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005441 goto Exit;
5442 }
5443 } else {
5444 // if uuid is not specified, look for an available implementation
5445 // of the required type in effect factory
5446 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005447 ALOGW("createEffect() no effect type");
Eric Laurent65b65452010-06-01 23:49:17 -07005448 lStatus = BAD_VALUE;
5449 goto Exit;
5450 }
5451 uint32_t numEffects = 0;
5452 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005453 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005454 bool found = false;
5455
5456 lStatus = EffectQueryNumberEffects(&numEffects);
5457 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005458 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005459 goto Exit;
5460 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005461 for (uint32_t i = 0; i < numEffects; i++) {
5462 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005463 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005464 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005465 continue;
5466 }
5467 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5468 // If matching type found save effect descriptor. If the session is
5469 // 0 and the effect is not auxiliary, continue enumeration in case
5470 // an auxiliary version of this effect type is available
5471 found = true;
5472 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005473 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005474 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5475 break;
5476 }
5477 }
5478 }
5479 if (!found) {
5480 lStatus = BAD_VALUE;
Steve Block8564c8d2012-01-05 23:22:43 +00005481 ALOGW("createEffect() effect not found");
Eric Laurent65b65452010-06-01 23:49:17 -07005482 goto Exit;
5483 }
5484 // For same effect type, chose auxiliary version over insert version if
5485 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005486 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005487 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5488 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5489 }
5490 }
5491
5492 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005493 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005494 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5495 lStatus = INVALID_OPERATION;
5496 goto Exit;
5497 }
5498
Eric Laurentf82fccd2011-07-27 19:49:51 -07005499 // check recording permission for visualizer
5500 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5501 !recordingAllowed()) {
5502 lStatus = PERMISSION_DENIED;
5503 goto Exit;
5504 }
5505
Eric Laurent65b65452010-06-01 23:49:17 -07005506 // return effect descriptor
5507 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5508
5509 // If output is not specified try to find a matching audio session ID in one of the
5510 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005511 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5512 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005513 // Note: io is never 0 when creating an effect on an input
5514 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005515 // look for the thread where the specified audio session is present
5516 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5517 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005518 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005519 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005520 }
Eric Laurent65b65452010-06-01 23:49:17 -07005521 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005522 if (io == 0) {
5523 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5524 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5525 io = mRecordThreads.keyAt(i);
5526 break;
5527 }
5528 }
5529 }
Eric Laurent98c92592010-09-23 16:10:16 -07005530 // If no output thread contains the requested session ID, default to
5531 // first output. The effect chain will be moved to the correct output
5532 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005533 if (io == 0 && mPlaybackThreads.size()) {
5534 io = mPlaybackThreads.keyAt(0);
5535 }
Steve Block71f2cf12011-10-20 11:56:00 +01005536 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005537 }
5538 ThreadBase *thread = checkRecordThread_l(io);
5539 if (thread == NULL) {
5540 thread = checkPlaybackThread_l(io);
5541 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +00005542 ALOGE("createEffect() unknown output thread");
Eric Laurent464d5b32011-06-17 21:29:58 -07005543 lStatus = BAD_VALUE;
5544 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005545 }
Eric Laurent65b65452010-06-01 23:49:17 -07005546 }
Eric Laurent98c92592010-09-23 16:10:16 -07005547
Glenn Kasten803a86a2012-01-25 14:28:29 -08005548 sp<Client> client = registerPid_l(pid);
Eric Laurent65b65452010-06-01 23:49:17 -07005549
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005550 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005551 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5552 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005553 if (handle != 0 && id != NULL) {
5554 *id = handle->id();
5555 }
5556 }
5557
5558Exit:
5559 if(status) {
5560 *status = lStatus;
5561 }
5562 return handle;
5563}
5564
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005565status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
5566 audio_io_handle_t dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005567{
Steve Block71f2cf12011-10-20 11:56:00 +01005568 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005569 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005570 Mutex::Autolock _l(mLock);
5571 if (srcOutput == dstOutput) {
Steve Block8564c8d2012-01-05 23:22:43 +00005572 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005573 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005574 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005575 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5576 if (srcThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005577 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005578 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005579 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005580 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5581 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005582 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005583 return BAD_VALUE;
5584 }
5585
5586 Mutex::Autolock _dl(dstThread->mLock);
5587 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005588 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005589
Eric Laurent53334cd2010-06-23 17:38:20 -07005590 return NO_ERROR;
5591}
5592
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005593// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005594status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005595 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005596 AudioFlinger::PlaybackThread *dstThread,
5597 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005598{
Steve Block71f2cf12011-10-20 11:56:00 +01005599 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005600 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005601
Eric Laurentf82fccd2011-07-27 19:49:51 -07005602 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005603 if (chain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005604 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005605 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005606 return INVALID_OPERATION;
5607 }
5608
Eric Laurent493941b2010-07-28 01:32:47 -07005609 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005610 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005611 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005612 // removed.
5613 srcThread->removeEffectChain_l(chain);
5614
5615 // transfer all effects one by one so that new effect chain is created on new thread with
5616 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005617 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent493941b2010-07-28 01:32:47 -07005618 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005619 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005620 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5621 while (effect != 0) {
5622 srcThread->removeEffect_l(effect);
5623 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005624 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5625 if (effect->state() == EffectModule::ACTIVE ||
5626 effect->state() == EffectModule::STOPPING) {
5627 effect->start();
5628 }
Eric Laurent493941b2010-07-28 01:32:47 -07005629 // if the move request is not received from audio policy manager, the effect must be
5630 // re-registered with the new strategy and output
5631 if (dstChain == 0) {
5632 dstChain = effect->chain().promote();
5633 if (dstChain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005634 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent493941b2010-07-28 01:32:47 -07005635 srcThread->addEffect_l(effect);
5636 return NO_INIT;
5637 }
5638 strategy = dstChain->strategy();
5639 }
5640 if (reRegister) {
5641 AudioSystem::unregisterEffect(effect->id());
5642 AudioSystem::registerEffect(&effect->desc(),
5643 dstOutput,
5644 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005645 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005646 effect->id());
5647 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005648 effect = chain->getEffectFromId_l(0);
5649 }
5650
5651 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005652}
5653
Eric Laurent464d5b32011-06-17 21:29:58 -07005654
Eric Laurent65b65452010-06-01 23:49:17 -07005655// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005656sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005657 const sp<AudioFlinger::Client>& client,
5658 const sp<IEffectClient>& effectClient,
5659 int32_t priority,
5660 int sessionId,
5661 effect_descriptor_t *desc,
5662 int *enabled,
5663 status_t *status
5664 )
5665{
5666 sp<EffectModule> effect;
5667 sp<EffectHandle> handle;
5668 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005669 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005670 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005671 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005672 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005673
Eric Laurent464d5b32011-06-17 21:29:58 -07005674 lStatus = initCheck();
5675 if (lStatus != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00005676 ALOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005677 goto Exit;
5678 }
5679
5680 // Do not allow effects with session ID 0 on direct output or duplicating threads
5681 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005682 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block8564c8d2012-01-05 23:22:43 +00005683 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005684 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005685 lStatus = BAD_VALUE;
5686 goto Exit;
5687 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005688 // Only Pre processor effects are allowed on input threads and only on input threads
5689 if ((mType == RECORD &&
5690 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5691 (mType != RECORD &&
5692 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005693 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005694 desc->name, desc->flags, mType);
5695 lStatus = BAD_VALUE;
5696 goto Exit;
5697 }
Eric Laurent65b65452010-06-01 23:49:17 -07005698
Steve Block71f2cf12011-10-20 11:56:00 +01005699 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005700
5701 { // scope for mLock
5702 Mutex::Autolock _l(mLock);
5703
5704 // check for existing effect chain with the requested audio session
5705 chain = getEffectChain_l(sessionId);
5706 if (chain == 0) {
5707 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005708 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005709 chain = new EffectChain(this, sessionId);
5710 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005711 chain->setStrategy(getStrategyForSession_l(sessionId));
5712 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005713 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005714 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005715 }
5716
Glenn Kasten70ed6b72012-01-10 10:46:34 -08005717 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005718
5719 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005720 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005721 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005722 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005723 if (lStatus != NO_ERROR) {
5724 goto Exit;
5725 }
5726 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005727 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005728 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005729 lStatus = effect->status();
5730 if (lStatus != NO_ERROR) {
5731 goto Exit;
5732 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005733 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005734 if (lStatus != NO_ERROR) {
5735 goto Exit;
5736 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005737 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005738
5739 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005740 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005741 }
5742 // create effect handle and connect it to effect module
5743 handle = new EffectHandle(effect, client, effectClient, priority);
5744 lStatus = effect->addHandle(handle);
Glenn Kasten3694ec12012-01-27 16:47:15 -08005745 if (enabled != NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005746 *enabled = (int)effect->isEnabled();
5747 }
5748 }
5749
5750Exit:
5751 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005752 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005753 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005754 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005755 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005756 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005757 AudioSystem::unregisterEffect(effect->id());
5758 }
5759 if (chainCreated) {
5760 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005761 }
Eric Laurent65b65452010-06-01 23:49:17 -07005762 handle.clear();
5763 }
5764
5765 if(status) {
5766 *status = lStatus;
5767 }
5768 return handle;
5769}
5770
Eric Laurent464d5b32011-06-17 21:29:58 -07005771sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5772{
Eric Laurent464d5b32011-06-17 21:29:58 -07005773 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kastenc64a6f02012-01-30 13:00:02 -08005774 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent464d5b32011-06-17 21:29:58 -07005775}
5776
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005777// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5778// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005779status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005780{
5781 // check for existing effect chain with the requested audio session
5782 int sessionId = effect->sessionId();
5783 sp<EffectChain> chain = getEffectChain_l(sessionId);
5784 bool chainCreated = false;
5785
5786 if (chain == 0) {
5787 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005788 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005789 chain = new EffectChain(this, sessionId);
5790 addEffectChain_l(chain);
5791 chain->setStrategy(getStrategyForSession_l(sessionId));
5792 chainCreated = true;
5793 }
Steve Block71f2cf12011-10-20 11:56:00 +01005794 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005795
5796 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005797 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005798 this, effect->desc().name, chain.get());
5799 return BAD_VALUE;
5800 }
5801
5802 status_t status = chain->addEffect_l(effect);
5803 if (status != NO_ERROR) {
5804 if (chainCreated) {
5805 removeEffectChain_l(chain);
5806 }
5807 return status;
5808 }
5809
5810 effect->setDevice(mDevice);
5811 effect->setMode(mAudioFlinger->getMode());
5812 return NO_ERROR;
5813}
5814
Eric Laurent464d5b32011-06-17 21:29:58 -07005815void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005816
Steve Block71f2cf12011-10-20 11:56:00 +01005817 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005818 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005819 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5820 detachAuxEffect_l(effect->id());
5821 }
5822
5823 sp<EffectChain> chain = effect->chain().promote();
5824 if (chain != 0) {
5825 // remove effect chain if removing last effect
5826 if (chain->removeEffect_l(effect) == 0) {
5827 removeEffectChain_l(chain);
5828 }
5829 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00005830 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005831 }
5832}
5833
Eric Laurent464d5b32011-06-17 21:29:58 -07005834void AudioFlinger::ThreadBase::lockEffectChains_l(
5835 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5836{
5837 effectChains = mEffectChains;
5838 for (size_t i = 0; i < mEffectChains.size(); i++) {
5839 mEffectChains[i]->lock();
5840 }
5841}
5842
5843void AudioFlinger::ThreadBase::unlockEffectChains(
5844 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5845{
5846 for (size_t i = 0; i < effectChains.size(); i++) {
5847 effectChains[i]->unlock();
5848 }
5849}
5850
5851sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5852{
5853 Mutex::Autolock _l(mLock);
5854 return getEffectChain_l(sessionId);
5855}
5856
5857sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5858{
Eric Laurent464d5b32011-06-17 21:29:58 -07005859 size_t size = mEffectChains.size();
5860 for (size_t i = 0; i < size; i++) {
5861 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08005862 return mEffectChains[i];
Eric Laurent464d5b32011-06-17 21:29:58 -07005863 }
5864 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08005865 return 0;
Eric Laurent464d5b32011-06-17 21:29:58 -07005866}
5867
Glenn Kastenaccb1142012-01-04 11:00:47 -08005868void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent464d5b32011-06-17 21:29:58 -07005869{
5870 Mutex::Autolock _l(mLock);
5871 size_t size = mEffectChains.size();
5872 for (size_t i = 0; i < size; i++) {
5873 mEffectChains[i]->setMode_l(mode);
5874 }
5875}
5876
5877void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005878 const wp<EffectHandle>& handle,
5879 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005880
Eric Laurent53334cd2010-06-23 17:38:20 -07005881 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01005882 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005883 // delete the effect module if removing last handle on it
5884 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005885 if (!effect->isPinned() || unpiniflast) {
5886 removeEffect_l(effect);
5887 AudioSystem::unregisterEffect(effect->id());
5888 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005889 }
5890}
5891
Eric Laurent65b65452010-06-01 23:49:17 -07005892status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5893{
5894 int session = chain->sessionId();
5895 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005896 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005897
Steve Block71f2cf12011-10-20 11:56:00 +01005898 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005899 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005900 // Only one effect chain can be present in direct output thread and it uses
5901 // the mix buffer as input
5902 if (mType != DIRECT) {
5903 size_t numSamples = mFrameCount * mChannelCount;
5904 buffer = new int16_t[numSamples];
5905 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01005906 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005907 ownsBuffer = true;
5908 }
Eric Laurent65b65452010-06-01 23:49:17 -07005909
Eric Laurent53334cd2010-06-23 17:38:20 -07005910 // Attach all tracks with same session ID to this chain.
5911 for (size_t i = 0; i < mTracks.size(); ++i) {
5912 sp<Track> track = mTracks[i];
5913 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005914 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07005915 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005916 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005917 }
5918 }
5919
5920 // indicate all active tracks in the chain
5921 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5922 sp<Track> track = mActiveTracks[i].promote();
5923 if (track == 0) continue;
5924 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005925 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005926 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005927 }
Eric Laurent65b65452010-06-01 23:49:17 -07005928 }
5929 }
5930
Eric Laurent53334cd2010-06-23 17:38:20 -07005931 chain->setInBuffer(buffer, ownsBuffer);
5932 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005933 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005934 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005935 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5936 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005937 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005938 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5939 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005940 // Effect chain for other sessions are inserted at beginning of effect
5941 // chains list to be processed before output mix effects. Relative order between other
5942 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005943 size_t size = mEffectChains.size();
5944 size_t i = 0;
5945 for (i = 0; i < size; i++) {
5946 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005947 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005948 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005949 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005950
5951 return NO_ERROR;
5952}
5953
5954size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5955{
5956 int session = chain->sessionId();
5957
Steve Block71f2cf12011-10-20 11:56:00 +01005958 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005959
5960 for (size_t i = 0; i < mEffectChains.size(); i++) {
5961 if (chain == mEffectChains[i]) {
5962 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005963 // detach all active tracks from the chain
5964 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5965 sp<Track> track = mActiveTracks[i].promote();
5966 if (track == 0) continue;
5967 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005968 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07005969 chain.get(), session);
5970 chain->decActiveTrackCnt();
5971 }
5972 }
5973
Eric Laurent65b65452010-06-01 23:49:17 -07005974 // detach all tracks with same session ID from this chain
5975 for (size_t i = 0; i < mTracks.size(); ++i) {
5976 sp<Track> track = mTracks[i];
5977 if (session == track->sessionId()) {
5978 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005979 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005980 }
5981 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005982 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005983 }
5984 }
5985 return mEffectChains.size();
5986}
5987
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005988status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5989 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005990{
5991 Mutex::Autolock _l(mLock);
5992 return attachAuxEffect_l(track, EffectId);
5993}
5994
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005995status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5996 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005997{
5998 status_t status = NO_ERROR;
5999
6000 if (EffectId == 0) {
6001 track->setAuxBuffer(0, NULL);
6002 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006003 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6004 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006005 if (effect != 0) {
6006 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6007 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6008 } else {
6009 status = INVALID_OPERATION;
6010 }
6011 } else {
6012 status = BAD_VALUE;
6013 }
6014 }
6015 return status;
6016}
6017
6018void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6019{
6020 for (size_t i = 0; i < mTracks.size(); ++i) {
6021 sp<Track> track = mTracks[i];
6022 if (track->auxEffectId() == effectId) {
6023 attachAuxEffect_l(track, 0);
6024 }
6025 }
6026}
6027
Eric Laurent464d5b32011-06-17 21:29:58 -07006028status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6029{
6030 // only one chain per input thread
6031 if (mEffectChains.size() != 0) {
6032 return INVALID_OPERATION;
6033 }
Steve Block71f2cf12011-10-20 11:56:00 +01006034 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006035
6036 chain->setInBuffer(NULL);
6037 chain->setOutBuffer(NULL);
6038
Eric Laurentf82fccd2011-07-27 19:49:51 -07006039 checkSuspendOnAddEffectChain_l(chain);
6040
Eric Laurent464d5b32011-06-17 21:29:58 -07006041 mEffectChains.add(chain);
6042
6043 return NO_ERROR;
6044}
6045
6046size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6047{
Steve Block71f2cf12011-10-20 11:56:00 +01006048 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block8564c8d2012-01-05 23:22:43 +00006049 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent464d5b32011-06-17 21:29:58 -07006050 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6051 chain.get(), mEffectChains.size(), this);
6052 if (mEffectChains.size() == 1) {
6053 mEffectChains.removeAt(0);
6054 }
6055 return 0;
6056}
6057
Eric Laurent65b65452010-06-01 23:49:17 -07006058// ----------------------------------------------------------------------------
6059// EffectModule implementation
6060// ----------------------------------------------------------------------------
6061
6062#undef LOG_TAG
6063#define LOG_TAG "AudioFlinger::EffectModule"
6064
6065AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6066 const wp<AudioFlinger::EffectChain>& chain,
6067 effect_descriptor_t *desc,
6068 int id,
6069 int sessionId)
6070 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006071 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006072{
Steve Block71f2cf12011-10-20 11:56:00 +01006073 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006074 int lStatus;
6075 sp<ThreadBase> thread = mThread.promote();
6076 if (thread == 0) {
6077 return;
6078 }
Eric Laurent65b65452010-06-01 23:49:17 -07006079
6080 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6081
6082 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006083 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006084
Eric Laurent65b65452010-06-01 23:49:17 -07006085 if (mStatus != NO_ERROR) {
6086 return;
6087 }
6088 lStatus = init();
6089 if (lStatus < 0) {
6090 mStatus = lStatus;
6091 goto Error;
6092 }
6093
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006094 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6095 mPinned = true;
6096 }
Steve Block71f2cf12011-10-20 11:56:00 +01006097 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006098 return;
6099Error:
6100 EffectRelease(mEffectInterface);
6101 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006102 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006103}
6104
6105AudioFlinger::EffectModule::~EffectModule()
6106{
Steve Block71f2cf12011-10-20 11:56:00 +01006107 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006108 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006109 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6110 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6111 sp<ThreadBase> thread = mThread.promote();
6112 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006113 audio_stream_t *stream = thread->stream();
6114 if (stream != NULL) {
6115 stream->remove_audio_effect(stream, mEffectInterface);
6116 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006117 }
6118 }
Eric Laurent65b65452010-06-01 23:49:17 -07006119 // release effect engine
6120 EffectRelease(mEffectInterface);
6121 }
6122}
6123
Glenn Kasten1f812f72012-01-30 10:15:48 -08006124status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Eric Laurent65b65452010-06-01 23:49:17 -07006125{
6126 status_t status;
6127
6128 Mutex::Autolock _l(mLock);
6129 // First handle in mHandles has highest priority and controls the effect module
6130 int priority = handle->priority();
6131 size_t size = mHandles.size();
6132 sp<EffectHandle> h;
6133 size_t i;
6134 for (i = 0; i < size; i++) {
6135 h = mHandles[i].promote();
6136 if (h == 0) continue;
6137 if (h->priority() <= priority) break;
6138 }
6139 // if inserted in first place, move effect control from previous owner to this handle
6140 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006141 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006142 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006143 enabled = h->enabled();
6144 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006145 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006146 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006147 status = NO_ERROR;
6148 } else {
6149 status = ALREADY_EXISTS;
6150 }
Steve Block71f2cf12011-10-20 11:56:00 +01006151 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006152 mHandles.insertAt(handle, i);
6153 return status;
6154}
6155
6156size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6157{
6158 Mutex::Autolock _l(mLock);
6159 size_t size = mHandles.size();
6160 size_t i;
6161 for (i = 0; i < size; i++) {
6162 if (mHandles[i] == handle) break;
6163 }
6164 if (i == size) {
6165 return size;
6166 }
Steve Block71f2cf12011-10-20 11:56:00 +01006167 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006168
6169 bool enabled = false;
6170 EffectHandle *hdl = handle.unsafe_get();
Glenn Kasten3694ec12012-01-27 16:47:15 -08006171 if (hdl != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01006172 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006173 enabled = hdl->enabled();
6174 }
Eric Laurent65b65452010-06-01 23:49:17 -07006175 mHandles.removeAt(i);
6176 size = mHandles.size();
6177 // if removed from first place, move effect control from this handle to next in line
6178 if (i == 0 && size != 0) {
6179 sp<EffectHandle> h = mHandles[0].promote();
6180 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006181 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006182 }
6183 }
6184
Eric Laurent21b5c472011-07-26 20:54:46 -07006185 // Prevent calls to process() and other functions on effect interface from now on.
6186 // The effect engine will be released by the destructor when the last strong reference on
6187 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006188 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006189 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006190 }
6191
Eric Laurent65b65452010-06-01 23:49:17 -07006192 return size;
6193}
6194
Eric Laurentf82fccd2011-07-27 19:49:51 -07006195sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6196{
6197 Mutex::Autolock _l(mLock);
Glenn Kastenc64a6f02012-01-30 13:00:02 -08006198 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006199}
6200
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006201void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006202{
Steve Block71f2cf12011-10-20 11:56:00 +01006203 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006204 // keep a strong reference on this EffectModule to avoid calling the
6205 // destructor before we exit
6206 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006207 {
6208 sp<ThreadBase> thread = mThread.promote();
6209 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006210 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006211 }
6212 }
6213}
6214
Eric Laurent7d850f22010-07-09 13:34:17 -07006215void AudioFlinger::EffectModule::updateState() {
6216 Mutex::Autolock _l(mLock);
6217
6218 switch (mState) {
6219 case RESTART:
6220 reset_l();
6221 // FALL THROUGH
6222
6223 case STARTING:
6224 // clear auxiliary effect input buffer for next accumulation
6225 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6226 memset(mConfig.inputCfg.buffer.raw,
6227 0,
6228 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6229 }
6230 start_l();
6231 mState = ACTIVE;
6232 break;
6233 case STOPPING:
6234 stop_l();
6235 mDisableWaitCnt = mMaxDisableWaitCnt;
6236 mState = STOPPED;
6237 break;
6238 case STOPPED:
6239 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6240 // turn off sequence.
6241 if (--mDisableWaitCnt == 0) {
6242 reset_l();
6243 mState = IDLE;
6244 }
6245 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006246 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006247 break;
6248 }
6249}
6250
Eric Laurent65b65452010-06-01 23:49:17 -07006251void AudioFlinger::EffectModule::process()
6252{
6253 Mutex::Autolock _l(mLock);
6254
Eric Laurent21b5c472011-07-26 20:54:46 -07006255 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006256 mConfig.inputCfg.buffer.raw == NULL ||
6257 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006258 return;
6259 }
6260
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006261 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006262 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6263 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten490909d2011-12-15 09:52:39 -08006264 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Eric Laurent65b65452010-06-01 23:49:17 -07006265 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006266 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006267 }
6268
Eric Laurent65b65452010-06-01 23:49:17 -07006269 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006270 int ret = (*mEffectInterface)->process(mEffectInterface,
6271 &mConfig.inputCfg.buffer,
6272 &mConfig.outputCfg.buffer);
6273
6274 // force transition to IDLE state when engine is ready
6275 if (mState == STOPPED && ret == -ENODATA) {
6276 mDisableWaitCnt = 1;
6277 }
Eric Laurent65b65452010-06-01 23:49:17 -07006278
6279 // clear auxiliary effect input buffer for next accumulation
6280 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006281 memset(mConfig.inputCfg.buffer.raw, 0,
6282 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006283 }
6284 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006285 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6286 // If an insert effect is idle and input buffer is different from output buffer,
6287 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006288 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006289 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006290 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6291 int16_t *in = mConfig.inputCfg.buffer.s16;
6292 int16_t *out = mConfig.outputCfg.buffer.s16;
6293 for (size_t i = 0; i < frameCnt; i++) {
6294 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006295 }
Eric Laurent65b65452010-06-01 23:49:17 -07006296 }
6297 }
6298}
6299
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006300void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006301{
6302 if (mEffectInterface == NULL) {
6303 return;
6304 }
6305 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6306}
6307
6308status_t AudioFlinger::EffectModule::configure()
6309{
6310 uint32_t channels;
6311 if (mEffectInterface == NULL) {
6312 return NO_INIT;
6313 }
6314
6315 sp<ThreadBase> thread = mThread.promote();
6316 if (thread == 0) {
6317 return DEAD_OBJECT;
6318 }
6319
6320 // TODO: handle configuration of effects replacing track process
6321 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006322 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006323 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006324 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006325 }
6326
6327 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006328 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006329 } else {
6330 mConfig.inputCfg.channels = channels;
6331 }
6332 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006333 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6334 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006335 mConfig.inputCfg.samplingRate = thread->sampleRate();
6336 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6337 mConfig.inputCfg.bufferProvider.cookie = NULL;
6338 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6339 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6340 mConfig.outputCfg.bufferProvider.cookie = NULL;
6341 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6342 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6343 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6344 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006345 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006346 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006347 // - in other sessions:
6348 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6349 // other effect: overwrites output buffer: input buffer == output buffer
6350 // Auxiliary effect:
6351 // accumulates in output buffer: input buffer != output buffer
6352 // Therefore: accumulate <=> input buffer != output buffer
6353 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6354 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6355 } else {
6356 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6357 }
6358 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6359 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6360 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6361 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6362
Steve Block71f2cf12011-10-20 11:56:00 +01006363 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006364 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6365
Eric Laurent65b65452010-06-01 23:49:17 -07006366 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006367 uint32_t size = sizeof(int);
6368 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent4abf8822011-12-16 15:30:36 -08006369 EFFECT_CMD_SET_CONFIG,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006370 sizeof(effect_config_t),
6371 &mConfig,
6372 &size,
6373 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006374 if (status == 0) {
6375 status = cmdStatus;
6376 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006377
6378 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6379 (1000 * mConfig.outputCfg.buffer.frameCount);
6380
Eric Laurent65b65452010-06-01 23:49:17 -07006381 return status;
6382}
6383
6384status_t AudioFlinger::EffectModule::init()
6385{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006386 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006387 if (mEffectInterface == NULL) {
6388 return NO_INIT;
6389 }
6390 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006391 uint32_t size = sizeof(status_t);
6392 status_t status = (*mEffectInterface)->command(mEffectInterface,
6393 EFFECT_CMD_INIT,
6394 0,
6395 NULL,
6396 &size,
6397 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006398 if (status == 0) {
6399 status = cmdStatus;
6400 }
6401 return status;
6402}
6403
Eric Laurent6fccbd02011-10-05 17:42:25 -07006404status_t AudioFlinger::EffectModule::start()
6405{
6406 Mutex::Autolock _l(mLock);
6407 return start_l();
6408}
6409
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006410status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006411{
6412 if (mEffectInterface == NULL) {
6413 return NO_INIT;
6414 }
6415 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006416 uint32_t size = sizeof(status_t);
6417 status_t status = (*mEffectInterface)->command(mEffectInterface,
6418 EFFECT_CMD_ENABLE,
6419 0,
6420 NULL,
6421 &size,
6422 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006423 if (status == 0) {
6424 status = cmdStatus;
6425 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006426 if (status == 0 &&
6427 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6428 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6429 sp<ThreadBase> thread = mThread.promote();
6430 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006431 audio_stream_t *stream = thread->stream();
6432 if (stream != NULL) {
6433 stream->add_audio_effect(stream, mEffectInterface);
6434 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006435 }
6436 }
Eric Laurent65b65452010-06-01 23:49:17 -07006437 return status;
6438}
6439
Eric Laurent21b5c472011-07-26 20:54:46 -07006440status_t AudioFlinger::EffectModule::stop()
6441{
6442 Mutex::Autolock _l(mLock);
6443 return stop_l();
6444}
6445
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006446status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006447{
6448 if (mEffectInterface == NULL) {
6449 return NO_INIT;
6450 }
6451 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006452 uint32_t size = sizeof(status_t);
6453 status_t status = (*mEffectInterface)->command(mEffectInterface,
6454 EFFECT_CMD_DISABLE,
6455 0,
6456 NULL,
6457 &size,
6458 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006459 if (status == 0) {
6460 status = cmdStatus;
6461 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006462 if (status == 0 &&
6463 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6464 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6465 sp<ThreadBase> thread = mThread.promote();
6466 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006467 audio_stream_t *stream = thread->stream();
6468 if (stream != NULL) {
6469 stream->remove_audio_effect(stream, mEffectInterface);
6470 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006471 }
6472 }
Eric Laurent65b65452010-06-01 23:49:17 -07006473 return status;
6474}
6475
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006476status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6477 uint32_t cmdSize,
6478 void *pCmdData,
6479 uint32_t *replySize,
6480 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006481{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006482 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006483// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006484
Eric Laurent21b5c472011-07-26 20:54:46 -07006485 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006486 return NO_INIT;
6487 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006488 status_t status = (*mEffectInterface)->command(mEffectInterface,
6489 cmdCode,
6490 cmdSize,
6491 pCmdData,
6492 replySize,
6493 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006494 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006495 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006496 for (size_t i = 1; i < mHandles.size(); i++) {
6497 sp<EffectHandle> h = mHandles[i].promote();
6498 if (h != 0) {
6499 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6500 }
6501 }
6502 }
6503 return status;
6504}
6505
6506status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6507{
Eric Laurent6752ec82011-08-10 10:37:50 -07006508
Eric Laurent65b65452010-06-01 23:49:17 -07006509 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006510 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006511
6512 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006513 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6514 if (enabled && status != NO_ERROR) {
6515 return status;
6516 }
6517
Eric Laurent65b65452010-06-01 23:49:17 -07006518 switch (mState) {
6519 // going from disabled to enabled
6520 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006521 mState = STARTING;
6522 break;
6523 case STOPPED:
6524 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006525 break;
6526 case STOPPING:
6527 mState = ACTIVE;
6528 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006529
6530 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006531 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006532 mState = STOPPED;
6533 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006534 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006535 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006536 break;
6537 case ACTIVE:
6538 mState = STOPPING;
6539 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006540 case DESTROYED:
6541 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006542 }
6543 for (size_t i = 1; i < mHandles.size(); i++) {
6544 sp<EffectHandle> h = mHandles[i].promote();
6545 if (h != 0) {
6546 h->setEnabled(enabled);
6547 }
6548 }
6549 }
6550 return NO_ERROR;
6551}
6552
Glenn Kasteneabd94a2012-02-02 14:06:11 -08006553bool AudioFlinger::EffectModule::isEnabled() const
Eric Laurent65b65452010-06-01 23:49:17 -07006554{
6555 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006556 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006557 case STARTING:
6558 case ACTIVE:
6559 return true;
6560 case IDLE:
6561 case STOPPING:
6562 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006563 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006564 default:
6565 return false;
6566 }
6567}
6568
Glenn Kasteneabd94a2012-02-02 14:06:11 -08006569bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006570{
6571 switch (mState) {
6572 case RESTART:
6573 case ACTIVE:
6574 case STOPPING:
6575 case STOPPED:
6576 return true;
6577 case IDLE:
6578 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006579 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006580 default:
6581 return false;
6582 }
6583}
6584
Eric Laurent65b65452010-06-01 23:49:17 -07006585status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6586{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006587 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006588 status_t status = NO_ERROR;
6589
6590 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6591 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006592 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006593 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6594 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006595 status_t cmdStatus;
6596 uint32_t volume[2];
6597 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006598 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006599 volume[0] = *left;
6600 volume[1] = *right;
6601 if (controller) {
6602 pVolume = volume;
6603 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006604 status = (*mEffectInterface)->command(mEffectInterface,
6605 EFFECT_CMD_SET_VOLUME,
6606 size,
6607 volume,
6608 &size,
6609 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006610 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6611 *left = volume[0];
6612 *right = volume[1];
6613 }
6614 }
6615 return status;
6616}
6617
6618status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6619{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006620 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006621 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006622 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6623 // audio pre processing modules on RecordThread can receive both output and
6624 // input device indication in the same call
6625 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6626 if (dev) {
6627 status_t cmdStatus;
6628 uint32_t size = sizeof(status_t);
6629
6630 status = (*mEffectInterface)->command(mEffectInterface,
6631 EFFECT_CMD_SET_DEVICE,
6632 sizeof(uint32_t),
6633 &dev,
6634 &size,
6635 &cmdStatus);
6636 if (status == NO_ERROR) {
6637 status = cmdStatus;
6638 }
6639 }
6640 dev = device & AUDIO_DEVICE_IN_ALL;
6641 if (dev) {
6642 status_t cmdStatus;
6643 uint32_t size = sizeof(status_t);
6644
6645 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6646 EFFECT_CMD_SET_INPUT_DEVICE,
6647 sizeof(uint32_t),
6648 &dev,
6649 &size,
6650 &cmdStatus);
6651 if (status2 == NO_ERROR) {
6652 status2 = cmdStatus;
6653 }
6654 if (status == NO_ERROR) {
6655 status = status2;
6656 }
Eric Laurent65b65452010-06-01 23:49:17 -07006657 }
6658 }
6659 return status;
6660}
6661
Glenn Kastenaccb1142012-01-04 11:00:47 -08006662status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006663{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006664 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006665 status_t status = NO_ERROR;
6666 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006667 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006668 uint32_t size = sizeof(status_t);
6669 status = (*mEffectInterface)->command(mEffectInterface,
6670 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenaccb1142012-01-04 11:00:47 -08006671 sizeof(audio_mode_t),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006672 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006673 &size,
6674 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006675 if (status == NO_ERROR) {
6676 status = cmdStatus;
6677 }
6678 }
6679 return status;
6680}
6681
Eric Laurentf82fccd2011-07-27 19:49:51 -07006682void AudioFlinger::EffectModule::setSuspended(bool suspended)
6683{
6684 Mutex::Autolock _l(mLock);
6685 mSuspended = suspended;
6686}
Glenn Kasten1dce8412012-01-04 11:01:11 -08006687
6688bool AudioFlinger::EffectModule::suspended() const
Eric Laurentf82fccd2011-07-27 19:49:51 -07006689{
6690 Mutex::Autolock _l(mLock);
6691 return mSuspended;
6692}
6693
Eric Laurent65b65452010-06-01 23:49:17 -07006694status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6695{
6696 const size_t SIZE = 256;
6697 char buffer[SIZE];
6698 String8 result;
6699
6700 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6701 result.append(buffer);
6702
6703 bool locked = tryLock(mLock);
6704 // failed to lock - AudioFlinger is probably deadlocked
6705 if (!locked) {
6706 result.append("\t\tCould not lock Fx mutex:\n");
6707 }
6708
6709 result.append("\t\tSession Status State Engine:\n");
6710 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6711 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6712 result.append(buffer);
6713
6714 result.append("\t\tDescriptor:\n");
6715 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6716 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6717 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6718 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6719 result.append(buffer);
6720 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6721 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6722 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6723 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6724 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006725 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006726 mDescriptor.apiVersion,
6727 mDescriptor.flags);
6728 result.append(buffer);
6729 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6730 mDescriptor.name);
6731 result.append(buffer);
6732 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6733 mDescriptor.implementor);
6734 result.append(buffer);
6735
6736 result.append("\t\t- Input configuration:\n");
6737 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6738 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6739 (uint32_t)mConfig.inputCfg.buffer.raw,
6740 mConfig.inputCfg.buffer.frameCount,
6741 mConfig.inputCfg.samplingRate,
6742 mConfig.inputCfg.channels,
6743 mConfig.inputCfg.format);
6744 result.append(buffer);
6745
6746 result.append("\t\t- Output configuration:\n");
6747 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6748 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6749 (uint32_t)mConfig.outputCfg.buffer.raw,
6750 mConfig.outputCfg.buffer.frameCount,
6751 mConfig.outputCfg.samplingRate,
6752 mConfig.outputCfg.channels,
6753 mConfig.outputCfg.format);
6754 result.append(buffer);
6755
6756 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6757 result.append(buffer);
6758 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6759 for (size_t i = 0; i < mHandles.size(); ++i) {
6760 sp<EffectHandle> handle = mHandles[i].promote();
6761 if (handle != 0) {
6762 handle->dump(buffer, SIZE);
6763 result.append(buffer);
6764 }
6765 }
6766
6767 result.append("\n");
6768
6769 write(fd, result.string(), result.length());
6770
6771 if (locked) {
6772 mLock.unlock();
6773 }
6774
6775 return NO_ERROR;
6776}
6777
6778// ----------------------------------------------------------------------------
6779// EffectHandle implementation
6780// ----------------------------------------------------------------------------
6781
6782#undef LOG_TAG
6783#define LOG_TAG "AudioFlinger::EffectHandle"
6784
6785AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6786 const sp<AudioFlinger::Client>& client,
6787 const sp<IEffectClient>& effectClient,
6788 int32_t priority)
6789 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006790 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006791 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006792{
Steve Block71f2cf12011-10-20 11:56:00 +01006793 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006794
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006795 if (client == 0) {
6796 return;
6797 }
Eric Laurent65b65452010-06-01 23:49:17 -07006798 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6799 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6800 if (mCblkMemory != 0) {
6801 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6802
Glenn Kasten3694ec12012-01-27 16:47:15 -08006803 if (mCblk != NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006804 new(mCblk) effect_param_cblk_t();
6805 mBuffer = (uint8_t *)mCblk + bufOffset;
6806 }
6807 } else {
Steve Block3762c312012-01-06 19:20:56 +00006808 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006809 return;
6810 }
6811}
6812
6813AudioFlinger::EffectHandle::~EffectHandle()
6814{
Steve Block71f2cf12011-10-20 11:56:00 +01006815 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006816 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01006817 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006818}
6819
6820status_t AudioFlinger::EffectHandle::enable()
6821{
Steve Block71f2cf12011-10-20 11:56:00 +01006822 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006823 if (!mHasControl) return INVALID_OPERATION;
6824 if (mEffect == 0) return DEAD_OBJECT;
6825
Eric Laurent6752ec82011-08-10 10:37:50 -07006826 if (mEnabled) {
6827 return NO_ERROR;
6828 }
6829
Eric Laurentf82fccd2011-07-27 19:49:51 -07006830 mEnabled = true;
6831
6832 sp<ThreadBase> thread = mEffect->thread().promote();
6833 if (thread != 0) {
6834 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6835 }
6836
6837 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6838 if (mEffect->suspended()) {
6839 return NO_ERROR;
6840 }
6841
Eric Laurent6752ec82011-08-10 10:37:50 -07006842 status_t status = mEffect->setEnabled(true);
6843 if (status != NO_ERROR) {
6844 if (thread != 0) {
6845 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6846 }
6847 mEnabled = false;
6848 }
6849 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006850}
6851
6852status_t AudioFlinger::EffectHandle::disable()
6853{
Steve Block71f2cf12011-10-20 11:56:00 +01006854 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006855 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006856 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006857
Eric Laurent6752ec82011-08-10 10:37:50 -07006858 if (!mEnabled) {
6859 return NO_ERROR;
6860 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006861 mEnabled = false;
6862
6863 if (mEffect->suspended()) {
6864 return NO_ERROR;
6865 }
6866
6867 status_t status = mEffect->setEnabled(false);
6868
6869 sp<ThreadBase> thread = mEffect->thread().promote();
6870 if (thread != 0) {
6871 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6872 }
6873
6874 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006875}
6876
6877void AudioFlinger::EffectHandle::disconnect()
6878{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006879 disconnect(true);
6880}
6881
6882void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6883{
Steve Block71f2cf12011-10-20 11:56:00 +01006884 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006885 if (mEffect == 0) {
6886 return;
6887 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006888 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006889
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006890 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006891 sp<ThreadBase> thread = mEffect->thread().promote();
6892 if (thread != 0) {
6893 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6894 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006895 }
6896
Eric Laurent65b65452010-06-01 23:49:17 -07006897 // release sp on module => module destructor can be called now
6898 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006899 if (mClient != 0) {
Glenn Kasten3694ec12012-01-27 16:47:15 -08006900 if (mCblk != NULL) {
Glenn Kastend9d68dc2012-02-03 10:24:48 -08006901 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006902 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6903 }
Glenn Kastenf31d0502012-01-25 15:27:15 -08006904 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten803a86a2012-01-25 14:28:29 -08006905 // Client destructor must run with AudioFlinger mutex locked
Eric Laurent65b65452010-06-01 23:49:17 -07006906 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6907 mClient.clear();
6908 }
6909}
6910
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006911status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6912 uint32_t cmdSize,
6913 void *pCmdData,
6914 uint32_t *replySize,
6915 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006916{
Steve Block71f2cf12011-10-20 11:56:00 +01006917// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006918// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006919
6920 // only get parameter command is permitted for applications not controlling the effect
6921 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6922 return INVALID_OPERATION;
6923 }
6924 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006925 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006926
6927 // handle commands that are not forwarded transparently to effect engine
6928 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6929 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6930 // no risk to block the whole media server process or mixer threads is we are stuck here
6931 Mutex::Autolock _l(mCblk->lock);
6932 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6933 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6934 mCblk->serverIndex = 0;
6935 mCblk->clientIndex = 0;
6936 return BAD_VALUE;
6937 }
6938 status_t status = NO_ERROR;
6939 while (mCblk->serverIndex < mCblk->clientIndex) {
6940 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006941 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006942 int *p = (int *)(mBuffer + mCblk->serverIndex);
6943 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006944 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block8564c8d2012-01-05 23:22:43 +00006945 ALOGW("command(): invalid parameter block size");
Eric Laurent53334cd2010-06-23 17:38:20 -07006946 break;
6947 }
Eric Laurent65b65452010-06-01 23:49:17 -07006948 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006949 if (param->psize == 0 || param->vsize == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006950 ALOGW("command(): null parameter or value size");
Eric Laurent53334cd2010-06-23 17:38:20 -07006951 mCblk->serverIndex += size;
6952 continue;
6953 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006954 uint32_t psize = sizeof(effect_param_t) +
6955 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6956 param->vsize;
6957 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6958 psize,
6959 p,
6960 &rsize,
6961 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006962 // stop at first error encountered
6963 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006964 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006965 *(int *)pReplyData = reply;
6966 break;
6967 } else if (reply != NO_ERROR) {
6968 *(int *)pReplyData = reply;
6969 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006970 }
6971 mCblk->serverIndex += size;
6972 }
6973 mCblk->serverIndex = 0;
6974 mCblk->clientIndex = 0;
6975 return status;
6976 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006977 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006978 return enable();
6979 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006980 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006981 return disable();
6982 }
6983
6984 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6985}
6986
Eric Laurentf82fccd2011-07-27 19:49:51 -07006987void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07006988{
Steve Block71f2cf12011-10-20 11:56:00 +01006989 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07006990
6991 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006992 mEnabled = enabled;
6993
Eric Laurent65b65452010-06-01 23:49:17 -07006994 if (signal && mEffectClient != 0) {
6995 mEffectClient->controlStatusChanged(hasControl);
6996 }
6997}
6998
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006999void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7000 uint32_t cmdSize,
7001 void *pCmdData,
7002 uint32_t replySize,
7003 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007004{
7005 if (mEffectClient != 0) {
7006 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7007 }
7008}
7009
7010
7011
7012void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7013{
7014 if (mEffectClient != 0) {
7015 mEffectClient->enableStatusChanged(enabled);
7016 }
7017}
7018
7019status_t AudioFlinger::EffectHandle::onTransact(
7020 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7021{
7022 return BnEffect::onTransact(code, data, reply, flags);
7023}
7024
7025
7026void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7027{
Glenn Kasten3694ec12012-01-27 16:47:15 -08007028 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Eric Laurent65b65452010-06-01 23:49:17 -07007029
7030 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten706b6182012-01-20 13:44:40 -08007031 (mClient == 0) ? getpid() : mClient->pid(),
Eric Laurent65b65452010-06-01 23:49:17 -07007032 mPriority,
7033 mHasControl,
7034 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007035 mCblk ? mCblk->clientIndex : 0,
7036 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007037 );
7038
7039 if (locked) {
7040 mCblk->lock.unlock();
7041 }
7042}
7043
7044#undef LOG_TAG
7045#define LOG_TAG "AudioFlinger::EffectChain"
7046
7047AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7048 int sessionId)
Eric Laurentf9c361d2011-11-11 15:42:52 -08007049 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007050 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7051 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007052{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007053 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007054 sp<ThreadBase> thread = mThread.promote();
7055 if (thread == 0) {
7056 return;
7057 }
7058 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7059 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007060}
7061
7062AudioFlinger::EffectChain::~EffectChain()
7063{
7064 if (mOwnInBuffer) {
7065 delete mInBuffer;
7066 }
7067
7068}
7069
Eric Laurentf82fccd2011-07-27 19:49:51 -07007070// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007071sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007072{
Eric Laurent65b65452010-06-01 23:49:17 -07007073 size_t size = mEffects.size();
7074
7075 for (size_t i = 0; i < size; i++) {
7076 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007077 return mEffects[i];
Eric Laurent65b65452010-06-01 23:49:17 -07007078 }
7079 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007080 return 0;
Eric Laurent65b65452010-06-01 23:49:17 -07007081}
7082
Eric Laurentf82fccd2011-07-27 19:49:51 -07007083// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007084sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007085{
Eric Laurent65b65452010-06-01 23:49:17 -07007086 size_t size = mEffects.size();
7087
7088 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007089 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7090 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007091 return mEffects[i];
Eric Laurent65b65452010-06-01 23:49:17 -07007092 }
7093 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007094 return 0;
Eric Laurent65b65452010-06-01 23:49:17 -07007095}
7096
Eric Laurentf82fccd2011-07-27 19:49:51 -07007097// getEffectFromType_l() must be called with ThreadBase::mLock held
7098sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7099 const effect_uuid_t *type)
7100{
Eric Laurentf82fccd2011-07-27 19:49:51 -07007101 size_t size = mEffects.size();
7102
7103 for (size_t i = 0; i < size; i++) {
7104 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007105 return mEffects[i];
Eric Laurentf82fccd2011-07-27 19:49:51 -07007106 }
7107 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007108 return 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007109}
7110
Eric Laurent65b65452010-06-01 23:49:17 -07007111// Must be called with EffectChain::mLock locked
7112void AudioFlinger::EffectChain::process_l()
7113{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007114 sp<ThreadBase> thread = mThread.promote();
7115 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007116 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007117 return;
7118 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007119 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7120 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007121 // always process effects unless no more tracks are on the session and the effect tail
7122 // has been rendered
7123 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007124 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007125 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007126
Eric Laurentf9c361d2011-11-11 15:42:52 -08007127 if (!tracksOnSession && mTailBufferCount == 0) {
7128 doProcess = false;
7129 }
7130
7131 if (activeTrackCnt() == 0) {
7132 // if no track is active and the effect tail has not been rendered,
7133 // the input buffer must be cleared here as the mixer process will not do it
7134 if (tracksOnSession || mTailBufferCount > 0) {
7135 size_t numSamples = thread->frameCount() * thread->channelCount();
7136 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7137 if (mTailBufferCount > 0) {
7138 mTailBufferCount--;
7139 }
7140 }
7141 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007142 }
7143
Eric Laurent65b65452010-06-01 23:49:17 -07007144 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007145 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007146 for (size_t i = 0; i < size; i++) {
7147 mEffects[i]->process();
7148 }
Eric Laurent65b65452010-06-01 23:49:17 -07007149 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007150 for (size_t i = 0; i < size; i++) {
7151 mEffects[i]->updateState();
7152 }
Eric Laurent65b65452010-06-01 23:49:17 -07007153}
7154
Eric Laurent76c40f72010-07-15 12:50:15 -07007155// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007156status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007157{
7158 effect_descriptor_t desc = effect->desc();
7159 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7160
7161 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007162 effect->setChain(this);
7163 sp<ThreadBase> thread = mThread.promote();
7164 if (thread == 0) {
7165 return NO_INIT;
7166 }
7167 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007168
7169 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7170 // Auxiliary effects are inserted at the beginning of mEffects vector as
7171 // they are processed first and accumulated in chain input buffer
7172 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007173
Eric Laurent65b65452010-06-01 23:49:17 -07007174 // the input buffer for auxiliary effect contains mono samples in
7175 // 32 bit format. This is to avoid saturation in AudoMixer
7176 // accumulation stage. Saturation is done in EffectModule::process() before
7177 // calling the process in effect engine
7178 size_t numSamples = thread->frameCount();
7179 int32_t *buffer = new int32_t[numSamples];
7180 memset(buffer, 0, numSamples * sizeof(int32_t));
7181 effect->setInBuffer((int16_t *)buffer);
7182 // auxiliary effects output samples to chain input buffer for further processing
7183 // by insert effects
7184 effect->setOutBuffer(mInBuffer);
7185 } else {
7186 // Insert effects are inserted at the end of mEffects vector as they are processed
7187 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007188 // Insert effect order as a function of indicated preference:
7189 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7190 // another effect is present
7191 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7192 // last effect claiming first position
7193 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7194 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007195 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007196 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7197 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007198
7199 int size = (int)mEffects.size();
7200 int idx_insert = size;
7201 int idx_insert_first = -1;
7202 int idx_insert_last = -1;
7203
7204 for (int i = 0; i < size; i++) {
7205 effect_descriptor_t d = mEffects[i]->desc();
7206 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7207 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7208 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7209 // check invalid effect chaining combinations
7210 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007211 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block8564c8d2012-01-05 23:22:43 +00007212 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007213 return INVALID_OPERATION;
7214 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007215 // remember position of first insert effect and by default
7216 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007217 if (idx_insert == size) {
7218 idx_insert = i;
7219 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007220 // remember position of last insert effect claiming
7221 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007222 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7223 idx_insert_first = i;
7224 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007225 // remember position of first insert effect claiming
7226 // last position
7227 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7228 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007229 idx_insert_last = i;
7230 }
7231 }
7232 }
7233
Eric Laurent53334cd2010-06-23 17:38:20 -07007234 // modify idx_insert from first position if needed
7235 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7236 if (idx_insert_last != -1) {
7237 idx_insert = idx_insert_last;
7238 } else {
7239 idx_insert = size;
7240 }
7241 } else {
7242 if (idx_insert_first != -1) {
7243 idx_insert = idx_insert_first + 1;
7244 }
Eric Laurent65b65452010-06-01 23:49:17 -07007245 }
7246
7247 // always read samples from chain input buffer
7248 effect->setInBuffer(mInBuffer);
7249
7250 // if last effect in the chain, output samples to chain
7251 // output buffer, otherwise to chain input buffer
7252 if (idx_insert == size) {
7253 if (idx_insert != 0) {
7254 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7255 mEffects[idx_insert-1]->configure();
7256 }
7257 effect->setOutBuffer(mOutBuffer);
7258 } else {
7259 effect->setOutBuffer(mInBuffer);
7260 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007261 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007262
Steve Block71f2cf12011-10-20 11:56:00 +01007263 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007264 }
7265 effect->configure();
7266 return NO_ERROR;
7267}
7268
Eric Laurent76c40f72010-07-15 12:50:15 -07007269// removeEffect_l() must be called with PlaybackThread::mLock held
7270size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007271{
7272 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007273 int size = (int)mEffects.size();
7274 int i;
7275 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7276
7277 for (i = 0; i < size; i++) {
7278 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007279 // calling stop here will remove pre-processing effect from the audio HAL.
7280 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7281 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007282 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7283 mEffects[i]->state() == EffectModule::STOPPING) {
7284 mEffects[i]->stop();
7285 }
Eric Laurent65b65452010-06-01 23:49:17 -07007286 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7287 delete[] effect->inBuffer();
7288 } else {
7289 if (i == size - 1 && i != 0) {
7290 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7291 mEffects[i - 1]->configure();
7292 }
7293 }
7294 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007295 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007296 break;
7297 }
7298 }
Eric Laurent65b65452010-06-01 23:49:17 -07007299
7300 return mEffects.size();
7301}
7302
Eric Laurent76c40f72010-07-15 12:50:15 -07007303// setDevice_l() must be called with PlaybackThread::mLock held
7304void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007305{
7306 size_t size = mEffects.size();
7307 for (size_t i = 0; i < size; i++) {
7308 mEffects[i]->setDevice(device);
7309 }
7310}
7311
Eric Laurent76c40f72010-07-15 12:50:15 -07007312// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenaccb1142012-01-04 11:00:47 -08007313void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007314{
7315 size_t size = mEffects.size();
7316 for (size_t i = 0; i < size; i++) {
7317 mEffects[i]->setMode(mode);
7318 }
7319}
7320
Eric Laurent76c40f72010-07-15 12:50:15 -07007321// setVolume_l() must be called with PlaybackThread::mLock held
7322bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007323{
7324 uint32_t newLeft = *left;
7325 uint32_t newRight = *right;
7326 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007327 int ctrlIdx = -1;
7328 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007329
Eric Laurent76c40f72010-07-15 12:50:15 -07007330 // first update volume controller
7331 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007332 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007333 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7334 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007335 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007336 break;
7337 }
7338 }
7339
7340 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007341 if (hasControl) {
7342 *left = mNewLeftVolume;
7343 *right = mNewRightVolume;
7344 }
7345 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007346 }
7347
7348 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007349 mLeftVolume = newLeft;
7350 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007351
7352 // second get volume update from volume controller
7353 if (ctrlIdx >= 0) {
7354 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007355 mNewLeftVolume = newLeft;
7356 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007357 }
7358 // then indicate volume to all other effects in chain.
7359 // Pass altered volume to effects before volume controller
7360 // and requested volume to effects after controller
7361 uint32_t lVol = newLeft;
7362 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007363
Eric Laurent65b65452010-06-01 23:49:17 -07007364 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007365 if ((int)i == ctrlIdx) continue;
7366 // this also works for ctrlIdx == -1 when there is no volume controller
7367 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007368 lVol = *left;
7369 rVol = *right;
7370 }
7371 mEffects[i]->setVolume(&lVol, &rVol, false);
7372 }
7373 *left = newLeft;
7374 *right = newRight;
7375
7376 return hasControl;
7377}
7378
Eric Laurent65b65452010-06-01 23:49:17 -07007379status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7380{
7381 const size_t SIZE = 256;
7382 char buffer[SIZE];
7383 String8 result;
7384
7385 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7386 result.append(buffer);
7387
7388 bool locked = tryLock(mLock);
7389 // failed to lock - AudioFlinger is probably deadlocked
7390 if (!locked) {
7391 result.append("\tCould not lock mutex:\n");
7392 }
7393
Eric Laurent76c40f72010-07-15 12:50:15 -07007394 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7395 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007396 mEffects.size(),
7397 (uint32_t)mInBuffer,
7398 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007399 mActiveTrackCnt);
7400 result.append(buffer);
7401 write(fd, result.string(), result.size());
7402
7403 for (size_t i = 0; i < mEffects.size(); ++i) {
7404 sp<EffectModule> effect = mEffects[i];
7405 if (effect != 0) {
7406 effect->dump(fd, args);
7407 }
7408 }
7409
7410 if (locked) {
7411 mLock.unlock();
7412 }
7413
7414 return NO_ERROR;
7415}
7416
Eric Laurentf82fccd2011-07-27 19:49:51 -07007417// must be called with ThreadBase::mLock held
7418void AudioFlinger::EffectChain::setEffectSuspended_l(
7419 const effect_uuid_t *type, bool suspend)
7420{
7421 sp<SuspendedEffectDesc> desc;
7422 // use effect type UUID timelow as key as there is no real risk of identical
7423 // timeLow fields among effect type UUIDs.
7424 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7425 if (suspend) {
7426 if (index >= 0) {
7427 desc = mSuspendedEffects.valueAt(index);
7428 } else {
7429 desc = new SuspendedEffectDesc();
7430 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7431 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007432 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007433 }
7434 if (desc->mRefCount++ == 0) {
7435 sp<EffectModule> effect = getEffectIfEnabled(type);
7436 if (effect != 0) {
7437 desc->mEffect = effect;
7438 effect->setSuspended(true);
7439 effect->setEnabled(false);
7440 }
7441 }
7442 } else {
7443 if (index < 0) {
7444 return;
7445 }
7446 desc = mSuspendedEffects.valueAt(index);
7447 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007448 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007449 desc->mRefCount = 1;
7450 }
7451 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007452 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007453 if (desc->mEffect != 0) {
7454 sp<EffectModule> effect = desc->mEffect.promote();
7455 if (effect != 0) {
7456 effect->setSuspended(false);
7457 sp<EffectHandle> handle = effect->controlHandle();
7458 if (handle != 0) {
7459 effect->setEnabled(handle->enabled());
7460 }
7461 }
7462 desc->mEffect.clear();
7463 }
7464 mSuspendedEffects.removeItemsAt(index);
7465 }
7466 }
7467}
7468
7469// must be called with ThreadBase::mLock held
7470void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7471{
7472 sp<SuspendedEffectDesc> desc;
7473
7474 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7475 if (suspend) {
7476 if (index >= 0) {
7477 desc = mSuspendedEffects.valueAt(index);
7478 } else {
7479 desc = new SuspendedEffectDesc();
7480 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007481 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007482 }
7483 if (desc->mRefCount++ == 0) {
Glenn Kasten97040262012-01-30 12:56:03 -08007484 Vector< sp<EffectModule> > effects;
7485 getSuspendEligibleEffects(effects);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007486 for (size_t i = 0; i < effects.size(); i++) {
7487 setEffectSuspended_l(&effects[i]->desc().type, true);
7488 }
7489 }
7490 } else {
7491 if (index < 0) {
7492 return;
7493 }
7494 desc = mSuspendedEffects.valueAt(index);
7495 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007496 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007497 desc->mRefCount = 1;
7498 }
7499 if (--desc->mRefCount == 0) {
7500 Vector<const effect_uuid_t *> types;
7501 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7502 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7503 continue;
7504 }
7505 types.add(&mSuspendedEffects.valueAt(i)->mType);
7506 }
7507 for (size_t i = 0; i < types.size(); i++) {
7508 setEffectSuspended_l(types[i], false);
7509 }
Steve Block71f2cf12011-10-20 11:56:00 +01007510 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007511 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7512 }
7513 }
7514}
7515
Eric Laurent5e7acae2011-09-23 08:40:41 -07007516
7517// The volume effect is used for automated tests only
7518#ifndef OPENSL_ES_H_
7519static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7520 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7521const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7522#endif //OPENSL_ES_H_
7523
Eric Laurent6752ec82011-08-10 10:37:50 -07007524bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7525{
7526 // auxiliary effects and visualizer are never suspended on output mix
7527 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7528 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007529 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7530 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007531 return false;
7532 }
7533 return true;
7534}
7535
Glenn Kasten97040262012-01-30 12:56:03 -08007536void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurentf82fccd2011-07-27 19:49:51 -07007537{
Glenn Kasten97040262012-01-30 12:56:03 -08007538 effects.clear();
Eric Laurentf82fccd2011-07-27 19:49:51 -07007539 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kasten97040262012-01-30 12:56:03 -08007540 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7541 effects.add(mEffects[i]);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007542 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007543 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007544}
7545
7546sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7547 const effect_uuid_t *type)
7548{
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007549 sp<EffectModule> effect = getEffectFromType_l(type);
7550 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007551}
7552
7553void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7554 bool enabled)
7555{
7556 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7557 if (enabled) {
7558 if (index < 0) {
7559 // if the effect is not suspend check if all effects are suspended
7560 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7561 if (index < 0) {
7562 return;
7563 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007564 if (!isEffectEligibleForSuspend(effect->desc())) {
7565 return;
7566 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007567 setEffectSuspended_l(&effect->desc().type, enabled);
7568 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007569 if (index < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007570 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurent6752ec82011-08-10 10:37:50 -07007571 return;
7572 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007573 }
Steve Block71f2cf12011-10-20 11:56:00 +01007574 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007575 effect->desc().type.timeLow);
7576 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7577 // if effect is requested to suspended but was not yet enabled, supend it now.
7578 if (desc->mEffect == 0) {
7579 desc->mEffect = effect;
7580 effect->setEnabled(false);
7581 effect->setSuspended(true);
7582 }
7583 } else {
7584 if (index < 0) {
7585 return;
7586 }
Steve Block71f2cf12011-10-20 11:56:00 +01007587 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007588 effect->desc().type.timeLow);
7589 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7590 desc->mEffect.clear();
7591 effect->setSuspended(false);
7592 }
7593}
7594
Eric Laurent65b65452010-06-01 23:49:17 -07007595#undef LOG_TAG
7596#define LOG_TAG "AudioFlinger"
7597
Eric Laurenta553c252009-07-17 12:17:14 -07007598// ----------------------------------------------------------------------------
7599
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007600status_t AudioFlinger::onTransact(
7601 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7602{
7603 return BnAudioFlinger::onTransact(code, data, reply, flags);
7604}
7605
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007606}; // namespace android