blob: efa3c705264eb9a54afef36f66f977f72393d5b6 [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),
Glenn Kasten761286f2012-01-06 08:39:38 -08001001 mStandby(false), mId(id),
Glenn Kastendc3ac852012-01-25 15:28:08 -08001002 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{
Steve Block71f2cf12011-10-20 11:56:00 +01001020 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001021 {
Glenn Kasten761286f2012-01-06 08:39:38 -08001022 // This lock prevents the following race in thread (uniprocessor for illustration):
1023 // if (!exitPending()) {
1024 // // context switch from here to exit()
1025 // // exit() calls requestExit(), what exitPending() observes
1026 // // exit() calls signal(), which is dropped since no waiters
1027 // // context switch back from exit() to here
1028 // mWaitWorkCV.wait(...);
1029 // // now thread is hung
1030 // }
Glenn Kasten325ee1c2012-01-05 15:41:56 -08001031 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001032 requestExit();
1033 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001034 }
Glenn Kasten761286f2012-01-06 08:39:38 -08001035 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1036 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Eric Laurenta553c252009-07-17 12:17:14 -07001037 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001038}
Eric Laurenta553c252009-07-17 12:17:14 -07001039
Eric Laurenta553c252009-07-17 12:17:14 -07001040status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1041{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001042 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001043
Steve Block71f2cf12011-10-20 11:56:00 +01001044 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001045 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001046
Eric Laurent8fce46a2009-08-04 09:45:33 -07001047 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001048 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001049 // wait condition with timeout in case the thread loop has exited
1050 // before the request could be processed
Glenn Kastencbfe2e12011-12-13 11:04:14 -08001051 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001052 status = mParamStatus;
1053 mWaitWorkCV.signal();
1054 } else {
1055 status = TIMED_OUT;
1056 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001057 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001058}
1059
1060void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1061{
1062 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001063 sendConfigEvent_l(event, param);
1064}
1065
1066// sendConfigEvent_l() must be called with ThreadBase::mLock held
1067void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1068{
Glenn Kasten4b220f02011-12-13 11:50:00 -08001069 ConfigEvent configEvent;
1070 configEvent.mEvent = event;
1071 configEvent.mParam = param;
Eric Laurenta553c252009-07-17 12:17:14 -07001072 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001073 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001074 mWaitWorkCV.signal();
1075}
1076
1077void AudioFlinger::ThreadBase::processConfigEvents()
1078{
1079 mLock.lock();
1080 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001081 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kasten4b220f02011-12-13 11:50:00 -08001082 ConfigEvent configEvent = mConfigEvents[0];
Eric Laurenta553c252009-07-17 12:17:14 -07001083 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001084 // release mLock before locking AudioFlinger mLock: lock order is always
1085 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001086 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001087 mAudioFlinger->mLock.lock();
Glenn Kasten4b220f02011-12-13 11:50:00 -08001088 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001089 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001090 mLock.lock();
1091 }
1092 mLock.unlock();
1093}
1094
Eric Laurent3fdb1262009-11-07 00:01:32 -08001095status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1096{
1097 const size_t SIZE = 256;
1098 char buffer[SIZE];
1099 String8 result;
1100
1101 bool locked = tryLock(mLock);
1102 if (!locked) {
1103 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1104 write(fd, buffer, strlen(buffer));
1105 }
1106
1107 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1108 result.append(buffer);
1109 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1110 result.append(buffer);
1111 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1112 result.append(buffer);
1113 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1114 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001115 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1116 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001117 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1118 result.append(buffer);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001119 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001120 result.append(buffer);
1121
1122 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1123 result.append(buffer);
1124 result.append(" Index Command");
1125 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1126 snprintf(buffer, SIZE, "\n %02d ", i);
1127 result.append(buffer);
1128 result.append(mNewParameters[i]);
1129 }
1130
1131 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1132 result.append(buffer);
1133 snprintf(buffer, SIZE, " Index event param\n");
1134 result.append(buffer);
1135 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kasten4b220f02011-12-13 11:50:00 -08001136 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001137 result.append(buffer);
1138 }
1139 result.append("\n");
1140
1141 write(fd, result.string(), result.size());
1142
1143 if (locked) {
1144 mLock.unlock();
1145 }
1146 return NO_ERROR;
1147}
1148
Eric Laurent1345d332011-07-24 17:49:51 -07001149status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1150{
1151 const size_t SIZE = 256;
1152 char buffer[SIZE];
1153 String8 result;
1154
1155 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1156 write(fd, buffer, strlen(buffer));
1157
1158 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1159 sp<EffectChain> chain = mEffectChains[i];
1160 if (chain != 0) {
1161 chain->dump(fd, args);
1162 }
1163 }
1164 return NO_ERROR;
1165}
1166
Eric Laurent6dbdc402011-07-22 09:04:31 -07001167void AudioFlinger::ThreadBase::acquireWakeLock()
1168{
1169 Mutex::Autolock _l(mLock);
1170 acquireWakeLock_l();
1171}
1172
1173void AudioFlinger::ThreadBase::acquireWakeLock_l()
1174{
1175 if (mPowerManager == 0) {
1176 // use checkService() to avoid blocking if power service is not up yet
1177 sp<IBinder> binder =
1178 defaultServiceManager()->checkService(String16("power"));
1179 if (binder == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00001180 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001181 } else {
1182 mPowerManager = interface_cast<IPowerManager>(binder);
1183 binder->linkToDeath(mDeathRecipient);
1184 }
1185 }
1186 if (mPowerManager != 0) {
1187 sp<IBinder> binder = new BBinder();
1188 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1189 binder,
1190 String16(mName));
1191 if (status == NO_ERROR) {
1192 mWakeLockToken = binder;
1193 }
Steve Block71f2cf12011-10-20 11:56:00 +01001194 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001195 }
1196}
1197
1198void AudioFlinger::ThreadBase::releaseWakeLock()
1199{
1200 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001201 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001202}
1203
1204void AudioFlinger::ThreadBase::releaseWakeLock_l()
1205{
1206 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001207 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001208 if (mPowerManager != 0) {
1209 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1210 }
1211 mWakeLockToken.clear();
1212 }
1213}
1214
1215void AudioFlinger::ThreadBase::clearPowerManager()
1216{
1217 Mutex::Autolock _l(mLock);
1218 releaseWakeLock_l();
1219 mPowerManager.clear();
1220}
1221
1222void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1223{
1224 sp<ThreadBase> thread = mThread.promote();
1225 if (thread != 0) {
1226 thread->clearPowerManager();
1227 }
Steve Block8564c8d2012-01-05 23:22:43 +00001228 ALOGW("power manager service died !!!");
Eric Laurent6dbdc402011-07-22 09:04:31 -07001229}
Eric Laurent1345d332011-07-24 17:49:51 -07001230
Eric Laurentf82fccd2011-07-27 19:49:51 -07001231void AudioFlinger::ThreadBase::setEffectSuspended(
1232 const effect_uuid_t *type, bool suspend, int sessionId)
1233{
1234 Mutex::Autolock _l(mLock);
1235 setEffectSuspended_l(type, suspend, sessionId);
1236}
1237
1238void AudioFlinger::ThreadBase::setEffectSuspended_l(
1239 const effect_uuid_t *type, bool suspend, int sessionId)
1240{
Glenn Kastenc64a6f02012-01-30 13:00:02 -08001241 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001242 if (chain != 0) {
1243 if (type != NULL) {
1244 chain->setEffectSuspended_l(type, suspend);
1245 } else {
1246 chain->setEffectSuspendedAll_l(suspend);
1247 }
1248 }
1249
1250 updateSuspendedSessions_l(type, suspend, sessionId);
1251}
1252
1253void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1254{
1255 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1256 if (index < 0) {
1257 return;
1258 }
1259
1260 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1261 mSuspendedSessions.editValueAt(index);
1262
1263 for (size_t i = 0; i < sessionEffects.size(); i++) {
1264 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1265 for (int j = 0; j < desc->mRefCount; j++) {
1266 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1267 chain->setEffectSuspendedAll_l(true);
1268 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001269 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001270 desc->mType.timeLow);
1271 chain->setEffectSuspended_l(&desc->mType, true);
1272 }
1273 }
1274 }
1275}
1276
Eric Laurentf82fccd2011-07-27 19:49:51 -07001277void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1278 bool suspend,
1279 int sessionId)
1280{
1281 int index = mSuspendedSessions.indexOfKey(sessionId);
1282
1283 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1284
1285 if (suspend) {
1286 if (index >= 0) {
1287 sessionEffects = mSuspendedSessions.editValueAt(index);
1288 } else {
1289 mSuspendedSessions.add(sessionId, sessionEffects);
1290 }
1291 } else {
1292 if (index < 0) {
1293 return;
1294 }
1295 sessionEffects = mSuspendedSessions.editValueAt(index);
1296 }
1297
1298
1299 int key = EffectChain::kKeyForSuspendAll;
1300 if (type != NULL) {
1301 key = type->timeLow;
1302 }
1303 index = sessionEffects.indexOfKey(key);
1304
1305 sp <SuspendedSessionDesc> desc;
1306 if (suspend) {
1307 if (index >= 0) {
1308 desc = sessionEffects.valueAt(index);
1309 } else {
1310 desc = new SuspendedSessionDesc();
1311 if (type != NULL) {
1312 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1313 }
1314 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001315 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001316 }
1317 desc->mRefCount++;
1318 } else {
1319 if (index < 0) {
1320 return;
1321 }
1322 desc = sessionEffects.valueAt(index);
1323 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001324 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001325 sessionEffects.removeItemsAt(index);
1326 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001327 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001328 sessionId);
1329 mSuspendedSessions.removeItem(sessionId);
1330 }
1331 }
1332 }
1333 if (!sessionEffects.isEmpty()) {
1334 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1335 }
1336}
1337
1338void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1339 bool enabled,
1340 int sessionId)
1341{
1342 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001343 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1344}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001345
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001346void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1347 bool enabled,
1348 int sessionId)
1349{
Eric Laurent6752ec82011-08-10 10:37:50 -07001350 if (mType != RECORD) {
1351 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1352 // another session. This gives the priority to well behaved effect control panels
1353 // and applications not using global effects.
1354 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1355 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1356 }
1357 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001358
1359 sp<EffectChain> chain = getEffectChain_l(sessionId);
1360 if (chain != 0) {
1361 chain->checkSuspendOnEffectEnabled(effect, enabled);
1362 }
1363}
1364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365// ----------------------------------------------------------------------------
1366
Eric Laurent464d5b32011-06-17 21:29:58 -07001367AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1368 AudioStreamOut* output,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08001369 audio_io_handle_t id,
Glenn Kastenefd511a2012-01-26 10:38:26 -08001370 uint32_t device,
1371 type_t type)
1372 : ThreadBase(audioFlinger, id, device, type),
Glenn Kastendc3ac852012-01-25 15:28:08 -08001373 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1374 // Assumes constructor is called by AudioFlinger with it's mLock held,
1375 // but it would be safer to explicitly pass initial masterMute as parameter
1376 mMasterMute(audioFlinger->masterMute_l()),
1377 // mStreamTypes[] initialized in constructor body
1378 mOutput(output),
1379 // Assumes constructor is called by AudioFlinger with it's mLock held,
1380 // but it would be safer to explicitly pass initial masterVolume as parameter
1381 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent464d5b32011-06-17 21:29:58 -07001382 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001384 snprintf(mName, kNameLength, "AudioOut_%d", id);
1385
Eric Laurenta553c252009-07-17 12:17:14 -07001386 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387
Glenn Kasten6e987a42012-01-06 08:40:01 -08001388 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001389 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1390 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1391 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001392 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1393 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten6e987a42012-01-06 08:40:01 -08001394 // initialized by stream_type_t default constructor
1395 // mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397}
1398
Eric Laurenta553c252009-07-17 12:17:14 -07001399AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400{
1401 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402}
1403
Eric Laurenta553c252009-07-17 12:17:14 -07001404status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405{
1406 dumpInternals(fd, args);
1407 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001408 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 return NO_ERROR;
1410}
1411
Eric Laurenta553c252009-07-17 12:17:14 -07001412status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413{
1414 const size_t SIZE = 256;
1415 char buffer[SIZE];
1416 String8 result;
1417
Eric Laurenta553c252009-07-17 12:17:14 -07001418 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001420 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001422 sp<Track> track = mTracks[i];
1423 if (track != 0) {
1424 track->dump(buffer, SIZE);
1425 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
1427 }
1428
Eric Laurenta553c252009-07-17 12:17:14 -07001429 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001431 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 -08001432 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kastene4787422012-01-25 14:27:41 -08001433 sp<Track> track = mActiveTracks[i].promote();
1434 if (track != 0) {
1435 track->dump(buffer, SIZE);
1436 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 }
1438 }
1439 write(fd, result.string(), result.size());
1440 return NO_ERROR;
1441}
1442
Eric Laurenta553c252009-07-17 12:17:14 -07001443status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444{
1445 const size_t SIZE = 256;
1446 char buffer[SIZE];
1447 String8 result;
1448
Eric Laurent3fdb1262009-11-07 00:01:32 -08001449 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 result.append(buffer);
1451 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1452 result.append(buffer);
1453 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1454 result.append(buffer);
1455 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1456 result.append(buffer);
1457 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1458 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001459 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1460 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001461 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1462 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001464
1465 dumpBase(fd, args);
1466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 return NO_ERROR;
1468}
1469
1470// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001471status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472{
Eric Laurent828b9772011-08-07 16:32:26 -07001473 status_t status = initCheck();
1474 if (status == NO_ERROR) {
Steve Block6215d3f2012-01-04 20:05:49 +00001475 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurent828b9772011-08-07 16:32:26 -07001476 } else {
Steve Block3762c312012-01-06 19:20:56 +00001477 ALOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 }
Eric Laurent828b9772011-08-07 16:32:26 -07001479 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480}
1481
Eric Laurenta553c252009-07-17 12:17:14 -07001482void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001484 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485}
1486
Eric Laurenta553c252009-07-17 12:17:14 -07001487// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1488sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 const sp<AudioFlinger::Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001490 audio_stream_type_t streamType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08001492 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001493 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 int frameCount,
1495 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001496 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 status_t *status)
1498{
1499 sp<Track> track;
1500 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001501
1502 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001503 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1504 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block3762c312012-01-06 19:20:56 +00001505 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001506 "for output %p with format %d",
1507 sampleRate, format, channelMask, mOutput, mFormat);
1508 lStatus = BAD_VALUE;
1509 goto Exit;
1510 }
Eric Laurenta553c252009-07-17 12:17:14 -07001511 }
1512 } else {
1513 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1514 if (sampleRate > mSampleRate*2) {
Steve Block3762c312012-01-06 19:20:56 +00001515 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Eric Laurenta553c252009-07-17 12:17:14 -07001516 lStatus = BAD_VALUE;
1517 goto Exit;
1518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 }
1520
Eric Laurent464d5b32011-06-17 21:29:58 -07001521 lStatus = initCheck();
1522 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00001523 ALOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001524 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 }
1526
Eric Laurenta553c252009-07-17 12:17:14 -07001527 { // scope for mLock
1528 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001529
1530 // all tracks in same audio session must share the same routing strategy otherwise
1531 // conflicts will happen when tracks are moved from one output to another by audio policy
1532 // manager
1533 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001534 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001535 for (size_t i = 0; i < mTracks.size(); ++i) {
1536 sp<Track> t = mTracks[i];
1537 if (t != 0) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001538 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1539 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block3762c312012-01-06 19:20:56 +00001540 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001541 strategy, actual);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001542 lStatus = BAD_VALUE;
1543 goto Exit;
1544 }
1545 }
1546 }
1547
Eric Laurenta553c252009-07-17 12:17:14 -07001548 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001549 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001550 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001551 lStatus = NO_MEMORY;
1552 goto Exit;
1553 }
1554 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001555
1556 sp<EffectChain> chain = getEffectChain_l(sessionId);
1557 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001558 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001559 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001560 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001561 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001562 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001563
1564 // invalidate track immediately if the stream type was moved to another thread since
1565 // createTrack() was called by the client process.
1566 if (!mStreamTypes[streamType].valid) {
Steve Block8564c8d2012-01-05 23:22:43 +00001567 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07001568 this, streamType);
1569 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1570 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001571 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001572 lStatus = NO_ERROR;
1573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574Exit:
1575 if(status) {
1576 *status = lStatus;
1577 }
1578 return track;
1579}
1580
Eric Laurenta553c252009-07-17 12:17:14 -07001581uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582{
Eric Laurent828b9772011-08-07 16:32:26 -07001583 Mutex::Autolock _l(mLock);
1584 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001585 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001586 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 return 0;
1588 }
1589}
1590
Eric Laurenta553c252009-07-17 12:17:14 -07001591status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592{
1593 mMasterVolume = value;
1594 return NO_ERROR;
1595}
1596
Eric Laurenta553c252009-07-17 12:17:14 -07001597status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598{
1599 mMasterMute = muted;
1600 return NO_ERROR;
1601}
1602
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001603status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604{
1605 mStreamTypes[stream].volume = value;
1606 return NO_ERROR;
1607}
1608
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001609status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610{
1611 mStreamTypes[stream].mute = muted;
1612 return NO_ERROR;
1613}
1614
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001615float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616{
1617 return mStreamTypes[stream].volume;
1618}
1619
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001620bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621{
1622 return mStreamTypes[stream].mute;
1623}
1624
Eric Laurenta553c252009-07-17 12:17:14 -07001625// addTrack_l() must be called with ThreadBase::mLock held
1626status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627{
1628 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001629
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001630 // set retry count for buffer fill
1631 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001632 if (mActiveTracks.indexOf(track) < 0) {
1633 // the track is newly added, make sure it fills up all its
1634 // buffers before playing. This is to ensure the client will
1635 // effectively get the latency it requested.
1636 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001637 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001638 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001639 if (track->mainBuffer() != mMixBuffer) {
1640 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1641 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001642 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001643 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001644 }
1645 }
1646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001648 }
Eric Laurenta553c252009-07-17 12:17:14 -07001649
Steve Block71f2cf12011-10-20 11:56:00 +01001650 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001651 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652
1653 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001654}
1655
Eric Laurenta553c252009-07-17 12:17:14 -07001656// destroyTrack_l() must be called with ThreadBase::mLock held
1657void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001658{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001659 track->mState = TrackBase::TERMINATED;
1660 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001661 removeTrack_l(track);
1662 }
1663}
1664
1665void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1666{
1667 mTracks.remove(track);
1668 deleteTrackName_l(track->name());
1669 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1670 if (chain != 0) {
1671 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001672 }
1673}
1674
Eric Laurenta553c252009-07-17 12:17:14 -07001675String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001676{
Eric Laurent828b9772011-08-07 16:32:26 -07001677 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001678 char *s;
1679
Eric Laurent828b9772011-08-07 16:32:26 -07001680 Mutex::Autolock _l(mLock);
1681 if (initCheck() != NO_ERROR) {
1682 return out_s8;
1683 }
1684
Dima Zavin31f188892011-04-18 16:57:27 -07001685 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001686 out_s8 = String8(s);
1687 free(s);
1688 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001689}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001690
Eric Laurent828b9772011-08-07 16:32:26 -07001691// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001692void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001693 AudioSystem::OutputDescriptor desc;
Glenn Kasten3694ec12012-01-27 16:47:15 -08001694 void *param2 = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07001695
Steve Block71f2cf12011-10-20 11:56:00 +01001696 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001697
1698 switch (event) {
1699 case AudioSystem::OUTPUT_OPENED:
1700 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001701 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001702 desc.samplingRate = mSampleRate;
1703 desc.format = mFormat;
1704 desc.frameCount = mFrameCount;
1705 desc.latency = latency();
1706 param2 = &desc;
1707 break;
1708
1709 case AudioSystem::STREAM_CONFIG_CHANGED:
1710 param2 = &param;
1711 case AudioSystem::OUTPUT_CLOSED:
1712 default:
1713 break;
1714 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001715 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001716}
1717
1718void AudioFlinger::PlaybackThread::readOutputParameters()
1719{
Dima Zavin31f188892011-04-18 16:57:27 -07001720 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001721 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1722 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001723 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08001724 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin31f188892011-04-18 16:57:27 -07001725 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001726
Eric Laurenta553c252009-07-17 12:17:14 -07001727 // FIXME - Current mixer implementation only supports stereo output: Always
1728 // Allocate a stereo buffer even if HW output is mono.
Glenn Kasten2589cf92012-01-27 18:08:45 -08001729 delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001730 mMixBuffer = new int16_t[mFrameCount * 2];
1731 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001732
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001733 // force reconfiguration of effect chains and engines to take new buffer size and audio
1734 // parameters into account
1735 // Note that mLock is not held when readOutputParameters() is called from the constructor
1736 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1737 // matter.
1738 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1739 Vector< sp<EffectChain> > effectChains = mEffectChains;
1740 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001741 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001742 }
Eric Laurenta553c252009-07-17 12:17:14 -07001743}
1744
Eric Laurent0986e792010-01-19 17:37:09 -08001745status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1746{
Glenn Kasten3694ec12012-01-27 16:47:15 -08001747 if (halFrames == NULL || dspFrames == NULL) {
Eric Laurent0986e792010-01-19 17:37:09 -08001748 return BAD_VALUE;
1749 }
Eric Laurent828b9772011-08-07 16:32:26 -07001750 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001751 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001752 return INVALID_OPERATION;
1753 }
Dima Zavin31f188892011-04-18 16:57:27 -07001754 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001755
Dima Zavin31f188892011-04-18 16:57:27 -07001756 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001757}
1758
Eric Laurent493941b2010-07-28 01:32:47 -07001759uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001760{
1761 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001762 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001763 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001764 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001765 }
1766
1767 for (size_t i = 0; i < mTracks.size(); ++i) {
1768 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001769 if (sessionId == track->sessionId() &&
1770 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001771 result |= TRACK_SESSION;
1772 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001773 }
1774 }
1775
Eric Laurent493941b2010-07-28 01:32:47 -07001776 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001777}
1778
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001779uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1780{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001781 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001782 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001783 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1784 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001785 }
1786 for (size_t i = 0; i < mTracks.size(); i++) {
1787 sp<Track> track = mTracks[i];
1788 if (sessionId == track->sessionId() &&
1789 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001790 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001791 }
1792 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001793 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001794}
1795
Eric Laurent53334cd2010-06-23 17:38:20 -07001796
Glenn Kasten5b0135e2012-01-26 09:46:34 -08001797AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent828b9772011-08-07 16:32:26 -07001798{
1799 Mutex::Autolock _l(mLock);
1800 return mOutput;
1801}
1802
1803AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1804{
1805 Mutex::Autolock _l(mLock);
1806 AudioStreamOut *output = mOutput;
1807 mOutput = NULL;
1808 return output;
1809}
1810
1811// this method must always be called either with ThreadBase mLock held or inside the thread loop
1812audio_stream_t* AudioFlinger::PlaybackThread::stream()
1813{
1814 if (mOutput == NULL) {
1815 return NULL;
1816 }
1817 return &mOutput->stream->common;
1818}
1819
Eric Laurent44331692011-12-05 09:47:19 -08001820uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1821{
1822 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1823 // decoding and transfer time. So sleeping for half of the latency would likely cause
1824 // underruns
1825 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1826 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1827 } else {
1828 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1829 }
1830}
1831
Eric Laurenta553c252009-07-17 12:17:14 -07001832// ----------------------------------------------------------------------------
1833
Glenn Kastenefd511a2012-01-26 10:38:26 -08001834AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08001835 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kastenefd511a2012-01-26 10:38:26 -08001836 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kastendc3ac852012-01-25 15:28:08 -08001837 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1838 mPrevMixerStatus(MIXER_IDLE)
Eric Laurenta553c252009-07-17 12:17:14 -07001839{
Eric Laurenta553c252009-07-17 12:17:14 -07001840 // FIXME - Current mixer implementation only supports stereo output
1841 if (mChannelCount == 1) {
Steve Block3762c312012-01-06 19:20:56 +00001842 ALOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001844}
1845
Eric Laurenta553c252009-07-17 12:17:14 -07001846AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001847{
Eric Laurenta553c252009-07-17 12:17:14 -07001848 delete mAudioMixer;
1849}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850
Eric Laurenta553c252009-07-17 12:17:14 -07001851bool AudioFlinger::MixerThread::threadLoop()
1852{
Eric Laurenta553c252009-07-17 12:17:14 -07001853 Vector< sp<Track> > tracksToRemove;
Glenn Kasten789fef12012-01-26 13:37:52 -08001854 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001855 nsecs_t standbyTime = systemTime();
1856 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001857 // FIXME: Relaxed timing because of a certain device that can't meet latency
1858 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001859 // increase threshold again due to low power audio mode. The way this warning threshold is
1860 // calculated and its usefulness should be reconsidered anyway.
1861 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001862 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001863 bool longStandbyExit = false;
1864 uint32_t activeSleepTime = activeSleepTimeUs();
1865 uint32_t idleSleepTime = idleSleepTimeUs();
1866 uint32_t sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001867 uint32_t sleepTimeShift = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001868 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001869#ifdef DEBUG_CPU_USAGE
1870 ThreadCpuUsage cpu;
1871 const CentralTendencyStatistics& stats = cpu.statistics();
1872#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873
Eric Laurent6dbdc402011-07-22 09:04:31 -07001874 acquireWakeLock();
1875
Eric Laurenta553c252009-07-17 12:17:14 -07001876 while (!exitPending())
1877 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001878#ifdef DEBUG_CPU_USAGE
1879 cpu.sampleAndEnable();
1880 unsigned n = stats.n();
1881 // cpu.elapsed() is expensive, so don't call it every loop
1882 if ((n & 127) == 1) {
1883 long long elapsed = cpu.elapsed();
1884 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1885 double perLoop = elapsed / (double) n;
1886 double perLoop100 = perLoop * 0.01;
1887 double mean = stats.mean();
1888 double stddev = stats.stddev();
1889 double minimum = stats.minimum();
1890 double maximum = stats.maximum();
1891 cpu.resetStatistics();
Steve Block6215d3f2012-01-04 20:05:49 +00001892 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 -07001893 elapsed * .000000001, n, perLoop * .000001,
1894 mean * .001,
1895 stddev * .001,
1896 minimum * .001,
1897 maximum * .001,
1898 mean / perLoop100,
1899 stddev / perLoop100,
1900 minimum / perLoop100,
1901 maximum / perLoop100);
1902 }
1903 }
1904#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001905 processConfigEvents();
1906
Eric Laurent059b4be2009-11-09 23:32:22 -08001907 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001908 { // scope for mLock
1909
1910 Mutex::Autolock _l(mLock);
1911
1912 if (checkForNewParameters_l()) {
1913 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001914 // FIXME: Relaxed timing because of a certain device that can't meet latency
1915 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001916 // increase threshold again due to low power audio mode. The way this warning
1917 // threshold is calculated and its usefulness should be reconsidered anyway.
1918 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001919 activeSleepTime = activeSleepTimeUs();
1920 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001921 }
1922
1923 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1924
1925 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001926 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1927 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001928 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01001929 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001930 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001931 mStandby = true;
1932 mBytesWritten = 0;
1933 }
1934
1935 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1936 // we're about to wait, flush the binder command buffer
1937 IPCThreadState::self()->flushCommands();
1938
1939 if (exitPending()) break;
1940
Eric Laurent6dbdc402011-07-22 09:04:31 -07001941 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001942 // wait until we have something to do...
Steve Block71f2cf12011-10-20 11:56:00 +01001943 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07001944 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01001945 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001946 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001947
Eric Laurent71c44962012-01-17 19:20:12 -08001948 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenb737dbb2012-01-13 15:54:24 -08001949 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07001950 char value[PROPERTY_VALUE_MAX];
1951 property_get("ro.audio.silent", value, "0");
1952 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00001953 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07001954 setMasterMute(true);
1955 }
1956 }
1957
1958 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001959 sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001960 sleepTimeShift = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001961 continue;
1962 }
1963 }
1964
Eric Laurent059b4be2009-11-09 23:32:22 -08001965 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001966
1967 // prevent any changes in effect chain list and in each effect chain
1968 // during mixing and effect process as the audio buffers could be deleted
1969 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001970 lockEffectChains_l(effectChains);
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08001971 }
Eric Laurenta553c252009-07-17 12:17:14 -07001972
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001973 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001974 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001975 mAudioMixer->process();
Eric Laurent06092312012-01-23 18:56:59 -08001976 // increase sleep time progressively when application underrun condition clears.
1977 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1978 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1979 // such that we would underrun the audio HAL.
1980 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001981 sleepTimeShift--;
1982 }
Eric Laurent06092312012-01-23 18:56:59 -08001983 sleepTime = 0;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001984 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001985 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001986 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001987 // If no tracks are ready, sleep once for the duration of an output
1988 // buffer size, then write 0s to the output
1989 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001990 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001991 sleepTime = activeSleepTime >> sleepTimeShift;
1992 if (sleepTime < kMinThreadSleepTimeUs) {
1993 sleepTime = kMinThreadSleepTimeUs;
1994 }
1995 // reduce sleep time in case of consecutive application underruns to avoid
1996 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1997 // duration we would end up writing less data than needed by the audio HAL if
1998 // the condition persists.
1999 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2000 sleepTimeShift++;
2001 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002002 } else {
2003 sleepTime = idleSleepTime;
2004 }
2005 } else if (mBytesWritten != 0 ||
2006 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002007 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002008 sleepTime = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01002009 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07002010 }
Eric Laurent65b65452010-06-01 23:49:17 -07002011 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07002012 }
2013
2014 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002015 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002016 }
2017 // sleepTime == 0 means we must write to audio hardware
2018 if (sleepTime == 0) {
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08002019 for (size_t i = 0; i < effectChains.size(); i ++) {
2020 effectChains[i]->process_l();
2021 }
2022 // enable changes in effect chain
2023 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002024 mLastWriteTime = systemTime();
2025 mInWrite = true;
2026 mBytesWritten += mixBufferSize;
2027
Dima Zavin31f188892011-04-18 16:57:27 -07002028 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002029 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002030 mNumWrites++;
2031 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002032 nsecs_t now = systemTime();
2033 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07002034 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002035 mNumDelayedWrites++;
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002036 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00002037 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002038 ns2ms(delta), mNumDelayedWrites, this);
2039 lastWarning = now;
2040 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002041 if (mStandby) {
2042 longStandbyExit = true;
2043 }
Eric Laurenta553c252009-07-17 12:17:14 -07002044 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002045 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002046 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002047 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002048 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002049 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002050 }
2051
2052 // finally let go of all our tracks, without the lock held
2053 // since we can't guarantee the destructors won't acquire that
2054 // same lock.
2055 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002056
2057 // Effect chains will be actually deleted here if they were removed from
2058 // mEffectChains list during mixing or effects processing
2059 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002060 }
2061
2062 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002063 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002064 }
Eric Laurenta553c252009-07-17 12:17:14 -07002065
Eric Laurent6dbdc402011-07-22 09:04:31 -07002066 releaseWakeLock();
2067
Steve Block71f2cf12011-10-20 11:56:00 +01002068 ALOGV("MixerThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002069 return false;
2070}
2071
2072// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten789fef12012-01-26 13:37:52 -08002073AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2074 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002075{
2076
Glenn Kasten789fef12012-01-26 13:37:52 -08002077 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002078 // find out which tracks need to be processed
2079 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002080 size_t mixedTracks = 0;
2081 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002082
2083 float masterVolume = mMasterVolume;
2084 bool masterMute = mMasterMute;
2085
Eric Laurent8cc93b92010-08-11 05:20:11 -07002086 if (masterMute) {
2087 masterVolume = 0;
2088 }
Eric Laurent65b65452010-06-01 23:49:17 -07002089 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002090 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002091 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002092 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002093 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002094 masterVolume = (float)((v + (1 << 23)) >> 24);
2095 chain.clear();
2096 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002097
Eric Laurenta553c252009-07-17 12:17:14 -07002098 for (size_t i=0 ; i<count ; i++) {
2099 sp<Track> t = activeTracks[i].promote();
2100 if (t == 0) continue;
2101
Glenn Kasten68deb152011-12-19 15:06:39 -08002102 // this const just means the local variable doesn't change
Eric Laurenta553c252009-07-17 12:17:14 -07002103 Track* const track = t.get();
2104 audio_track_cblk_t* cblk = track->cblk();
2105
2106 // The first time a track is added we wait
2107 // for all its buffers to be filled before processing it
Glenn Kasten68deb152011-12-19 15:06:39 -08002108 int name = track->name();
Eric Laurent8a04fe02011-11-08 18:10:16 -08002109 // make sure that we have enough frames to mix one full buffer.
2110 // enforce this condition only once to enable draining the buffer in case the client
2111 // app does not call stop() and relies on underrun to stop:
Eric Laurent71c44962012-01-17 19:20:12 -08002112 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurent8a04fe02011-11-08 18:10:16 -08002113 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002114 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002115 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent71c44962012-01-17 19:20:12 -08002116 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002117 if (t->sampleRate() == (int)mSampleRate) {
2118 minFrames = mFrameCount;
2119 } else {
Eric Laurent72dafb22011-12-22 16:08:41 -08002120 // +1 for rounding and +1 for additional sample needed for interpolation
2121 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2122 // add frames already consumed but not yet released by the resampler
2123 // because cblk->framesReady() will include these frames
2124 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2125 // the minimum track buffer size is normally twice the number of frames necessary
2126 // to fill one buffer and the resampler should not leave more than one buffer worth
2127 // of unreleased frames after each pass, but just in case...
Steve Blockec193de2012-01-09 18:35:44 +00002128 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002129 }
2130 }
2131 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002132 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002133 {
Glenn Kasten68deb152011-12-19 15:06:39 -08002134 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002135
Eric Laurent65b65452010-06-01 23:49:17 -07002136 mixedTracks++;
2137
2138 // track->mainBuffer() != mMixBuffer means there is an effect chain
2139 // connected to the track
2140 chain.clear();
2141 if (track->mainBuffer() != mMixBuffer) {
2142 chain = getEffectChain_l(track->sessionId());
2143 // Delegate volume control to effect in track effect chain if needed
2144 if (chain != 0) {
2145 tracksWithEffect++;
2146 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00002147 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten68deb152011-12-19 15:06:39 -08002148 name, track->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002149 }
2150 }
2151
2152
2153 int param = AudioMixer::VOLUME;
2154 if (track->mFillingUpStatus == Track::FS_FILLED) {
2155 // no ramp for the first volume setting
2156 track->mFillingUpStatus = Track::FS_ACTIVE;
2157 if (track->mState == TrackBase::RESUMING) {
2158 track->mState = TrackBase::ACTIVE;
2159 param = AudioMixer::RAMP_VOLUME;
2160 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002161 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002162 } else if (cblk->server != 0) {
2163 // If the track is stopped before the first frame was mixed,
2164 // do not apply ramp
2165 param = AudioMixer::RAMP_VOLUME;
2166 }
2167
Eric Laurenta553c252009-07-17 12:17:14 -07002168 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002169 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002170 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002171 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002172 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002173 if (track->isPausing()) {
2174 track->setPaused();
2175 }
2176 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002177
Glenn Kasten871c16c2010-03-05 12:18:01 -08002178 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002179 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002180 float v = masterVolume * typeVolume;
Glenn Kastenbc4de882012-01-17 14:39:34 -08002181 uint32_t vlr = cblk->getVolumeLR();
Glenn Kasten0632bad2012-01-17 12:20:54 -08002182 vl = vlr & 0xFFFF;
2183 vr = vlr >> 16;
2184 // track volumes come from shared memory, so can't be trusted and must be clamped
2185 if (vl > MAX_GAIN_INT) {
2186 ALOGV("Track left volume out of range: %04X", vl);
2187 vl = MAX_GAIN_INT;
2188 }
2189 if (vr > MAX_GAIN_INT) {
2190 ALOGV("Track right volume out of range: %04X", vr);
2191 vr = MAX_GAIN_INT;
2192 }
2193 // now apply the master volume and stream type volume
2194 vl = (uint32_t)(v * vl) << 12;
2195 vr = (uint32_t)(v * vr) << 12;
2196 // assuming master volume and stream type volume each go up to 1.0,
2197 // vl and vr are now in 8.24 format
Eric Laurenta553c252009-07-17 12:17:14 -07002198
Glenn Kasten4790bd82012-01-03 14:22:33 -08002199 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2200 // send level comes from shared memory and so may be corrupt
Glenn Kasten0632bad2012-01-17 12:20:54 -08002201 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten4790bd82012-01-03 14:22:33 -08002202 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kasten0632bad2012-01-17 12:20:54 -08002203 sendLevel = MAX_GAIN_INT;
Glenn Kasten4790bd82012-01-03 14:22:33 -08002204 }
2205 va = (uint32_t)(v * sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002206 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002207 // Delegate volume control to effect in track effect chain if needed
2208 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2209 // Do not ramp volume if volume is controlled by effect
2210 param = AudioMixer::VOLUME;
2211 track->mHasVolumeController = true;
2212 } else {
2213 // force no volume ramp when volume controller was just disabled or removed
2214 // from effect chain to avoid volume spike
2215 if (track->mHasVolumeController) {
2216 param = AudioMixer::VOLUME;
2217 }
2218 track->mHasVolumeController = false;
2219 }
2220
2221 // Convert volumes from 8.24 to 4.12 format
2222 int16_t left, right, aux;
Glenn Kasten0632bad2012-01-17 12:20:54 -08002223 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002224 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2225 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2226 left = int16_t(v_clamped);
2227 v_clamped = (vr + (1 << 11)) >> 12;
2228 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2229 right = int16_t(v_clamped);
2230
2231 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2232 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002233
Eric Laurent65b65452010-06-01 23:49:17 -07002234 // XXX: these things DON'T need to be done each time
Glenn Kasten68deb152011-12-19 15:06:39 -08002235 mAudioMixer->setBufferProvider(name, track);
2236 mAudioMixer->enable(name);
Eric Laurent65b65452010-06-01 23:49:17 -07002237
Glenn Kasten68deb152011-12-19 15:06:39 -08002238 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2239 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2240 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002241 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002242 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002243 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002244 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002245 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002246 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002247 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002248 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002249 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002250 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002251 AudioMixer::RESAMPLE,
2252 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002253 (void *)(cblk->sampleRate));
2254 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002255 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002256 AudioMixer::TRACK,
2257 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2258 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002259 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002260 AudioMixer::TRACK,
2261 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002262
2263 // reset retry count
2264 track->mRetryCount = kMaxTrackRetries;
Eric Laurent71c44962012-01-17 19:20:12 -08002265 // If one track is ready, set the mixer ready if:
2266 // - the mixer was not ready during previous round OR
2267 // - no other track is not ready
2268 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2269 mixerStatus != MIXER_TRACKS_ENABLED) {
2270 mixerStatus = MIXER_TRACKS_READY;
2271 }
Eric Laurenta553c252009-07-17 12:17:14 -07002272 } else {
Glenn Kasten68deb152011-12-19 15:06:39 -08002273 //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 -07002274 if (track->isStopped()) {
2275 track->reset();
2276 }
2277 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2278 // We have consumed all the buffers of this track.
2279 // Remove it from the list of active tracks.
2280 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002281 } else {
2282 // No buffers for this track. Give it a few chances to
2283 // fill a buffer, then remove it from active list.
2284 if (--(track->mRetryCount) <= 0) {
Glenn Kasten68deb152011-12-19 15:06:39 -08002285 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002286 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002287 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002288 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent71c44962012-01-17 19:20:12 -08002289 // If one track is not ready, mark the mixer also not ready if:
2290 // - the mixer was ready during previous round OR
2291 // - no other track is ready
2292 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2293 mixerStatus != MIXER_TRACKS_READY) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002294 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002295 }
Eric Laurenta553c252009-07-17 12:17:14 -07002296 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002297 mAudioMixer->disable(name);
Eric Laurenta553c252009-07-17 12:17:14 -07002298 }
2299 }
2300
2301 // remove all the tracks that need to be...
2302 count = tracksToRemove->size();
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002303 if (CC_UNLIKELY(count)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002304 for (size_t i=0 ; i<count ; i++) {
2305 const sp<Track>& track = tracksToRemove->itemAt(i);
2306 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002307 if (track->mainBuffer() != mMixBuffer) {
2308 chain = getEffectChain_l(track->sessionId());
2309 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002310 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002311 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002312 }
2313 }
Eric Laurenta553c252009-07-17 12:17:14 -07002314 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002315 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002316 }
2317 }
2318 }
2319
Eric Laurent65b65452010-06-01 23:49:17 -07002320 // mix buffer must be cleared if all tracks are connected to an
2321 // effect chain as in this case the mixer will not write to
2322 // mix buffer and track effects will accumulate into it
2323 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2324 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2325 }
2326
Eric Laurent71c44962012-01-17 19:20:12 -08002327 mPrevMixerStatus = mixerStatus;
Eric Laurent059b4be2009-11-09 23:32:22 -08002328 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002329}
2330
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002331void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002332{
Steve Block71f2cf12011-10-20 11:56:00 +01002333 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002334 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002335 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002336
Eric Laurenta553c252009-07-17 12:17:14 -07002337 size_t size = mTracks.size();
2338 for (size_t i = 0; i < size; i++) {
2339 sp<Track> t = mTracks[i];
2340 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002341 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002342 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002343 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002344 }
2345}
Eric Laurenta553c252009-07-17 12:17:14 -07002346
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002347void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent05ce0942011-08-30 10:18:54 -07002348{
Steve Block71f2cf12011-10-20 11:56:00 +01002349 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002350 this, streamType, valid);
2351 Mutex::Autolock _l(mLock);
2352
2353 mStreamTypes[streamType].valid = valid;
2354}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355
Eric Laurenta553c252009-07-17 12:17:14 -07002356// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002357int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358{
2359 return mAudioMixer->getTrackName();
2360}
2361
Eric Laurenta553c252009-07-17 12:17:14 -07002362// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002363void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364{
Steve Block71f2cf12011-10-20 11:56:00 +01002365 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 mAudioMixer->deleteTrackName(name);
2367}
2368
Eric Laurenta553c252009-07-17 12:17:14 -07002369// checkForNewParameters_l() must be called with ThreadBase::mLock held
2370bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371{
Eric Laurenta553c252009-07-17 12:17:14 -07002372 bool reconfig = false;
2373
Eric Laurent8fce46a2009-08-04 09:45:33 -07002374 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002375 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002376 String8 keyValuePair = mNewParameters[0];
2377 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002378 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002379
Eric Laurenta553c252009-07-17 12:17:14 -07002380 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2381 reconfig = true;
2382 }
2383 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08002384 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002385 status = BAD_VALUE;
2386 } else {
2387 reconfig = true;
2388 }
2389 }
2390 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002391 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002392 status = BAD_VALUE;
2393 } else {
2394 reconfig = true;
2395 }
2396 }
2397 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2398 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastene5fb2632011-12-14 10:28:06 -08002399 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07002400 // if frame count is changed after track creation
2401 if (!mTracks.isEmpty()) {
2402 status = INVALID_OPERATION;
2403 } else {
2404 reconfig = true;
2405 }
2406 }
Eric Laurent65b65452010-06-01 23:49:17 -07002407 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002408 // when changing the audio output device, call addBatteryData to notify
2409 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002410 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002411 uint32_t params = 0;
2412 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002413 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002414 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2415 }
2416
2417 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002418 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002419 // check if any other device (except speaker) is on
2420 if (value & deviceWithoutSpeaker ) {
2421 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2422 }
2423
2424 if (params != 0) {
2425 addBatteryData(params);
2426 }
2427 }
2428
Eric Laurent65b65452010-06-01 23:49:17 -07002429 // forward device change to effects that have requested to be
2430 // aware of attached audio device.
2431 mDevice = (uint32_t)value;
2432 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002433 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002434 }
2435 }
2436
Eric Laurenta553c252009-07-17 12:17:14 -07002437 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002438 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002439 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002440 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002441 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002442 mStandby = true;
2443 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002444 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002445 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002446 }
2447 if (status == NO_ERROR && reconfig) {
2448 delete mAudioMixer;
Glenn Kasten2589cf92012-01-27 18:08:45 -08002449 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2450 mAudioMixer = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07002451 readOutputParameters();
2452 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2453 for (size_t i = 0; i < mTracks.size() ; i++) {
2454 int name = getTrackName_l();
2455 if (name < 0) break;
2456 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002457 // limit track sample rate to 2 x new output sample rate
2458 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2459 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2460 }
Eric Laurenta553c252009-07-17 12:17:14 -07002461 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002462 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002463 }
2464 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002465
2466 mNewParameters.removeAt(0);
2467
Eric Laurenta553c252009-07-17 12:17:14 -07002468 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002469 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002470 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2471 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002472 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002473 }
2474 return reconfig;
2475}
2476
2477status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2478{
2479 const size_t SIZE = 256;
2480 char buffer[SIZE];
2481 String8 result;
2482
2483 PlaybackThread::dumpInternals(fd, args);
2484
2485 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2486 result.append(buffer);
2487 write(fd, result.string(), result.size());
2488 return NO_ERROR;
2489}
2490
Eric Laurent059b4be2009-11-09 23:32:22 -08002491uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2492{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002493 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002494}
2495
Eric Laurent8448a792010-08-18 18:13:17 -07002496uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2497{
2498 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2499}
2500
Eric Laurenta553c252009-07-17 12:17:14 -07002501// ----------------------------------------------------------------------------
Glenn Kasten39d00cb2012-01-17 11:09:42 -08002502AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2503 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kastenefd511a2012-01-26 10:38:26 -08002504 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kastendc3ac852012-01-25 15:28:08 -08002505 // mLeftVolFloat, mRightVolFloat
2506 // mLeftVolShort, mRightVolShort
Eric Laurenta553c252009-07-17 12:17:14 -07002507{
Eric Laurenta553c252009-07-17 12:17:14 -07002508}
2509
2510AudioFlinger::DirectOutputThread::~DirectOutputThread()
2511{
2512}
2513
Eric Laurent65b65452010-06-01 23:49:17 -07002514static inline
2515int32_t mul(int16_t in, int16_t v)
2516{
2517#if defined(__arm__) && !defined(__thumb__)
2518 int32_t out;
2519 asm( "smulbb %[out], %[in], %[v] \n"
2520 : [out]"=r"(out)
2521 : [in]"%r"(in), [v]"r"(v)
2522 : );
2523 return out;
2524#else
2525 return in * int32_t(v);
2526#endif
2527}
2528
2529void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2530{
2531 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002532 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002533 return;
2534 }
2535
2536 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002537 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002538 size_t count = mFrameCount * mChannelCount;
2539 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2540 int16_t *dst = mMixBuffer + count-1;
2541 while(count--) {
2542 *dst-- = (int16_t)(*src--^0x80) << 8;
2543 }
2544 }
2545
2546 size_t frameCount = mFrameCount;
2547 int16_t *out = mMixBuffer;
2548 if (ramp) {
2549 if (mChannelCount == 1) {
2550 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2551 int32_t vlInc = d / (int32_t)frameCount;
2552 int32_t vl = ((int32_t)mLeftVolShort << 16);
2553 do {
2554 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2555 out++;
2556 vl += vlInc;
2557 } while (--frameCount);
2558
2559 } else {
2560 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2561 int32_t vlInc = d / (int32_t)frameCount;
2562 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2563 int32_t vrInc = d / (int32_t)frameCount;
2564 int32_t vl = ((int32_t)mLeftVolShort << 16);
2565 int32_t vr = ((int32_t)mRightVolShort << 16);
2566 do {
2567 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2568 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2569 out += 2;
2570 vl += vlInc;
2571 vr += vrInc;
2572 } while (--frameCount);
2573 }
2574 } else {
2575 if (mChannelCount == 1) {
2576 do {
2577 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2578 out++;
2579 } while (--frameCount);
2580 } else {
2581 do {
2582 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2583 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2584 out += 2;
2585 } while (--frameCount);
2586 }
2587 }
2588
2589 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002590 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002591 size_t count = mFrameCount * mChannelCount;
2592 int16_t *src = mMixBuffer;
2593 uint8_t *dst = (uint8_t *)mMixBuffer;
2594 while(count--) {
2595 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2596 }
2597 }
2598
2599 mLeftVolShort = leftVol;
2600 mRightVolShort = rightVol;
2601}
2602
Eric Laurenta553c252009-07-17 12:17:14 -07002603bool AudioFlinger::DirectOutputThread::threadLoop()
2604{
Glenn Kasten789fef12012-01-26 13:37:52 -08002605 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002606 sp<Track> trackToRemove;
2607 sp<Track> activeTrack;
2608 nsecs_t standbyTime = systemTime();
2609 int8_t *curBuf;
2610 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002611 uint32_t activeSleepTime = activeSleepTimeUs();
2612 uint32_t idleSleepTime = idleSleepTimeUs();
2613 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002614 // use shorter standby delay as on normal output to release
2615 // hardware resources as soon as possible
2616 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002617
Eric Laurent6dbdc402011-07-22 09:04:31 -07002618 acquireWakeLock();
2619
Eric Laurenta553c252009-07-17 12:17:14 -07002620 while (!exitPending())
2621 {
Eric Laurent65b65452010-06-01 23:49:17 -07002622 bool rampVolume;
2623 uint16_t leftVol;
2624 uint16_t rightVol;
2625 Vector< sp<EffectChain> > effectChains;
2626
Eric Laurenta553c252009-07-17 12:17:14 -07002627 processConfigEvents();
2628
Eric Laurent059b4be2009-11-09 23:32:22 -08002629 mixerStatus = MIXER_IDLE;
2630
Eric Laurenta553c252009-07-17 12:17:14 -07002631 { // scope for the mLock
2632
2633 Mutex::Autolock _l(mLock);
2634
2635 if (checkForNewParameters_l()) {
2636 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002637 activeSleepTime = activeSleepTimeUs();
2638 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002639 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002640 }
2641
2642 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002643 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2644 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002645 // wait until we have something to do...
2646 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01002647 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002648 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002649 mStandby = true;
2650 mBytesWritten = 0;
2651 }
2652
2653 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2654 // we're about to wait, flush the binder command buffer
2655 IPCThreadState::self()->flushCommands();
2656
2657 if (exitPending()) break;
2658
Eric Laurent6dbdc402011-07-22 09:04:31 -07002659 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002660 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002661 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002662 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002663 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002664
Glenn Kastenb737dbb2012-01-13 15:54:24 -08002665 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07002666 char value[PROPERTY_VALUE_MAX];
2667 property_get("ro.audio.silent", value, "0");
2668 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00002669 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07002670 setMasterMute(true);
2671 }
2672 }
2673
Eric Laurentef9500f2010-03-11 14:47:00 -08002674 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002675 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002676 continue;
2677 }
2678 }
2679
Eric Laurent65b65452010-06-01 23:49:17 -07002680 effectChains = mEffectChains;
2681
Eric Laurenta553c252009-07-17 12:17:14 -07002682 // find out which tracks need to be processed
2683 if (mActiveTracks.size() != 0) {
2684 sp<Track> t = mActiveTracks[0].promote();
2685 if (t == 0) continue;
2686
2687 Track* const track = t.get();
2688 audio_track_cblk_t* cblk = track->cblk();
2689
2690 // The first time a track is added we wait
2691 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002692 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002693 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002694 {
Steve Block71f2cf12011-10-20 11:56:00 +01002695 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002696
Eric Laurent65b65452010-06-01 23:49:17 -07002697 if (track->mFillingUpStatus == Track::FS_FILLED) {
2698 track->mFillingUpStatus = Track::FS_ACTIVE;
2699 mLeftVolFloat = mRightVolFloat = 0;
2700 mLeftVolShort = mRightVolShort = 0;
2701 if (track->mState == TrackBase::RESUMING) {
2702 track->mState = TrackBase::ACTIVE;
2703 rampVolume = true;
2704 }
2705 } else if (cblk->server != 0) {
2706 // If the track is stopped before the first frame was mixed,
2707 // do not apply ramp
2708 rampVolume = true;
2709 }
Eric Laurenta553c252009-07-17 12:17:14 -07002710 // compute volume for this track
2711 float left, right;
2712 if (track->isMuted() || mMasterMute || track->isPausing() ||
2713 mStreamTypes[track->type()].mute) {
2714 left = right = 0;
2715 if (track->isPausing()) {
2716 track->setPaused();
2717 }
2718 } else {
2719 float typeVolume = mStreamTypes[track->type()].volume;
2720 float v = mMasterVolume * typeVolume;
Glenn Kastenbc4de882012-01-17 14:39:34 -08002721 uint32_t vlr = cblk->getVolumeLR();
Glenn Kasten0632bad2012-01-17 12:20:54 -08002722 float v_clamped = v * (vlr & 0xFFFF);
Eric Laurenta553c252009-07-17 12:17:14 -07002723 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2724 left = v_clamped/MAX_GAIN;
Glenn Kasten0632bad2012-01-17 12:20:54 -08002725 v_clamped = v * (vlr >> 16);
Eric Laurenta553c252009-07-17 12:17:14 -07002726 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2727 right = v_clamped/MAX_GAIN;
2728 }
2729
Eric Laurent65b65452010-06-01 23:49:17 -07002730 if (left != mLeftVolFloat || right != mRightVolFloat) {
2731 mLeftVolFloat = left;
2732 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002733
Eric Laurent65b65452010-06-01 23:49:17 -07002734 // If audio HAL implements volume control,
2735 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002736 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002737 left = 1.0f;
2738 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002739 }
Eric Laurent65b65452010-06-01 23:49:17 -07002740
2741 // Convert volumes from float to 8.24
2742 uint32_t vl = (uint32_t)(left * (1 << 24));
2743 uint32_t vr = (uint32_t)(right * (1 << 24));
2744
2745 // Delegate volume control to effect in track effect chain if needed
2746 // only one effect chain can be present on DirectOutputThread, so if
2747 // there is one, the track is connected to it
2748 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002749 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002750 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002751 rampVolume = false;
2752 }
2753 }
2754
2755 // Convert volumes from 8.24 to 4.12 format
2756 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2757 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2758 leftVol = (uint16_t)v_clamped;
2759 v_clamped = (vr + (1 << 11)) >> 12;
2760 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2761 rightVol = (uint16_t)v_clamped;
2762 } else {
2763 leftVol = mLeftVolShort;
2764 rightVol = mRightVolShort;
2765 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002766 }
2767
2768 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002769 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002770 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002771 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002772 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002773 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002774 if (track->isStopped()) {
2775 track->reset();
2776 }
2777 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2778 // We have consumed all the buffers of this track.
2779 // Remove it from the list of active tracks.
2780 trackToRemove = track;
2781 } else {
2782 // No buffers for this track. Give it a few chances to
2783 // fill a buffer, then remove it from active list.
2784 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002785 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurenta553c252009-07-17 12:17:14 -07002786 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002787 } else {
2788 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002789 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002790 }
Eric Laurenta553c252009-07-17 12:17:14 -07002791 }
2792 }
2793
2794 // remove all the tracks that need to be...
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002795 if (CC_UNLIKELY(trackToRemove != 0)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002796 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002797 if (!effectChains.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01002798 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002799 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002800 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002801 }
Eric Laurenta553c252009-07-17 12:17:14 -07002802 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002803 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002804 }
2805 }
Eric Laurent65b65452010-06-01 23:49:17 -07002806
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002807 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002808 }
2809
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002810 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002811 AudioBufferProvider::Buffer buffer;
2812 size_t frameCount = mFrameCount;
2813 curBuf = (int8_t *)mMixBuffer;
2814 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002815 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002816 buffer.frameCount = frameCount;
2817 activeTrack->getNextBuffer(&buffer);
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002818 if (CC_UNLIKELY(buffer.raw == NULL)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002819 memset(curBuf, 0, frameCount * mFrameSize);
2820 break;
2821 }
2822 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2823 frameCount -= buffer.frameCount;
2824 curBuf += buffer.frameCount * mFrameSize;
2825 activeTrack->releaseBuffer(&buffer);
2826 }
2827 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002828 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002829 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002830 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002831 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2832 sleepTime = activeSleepTime;
2833 } else {
2834 sleepTime = idleSleepTime;
2835 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002836 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002837 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002838 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002839 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002840 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002841
Eric Laurentf69a3f82009-09-22 00:35:48 -07002842 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002843 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002844 }
2845 // sleepTime == 0 means we must write to audio hardware
2846 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002847 if (mixerStatus == MIXER_TRACKS_READY) {
2848 applyVolume(leftVol, rightVol, rampVolume);
2849 }
2850 for (size_t i = 0; i < effectChains.size(); i ++) {
2851 effectChains[i]->process_l();
2852 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002853 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002854
Eric Laurentf69a3f82009-09-22 00:35:48 -07002855 mLastWriteTime = systemTime();
2856 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002857 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002858 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002859 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002860 mNumWrites++;
2861 mInWrite = false;
2862 mStandby = false;
2863 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002864 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002865 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002866 }
2867
2868 // finally let go of removed track, without the lock held
2869 // since we can't guarantee the destructors won't acquire that
2870 // same lock.
2871 trackToRemove.clear();
2872 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002873
2874 // Effect chains will be actually deleted here if they were removed from
2875 // mEffectChains list during mixing or effects processing
2876 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002877 }
2878
2879 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002880 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002881 }
Eric Laurenta553c252009-07-17 12:17:14 -07002882
Eric Laurent6dbdc402011-07-22 09:04:31 -07002883 releaseWakeLock();
2884
Steve Block71f2cf12011-10-20 11:56:00 +01002885 ALOGV("DirectOutputThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002886 return false;
2887}
2888
2889// getTrackName_l() must be called with ThreadBase::mLock held
2890int AudioFlinger::DirectOutputThread::getTrackName_l()
2891{
2892 return 0;
2893}
2894
2895// deleteTrackName_l() must be called with ThreadBase::mLock held
2896void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2897{
2898}
2899
2900// checkForNewParameters_l() must be called with ThreadBase::mLock held
2901bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2902{
2903 bool reconfig = false;
2904
Eric Laurent8fce46a2009-08-04 09:45:33 -07002905 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002906 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002907 String8 keyValuePair = mNewParameters[0];
2908 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002909 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002910
Eric Laurenta553c252009-07-17 12:17:14 -07002911 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2912 // do not accept frame count changes if tracks are open as the track buffer
2913 // size depends on frame count and correct behavior would not be garantied
2914 // if frame count is changed after track creation
2915 if (!mTracks.isEmpty()) {
2916 status = INVALID_OPERATION;
2917 } else {
2918 reconfig = true;
2919 }
2920 }
2921 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002922 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002923 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002924 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002925 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002926 mStandby = true;
2927 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002928 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002929 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002930 }
2931 if (status == NO_ERROR && reconfig) {
2932 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002933 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002934 }
2935 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002936
2937 mNewParameters.removeAt(0);
2938
Eric Laurenta553c252009-07-17 12:17:14 -07002939 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002940 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002941 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2942 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002943 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002944 }
2945 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002946}
2947
Eric Laurent059b4be2009-11-09 23:32:22 -08002948uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002949{
2950 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002951 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08002952 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08002953 } else {
2954 time = 10000;
2955 }
2956 return time;
2957}
2958
2959uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2960{
2961 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002962 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002963 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002964 } else {
2965 time = 10000;
2966 }
2967 return time;
2968}
2969
Eric Laurent8448a792010-08-18 18:13:17 -07002970uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2971{
2972 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002973 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002974 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2975 } else {
2976 time = 10000;
2977 }
2978 return time;
2979}
2980
2981
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002982// ----------------------------------------------------------------------------
2983
Glenn Kastenefd511a2012-01-26 10:38:26 -08002984AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08002985 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kastenefd511a2012-01-26 10:38:26 -08002986 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2987 mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002988{
Eric Laurenta553c252009-07-17 12:17:14 -07002989 addOutputTrack(mainThread);
2990}
2991
2992AudioFlinger::DuplicatingThread::~DuplicatingThread()
2993{
Eric Laurent0a080292009-12-07 10:53:10 -08002994 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2995 mOutputTracks[i]->destroy();
2996 }
Eric Laurenta553c252009-07-17 12:17:14 -07002997}
2998
2999bool AudioFlinger::DuplicatingThread::threadLoop()
3000{
Eric Laurenta553c252009-07-17 12:17:14 -07003001 Vector< sp<Track> > tracksToRemove;
Glenn Kasten789fef12012-01-26 13:37:52 -08003002 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07003003 nsecs_t standbyTime = systemTime();
3004 size_t mixBufferSize = mFrameCount*mFrameSize;
3005 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07003006 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08003007 uint32_t activeSleepTime = activeSleepTimeUs();
3008 uint32_t idleSleepTime = idleSleepTimeUs();
3009 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07003010 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07003011
Eric Laurent6dbdc402011-07-22 09:04:31 -07003012 acquireWakeLock();
3013
Eric Laurenta553c252009-07-17 12:17:14 -07003014 while (!exitPending())
3015 {
3016 processConfigEvents();
3017
Eric Laurent059b4be2009-11-09 23:32:22 -08003018 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07003019 { // scope for the mLock
3020
3021 Mutex::Autolock _l(mLock);
3022
3023 if (checkForNewParameters_l()) {
3024 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003025 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08003026 activeSleepTime = activeSleepTimeUs();
3027 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07003028 }
3029
3030 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3031
3032 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3033 outputTracks.add(mOutputTracks[i]);
3034 }
3035
3036 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003037 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3038 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003039 if (!mStandby) {
3040 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07003041 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07003042 }
3043 mStandby = true;
3044 mBytesWritten = 0;
3045 }
3046
3047 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3048 // we're about to wait, flush the binder command buffer
3049 IPCThreadState::self()->flushCommands();
3050 outputTracks.clear();
3051
3052 if (exitPending()) break;
3053
Eric Laurent6dbdc402011-07-22 09:04:31 -07003054 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01003055 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07003056 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01003057 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07003058 acquireWakeLock_l();
3059
Eric Laurent71c44962012-01-17 19:20:12 -08003060 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenb737dbb2012-01-13 15:54:24 -08003061 if (!mMasterMute) {
Eric Laurenta553c252009-07-17 12:17:14 -07003062 char value[PROPERTY_VALUE_MAX];
3063 property_get("ro.audio.silent", value, "0");
3064 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00003065 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07003066 setMasterMute(true);
3067 }
3068 }
3069
3070 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08003071 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07003072 continue;
3073 }
3074 }
3075
Eric Laurent059b4be2009-11-09 23:32:22 -08003076 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07003077
3078 // prevent any changes in effect chain list and in each effect chain
3079 // during mixing and effect process as the audio buffers could be deleted
3080 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003081 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003082 }
Eric Laurenta553c252009-07-17 12:17:14 -07003083
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003084 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003085 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003086 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003087 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003088 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003089 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003090 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003091 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003092 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003093 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003094 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003095 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3096 sleepTime = activeSleepTime;
3097 } else {
3098 sleepTime = idleSleepTime;
3099 }
Eric Laurent62443f52009-10-05 20:29:18 -07003100 } else if (mBytesWritten != 0) {
3101 // flush remaining overflow buffers in output tracks
3102 for (size_t i = 0; i < outputTracks.size(); i++) {
3103 if (outputTracks[i]->isActive()) {
3104 sleepTime = 0;
3105 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003106 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003107 break;
3108 }
3109 }
Eric Laurenta553c252009-07-17 12:17:14 -07003110 }
3111 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003112
3113 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003114 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003115 }
3116 // sleepTime == 0 means we must write to audio hardware
3117 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003118 for (size_t i = 0; i < effectChains.size(); i ++) {
3119 effectChains[i]->process_l();
3120 }
3121 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003122 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003123
Eric Laurent62443f52009-10-05 20:29:18 -07003124 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003125 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003126 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003127 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003128 mStandby = false;
3129 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003130 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003131 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003132 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003133 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003134 }
3135
3136 // finally let go of all our tracks, without the lock held
3137 // since we can't guarantee the destructors won't acquire that
3138 // same lock.
3139 tracksToRemove.clear();
3140 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003141
3142 // Effect chains will be actually deleted here if they were removed from
3143 // mEffectChains list during mixing or effects processing
3144 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003145 }
3146
Eric Laurent6dbdc402011-07-22 09:04:31 -07003147 releaseWakeLock();
3148
Eric Laurenta553c252009-07-17 12:17:14 -07003149 return false;
3150}
3151
3152void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3153{
3154 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3155 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003156 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003157 mSampleRate,
3158 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003159 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003160 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003161 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003162 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003163 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003164 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003165 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003166 }
Eric Laurenta553c252009-07-17 12:17:14 -07003167}
3168
3169void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3170{
3171 Mutex::Autolock _l(mLock);
3172 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3173 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003174 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003175 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003176 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003177 return;
3178 }
3179 }
Steve Block71f2cf12011-10-20 11:56:00 +01003180 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003181}
3182
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003183void AudioFlinger::DuplicatingThread::updateWaitTime()
3184{
3185 mWaitTimeMs = UINT_MAX;
3186 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3187 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten706b6182012-01-20 13:44:40 -08003188 if (strong != 0) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003189 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3190 if (waitTimeMs < mWaitTimeMs) {
3191 mWaitTimeMs = waitTimeMs;
3192 }
3193 }
3194 }
3195}
3196
3197
3198bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3199{
3200 for (size_t i = 0; i < outputTracks.size(); i++) {
3201 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3202 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003203 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003204 return false;
3205 }
3206 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3207 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003208 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003209 return false;
3210 }
3211 }
3212 return true;
3213}
3214
3215uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3216{
3217 return (mWaitTimeMs * 1000) / 2;
3218}
3219
Eric Laurenta553c252009-07-17 12:17:14 -07003220// ----------------------------------------------------------------------------
3221
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003222// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003223AudioFlinger::ThreadBase::TrackBase::TrackBase(
3224 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003225 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003226 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003227 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003228 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003229 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003231 const sp<IMemory>& sharedBuffer,
3232 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003233 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003234 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003235 mClient(client),
Glenn Kastendc3ac852012-01-25 15:28:08 -08003236 mCblk(NULL),
3237 // mBuffer
3238 // mBufferEnd
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003239 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003240 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003241 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003242 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3243 mSessionId(sessionId)
Glenn Kastendc3ac852012-01-25 15:28:08 -08003244 // mChannelCount
3245 // mChannelMask
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003246{
Steve Block71f2cf12011-10-20 11:56:00 +01003247 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003248
Steve Block5baa3a62011-12-20 16:23:08 +00003249 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003250 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003251 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003252 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3253 if (sharedBuffer == 0) {
3254 size += bufferSize;
3255 }
3256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 if (client != NULL) {
3258 mCblkMemory = client->heap()->allocate(size);
3259 if (mCblkMemory != 0) {
3260 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kasten3694ec12012-01-27 16:47:15 -08003261 if (mCblk != NULL) { // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 new(mCblk) audio_track_cblk_t();
3263 // clear all buffers
3264 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003265 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003266 mChannelCount = channelCount;
3267 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 if (sharedBuffer == 0) {
3269 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3270 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3271 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003272 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003273 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 } else {
3275 mBuffer = sharedBuffer->pointer();
3276 }
3277 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 } else {
Steve Block3762c312012-01-06 19:20:56 +00003280 ALOGE("not enough memory for AudioTrack size=%u", size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 client->heap()->dump("AudioTrack");
3282 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 } else {
3285 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenc95ca2c2012-01-06 15:03:11 -08003286 // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 new(mCblk) audio_track_cblk_t();
3288 // clear all buffers
3289 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003290 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003291 mChannelCount = channelCount;
3292 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3294 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3295 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003296 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003297 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003300}
3301
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003302AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003303{
Glenn Kasten3694ec12012-01-27 16:47:15 -08003304 if (mCblk != NULL) {
Glenn Kastend9d68dc2012-02-03 10:24:48 -08003305 if (mClient == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003306 delete mCblk;
Glenn Kastend9d68dc2012-02-03 10:24:48 -08003307 } else {
3308 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Eric Laurenta553c252009-07-17 12:17:14 -07003309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 }
Glenn Kastenf31d0502012-01-25 15:27:15 -08003311 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten706b6182012-01-20 13:44:40 -08003312 if (mClient != 0) {
Glenn Kastendc3ac852012-01-25 15:28:08 -08003313 // Client destructor must run with AudioFlinger mutex locked
Eric Laurentb9481d82009-09-17 05:12:56 -07003314 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten706b6182012-01-20 13:44:40 -08003315 // If the client's reference count drops to zero, the associated destructor
3316 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3317 // relying on the automatic clear() at end of scope.
Eric Laurentb9481d82009-09-17 05:12:56 -07003318 mClient.clear();
3319 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003320}
3321
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003322void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003323{
Glenn Kastenc434c902011-12-13 11:53:26 -08003324 buffer->raw = NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003325 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003326 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003327 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003328}
3329
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003330bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003331 bool result;
3332 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003333
3334 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003335 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003336 ALOGV("stepServer failed acquiring cblk mutex");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003337 mFlags |= STEPSERVER_FAILED;
3338 }
3339 return result;
3340}
3341
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003342void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003343 audio_track_cblk_t* cblk = this->cblk();
3344
3345 cblk->user = 0;
3346 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003347 cblk->userBase = 0;
3348 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block71f2cf12011-10-20 11:56:00 +01003350 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003351}
3352
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003353int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003354 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003355}
3356
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003357void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003358 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003359 size_t frameSize = cblk->frameSize;
3360 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3361 int8_t *bufferEnd = bufferStart + frames * frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003362
3363 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003364 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenfaf354d2012-01-11 09:48:27 -08003365 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block3762c312012-01-06 19:20:56 +00003366 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 -07003367 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003368 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003369 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kasten3694ec12012-01-27 16:47:15 -08003370 return NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003371 }
3372
3373 return bufferStart;
3374}
3375
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003376// ----------------------------------------------------------------------------
3377
Eric Laurenta553c252009-07-17 12:17:14 -07003378// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3379AudioFlinger::PlaybackThread::Track::Track(
3380 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003381 const sp<Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08003382 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003383 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003384 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003385 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003386 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003387 const sp<IMemory>& sharedBuffer,
3388 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003389 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003390 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3391 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003392{
Eric Laurent8a77a992009-09-09 05:16:08 -07003393 if (mCblk != NULL) {
3394 sp<ThreadBase> baseThread = thread.promote();
3395 if (baseThread != 0) {
3396 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3397 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003398 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003399 }
Steve Block71f2cf12011-10-20 11:56:00 +01003400 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003401 if (mName < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003402 ALOGE("no more track names available");
Eric Laurent8a77a992009-09-09 05:16:08 -07003403 }
Eric Laurent8a77a992009-09-09 05:16:08 -07003404 mStreamType = streamType;
3405 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3406 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003407 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003408 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003409}
3410
Eric Laurenta553c252009-07-17 12:17:14 -07003411AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003412{
Steve Block71f2cf12011-10-20 11:56:00 +01003413 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003414 sp<ThreadBase> thread = mThread.promote();
3415 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003416 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003417 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003418 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003419}
3420
Eric Laurenta553c252009-07-17 12:17:14 -07003421void AudioFlinger::PlaybackThread::Track::destroy()
3422{
3423 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3424 // by removing it from mTracks vector, so there is a risk that this Tracks's
3425 // desctructor is called. As the destructor needs to lock mLock,
3426 // we must acquire a strong reference on this Track before locking mLock
3427 // here so that the destructor is called only when exiting this function.
3428 // On the other hand, as long as Track::destroy() is only called by
3429 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3430 // this Track with its member mTrack.
3431 sp<Track> keep(this);
3432 { // scope for mLock
3433 sp<ThreadBase> thread = mThread.promote();
3434 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003435 if (!isOutputTrack()) {
3436 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003437 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003438 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003439 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003440
3441 // to track the speaker usage
3442 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003443 }
3444 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003445 }
Eric Laurenta553c252009-07-17 12:17:14 -07003446 Mutex::Autolock _l(thread->mLock);
3447 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3448 playbackThread->destroyTrack_l(this);
3449 }
3450 }
3451}
3452
3453void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003454{
Glenn Kastenbc4de882012-01-17 14:39:34 -08003455 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003456 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 -07003457 mName - AudioMixer::TRACK0,
Glenn Kasten706b6182012-01-20 13:44:40 -08003458 (mClient == 0) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003459 mStreamType,
3460 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003461 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003462 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003463 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003464 mState,
3465 mMute,
3466 mFillingUpStatus,
3467 mCblk->sampleRate,
Glenn Kasten0632bad2012-01-17 12:20:54 -08003468 vlr & 0xFFFF,
3469 vlr >> 16,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003470 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003471 mCblk->user,
3472 (int)mMainBuffer,
3473 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003474}
3475
Eric Laurenta553c252009-07-17 12:17:14 -07003476status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003477{
3478 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003479 uint32_t framesReady;
3480 uint32_t framesReq = buffer->frameCount;
3481
3482 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003483 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3484 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003485 ALOGV("stepServer recovered");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003486 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3487 }
3488
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003489 framesReady = cblk->framesReady();
3490
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003491 if (CC_LIKELY(framesReady)) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003492 uint32_t s = cblk->server;
3493 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3494
3495 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3496 if (framesReq > framesReady) {
3497 framesReq = framesReady;
3498 }
3499 if (s + framesReq > bufferEnd) {
3500 framesReq = bufferEnd - s;
3501 }
3502
3503 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003504 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003505
3506 buffer->frameCount = framesReq;
3507 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003508 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003509
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003510getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003511 buffer->raw = NULL;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003512 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003513 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 -07003514 return NOT_ENOUGH_DATA;
3515}
3516
Eric Laurenta553c252009-07-17 12:17:14 -07003517bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003518 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003519
3520 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003521 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003522 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003523 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003524 return true;
3525 }
3526 return false;
3527}
3528
Eric Laurenta553c252009-07-17 12:17:14 -07003529status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003530{
Eric Laurent49f02be2009-11-19 09:00:56 -08003531 status_t status = NO_ERROR;
Steve Block71f2cf12011-10-20 11:56:00 +01003532 ALOGV("start(%d), calling thread %d session %d",
Eric Laurent0d7e0482010-07-19 06:24:46 -07003533 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003534 sp<ThreadBase> thread = mThread.promote();
3535 if (thread != 0) {
3536 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003537 track_state state = mState;
Eric Laurent49f02be2009-11-19 09:00:56 -08003538 // here the track could be either new, or restarted
3539 // in both cases "unstop" the track
3540 if (mState == PAUSED) {
3541 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003542 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003543 } else {
3544 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003545 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003546 }
3547
3548 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3549 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003550 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003551 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003552 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003553 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003554
3555 // to track the speaker usage
3556 if (status == NO_ERROR) {
3557 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3558 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003559 }
3560 if (status == NO_ERROR) {
3561 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3562 playbackThread->addTrack_l(this);
3563 } else {
3564 mState = state;
3565 }
3566 } else {
3567 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003568 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003569 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003570}
3571
Eric Laurenta553c252009-07-17 12:17:14 -07003572void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003573{
Steve Block71f2cf12011-10-20 11:56:00 +01003574 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003575 sp<ThreadBase> thread = mThread.promote();
3576 if (thread != 0) {
3577 Mutex::Autolock _l(thread->mLock);
Glenn Kasten56356202012-01-26 13:39:18 -08003578 track_state state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003579 if (mState > STOPPED) {
3580 mState = STOPPED;
3581 // If the track is not active (PAUSED and buffers full), flush buffers
3582 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3583 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3584 reset();
3585 }
Steve Block71f2cf12011-10-20 11:56:00 +01003586 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003587 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003588 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3589 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003590 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003591 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003592 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003593 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003594
3595 // to track the speaker usage
3596 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003597 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003598 }
3599}
3600
Eric Laurenta553c252009-07-17 12:17:14 -07003601void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003602{
Steve Block71f2cf12011-10-20 11:56:00 +01003603 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003604 sp<ThreadBase> thread = mThread.promote();
3605 if (thread != 0) {
3606 Mutex::Autolock _l(thread->mLock);
3607 if (mState == ACTIVE || mState == RESUMING) {
3608 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003609 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003610 if (!isOutputTrack()) {
3611 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003612 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003613 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003614 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003615 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003616
3617 // to track the speaker usage
3618 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003619 }
Eric Laurenta553c252009-07-17 12:17:14 -07003620 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003621 }
3622}
3623
Eric Laurenta553c252009-07-17 12:17:14 -07003624void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003625{
Steve Block71f2cf12011-10-20 11:56:00 +01003626 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003627 sp<ThreadBase> thread = mThread.promote();
3628 if (thread != 0) {
3629 Mutex::Autolock _l(thread->mLock);
3630 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3631 return;
3632 }
3633 // No point remaining in PAUSED state after a flush => go to
3634 // STOPPED state
3635 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003636
Eric Laurentae29b762011-03-28 18:37:07 -07003637 // do not reset the track if it is still in the process of being stopped or paused.
3638 // this will be done by prepareTracks_l() when the track is stopped.
3639 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3640 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3641 reset();
3642 }
Eric Laurenta553c252009-07-17 12:17:14 -07003643 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003644}
3645
Eric Laurenta553c252009-07-17 12:17:14 -07003646void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003647{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003648 // Do not reset twice to avoid discarding data written just after a flush and before
3649 // the audioflinger thread detects the track is stopped.
3650 if (!mResetDone) {
3651 TrackBase::reset();
3652 // Force underrun condition to avoid false underrun callback until first data is
3653 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003654 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3655 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003656 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003657 mResetDone = true;
3658 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003659}
3660
Eric Laurenta553c252009-07-17 12:17:14 -07003661void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003662{
3663 mMute = muted;
3664}
3665
Eric Laurent65b65452010-06-01 23:49:17 -07003666status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3667{
3668 status_t status = DEAD_OBJECT;
3669 sp<ThreadBase> thread = mThread.promote();
3670 if (thread != 0) {
3671 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3672 status = playbackThread->attachAuxEffect(this, EffectId);
3673 }
3674 return status;
3675}
3676
3677void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3678{
3679 mAuxEffectId = EffectId;
3680 mAuxBuffer = buffer;
3681}
3682
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003683// ----------------------------------------------------------------------------
3684
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003685// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003686AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3687 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003690 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003691 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003693 uint32_t flags,
3694 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003695 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003696 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003697 mOverflow(false)
3698{
Eric Laurent8a77a992009-09-09 05:16:08 -07003699 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003700 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003701 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003702 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003703 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003704 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003705 } else {
3706 mCblk->frameSize = sizeof(int8_t);
3707 }
3708 }
Eric Laurenta553c252009-07-17 12:17:14 -07003709}
3710
3711AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712{
Eric Laurent49f02be2009-11-19 09:00:56 -08003713 sp<ThreadBase> thread = mThread.promote();
3714 if (thread != 0) {
3715 AudioSystem::releaseInput(thread->id());
3716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717}
3718
Eric Laurenta553c252009-07-17 12:17:14 -07003719status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720{
3721 audio_track_cblk_t* cblk = this->cblk();
3722 uint32_t framesAvail;
3723 uint32_t framesReq = buffer->frameCount;
3724
3725 // Check if last stepServer failed, try to step now
3726 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3727 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003728 ALOGV("stepServer recovered");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3730 }
3731
3732 framesAvail = cblk->framesAvailable_l();
3733
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003734 if (CC_LIKELY(framesAvail)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 uint32_t s = cblk->server;
3736 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3737
3738 if (framesReq > framesAvail) {
3739 framesReq = framesAvail;
3740 }
3741 if (s + framesReq > bufferEnd) {
3742 framesReq = bufferEnd - s;
3743 }
3744
3745 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003746 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747
3748 buffer->frameCount = framesReq;
3749 return NO_ERROR;
3750 }
3751
3752getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003753 buffer->raw = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 buffer->frameCount = 0;
3755 return NOT_ENOUGH_DATA;
3756}
3757
Eric Laurenta553c252009-07-17 12:17:14 -07003758status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759{
Eric Laurenta553c252009-07-17 12:17:14 -07003760 sp<ThreadBase> thread = mThread.promote();
3761 if (thread != 0) {
3762 RecordThread *recordThread = (RecordThread *)thread.get();
3763 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003764 } else {
3765 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767}
3768
Eric Laurenta553c252009-07-17 12:17:14 -07003769void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770{
Eric Laurenta553c252009-07-17 12:17:14 -07003771 sp<ThreadBase> thread = mThread.promote();
3772 if (thread != 0) {
3773 RecordThread *recordThread = (RecordThread *)thread.get();
3774 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003775 TrackBase::reset();
3776 // Force overerrun condition to avoid false overrun callback until first data is
3777 // read from buffer
3778 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780}
3781
Eric Laurent3fdb1262009-11-07 00:01:32 -08003782void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3783{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003784 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten706b6182012-01-20 13:44:40 -08003785 (mClient == 0) ? getpid() : mClient->pid(),
Eric Laurent3fdb1262009-11-07 00:01:32 -08003786 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003787 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003788 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003789 mFrameCount,
3790 mState,
3791 mCblk->sampleRate,
3792 mCblk->server,
3793 mCblk->user);
3794}
3795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796
3797// ----------------------------------------------------------------------------
3798
Eric Laurenta553c252009-07-17 12:17:14 -07003799AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3800 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003801 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08003803 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003804 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003806 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003807 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808{
Eric Laurenta553c252009-07-17 12:17:14 -07003809
3810 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003811 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003812 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003813 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Eric Laurent6c30a712009-08-10 23:22:32 -07003814 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003815 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01003816 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003817 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3818 mCblk, mBuffer, mCblk->buffers,
3819 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003820 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003821 ALOGW("Error creating output track on thread %p", playbackThread);
Eric Laurent6c30a712009-08-10 23:22:32 -07003822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823}
3824
Eric Laurenta553c252009-07-17 12:17:14 -07003825AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826{
Eric Laurent6c30a712009-08-10 23:22:32 -07003827 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828}
3829
Eric Laurenta553c252009-07-17 12:17:14 -07003830status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831{
3832 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003833 if (status != NO_ERROR) {
3834 return status;
3835 }
3836
3837 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 mRetryCount = 127;
3839 return status;
3840}
3841
Eric Laurenta553c252009-07-17 12:17:14 -07003842void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843{
3844 Track::stop();
3845 clearBufferQueue();
3846 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003847 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003848}
3849
Eric Laurenta553c252009-07-17 12:17:14 -07003850bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851{
3852 Buffer *pInBuffer;
3853 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003854 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003855 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 inBuffer.frameCount = frames;
3857 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003858
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003859 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003860
Eric Laurent62443f52009-10-05 20:29:18 -07003861 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003862 start();
3863 sp<ThreadBase> thread = mThread.promote();
3864 if (thread != 0) {
3865 MixerThread *mixerThread = (MixerThread *)thread.get();
3866 if (mCblk->frameCount > frames){
3867 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3868 uint32_t startFrames = (mCblk->frameCount - frames);
3869 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003870 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003871 pInBuffer->frameCount = startFrames;
3872 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003873 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003874 mBufferQueue.add(pInBuffer);
3875 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003876 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurenta553c252009-07-17 12:17:14 -07003877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 }
Eric Laurenta553c252009-07-17 12:17:14 -07003879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 }
3881
Eric Laurenta553c252009-07-17 12:17:14 -07003882 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 // First write pending buffers, then new data
3884 if (mBufferQueue.size()) {
3885 pInBuffer = mBufferQueue.itemAt(0);
3886 } else {
3887 pInBuffer = &inBuffer;
3888 }
Eric Laurenta553c252009-07-17 12:17:14 -07003889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 if (pInBuffer->frameCount == 0) {
3891 break;
3892 }
Eric Laurenta553c252009-07-17 12:17:14 -07003893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 if (mOutBuffer.frameCount == 0) {
3895 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003896 nsecs_t startTime = systemTime();
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003897 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01003898 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003899 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 break;
3901 }
Eric Laurenta553c252009-07-17 12:17:14 -07003902 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003903 if (waitTimeLeftMs >= waitTimeMs) {
3904 waitTimeLeftMs -= waitTimeMs;
3905 } else {
3906 waitTimeLeftMs = 0;
3907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
Eric Laurenta553c252009-07-17 12:17:14 -07003909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003911 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 mCblk->stepUser(outFrames);
3913 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003914 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003916 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 if (pInBuffer->frameCount == 0) {
3919 if (mBufferQueue.size()) {
3920 mBufferQueue.removeAt(0);
3921 delete [] pInBuffer->mBuffer;
3922 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01003923 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 -08003924 } else {
3925 break;
3926 }
3927 }
3928 }
Eric Laurenta553c252009-07-17 12:17:14 -07003929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 // If we could not write all frames, allocate a buffer and queue it for next time.
3931 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003932 sp<ThreadBase> thread = mThread.promote();
3933 if (thread != 0 && !thread->standby()) {
3934 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3935 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003936 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003937 pInBuffer->frameCount = inBuffer.frameCount;
3938 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003939 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003940 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01003941 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003942 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003943 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 }
3946 }
Eric Laurenta553c252009-07-17 12:17:14 -07003947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003949 // 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 -08003950 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003951 if (frames == 0 && mBufferQueue.size() == 0) {
3952 if (mCblk->user < mCblk->frameCount) {
3953 frames = mCblk->frameCount - mCblk->user;
3954 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003955 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003956 pInBuffer->frameCount = frames;
3957 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003958 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003959 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003960 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003961 stop();
3962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 }
3964
Eric Laurenta553c252009-07-17 12:17:14 -07003965 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966}
3967
Eric Laurenta553c252009-07-17 12:17:14 -07003968status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969{
3970 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 status_t result;
3972 audio_track_cblk_t* cblk = mCblk;
3973 uint32_t framesReq = buffer->frameCount;
3974
Steve Block71f2cf12011-10-20 11:56:00 +01003975// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 uint32_t framesAvail = cblk->framesAvailable();
3979
Eric Laurenta553c252009-07-17 12:17:14 -07003980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003982 Mutex::Autolock _l(cblk->lock);
3983 goto start_loop_here;
3984 while (framesAvail == 0) {
3985 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003986 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01003987 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003988 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07003989 }
3990 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3991 if (result != NO_ERROR) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08003992 return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07003993 }
3994 // read the server count again
3995 start_loop_here:
3996 framesAvail = cblk->framesAvailable_l();
3997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 }
3999
Eric Laurenta553c252009-07-17 12:17:14 -07004000// if (framesAvail < framesReq) {
Glenn Kasten34f9f8b2012-01-20 17:00:00 -08004001// return NO_MORE_BUFFERS;
Eric Laurenta553c252009-07-17 12:17:14 -07004002// }
4003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 if (framesReq > framesAvail) {
4005 framesReq = framesAvail;
4006 }
4007
4008 uint32_t u = cblk->user;
4009 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4010
4011 if (u + framesReq > bufferEnd) {
4012 framesReq = bufferEnd - u;
4013 }
4014
4015 buffer->frameCount = framesReq;
4016 buffer->raw = (void *)cblk->buffer(u);
4017 return NO_ERROR;
4018}
4019
4020
Eric Laurenta553c252009-07-17 12:17:14 -07004021void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022{
4023 size_t size = mBufferQueue.size();
4024 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 for (size_t i = 0; i < size; i++) {
4027 pBuffer = mBufferQueue.itemAt(i);
4028 delete [] pBuffer->mBuffer;
4029 delete pBuffer;
4030 }
4031 mBufferQueue.clear();
4032}
4033
4034// ----------------------------------------------------------------------------
4035
4036AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4037 : RefBase(),
4038 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08004039 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 mPid(pid)
4041{
4042 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4043}
4044
Eric Laurentb9481d82009-09-17 05:12:56 -07004045// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046AudioFlinger::Client::~Client()
4047{
Eric Laurentb9481d82009-09-17 05:12:56 -07004048 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049}
4050
Glenn Kasten1f812f72012-01-30 10:15:48 -08004051sp<MemoryDealer> AudioFlinger::Client::heap() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052{
4053 return mMemoryDealer;
4054}
4055
4056// ----------------------------------------------------------------------------
4057
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004058AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4059 const sp<IAudioFlingerClient>& client,
4060 pid_t pid)
Glenn Kastendc3ac852012-01-25 15:28:08 -08004061 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004062{
4063}
4064
4065AudioFlinger::NotificationClient::~NotificationClient()
4066{
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004067}
4068
4069void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4070{
4071 sp<NotificationClient> keep(this);
4072 {
4073 mAudioFlinger->removeNotificationClient(mPid);
4074 }
4075}
4076
4077// ----------------------------------------------------------------------------
4078
Eric Laurenta553c252009-07-17 12:17:14 -07004079AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004080 : BnAudioTrack(),
4081 mTrack(track)
4082{
4083}
4084
4085AudioFlinger::TrackHandle::~TrackHandle() {
4086 // just stop the track on deletion, associated resources
4087 // will be freed from the main thread once all pending buffers have
4088 // been played. Unless it's not in the active track list, in which
4089 // case we free everything now...
4090 mTrack->destroy();
4091}
4092
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004093sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4094 return mTrack->getCblk();
4095}
4096
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004097status_t AudioFlinger::TrackHandle::start() {
4098 return mTrack->start();
4099}
4100
4101void AudioFlinger::TrackHandle::stop() {
4102 mTrack->stop();
4103}
4104
4105void AudioFlinger::TrackHandle::flush() {
4106 mTrack->flush();
4107}
4108
4109void AudioFlinger::TrackHandle::mute(bool e) {
4110 mTrack->mute(e);
4111}
4112
4113void AudioFlinger::TrackHandle::pause() {
4114 mTrack->pause();
4115}
4116
Eric Laurent65b65452010-06-01 23:49:17 -07004117status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4118{
4119 return mTrack->attachAuxEffect(EffectId);
4120}
4121
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004122status_t AudioFlinger::TrackHandle::onTransact(
4123 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4124{
4125 return BnAudioTrack::onTransact(code, data, reply, flags);
4126}
4127
4128// ----------------------------------------------------------------------------
4129
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004130sp<IAudioRecord> AudioFlinger::openRecord(
4131 pid_t pid,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004132 audio_io_handle_t input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004133 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004134 audio_format_t format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004135 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004136 int frameCount,
4137 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004138 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004139 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004140{
Eric Laurenta553c252009-07-17 12:17:14 -07004141 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004142 sp<RecordHandle> recordHandle;
4143 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004144 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004145 RecordThread *thread;
4146 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004147 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004148
4149 // check calling permissions
4150 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004151 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004152 goto Exit;
4153 }
4154
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004155 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004156 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004157 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004158 thread = checkRecordThread_l(input);
4159 if (thread == NULL) {
4160 lStatus = BAD_VALUE;
4161 goto Exit;
4162 }
4163
Glenn Kasten803a86a2012-01-25 14:28:29 -08004164 client = registerPid_l(pid);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004165
Eric Laurent65b65452010-06-01 23:49:17 -07004166 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004167 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004168 lSessionId = *sessionId;
4169 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004170 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004171 if (sessionId != NULL) {
4172 *sessionId = lSessionId;
4173 }
4174 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004175 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004176 recordTrack = thread->createRecordTrack_l(client,
4177 sampleRate,
4178 format,
4179 channelMask,
4180 frameCount,
4181 flags,
4182 lSessionId,
4183 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004184 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004185 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004186 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4187 // destructor is called by the TrackBase destructor with mLock held
4188 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004189 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 goto Exit;
4191 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004192
4193 // return to handle to client
4194 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004195 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004196
4197Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004198 if (status) {
4199 *status = lStatus;
4200 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004201 return recordHandle;
4202}
4203
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004204// ----------------------------------------------------------------------------
4205
Eric Laurenta553c252009-07-17 12:17:14 -07004206AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004207 : BnAudioRecord(),
4208 mRecordTrack(recordTrack)
4209{
4210}
4211
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004212AudioFlinger::RecordHandle::~RecordHandle() {
4213 stop();
4214}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004215
Glenn Kasten0ae4d972012-01-26 13:40:12 -08004216sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4217 return mRecordTrack->getCblk();
4218}
4219
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004220status_t AudioFlinger::RecordHandle::start() {
Steve Block71f2cf12011-10-20 11:56:00 +01004221 ALOGV("RecordHandle::start()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004222 return mRecordTrack->start();
4223}
4224
4225void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004226 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004227 mRecordTrack->stop();
4228}
4229
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004230status_t AudioFlinger::RecordHandle::onTransact(
4231 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4232{
4233 return BnAudioRecord::onTransact(code, data, reply, flags);
4234}
4235
4236// ----------------------------------------------------------------------------
4237
Eric Laurent464d5b32011-06-17 21:29:58 -07004238AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4239 AudioStreamIn *input,
4240 uint32_t sampleRate,
4241 uint32_t channels,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004242 audio_io_handle_t id,
Eric Laurent464d5b32011-06-17 21:29:58 -07004243 uint32_t device) :
Glenn Kastenefd511a2012-01-26 10:38:26 -08004244 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kastendc3ac852012-01-25 15:28:08 -08004245 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4246 // mRsmpInIndex and mInputBytes set by readInputParameters()
4247 mReqChannelCount(popcount(channels)),
4248 mReqSampleRate(sampleRate)
4249 // mBytesRead is only meaningful while active, and so is cleared in start()
4250 // (but might be better to also clear here for dump?)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004251{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004252 snprintf(mName, kNameLength, "AudioIn_%d", id);
4253
Eric Laurenta553c252009-07-17 12:17:14 -07004254 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004255}
4256
Eric Laurenta553c252009-07-17 12:17:14 -07004257
4258AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004259{
Eric Laurenta553c252009-07-17 12:17:14 -07004260 delete[] mRsmpInBuffer;
Glenn Kasten2589cf92012-01-27 18:08:45 -08004261 delete mResampler;
4262 delete[] mRsmpOutBuffer;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004263}
4264
Eric Laurenta553c252009-07-17 12:17:14 -07004265void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004266{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004267 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004268}
Eric Laurent49f02be2009-11-19 09:00:56 -08004269
Eric Laurent828b9772011-08-07 16:32:26 -07004270status_t AudioFlinger::RecordThread::readyToRun()
4271{
4272 status_t status = initCheck();
Steve Block8564c8d2012-01-05 23:22:43 +00004273 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurent828b9772011-08-07 16:32:26 -07004274 return status;
4275}
4276
Eric Laurenta553c252009-07-17 12:17:14 -07004277bool AudioFlinger::RecordThread::threadLoop()
4278{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004279 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004280 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004281 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004282
Eric Laurent4712baa2010-09-30 16:12:31 -07004283 nsecs_t lastWarning = 0;
4284
Eric Laurent6dbdc402011-07-22 09:04:31 -07004285 acquireWakeLock();
4286
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004287 // start recording
4288 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004289
Eric Laurenta553c252009-07-17 12:17:14 -07004290 processConfigEvents();
4291
4292 { // scope for mLock
4293 Mutex::Autolock _l(mLock);
4294 checkForNewParameters_l();
4295 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4296 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004297 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004298 mStandby = true;
4299 }
4300
4301 if (exitPending()) break;
4302
Eric Laurent6dbdc402011-07-22 09:04:31 -07004303 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004304 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004305 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004306 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004307 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004308 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004309 continue;
4310 }
4311 if (mActiveTrack != 0) {
4312 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004313 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004314 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004315 mStandby = true;
4316 }
Eric Laurenta553c252009-07-17 12:17:14 -07004317 mActiveTrack.clear();
4318 mStartStopCond.broadcast();
4319 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004320 if (mReqChannelCount != mActiveTrack->channelCount()) {
4321 mActiveTrack.clear();
Eric Laurent9cc489a2009-12-05 05:20:01 -08004322 mStartStopCond.broadcast();
4323 } else if (mBytesRead != 0) {
4324 // record start succeeds only if first read from audio input
4325 // succeeds
4326 if (mBytesRead > 0) {
4327 mActiveTrack->mState = TrackBase::ACTIVE;
4328 } else {
4329 mActiveTrack.clear();
4330 }
4331 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004332 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004333 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004334 }
Eric Laurenta553c252009-07-17 12:17:14 -07004335 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004336 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004337 }
4338
4339 if (mActiveTrack != 0) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004340 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4341 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004342 unlockEffectChains(effectChains);
4343 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004344 continue;
4345 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004346 for (size_t i = 0; i < effectChains.size(); i ++) {
4347 effectChains[i]->process_l();
4348 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004349
Eric Laurenta553c252009-07-17 12:17:14 -07004350 buffer.frameCount = mFrameCount;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004351 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004352 size_t framesOut = buffer.frameCount;
Glenn Kastenc434c902011-12-13 11:53:26 -08004353 if (mResampler == NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004354 // no resampling
4355 while (framesOut) {
4356 size_t framesIn = mFrameCount - mRsmpInIndex;
4357 if (framesIn) {
4358 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4359 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4360 if (framesIn > framesOut)
4361 framesIn = framesOut;
4362 mRsmpInIndex += framesIn;
4363 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004364 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004365 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004366 memcpy(dst, src, framesIn * mFrameSize);
4367 } else {
4368 int16_t *src16 = (int16_t *)src;
4369 int16_t *dst16 = (int16_t *)dst;
4370 if (mChannelCount == 1) {
4371 while (framesIn--) {
4372 *dst16++ = *src16;
4373 *dst16++ = *src16++;
4374 }
4375 } else {
4376 while (framesIn--) {
4377 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4378 src16 += 2;
4379 }
4380 }
4381 }
4382 }
4383 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004384 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004385 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004386 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004387 framesOut = 0;
4388 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004389 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004390 mRsmpInIndex = 0;
4391 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004392 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004393 ALOGE("Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08004394 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004395 // Force input into standby so that it tries to
4396 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004397 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004398 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004399 }
Eric Laurenta553c252009-07-17 12:17:14 -07004400 mRsmpInIndex = mFrameCount;
4401 framesOut = 0;
4402 buffer.frameCount = 0;
4403 }
4404 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004405 }
4406 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004407 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004408
Eric Laurenta553c252009-07-17 12:17:14 -07004409 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4410 // alter output frame count as if we were expecting stereo samples
4411 if (mChannelCount == 1 && mReqChannelCount == 1) {
4412 framesOut >>= 1;
4413 }
4414 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4415 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4416 // are 32 bit aligned which should be always true.
4417 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten490909d2011-12-15 09:52:39 -08004418 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004419 // the resampler always outputs stereo samples: do post stereo to mono conversion
4420 int16_t *src = (int16_t *)mRsmpOutBuffer;
4421 int16_t *dst = buffer.i16;
4422 while (framesOut--) {
4423 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4424 src += 2;
4425 }
4426 } else {
Glenn Kasten490909d2011-12-15 09:52:39 -08004427 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004428 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004429
Eric Laurenta553c252009-07-17 12:17:14 -07004430 }
4431 mActiveTrack->releaseBuffer(&buffer);
4432 mActiveTrack->overflow();
4433 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004434 // client isn't retrieving buffers fast enough
4435 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004436 if (!mActiveTrack->setOverflow()) {
4437 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004438 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00004439 ALOGW("RecordThread: buffer overflow");
Eric Laurent4712baa2010-09-30 16:12:31 -07004440 lastWarning = now;
4441 }
4442 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004443 // Release the processor for a while before asking for a new buffer.
4444 // This will give the application more chance to read from the buffer and
4445 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004446 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004447 }
4448 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004449 // enable changes in effect chain
4450 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004451 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004452 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004453
Eric Laurenta553c252009-07-17 12:17:14 -07004454 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004455 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004456 }
Eric Laurenta553c252009-07-17 12:17:14 -07004457 mActiveTrack.clear();
4458
Eric Laurent49f02be2009-11-19 09:00:56 -08004459 mStartStopCond.broadcast();
4460
Eric Laurent6dbdc402011-07-22 09:04:31 -07004461 releaseWakeLock();
4462
Steve Block71f2cf12011-10-20 11:56:00 +01004463 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004464 return false;
4465}
4466
Eric Laurent464d5b32011-06-17 21:29:58 -07004467
4468sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4469 const sp<AudioFlinger::Client>& client,
4470 uint32_t sampleRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004471 audio_format_t format,
Eric Laurent464d5b32011-06-17 21:29:58 -07004472 int channelMask,
4473 int frameCount,
4474 uint32_t flags,
4475 int sessionId,
4476 status_t *status)
4477{
4478 sp<RecordTrack> track;
4479 status_t lStatus;
4480
4481 lStatus = initCheck();
4482 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00004483 ALOGE("Audio driver not initialized.");
Eric Laurent464d5b32011-06-17 21:29:58 -07004484 goto Exit;
4485 }
4486
4487 { // scope for mLock
4488 Mutex::Autolock _l(mLock);
4489
4490 track = new RecordTrack(this, client, sampleRate,
4491 format, channelMask, frameCount, flags, sessionId);
4492
Glenn Kasten706b6182012-01-20 13:44:40 -08004493 if (track->getCblk() == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004494 lStatus = NO_MEMORY;
4495 goto Exit;
4496 }
4497
4498 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004499 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4500 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004501 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004502 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4503 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004504 }
4505 lStatus = NO_ERROR;
4506
4507Exit:
4508 if (status) {
4509 *status = lStatus;
4510 }
4511 return track;
4512}
4513
Eric Laurenta553c252009-07-17 12:17:14 -07004514status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004515{
Steve Block71f2cf12011-10-20 11:56:00 +01004516 ALOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004517 sp <ThreadBase> strongMe = this;
4518 status_t status = NO_ERROR;
4519 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004520 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004521 if (mActiveTrack != 0) {
4522 if (recordTrack != mActiveTrack.get()) {
4523 status = -EBUSY;
4524 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004525 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004526 }
4527 return status;
4528 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004529
Eric Laurent49f02be2009-11-19 09:00:56 -08004530 recordTrack->mState = TrackBase::IDLE;
4531 mActiveTrack = recordTrack;
4532 mLock.unlock();
4533 status_t status = AudioSystem::startInput(mId);
4534 mLock.lock();
4535 if (status != NO_ERROR) {
4536 mActiveTrack.clear();
4537 return status;
4538 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004539 mRsmpInIndex = mFrameCount;
4540 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004541 if (mResampler != NULL) {
4542 mResampler->reset();
4543 }
4544 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004545 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004546 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004547 mWaitWorkCV.signal();
4548 // do not wait for mStartStopCond if exiting
Glenn Kasten761286f2012-01-06 08:39:38 -08004549 if (exitPending()) {
Eric Laurent49f02be2009-11-19 09:00:56 -08004550 mActiveTrack.clear();
4551 status = INVALID_OPERATION;
4552 goto startError;
4553 }
4554 mStartStopCond.wait(mLock);
4555 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01004556 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004557 status = BAD_VALUE;
4558 goto startError;
4559 }
Steve Block71f2cf12011-10-20 11:56:00 +01004560 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004561 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004562 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004563startError:
4564 AudioSystem::stopInput(mId);
4565 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004566}
4567
Eric Laurenta553c252009-07-17 12:17:14 -07004568void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01004569 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004570 sp <ThreadBase> strongMe = this;
4571 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004572 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004573 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4574 mActiveTrack->mState = TrackBase::PAUSING;
4575 // do not wait for mStartStopCond if exiting
Glenn Kasten761286f2012-01-06 08:39:38 -08004576 if (exitPending()) {
Eric Laurent49f02be2009-11-19 09:00:56 -08004577 return;
4578 }
4579 mStartStopCond.wait(mLock);
4580 // if we have been restarted, recordTrack == mActiveTrack.get() here
4581 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4582 mLock.unlock();
4583 AudioSystem::stopInput(mId);
4584 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01004585 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004586 }
4587 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004588 }
4589}
4590
Eric Laurenta553c252009-07-17 12:17:14 -07004591status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592{
4593 const size_t SIZE = 256;
4594 char buffer[SIZE];
4595 String8 result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596
Eric Laurent3fdb1262009-11-07 00:01:32 -08004597 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4598 result.append(buffer);
4599
4600 if (mActiveTrack != 0) {
4601 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004602 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004603 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004605
4606 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4607 result.append(buffer);
4608 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4609 result.append(buffer);
Glenn Kastenc434c902011-12-13 11:53:26 -08004610 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Eric Laurent3fdb1262009-11-07 00:01:32 -08004611 result.append(buffer);
4612 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4613 result.append(buffer);
4614 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4615 result.append(buffer);
4616
4617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004618 } else {
4619 result.append("No record client\n");
4620 }
4621 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004622
4623 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004624 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 return NO_ERROR;
4627}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004628
Eric Laurenta553c252009-07-17 12:17:14 -07004629status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4630{
4631 size_t framesReq = buffer->frameCount;
4632 size_t framesReady = mFrameCount - mRsmpInIndex;
4633 int channelCount;
4634
4635 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004636 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004637 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004638 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08004639 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004640 // Force input into standby so that it tries to
4641 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004642 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004643 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004644 }
Glenn Kastenc434c902011-12-13 11:53:26 -08004645 buffer->raw = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004646 buffer->frameCount = 0;
4647 return NOT_ENOUGH_DATA;
4648 }
4649 mRsmpInIndex = 0;
4650 framesReady = mFrameCount;
4651 }
4652
4653 if (framesReq > framesReady) {
4654 framesReq = framesReady;
4655 }
4656
4657 if (mChannelCount == 1 && mReqChannelCount == 2) {
4658 channelCount = 1;
4659 } else {
4660 channelCount = 2;
4661 }
4662 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4663 buffer->frameCount = framesReq;
4664 return NO_ERROR;
4665}
4666
4667void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4668{
4669 mRsmpInIndex += buffer->frameCount;
4670 buffer->frameCount = 0;
4671}
4672
4673bool AudioFlinger::RecordThread::checkForNewParameters_l()
4674{
4675 bool reconfig = false;
4676
Eric Laurent8fce46a2009-08-04 09:45:33 -07004677 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004678 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004679 String8 keyValuePair = mNewParameters[0];
4680 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004681 int value;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004682 audio_format_t reqFormat = mFormat;
Eric Laurenta553c252009-07-17 12:17:14 -07004683 int reqSamplingRate = mReqSampleRate;
4684 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004685
Eric Laurenta553c252009-07-17 12:17:14 -07004686 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4687 reqSamplingRate = value;
4688 reconfig = true;
4689 }
4690 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004691 reqFormat = (audio_format_t) value;
Eric Laurenta553c252009-07-17 12:17:14 -07004692 reconfig = true;
4693 }
4694 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004695 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004696 reconfig = true;
4697 }
4698 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4699 // do not accept frame count changes if tracks are open as the track buffer
4700 // size depends on frame count and correct behavior would not be garantied
4701 // if frame count is changed after track creation
4702 if (mActiveTrack != 0) {
4703 status = INVALID_OPERATION;
4704 } else {
4705 reconfig = true;
4706 }
4707 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004708 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4709 // forward device change to effects that have requested to be
4710 // aware of attached audio device.
4711 for (size_t i = 0; i < mEffectChains.size(); i++) {
4712 mEffectChains[i]->setDevice_l(value);
4713 }
4714 // store input device and output device but do not forward output device to audio HAL.
4715 // Note that status is ignored by the caller for output device
4716 // (see AudioFlinger::setParameters()
4717 if (value & AUDIO_DEVICE_OUT_ALL) {
4718 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4719 status = BAD_VALUE;
4720 } else {
4721 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004722 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4723 if (mTrack != NULL) {
4724 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004725 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004726 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4727 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4728 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004729 }
4730 mDevice |= (uint32_t)value;
4731 }
Eric Laurenta553c252009-07-17 12:17:14 -07004732 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004733 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004734 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004735 mInput->stream->common.standby(&mInput->stream->common);
4736 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004737 }
4738 if (reconfig) {
4739 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004740 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004741 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004742 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4743 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004744 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004745 status = NO_ERROR;
4746 }
4747 if (status == NO_ERROR) {
4748 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004749 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004750 }
4751 }
4752 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004753
4754 mNewParameters.removeAt(0);
4755
Eric Laurenta553c252009-07-17 12:17:14 -07004756 mParamStatus = status;
4757 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004758 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4759 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004760 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07004761 }
4762 return reconfig;
4763}
4764
4765String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4766{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004767 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004768 String8 out_s8 = String8();
4769
4770 Mutex::Autolock _l(mLock);
4771 if (initCheck() != NO_ERROR) {
4772 return out_s8;
4773 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004774
Dima Zavin31f188892011-04-18 16:57:27 -07004775 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004776 out_s8 = String8(s);
4777 free(s);
4778 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004779}
4780
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004781void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004782 AudioSystem::OutputDescriptor desc;
Glenn Kasten3694ec12012-01-27 16:47:15 -08004783 void *param2 = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004784
4785 switch (event) {
4786 case AudioSystem::INPUT_OPENED:
4787 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004788 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004789 desc.samplingRate = mSampleRate;
4790 desc.format = mFormat;
4791 desc.frameCount = mFrameCount;
4792 desc.latency = 0;
4793 param2 = &desc;
4794 break;
4795
4796 case AudioSystem::INPUT_CLOSED:
4797 default:
4798 break;
4799 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004800 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004801}
4802
4803void AudioFlinger::RecordThread::readInputParameters()
4804{
Glenn Kasten2589cf92012-01-27 18:08:45 -08004805 delete mRsmpInBuffer;
4806 // mRsmpInBuffer is always assigned a new[] below
4807 delete mRsmpOutBuffer;
4808 mRsmpOutBuffer = NULL;
4809 delete mResampler;
Glenn Kastenc434c902011-12-13 11:53:26 -08004810 mResampler = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004811
Dima Zavin31f188892011-04-18 16:57:27 -07004812 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004813 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4814 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004815 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenfaf354d2012-01-11 09:48:27 -08004816 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin31f188892011-04-18 16:57:27 -07004817 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004818 mFrameCount = mInputBytes / mFrameSize;
4819 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4820
4821 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4822 {
4823 int channelCount;
4824 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4825 // stereo to mono post process as the resampler always outputs stereo.
4826 if (mChannelCount == 1 && mReqChannelCount == 2) {
4827 channelCount = 1;
4828 } else {
4829 channelCount = 2;
4830 }
4831 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4832 mResampler->setSampleRate(mSampleRate);
4833 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4834 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4835
4836 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4837 if (mChannelCount == 1 && mReqChannelCount == 1) {
4838 mFrameCount >>= 1;
4839 }
4840
4841 }
4842 mRsmpInIndex = mFrameCount;
4843}
4844
Eric Laurent47d0a922010-02-26 02:47:27 -08004845unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4846{
Eric Laurent828b9772011-08-07 16:32:26 -07004847 Mutex::Autolock _l(mLock);
4848 if (initCheck() != NO_ERROR) {
4849 return 0;
4850 }
4851
Dima Zavin31f188892011-04-18 16:57:27 -07004852 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004853}
4854
Eric Laurent464d5b32011-06-17 21:29:58 -07004855uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4856{
4857 Mutex::Autolock _l(mLock);
4858 uint32_t result = 0;
4859 if (getEffectChain_l(sessionId) != 0) {
4860 result = EFFECT_SESSION;
4861 }
4862
4863 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4864 result |= TRACK_SESSION;
4865 }
4866
4867 return result;
4868}
4869
Eric Laurent6639b552011-08-01 09:52:20 -07004870AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4871{
4872 Mutex::Autolock _l(mLock);
4873 return mTrack;
4874}
4875
Glenn Kasten5b0135e2012-01-26 09:46:34 -08004876AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurent828b9772011-08-07 16:32:26 -07004877{
4878 Mutex::Autolock _l(mLock);
4879 return mInput;
4880}
4881
4882AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4883{
4884 Mutex::Autolock _l(mLock);
4885 AudioStreamIn *input = mInput;
4886 mInput = NULL;
4887 return input;
4888}
4889
4890// this method must always be called either with ThreadBase mLock held or inside the thread loop
4891audio_stream_t* AudioFlinger::RecordThread::stream()
4892{
4893 if (mInput == NULL) {
4894 return NULL;
4895 }
4896 return &mInput->stream->common;
4897}
4898
4899
Eric Laurenta553c252009-07-17 12:17:14 -07004900// ----------------------------------------------------------------------------
4901
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004902audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004903 uint32_t *pSamplingRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004904 audio_format_t *pFormat,
Eric Laurenta553c252009-07-17 12:17:14 -07004905 uint32_t *pChannels,
4906 uint32_t *pLatencyMs,
4907 uint32_t flags)
4908{
4909 status_t status;
4910 PlaybackThread *thread = NULL;
4911 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4912 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004913 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta553c252009-07-17 12:17:14 -07004914 uint32_t channels = pChannels ? *pChannels : 0;
4915 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004916 audio_stream_out_t *outStream;
4917 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004918
Steve Block71f2cf12011-10-20 11:56:00 +01004919 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07004920 pDevices ? *pDevices : 0,
4921 samplingRate,
4922 format,
4923 channels,
4924 flags);
4925
4926 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004927 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004928 }
Dima Zavin31f188892011-04-18 16:57:27 -07004929
Eric Laurenta553c252009-07-17 12:17:14 -07004930 Mutex::Autolock _l(mLock);
4931
Dima Zavin31f188892011-04-18 16:57:27 -07004932 outHwDev = findSuitableHwDev_l(*pDevices);
4933 if (outHwDev == NULL)
4934 return 0;
4935
Glenn Kasten0a204ed2012-01-12 12:27:51 -08004936 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07004937 &channels, &samplingRate, &outStream);
Steve Block71f2cf12011-10-20 11:56:00 +01004938 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004939 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004940 samplingRate,
4941 format,
4942 channels,
4943 status);
4944
4945 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004946 if (outStream != NULL) {
4947 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004948 audio_io_handle_t id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004949
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004950 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4951 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4952 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004953 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004954 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004955 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004956 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004957 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004958 }
Eric Laurent65b65452010-06-01 23:49:17 -07004959 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004960
Glenn Kasten3694ec12012-01-27 16:47:15 -08004961 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4962 if (pFormat != NULL) *pFormat = format;
4963 if (pChannels != NULL) *pChannels = channels;
4964 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Eric Laurent9cc489a2009-12-05 05:20:01 -08004965
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004966 // notify client processes of the new output creation
4967 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004968 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004969 }
4970
Eric Laurent9cc489a2009-12-05 05:20:01 -08004971 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004972}
4973
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004974audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
4975 audio_io_handle_t output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004976{
4977 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004978 MixerThread *thread1 = checkMixerThread_l(output1);
4979 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004980
Eric Laurentddb78e72009-07-28 08:44:33 -07004981 if (thread1 == NULL || thread2 == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00004982 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004983 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004984 }
4985
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004986 audio_io_handle_t id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004987 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004988 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004989 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004990 // notify client processes of the new output creation
4991 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004992 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004993}
4994
Glenn Kasten39d00cb2012-01-17 11:09:42 -08004995status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07004996{
Eric Laurent49018a52009-08-04 08:37:05 -07004997 // keep strong reference on the playback thread so that
4998 // it is not destroyed while exit() is executed
4999 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005000 {
5001 Mutex::Autolock _l(mLock);
5002 thread = checkPlaybackThread_l(output);
5003 if (thread == NULL) {
5004 return BAD_VALUE;
5005 }
5006
Steve Block71f2cf12011-10-20 11:56:00 +01005007 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005008
Eric Laurent464d5b32011-06-17 21:29:58 -07005009 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07005010 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005011 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005012 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07005013 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07005014 }
5015 }
5016 }
Glenn Kasten3694ec12012-01-27 16:47:15 -08005017 void *param2 = NULL;
Eric Laurent49f02be2009-11-19 09:00:56 -08005018 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005019 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07005020 }
5021 thread->exit();
Glenn Kasten761286f2012-01-06 08:39:38 -08005022 // The thread entity (active unit of execution) is no longer running here,
5023 // but the ThreadBase container still exists.
Eric Laurenta553c252009-07-17 12:17:14 -07005024
Eric Laurent464d5b32011-06-17 21:29:58 -07005025 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07005026 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005027 assert(out != NULL);
Eric Laurent828b9772011-08-07 16:32:26 -07005028 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005029 out->hwDev->close_output_stream(out->hwDev, out->stream);
5030 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005031 }
Eric Laurenta553c252009-07-17 12:17:14 -07005032 return NO_ERROR;
5033}
5034
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005035status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005036{
5037 Mutex::Autolock _l(mLock);
5038 PlaybackThread *thread = checkPlaybackThread_l(output);
5039
5040 if (thread == NULL) {
5041 return BAD_VALUE;
5042 }
5043
Steve Block71f2cf12011-10-20 11:56:00 +01005044 ALOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005045 thread->suspend();
5046
5047 return NO_ERROR;
5048}
5049
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005050status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005051{
5052 Mutex::Autolock _l(mLock);
5053 PlaybackThread *thread = checkPlaybackThread_l(output);
5054
5055 if (thread == NULL) {
5056 return BAD_VALUE;
5057 }
5058
Steve Block71f2cf12011-10-20 11:56:00 +01005059 ALOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005060
5061 thread->restore();
5062
5063 return NO_ERROR;
5064}
5065
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005066audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005067 uint32_t *pSamplingRate,
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005068 audio_format_t *pFormat,
Eric Laurenta553c252009-07-17 12:17:14 -07005069 uint32_t *pChannels,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005070 audio_in_acoustics_t acoustics)
Eric Laurenta553c252009-07-17 12:17:14 -07005071{
5072 status_t status;
5073 RecordThread *thread = NULL;
5074 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005075 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Eric Laurenta553c252009-07-17 12:17:14 -07005076 uint32_t channels = pChannels ? *pChannels : 0;
5077 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005078 audio_format_t reqFormat = format;
Eric Laurenta553c252009-07-17 12:17:14 -07005079 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005080 audio_stream_in_t *inStream;
5081 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005082
5083 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005084 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005085 }
Dima Zavin31f188892011-04-18 16:57:27 -07005086
Eric Laurenta553c252009-07-17 12:17:14 -07005087 Mutex::Autolock _l(mLock);
5088
Dima Zavin31f188892011-04-18 16:57:27 -07005089 inHwDev = findSuitableHwDev_l(*pDevices);
5090 if (inHwDev == NULL)
5091 return 0;
5092
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005093 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07005094 &channels, &samplingRate,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005095 acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005096 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005097 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005098 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005099 samplingRate,
5100 format,
5101 channels,
5102 acoustics,
5103 status);
5104
5105 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5106 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5107 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005108 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005109 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005110 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005111 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005112 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten0a204ed2012-01-12 12:27:51 -08005113 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin31f188892011-04-18 16:57:27 -07005114 &channels, &samplingRate,
Glenn Kasten882c0a22012-01-27 12:32:34 -08005115 acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005116 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005117 }
5118
Dima Zavin31f188892011-04-18 16:57:27 -07005119 if (inStream != NULL) {
5120 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5121
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005122 audio_io_handle_t id = nextUniqueId();
Eric Laurent464d5b32011-06-17 21:29:58 -07005123 // Start record thread
5124 // RecorThread require both input and output device indication to forward to audio
5125 // pre processing modules
5126 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5127 thread = new RecordThread(this,
5128 input,
5129 reqSamplingRate,
5130 reqChannels,
5131 id,
5132 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005133 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005134 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kasten3694ec12012-01-27 16:47:15 -08005135 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5136 if (pFormat != NULL) *pFormat = format;
5137 if (pChannels != NULL) *pChannels = reqChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07005138
Dima Zavin31f188892011-04-18 16:57:27 -07005139 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a2009-12-05 05:20:01 -08005140
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005141 // notify client processes of the new input creation
5142 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005143 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005144 }
5145
Eric Laurent9cc489a2009-12-05 05:20:01 -08005146 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005147}
5148
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005149status_t AudioFlinger::closeInput(audio_io_handle_t input)
Eric Laurenta553c252009-07-17 12:17:14 -07005150{
Eric Laurent49018a52009-08-04 08:37:05 -07005151 // keep strong reference on the record thread so that
5152 // it is not destroyed while exit() is executed
5153 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005154 {
5155 Mutex::Autolock _l(mLock);
5156 thread = checkRecordThread_l(input);
5157 if (thread == NULL) {
5158 return BAD_VALUE;
5159 }
5160
Steve Block71f2cf12011-10-20 11:56:00 +01005161 ALOGV("closeInput() %d", input);
Glenn Kasten3694ec12012-01-27 16:47:15 -08005162 void *param2 = NULL;
Eric Laurent49f02be2009-11-19 09:00:56 -08005163 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005164 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005165 }
5166 thread->exit();
Glenn Kasten761286f2012-01-06 08:39:38 -08005167 // The thread entity (active unit of execution) is no longer running here,
5168 // but the ThreadBase container still exists.
Eric Laurenta553c252009-07-17 12:17:14 -07005169
Eric Laurent828b9772011-08-07 16:32:26 -07005170 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5b0135e2012-01-26 09:46:34 -08005171 assert(in != NULL);
Eric Laurent828b9772011-08-07 16:32:26 -07005172 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005173 in->hwDev->close_input_stream(in->hwDev, in->stream);
5174 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005175
Eric Laurenta553c252009-07-17 12:17:14 -07005176 return NO_ERROR;
5177}
5178
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005179status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Eric Laurenta553c252009-07-17 12:17:14 -07005180{
5181 Mutex::Autolock _l(mLock);
5182 MixerThread *dstThread = checkMixerThread_l(output);
5183 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005184 ALOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005185 return BAD_VALUE;
5186 }
5187
Steve Block71f2cf12011-10-20 11:56:00 +01005188 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005189 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005190
Eric Laurent05ce0942011-08-30 10:18:54 -07005191 dstThread->setStreamValid(stream, true);
5192
Eric Laurenta553c252009-07-17 12:17:14 -07005193 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005194 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005195 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005196 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005197 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005198 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005199 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005200 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005201 }
Eric Laurentd069f322009-09-01 05:56:26 -07005202
Eric Laurenta553c252009-07-17 12:17:14 -07005203 return NO_ERROR;
5204}
5205
Eric Laurent65b65452010-06-01 23:49:17 -07005206
5207int AudioFlinger::newAudioSessionId()
5208{
Eric Laurent464d5b32011-06-17 21:29:58 -07005209 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005210}
5211
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005212void AudioFlinger::acquireAudioSessionId(int audioSession)
5213{
5214 Mutex::Autolock _l(mLock);
Glenn Kastend153b1f2012-02-03 11:10:26 -08005215 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005216 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005217 int num = mAudioSessionRefs.size();
5218 for (int i = 0; i< num; i++) {
5219 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5220 if (ref->sessionid == audioSession && ref->pid == caller) {
5221 ref->cnt++;
Steve Block71f2cf12011-10-20 11:56:00 +01005222 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005223 return;
5224 }
5225 }
Glenn Kastendc3ac852012-01-25 15:28:08 -08005226 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5227 ALOGV(" added new entry for %d", audioSession);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005228}
5229
5230void AudioFlinger::releaseAudioSessionId(int audioSession)
5231{
5232 Mutex::Autolock _l(mLock);
Glenn Kastend153b1f2012-02-03 11:10:26 -08005233 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005234 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005235 int num = mAudioSessionRefs.size();
5236 for (int i = 0; i< num; i++) {
5237 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5238 if (ref->sessionid == audioSession && ref->pid == caller) {
5239 ref->cnt--;
Steve Block71f2cf12011-10-20 11:56:00 +01005240 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005241 if (ref->cnt == 0) {
5242 mAudioSessionRefs.removeAt(i);
5243 delete ref;
5244 purgeStaleEffects_l();
5245 }
5246 return;
5247 }
5248 }
Steve Block8564c8d2012-01-05 23:22:43 +00005249 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005250}
5251
5252void AudioFlinger::purgeStaleEffects_l() {
5253
Steve Block71f2cf12011-10-20 11:56:00 +01005254 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005255
5256 Vector< sp<EffectChain> > chains;
5257
5258 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5259 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5260 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5261 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005262 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5263 chains.push(ec);
5264 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005265 }
5266 }
5267 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5268 sp<RecordThread> t = mRecordThreads.valueAt(i);
5269 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5270 sp<EffectChain> ec = t->mEffectChains[j];
5271 chains.push(ec);
5272 }
5273 }
5274
5275 for (size_t i = 0; i < chains.size(); i++) {
5276 sp<EffectChain> ec = chains[i];
5277 int sessionid = ec->sessionId();
5278 sp<ThreadBase> t = ec->mThread.promote();
5279 if (t == 0) {
5280 continue;
5281 }
5282 size_t numsessionrefs = mAudioSessionRefs.size();
5283 bool found = false;
5284 for (size_t k = 0; k < numsessionrefs; k++) {
5285 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5286 if (ref->sessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005287 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005288 sessionid, ref->pid, ref->cnt);
5289 found = true;
5290 break;
5291 }
5292 }
5293 if (!found) {
5294 // remove all effects from the chain
5295 while (ec->mEffects.size()) {
5296 sp<EffectModule> effect = ec->mEffects[0];
5297 effect->unPin();
5298 Mutex::Autolock _l (t->mLock);
5299 t->removeEffect_l(effect);
5300 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5301 sp<EffectHandle> handle = effect->mHandles[j].promote();
5302 if (handle != 0) {
5303 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005304 if (handle->mHasControl && handle->mEnabled) {
5305 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5306 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005307 }
5308 }
5309 AudioSystem::unregisterEffect(effect->id());
5310 }
5311 }
5312 }
5313 return;
5314}
5315
Eric Laurenta553c252009-07-17 12:17:14 -07005316// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005317AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005318{
5319 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005320 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5321 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005322 }
Eric Laurenta553c252009-07-17 12:17:14 -07005323 return thread;
5324}
5325
5326// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005327AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005328{
5329 PlaybackThread *thread = checkPlaybackThread_l(output);
5330 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005331 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005332 thread = NULL;
5333 }
5334 }
5335 return (MixerThread *)thread;
5336}
5337
5338// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005339AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005340{
5341 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005342 if (mRecordThreads.indexOfKey(input) >= 0) {
5343 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005344 }
Eric Laurenta553c252009-07-17 12:17:14 -07005345 return thread;
5346}
5347
Eric Laurent464d5b32011-06-17 21:29:58 -07005348uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005349{
Eric Laurent464d5b32011-06-17 21:29:58 -07005350 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005351}
5352
Eric Laurent464d5b32011-06-17 21:29:58 -07005353AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5354{
5355 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5356 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005357 AudioStreamOut *output = thread->getOutput();
5358 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005359 return thread;
5360 }
5361 }
5362 return NULL;
5363}
5364
5365uint32_t AudioFlinger::primaryOutputDevice_l()
5366{
5367 PlaybackThread *thread = primaryPlaybackThread_l();
5368
5369 if (thread == NULL) {
5370 return 0;
5371 }
5372
5373 return thread->device();
5374}
5375
5376
Eric Laurent65b65452010-06-01 23:49:17 -07005377// ----------------------------------------------------------------------------
5378// Effect management
5379// ----------------------------------------------------------------------------
5380
5381
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005382status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Eric Laurent65b65452010-06-01 23:49:17 -07005383{
5384 Mutex::Autolock _l(mLock);
5385 return EffectQueryNumberEffects(numEffects);
5386}
5387
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005388status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Eric Laurent65b65452010-06-01 23:49:17 -07005389{
5390 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005391 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005392}
5393
Glenn Kasten67313332012-01-30 07:40:52 -08005394status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kasten3f6d83a2012-01-26 16:25:10 -08005395 effect_descriptor_t *descriptor) const
Eric Laurent65b65452010-06-01 23:49:17 -07005396{
5397 Mutex::Autolock _l(mLock);
5398 return EffectGetDescriptor(pUuid, descriptor);
5399}
5400
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005401
Eric Laurent65b65452010-06-01 23:49:17 -07005402sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5403 effect_descriptor_t *pDesc,
5404 const sp<IEffectClient>& effectClient,
5405 int32_t priority,
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005406 audio_io_handle_t io,
Eric Laurent65b65452010-06-01 23:49:17 -07005407 int sessionId,
5408 status_t *status,
5409 int *id,
5410 int *enabled)
5411{
5412 status_t lStatus = NO_ERROR;
5413 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005414 effect_descriptor_t desc;
Eric Laurent65b65452010-06-01 23:49:17 -07005415
Glenn Kasten803a86a2012-01-25 14:28:29 -08005416 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005417 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005418
5419 if (pDesc == NULL) {
5420 lStatus = BAD_VALUE;
5421 goto Exit;
5422 }
5423
Eric Laurent98c92592010-09-23 16:10:16 -07005424 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005425 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005426 lStatus = PERMISSION_DENIED;
5427 goto Exit;
5428 }
5429
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005430 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005431 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005432 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005433 lStatus = PERMISSION_DENIED;
5434 goto Exit;
5435 }
5436
Eric Laurent464d5b32011-06-17 21:29:58 -07005437 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005438 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005439 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005440 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005441 lStatus = BAD_VALUE;
5442 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005443 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005444 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005445 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005446 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005447 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005448 }
5449 }
5450
Eric Laurent65b65452010-06-01 23:49:17 -07005451 {
5452 Mutex::Autolock _l(mLock);
5453
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005454
Eric Laurent65b65452010-06-01 23:49:17 -07005455 if (!EffectIsNullUuid(&pDesc->uuid)) {
5456 // if uuid is specified, request effect descriptor
5457 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5458 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005459 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005460 goto Exit;
5461 }
5462 } else {
5463 // if uuid is not specified, look for an available implementation
5464 // of the required type in effect factory
5465 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005466 ALOGW("createEffect() no effect type");
Eric Laurent65b65452010-06-01 23:49:17 -07005467 lStatus = BAD_VALUE;
5468 goto Exit;
5469 }
5470 uint32_t numEffects = 0;
5471 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005472 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005473 bool found = false;
5474
5475 lStatus = EffectQueryNumberEffects(&numEffects);
5476 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005477 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005478 goto Exit;
5479 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005480 for (uint32_t i = 0; i < numEffects; i++) {
5481 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005482 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005483 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005484 continue;
5485 }
5486 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5487 // If matching type found save effect descriptor. If the session is
5488 // 0 and the effect is not auxiliary, continue enumeration in case
5489 // an auxiliary version of this effect type is available
5490 found = true;
5491 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005492 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005493 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5494 break;
5495 }
5496 }
5497 }
5498 if (!found) {
5499 lStatus = BAD_VALUE;
Steve Block8564c8d2012-01-05 23:22:43 +00005500 ALOGW("createEffect() effect not found");
Eric Laurent65b65452010-06-01 23:49:17 -07005501 goto Exit;
5502 }
5503 // For same effect type, chose auxiliary version over insert version if
5504 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005505 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005506 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5507 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5508 }
5509 }
5510
5511 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005512 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005513 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5514 lStatus = INVALID_OPERATION;
5515 goto Exit;
5516 }
5517
Eric Laurentf82fccd2011-07-27 19:49:51 -07005518 // check recording permission for visualizer
5519 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5520 !recordingAllowed()) {
5521 lStatus = PERMISSION_DENIED;
5522 goto Exit;
5523 }
5524
Eric Laurent65b65452010-06-01 23:49:17 -07005525 // return effect descriptor
5526 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5527
5528 // If output is not specified try to find a matching audio session ID in one of the
5529 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005530 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5531 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005532 // Note: io is never 0 when creating an effect on an input
5533 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005534 // look for the thread where the specified audio session is present
5535 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5536 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005537 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005538 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005539 }
Eric Laurent65b65452010-06-01 23:49:17 -07005540 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005541 if (io == 0) {
5542 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5543 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5544 io = mRecordThreads.keyAt(i);
5545 break;
5546 }
5547 }
5548 }
Eric Laurent98c92592010-09-23 16:10:16 -07005549 // If no output thread contains the requested session ID, default to
5550 // first output. The effect chain will be moved to the correct output
5551 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005552 if (io == 0 && mPlaybackThreads.size()) {
5553 io = mPlaybackThreads.keyAt(0);
5554 }
Steve Block71f2cf12011-10-20 11:56:00 +01005555 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005556 }
5557 ThreadBase *thread = checkRecordThread_l(io);
5558 if (thread == NULL) {
5559 thread = checkPlaybackThread_l(io);
5560 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +00005561 ALOGE("createEffect() unknown output thread");
Eric Laurent464d5b32011-06-17 21:29:58 -07005562 lStatus = BAD_VALUE;
5563 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005564 }
Eric Laurent65b65452010-06-01 23:49:17 -07005565 }
Eric Laurent98c92592010-09-23 16:10:16 -07005566
Glenn Kasten803a86a2012-01-25 14:28:29 -08005567 sp<Client> client = registerPid_l(pid);
Eric Laurent65b65452010-06-01 23:49:17 -07005568
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005569 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005570 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5571 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005572 if (handle != 0 && id != NULL) {
5573 *id = handle->id();
5574 }
5575 }
5576
5577Exit:
5578 if(status) {
5579 *status = lStatus;
5580 }
5581 return handle;
5582}
5583
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005584status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
5585 audio_io_handle_t dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005586{
Steve Block71f2cf12011-10-20 11:56:00 +01005587 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005588 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005589 Mutex::Autolock _l(mLock);
5590 if (srcOutput == dstOutput) {
Steve Block8564c8d2012-01-05 23:22:43 +00005591 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005592 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005593 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005594 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5595 if (srcThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005596 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005597 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005598 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005599 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5600 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005601 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005602 return BAD_VALUE;
5603 }
5604
5605 Mutex::Autolock _dl(dstThread->mLock);
5606 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005607 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005608
Eric Laurent53334cd2010-06-23 17:38:20 -07005609 return NO_ERROR;
5610}
5611
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005612// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005613status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005614 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005615 AudioFlinger::PlaybackThread *dstThread,
5616 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005617{
Steve Block71f2cf12011-10-20 11:56:00 +01005618 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005619 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005620
Eric Laurentf82fccd2011-07-27 19:49:51 -07005621 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005622 if (chain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005623 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005624 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005625 return INVALID_OPERATION;
5626 }
5627
Eric Laurent493941b2010-07-28 01:32:47 -07005628 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005629 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005630 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005631 // removed.
5632 srcThread->removeEffectChain_l(chain);
5633
5634 // transfer all effects one by one so that new effect chain is created on new thread with
5635 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten39d00cb2012-01-17 11:09:42 -08005636 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent493941b2010-07-28 01:32:47 -07005637 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005638 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005639 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5640 while (effect != 0) {
5641 srcThread->removeEffect_l(effect);
5642 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005643 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5644 if (effect->state() == EffectModule::ACTIVE ||
5645 effect->state() == EffectModule::STOPPING) {
5646 effect->start();
5647 }
Eric Laurent493941b2010-07-28 01:32:47 -07005648 // if the move request is not received from audio policy manager, the effect must be
5649 // re-registered with the new strategy and output
5650 if (dstChain == 0) {
5651 dstChain = effect->chain().promote();
5652 if (dstChain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005653 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent493941b2010-07-28 01:32:47 -07005654 srcThread->addEffect_l(effect);
5655 return NO_INIT;
5656 }
5657 strategy = dstChain->strategy();
5658 }
5659 if (reRegister) {
5660 AudioSystem::unregisterEffect(effect->id());
5661 AudioSystem::registerEffect(&effect->desc(),
5662 dstOutput,
5663 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005664 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005665 effect->id());
5666 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005667 effect = chain->getEffectFromId_l(0);
5668 }
5669
5670 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005671}
5672
Eric Laurent464d5b32011-06-17 21:29:58 -07005673
Eric Laurent65b65452010-06-01 23:49:17 -07005674// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005675sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005676 const sp<AudioFlinger::Client>& client,
5677 const sp<IEffectClient>& effectClient,
5678 int32_t priority,
5679 int sessionId,
5680 effect_descriptor_t *desc,
5681 int *enabled,
5682 status_t *status
5683 )
5684{
5685 sp<EffectModule> effect;
5686 sp<EffectHandle> handle;
5687 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005688 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005689 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005690 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005691 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005692
Eric Laurent464d5b32011-06-17 21:29:58 -07005693 lStatus = initCheck();
5694 if (lStatus != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00005695 ALOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005696 goto Exit;
5697 }
5698
5699 // Do not allow effects with session ID 0 on direct output or duplicating threads
5700 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005701 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block8564c8d2012-01-05 23:22:43 +00005702 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005703 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005704 lStatus = BAD_VALUE;
5705 goto Exit;
5706 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005707 // Only Pre processor effects are allowed on input threads and only on input threads
5708 if ((mType == RECORD &&
5709 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5710 (mType != RECORD &&
5711 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005712 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005713 desc->name, desc->flags, mType);
5714 lStatus = BAD_VALUE;
5715 goto Exit;
5716 }
Eric Laurent65b65452010-06-01 23:49:17 -07005717
Steve Block71f2cf12011-10-20 11:56:00 +01005718 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005719
5720 { // scope for mLock
5721 Mutex::Autolock _l(mLock);
5722
5723 // check for existing effect chain with the requested audio session
5724 chain = getEffectChain_l(sessionId);
5725 if (chain == 0) {
5726 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005727 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005728 chain = new EffectChain(this, sessionId);
5729 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005730 chain->setStrategy(getStrategyForSession_l(sessionId));
5731 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005732 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005733 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005734 }
5735
Glenn Kasten70ed6b72012-01-10 10:46:34 -08005736 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005737
5738 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005739 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005740 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005741 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005742 if (lStatus != NO_ERROR) {
5743 goto Exit;
5744 }
5745 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005746 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005747 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005748 lStatus = effect->status();
5749 if (lStatus != NO_ERROR) {
5750 goto Exit;
5751 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005752 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005753 if (lStatus != NO_ERROR) {
5754 goto Exit;
5755 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005756 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005757
5758 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005759 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005760 }
5761 // create effect handle and connect it to effect module
5762 handle = new EffectHandle(effect, client, effectClient, priority);
5763 lStatus = effect->addHandle(handle);
Glenn Kasten3694ec12012-01-27 16:47:15 -08005764 if (enabled != NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07005765 *enabled = (int)effect->isEnabled();
5766 }
5767 }
5768
5769Exit:
5770 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005771 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005772 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005773 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005774 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005775 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005776 AudioSystem::unregisterEffect(effect->id());
5777 }
5778 if (chainCreated) {
5779 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005780 }
Eric Laurent65b65452010-06-01 23:49:17 -07005781 handle.clear();
5782 }
5783
5784 if(status) {
5785 *status = lStatus;
5786 }
5787 return handle;
5788}
5789
Eric Laurent464d5b32011-06-17 21:29:58 -07005790sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5791{
Eric Laurent464d5b32011-06-17 21:29:58 -07005792 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kastenc64a6f02012-01-30 13:00:02 -08005793 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent464d5b32011-06-17 21:29:58 -07005794}
5795
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005796// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5797// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005798status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005799{
5800 // check for existing effect chain with the requested audio session
5801 int sessionId = effect->sessionId();
5802 sp<EffectChain> chain = getEffectChain_l(sessionId);
5803 bool chainCreated = false;
5804
5805 if (chain == 0) {
5806 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005807 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005808 chain = new EffectChain(this, sessionId);
5809 addEffectChain_l(chain);
5810 chain->setStrategy(getStrategyForSession_l(sessionId));
5811 chainCreated = true;
5812 }
Steve Block71f2cf12011-10-20 11:56:00 +01005813 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005814
5815 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005816 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005817 this, effect->desc().name, chain.get());
5818 return BAD_VALUE;
5819 }
5820
5821 status_t status = chain->addEffect_l(effect);
5822 if (status != NO_ERROR) {
5823 if (chainCreated) {
5824 removeEffectChain_l(chain);
5825 }
5826 return status;
5827 }
5828
5829 effect->setDevice(mDevice);
5830 effect->setMode(mAudioFlinger->getMode());
5831 return NO_ERROR;
5832}
5833
Eric Laurent464d5b32011-06-17 21:29:58 -07005834void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005835
Steve Block71f2cf12011-10-20 11:56:00 +01005836 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005837 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005838 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5839 detachAuxEffect_l(effect->id());
5840 }
5841
5842 sp<EffectChain> chain = effect->chain().promote();
5843 if (chain != 0) {
5844 // remove effect chain if removing last effect
5845 if (chain->removeEffect_l(effect) == 0) {
5846 removeEffectChain_l(chain);
5847 }
5848 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00005849 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005850 }
5851}
5852
Eric Laurent464d5b32011-06-17 21:29:58 -07005853void AudioFlinger::ThreadBase::lockEffectChains_l(
5854 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5855{
5856 effectChains = mEffectChains;
5857 for (size_t i = 0; i < mEffectChains.size(); i++) {
5858 mEffectChains[i]->lock();
5859 }
5860}
5861
5862void AudioFlinger::ThreadBase::unlockEffectChains(
5863 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5864{
5865 for (size_t i = 0; i < effectChains.size(); i++) {
5866 effectChains[i]->unlock();
5867 }
5868}
5869
5870sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5871{
5872 Mutex::Autolock _l(mLock);
5873 return getEffectChain_l(sessionId);
5874}
5875
5876sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5877{
Eric Laurent464d5b32011-06-17 21:29:58 -07005878 size_t size = mEffectChains.size();
5879 for (size_t i = 0; i < size; i++) {
5880 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08005881 return mEffectChains[i];
Eric Laurent464d5b32011-06-17 21:29:58 -07005882 }
5883 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08005884 return 0;
Eric Laurent464d5b32011-06-17 21:29:58 -07005885}
5886
Glenn Kastenaccb1142012-01-04 11:00:47 -08005887void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent464d5b32011-06-17 21:29:58 -07005888{
5889 Mutex::Autolock _l(mLock);
5890 size_t size = mEffectChains.size();
5891 for (size_t i = 0; i < size; i++) {
5892 mEffectChains[i]->setMode_l(mode);
5893 }
5894}
5895
5896void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005897 const wp<EffectHandle>& handle,
5898 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005899
Eric Laurent53334cd2010-06-23 17:38:20 -07005900 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01005901 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005902 // delete the effect module if removing last handle on it
5903 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005904 if (!effect->isPinned() || unpiniflast) {
5905 removeEffect_l(effect);
5906 AudioSystem::unregisterEffect(effect->id());
5907 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005908 }
5909}
5910
Eric Laurent65b65452010-06-01 23:49:17 -07005911status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5912{
5913 int session = chain->sessionId();
5914 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005915 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005916
Steve Block71f2cf12011-10-20 11:56:00 +01005917 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005918 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005919 // Only one effect chain can be present in direct output thread and it uses
5920 // the mix buffer as input
5921 if (mType != DIRECT) {
5922 size_t numSamples = mFrameCount * mChannelCount;
5923 buffer = new int16_t[numSamples];
5924 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01005925 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005926 ownsBuffer = true;
5927 }
Eric Laurent65b65452010-06-01 23:49:17 -07005928
Eric Laurent53334cd2010-06-23 17:38:20 -07005929 // Attach all tracks with same session ID to this chain.
5930 for (size_t i = 0; i < mTracks.size(); ++i) {
5931 sp<Track> track = mTracks[i];
5932 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005933 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07005934 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005935 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005936 }
5937 }
5938
5939 // indicate all active tracks in the chain
5940 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5941 sp<Track> track = mActiveTracks[i].promote();
5942 if (track == 0) continue;
5943 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005944 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005945 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005946 }
Eric Laurent65b65452010-06-01 23:49:17 -07005947 }
5948 }
5949
Eric Laurent53334cd2010-06-23 17:38:20 -07005950 chain->setInBuffer(buffer, ownsBuffer);
5951 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005952 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005953 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005954 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5955 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005956 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005957 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5958 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005959 // Effect chain for other sessions are inserted at beginning of effect
5960 // chains list to be processed before output mix effects. Relative order between other
5961 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005962 size_t size = mEffectChains.size();
5963 size_t i = 0;
5964 for (i = 0; i < size; i++) {
5965 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005966 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005967 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005968 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005969
5970 return NO_ERROR;
5971}
5972
5973size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5974{
5975 int session = chain->sessionId();
5976
Steve Block71f2cf12011-10-20 11:56:00 +01005977 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005978
5979 for (size_t i = 0; i < mEffectChains.size(); i++) {
5980 if (chain == mEffectChains[i]) {
5981 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005982 // detach all active tracks from the chain
5983 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5984 sp<Track> track = mActiveTracks[i].promote();
5985 if (track == 0) continue;
5986 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005987 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07005988 chain.get(), session);
5989 chain->decActiveTrackCnt();
5990 }
5991 }
5992
Eric Laurent65b65452010-06-01 23:49:17 -07005993 // detach all tracks with same session ID from this chain
5994 for (size_t i = 0; i < mTracks.size(); ++i) {
5995 sp<Track> track = mTracks[i];
5996 if (session == track->sessionId()) {
5997 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005998 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005999 }
6000 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006001 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006002 }
6003 }
6004 return mEffectChains.size();
6005}
6006
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006007status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6008 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006009{
6010 Mutex::Autolock _l(mLock);
6011 return attachAuxEffect_l(track, EffectId);
6012}
6013
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006014status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6015 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006016{
6017 status_t status = NO_ERROR;
6018
6019 if (EffectId == 0) {
6020 track->setAuxBuffer(0, NULL);
6021 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006022 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6023 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006024 if (effect != 0) {
6025 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6026 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6027 } else {
6028 status = INVALID_OPERATION;
6029 }
6030 } else {
6031 status = BAD_VALUE;
6032 }
6033 }
6034 return status;
6035}
6036
6037void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6038{
6039 for (size_t i = 0; i < mTracks.size(); ++i) {
6040 sp<Track> track = mTracks[i];
6041 if (track->auxEffectId() == effectId) {
6042 attachAuxEffect_l(track, 0);
6043 }
6044 }
6045}
6046
Eric Laurent464d5b32011-06-17 21:29:58 -07006047status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6048{
6049 // only one chain per input thread
6050 if (mEffectChains.size() != 0) {
6051 return INVALID_OPERATION;
6052 }
Steve Block71f2cf12011-10-20 11:56:00 +01006053 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006054
6055 chain->setInBuffer(NULL);
6056 chain->setOutBuffer(NULL);
6057
Eric Laurentf82fccd2011-07-27 19:49:51 -07006058 checkSuspendOnAddEffectChain_l(chain);
6059
Eric Laurent464d5b32011-06-17 21:29:58 -07006060 mEffectChains.add(chain);
6061
6062 return NO_ERROR;
6063}
6064
6065size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6066{
Steve Block71f2cf12011-10-20 11:56:00 +01006067 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block8564c8d2012-01-05 23:22:43 +00006068 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent464d5b32011-06-17 21:29:58 -07006069 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6070 chain.get(), mEffectChains.size(), this);
6071 if (mEffectChains.size() == 1) {
6072 mEffectChains.removeAt(0);
6073 }
6074 return 0;
6075}
6076
Eric Laurent65b65452010-06-01 23:49:17 -07006077// ----------------------------------------------------------------------------
6078// EffectModule implementation
6079// ----------------------------------------------------------------------------
6080
6081#undef LOG_TAG
6082#define LOG_TAG "AudioFlinger::EffectModule"
6083
6084AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6085 const wp<AudioFlinger::EffectChain>& chain,
6086 effect_descriptor_t *desc,
6087 int id,
6088 int sessionId)
6089 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006090 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006091{
Steve Block71f2cf12011-10-20 11:56:00 +01006092 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006093 int lStatus;
6094 sp<ThreadBase> thread = mThread.promote();
6095 if (thread == 0) {
6096 return;
6097 }
Eric Laurent65b65452010-06-01 23:49:17 -07006098
6099 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6100
6101 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006102 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006103
Eric Laurent65b65452010-06-01 23:49:17 -07006104 if (mStatus != NO_ERROR) {
6105 return;
6106 }
6107 lStatus = init();
6108 if (lStatus < 0) {
6109 mStatus = lStatus;
6110 goto Error;
6111 }
6112
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006113 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6114 mPinned = true;
6115 }
Steve Block71f2cf12011-10-20 11:56:00 +01006116 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006117 return;
6118Error:
6119 EffectRelease(mEffectInterface);
6120 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006121 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006122}
6123
6124AudioFlinger::EffectModule::~EffectModule()
6125{
Steve Block71f2cf12011-10-20 11:56:00 +01006126 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006127 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006128 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6129 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6130 sp<ThreadBase> thread = mThread.promote();
6131 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006132 audio_stream_t *stream = thread->stream();
6133 if (stream != NULL) {
6134 stream->remove_audio_effect(stream, mEffectInterface);
6135 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006136 }
6137 }
Eric Laurent65b65452010-06-01 23:49:17 -07006138 // release effect engine
6139 EffectRelease(mEffectInterface);
6140 }
6141}
6142
Glenn Kasten1f812f72012-01-30 10:15:48 -08006143status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Eric Laurent65b65452010-06-01 23:49:17 -07006144{
6145 status_t status;
6146
6147 Mutex::Autolock _l(mLock);
6148 // First handle in mHandles has highest priority and controls the effect module
6149 int priority = handle->priority();
6150 size_t size = mHandles.size();
6151 sp<EffectHandle> h;
6152 size_t i;
6153 for (i = 0; i < size; i++) {
6154 h = mHandles[i].promote();
6155 if (h == 0) continue;
6156 if (h->priority() <= priority) break;
6157 }
6158 // if inserted in first place, move effect control from previous owner to this handle
6159 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006160 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006161 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006162 enabled = h->enabled();
6163 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006164 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006165 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006166 status = NO_ERROR;
6167 } else {
6168 status = ALREADY_EXISTS;
6169 }
Steve Block71f2cf12011-10-20 11:56:00 +01006170 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006171 mHandles.insertAt(handle, i);
6172 return status;
6173}
6174
6175size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6176{
6177 Mutex::Autolock _l(mLock);
6178 size_t size = mHandles.size();
6179 size_t i;
6180 for (i = 0; i < size; i++) {
6181 if (mHandles[i] == handle) break;
6182 }
6183 if (i == size) {
6184 return size;
6185 }
Steve Block71f2cf12011-10-20 11:56:00 +01006186 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006187
6188 bool enabled = false;
6189 EffectHandle *hdl = handle.unsafe_get();
Glenn Kasten3694ec12012-01-27 16:47:15 -08006190 if (hdl != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01006191 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006192 enabled = hdl->enabled();
6193 }
Eric Laurent65b65452010-06-01 23:49:17 -07006194 mHandles.removeAt(i);
6195 size = mHandles.size();
6196 // if removed from first place, move effect control from this handle to next in line
6197 if (i == 0 && size != 0) {
6198 sp<EffectHandle> h = mHandles[0].promote();
6199 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006200 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006201 }
6202 }
6203
Eric Laurent21b5c472011-07-26 20:54:46 -07006204 // Prevent calls to process() and other functions on effect interface from now on.
6205 // The effect engine will be released by the destructor when the last strong reference on
6206 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006207 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006208 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006209 }
6210
Eric Laurent65b65452010-06-01 23:49:17 -07006211 return size;
6212}
6213
Eric Laurentf82fccd2011-07-27 19:49:51 -07006214sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6215{
6216 Mutex::Autolock _l(mLock);
Glenn Kastenc64a6f02012-01-30 13:00:02 -08006217 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006218}
6219
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006220void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006221{
Steve Block71f2cf12011-10-20 11:56:00 +01006222 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006223 // keep a strong reference on this EffectModule to avoid calling the
6224 // destructor before we exit
6225 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006226 {
6227 sp<ThreadBase> thread = mThread.promote();
6228 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006229 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006230 }
6231 }
6232}
6233
Eric Laurent7d850f22010-07-09 13:34:17 -07006234void AudioFlinger::EffectModule::updateState() {
6235 Mutex::Autolock _l(mLock);
6236
6237 switch (mState) {
6238 case RESTART:
6239 reset_l();
6240 // FALL THROUGH
6241
6242 case STARTING:
6243 // clear auxiliary effect input buffer for next accumulation
6244 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6245 memset(mConfig.inputCfg.buffer.raw,
6246 0,
6247 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6248 }
6249 start_l();
6250 mState = ACTIVE;
6251 break;
6252 case STOPPING:
6253 stop_l();
6254 mDisableWaitCnt = mMaxDisableWaitCnt;
6255 mState = STOPPED;
6256 break;
6257 case STOPPED:
6258 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6259 // turn off sequence.
6260 if (--mDisableWaitCnt == 0) {
6261 reset_l();
6262 mState = IDLE;
6263 }
6264 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006265 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006266 break;
6267 }
6268}
6269
Eric Laurent65b65452010-06-01 23:49:17 -07006270void AudioFlinger::EffectModule::process()
6271{
6272 Mutex::Autolock _l(mLock);
6273
Eric Laurent21b5c472011-07-26 20:54:46 -07006274 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006275 mConfig.inputCfg.buffer.raw == NULL ||
6276 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006277 return;
6278 }
6279
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006280 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006281 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6282 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten490909d2011-12-15 09:52:39 -08006283 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Eric Laurent65b65452010-06-01 23:49:17 -07006284 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006285 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006286 }
6287
Eric Laurent65b65452010-06-01 23:49:17 -07006288 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006289 int ret = (*mEffectInterface)->process(mEffectInterface,
6290 &mConfig.inputCfg.buffer,
6291 &mConfig.outputCfg.buffer);
6292
6293 // force transition to IDLE state when engine is ready
6294 if (mState == STOPPED && ret == -ENODATA) {
6295 mDisableWaitCnt = 1;
6296 }
Eric Laurent65b65452010-06-01 23:49:17 -07006297
6298 // clear auxiliary effect input buffer for next accumulation
6299 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006300 memset(mConfig.inputCfg.buffer.raw, 0,
6301 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006302 }
6303 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006304 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6305 // If an insert effect is idle and input buffer is different from output buffer,
6306 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006307 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006308 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006309 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6310 int16_t *in = mConfig.inputCfg.buffer.s16;
6311 int16_t *out = mConfig.outputCfg.buffer.s16;
6312 for (size_t i = 0; i < frameCnt; i++) {
6313 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006314 }
Eric Laurent65b65452010-06-01 23:49:17 -07006315 }
6316 }
6317}
6318
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006319void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006320{
6321 if (mEffectInterface == NULL) {
6322 return;
6323 }
6324 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6325}
6326
6327status_t AudioFlinger::EffectModule::configure()
6328{
6329 uint32_t channels;
6330 if (mEffectInterface == NULL) {
6331 return NO_INIT;
6332 }
6333
6334 sp<ThreadBase> thread = mThread.promote();
6335 if (thread == 0) {
6336 return DEAD_OBJECT;
6337 }
6338
6339 // TODO: handle configuration of effects replacing track process
6340 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006341 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006342 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006343 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006344 }
6345
6346 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006347 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006348 } else {
6349 mConfig.inputCfg.channels = channels;
6350 }
6351 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006352 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6353 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006354 mConfig.inputCfg.samplingRate = thread->sampleRate();
6355 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6356 mConfig.inputCfg.bufferProvider.cookie = NULL;
6357 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6358 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6359 mConfig.outputCfg.bufferProvider.cookie = NULL;
6360 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6361 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6362 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6363 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006364 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006365 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006366 // - in other sessions:
6367 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6368 // other effect: overwrites output buffer: input buffer == output buffer
6369 // Auxiliary effect:
6370 // accumulates in output buffer: input buffer != output buffer
6371 // Therefore: accumulate <=> input buffer != output buffer
6372 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6373 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6374 } else {
6375 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6376 }
6377 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6378 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6379 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6380 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6381
Steve Block71f2cf12011-10-20 11:56:00 +01006382 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006383 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6384
Eric Laurent65b65452010-06-01 23:49:17 -07006385 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006386 uint32_t size = sizeof(int);
6387 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent4abf8822011-12-16 15:30:36 -08006388 EFFECT_CMD_SET_CONFIG,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006389 sizeof(effect_config_t),
6390 &mConfig,
6391 &size,
6392 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006393 if (status == 0) {
6394 status = cmdStatus;
6395 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006396
6397 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6398 (1000 * mConfig.outputCfg.buffer.frameCount);
6399
Eric Laurent65b65452010-06-01 23:49:17 -07006400 return status;
6401}
6402
6403status_t AudioFlinger::EffectModule::init()
6404{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006405 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006406 if (mEffectInterface == NULL) {
6407 return NO_INIT;
6408 }
6409 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006410 uint32_t size = sizeof(status_t);
6411 status_t status = (*mEffectInterface)->command(mEffectInterface,
6412 EFFECT_CMD_INIT,
6413 0,
6414 NULL,
6415 &size,
6416 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006417 if (status == 0) {
6418 status = cmdStatus;
6419 }
6420 return status;
6421}
6422
Eric Laurent6fccbd02011-10-05 17:42:25 -07006423status_t AudioFlinger::EffectModule::start()
6424{
6425 Mutex::Autolock _l(mLock);
6426 return start_l();
6427}
6428
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006429status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006430{
6431 if (mEffectInterface == NULL) {
6432 return NO_INIT;
6433 }
6434 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006435 uint32_t size = sizeof(status_t);
6436 status_t status = (*mEffectInterface)->command(mEffectInterface,
6437 EFFECT_CMD_ENABLE,
6438 0,
6439 NULL,
6440 &size,
6441 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006442 if (status == 0) {
6443 status = cmdStatus;
6444 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006445 if (status == 0 &&
6446 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6447 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6448 sp<ThreadBase> thread = mThread.promote();
6449 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006450 audio_stream_t *stream = thread->stream();
6451 if (stream != NULL) {
6452 stream->add_audio_effect(stream, mEffectInterface);
6453 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006454 }
6455 }
Eric Laurent65b65452010-06-01 23:49:17 -07006456 return status;
6457}
6458
Eric Laurent21b5c472011-07-26 20:54:46 -07006459status_t AudioFlinger::EffectModule::stop()
6460{
6461 Mutex::Autolock _l(mLock);
6462 return stop_l();
6463}
6464
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006465status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006466{
6467 if (mEffectInterface == NULL) {
6468 return NO_INIT;
6469 }
6470 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006471 uint32_t size = sizeof(status_t);
6472 status_t status = (*mEffectInterface)->command(mEffectInterface,
6473 EFFECT_CMD_DISABLE,
6474 0,
6475 NULL,
6476 &size,
6477 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006478 if (status == 0) {
6479 status = cmdStatus;
6480 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006481 if (status == 0 &&
6482 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6483 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6484 sp<ThreadBase> thread = mThread.promote();
6485 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006486 audio_stream_t *stream = thread->stream();
6487 if (stream != NULL) {
6488 stream->remove_audio_effect(stream, mEffectInterface);
6489 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006490 }
6491 }
Eric Laurent65b65452010-06-01 23:49:17 -07006492 return status;
6493}
6494
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006495status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6496 uint32_t cmdSize,
6497 void *pCmdData,
6498 uint32_t *replySize,
6499 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006500{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006501 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006502// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006503
Eric Laurent21b5c472011-07-26 20:54:46 -07006504 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006505 return NO_INIT;
6506 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006507 status_t status = (*mEffectInterface)->command(mEffectInterface,
6508 cmdCode,
6509 cmdSize,
6510 pCmdData,
6511 replySize,
6512 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006513 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006514 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006515 for (size_t i = 1; i < mHandles.size(); i++) {
6516 sp<EffectHandle> h = mHandles[i].promote();
6517 if (h != 0) {
6518 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6519 }
6520 }
6521 }
6522 return status;
6523}
6524
6525status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6526{
Eric Laurent6752ec82011-08-10 10:37:50 -07006527
Eric Laurent65b65452010-06-01 23:49:17 -07006528 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006529 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006530
6531 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006532 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6533 if (enabled && status != NO_ERROR) {
6534 return status;
6535 }
6536
Eric Laurent65b65452010-06-01 23:49:17 -07006537 switch (mState) {
6538 // going from disabled to enabled
6539 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006540 mState = STARTING;
6541 break;
6542 case STOPPED:
6543 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006544 break;
6545 case STOPPING:
6546 mState = ACTIVE;
6547 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006548
6549 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006550 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006551 mState = STOPPED;
6552 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006553 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006554 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006555 break;
6556 case ACTIVE:
6557 mState = STOPPING;
6558 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006559 case DESTROYED:
6560 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006561 }
6562 for (size_t i = 1; i < mHandles.size(); i++) {
6563 sp<EffectHandle> h = mHandles[i].promote();
6564 if (h != 0) {
6565 h->setEnabled(enabled);
6566 }
6567 }
6568 }
6569 return NO_ERROR;
6570}
6571
Glenn Kasteneabd94a2012-02-02 14:06:11 -08006572bool AudioFlinger::EffectModule::isEnabled() const
Eric Laurent65b65452010-06-01 23:49:17 -07006573{
6574 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006575 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006576 case STARTING:
6577 case ACTIVE:
6578 return true;
6579 case IDLE:
6580 case STOPPING:
6581 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006582 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006583 default:
6584 return false;
6585 }
6586}
6587
Glenn Kasteneabd94a2012-02-02 14:06:11 -08006588bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006589{
6590 switch (mState) {
6591 case RESTART:
6592 case ACTIVE:
6593 case STOPPING:
6594 case STOPPED:
6595 return true;
6596 case IDLE:
6597 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006598 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006599 default:
6600 return false;
6601 }
6602}
6603
Eric Laurent65b65452010-06-01 23:49:17 -07006604status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6605{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006606 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006607 status_t status = NO_ERROR;
6608
6609 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6610 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006611 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006612 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6613 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006614 status_t cmdStatus;
6615 uint32_t volume[2];
6616 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006617 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006618 volume[0] = *left;
6619 volume[1] = *right;
6620 if (controller) {
6621 pVolume = volume;
6622 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006623 status = (*mEffectInterface)->command(mEffectInterface,
6624 EFFECT_CMD_SET_VOLUME,
6625 size,
6626 volume,
6627 &size,
6628 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006629 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6630 *left = volume[0];
6631 *right = volume[1];
6632 }
6633 }
6634 return status;
6635}
6636
6637status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6638{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006639 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006640 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006641 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6642 // audio pre processing modules on RecordThread can receive both output and
6643 // input device indication in the same call
6644 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6645 if (dev) {
6646 status_t cmdStatus;
6647 uint32_t size = sizeof(status_t);
6648
6649 status = (*mEffectInterface)->command(mEffectInterface,
6650 EFFECT_CMD_SET_DEVICE,
6651 sizeof(uint32_t),
6652 &dev,
6653 &size,
6654 &cmdStatus);
6655 if (status == NO_ERROR) {
6656 status = cmdStatus;
6657 }
6658 }
6659 dev = device & AUDIO_DEVICE_IN_ALL;
6660 if (dev) {
6661 status_t cmdStatus;
6662 uint32_t size = sizeof(status_t);
6663
6664 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6665 EFFECT_CMD_SET_INPUT_DEVICE,
6666 sizeof(uint32_t),
6667 &dev,
6668 &size,
6669 &cmdStatus);
6670 if (status2 == NO_ERROR) {
6671 status2 = cmdStatus;
6672 }
6673 if (status == NO_ERROR) {
6674 status = status2;
6675 }
Eric Laurent65b65452010-06-01 23:49:17 -07006676 }
6677 }
6678 return status;
6679}
6680
Glenn Kastenaccb1142012-01-04 11:00:47 -08006681status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07006682{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006683 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006684 status_t status = NO_ERROR;
6685 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006686 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006687 uint32_t size = sizeof(status_t);
6688 status = (*mEffectInterface)->command(mEffectInterface,
6689 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenaccb1142012-01-04 11:00:47 -08006690 sizeof(audio_mode_t),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006691 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006692 &size,
6693 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006694 if (status == NO_ERROR) {
6695 status = cmdStatus;
6696 }
6697 }
6698 return status;
6699}
6700
Eric Laurentf82fccd2011-07-27 19:49:51 -07006701void AudioFlinger::EffectModule::setSuspended(bool suspended)
6702{
6703 Mutex::Autolock _l(mLock);
6704 mSuspended = suspended;
6705}
Glenn Kasten1dce8412012-01-04 11:01:11 -08006706
6707bool AudioFlinger::EffectModule::suspended() const
Eric Laurentf82fccd2011-07-27 19:49:51 -07006708{
6709 Mutex::Autolock _l(mLock);
6710 return mSuspended;
6711}
6712
Eric Laurent65b65452010-06-01 23:49:17 -07006713status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6714{
6715 const size_t SIZE = 256;
6716 char buffer[SIZE];
6717 String8 result;
6718
6719 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6720 result.append(buffer);
6721
6722 bool locked = tryLock(mLock);
6723 // failed to lock - AudioFlinger is probably deadlocked
6724 if (!locked) {
6725 result.append("\t\tCould not lock Fx mutex:\n");
6726 }
6727
6728 result.append("\t\tSession Status State Engine:\n");
6729 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6730 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6731 result.append(buffer);
6732
6733 result.append("\t\tDescriptor:\n");
6734 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6735 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6736 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6737 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6738 result.append(buffer);
6739 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6740 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6741 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6742 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6743 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006744 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006745 mDescriptor.apiVersion,
6746 mDescriptor.flags);
6747 result.append(buffer);
6748 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6749 mDescriptor.name);
6750 result.append(buffer);
6751 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6752 mDescriptor.implementor);
6753 result.append(buffer);
6754
6755 result.append("\t\t- Input configuration:\n");
6756 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6757 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6758 (uint32_t)mConfig.inputCfg.buffer.raw,
6759 mConfig.inputCfg.buffer.frameCount,
6760 mConfig.inputCfg.samplingRate,
6761 mConfig.inputCfg.channels,
6762 mConfig.inputCfg.format);
6763 result.append(buffer);
6764
6765 result.append("\t\t- Output configuration:\n");
6766 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6767 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6768 (uint32_t)mConfig.outputCfg.buffer.raw,
6769 mConfig.outputCfg.buffer.frameCount,
6770 mConfig.outputCfg.samplingRate,
6771 mConfig.outputCfg.channels,
6772 mConfig.outputCfg.format);
6773 result.append(buffer);
6774
6775 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6776 result.append(buffer);
6777 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6778 for (size_t i = 0; i < mHandles.size(); ++i) {
6779 sp<EffectHandle> handle = mHandles[i].promote();
6780 if (handle != 0) {
6781 handle->dump(buffer, SIZE);
6782 result.append(buffer);
6783 }
6784 }
6785
6786 result.append("\n");
6787
6788 write(fd, result.string(), result.length());
6789
6790 if (locked) {
6791 mLock.unlock();
6792 }
6793
6794 return NO_ERROR;
6795}
6796
6797// ----------------------------------------------------------------------------
6798// EffectHandle implementation
6799// ----------------------------------------------------------------------------
6800
6801#undef LOG_TAG
6802#define LOG_TAG "AudioFlinger::EffectHandle"
6803
6804AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6805 const sp<AudioFlinger::Client>& client,
6806 const sp<IEffectClient>& effectClient,
6807 int32_t priority)
6808 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006809 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006810 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006811{
Steve Block71f2cf12011-10-20 11:56:00 +01006812 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006813
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006814 if (client == 0) {
6815 return;
6816 }
Eric Laurent65b65452010-06-01 23:49:17 -07006817 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6818 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6819 if (mCblkMemory != 0) {
6820 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6821
Glenn Kasten3694ec12012-01-27 16:47:15 -08006822 if (mCblk != NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006823 new(mCblk) effect_param_cblk_t();
6824 mBuffer = (uint8_t *)mCblk + bufOffset;
6825 }
6826 } else {
Steve Block3762c312012-01-06 19:20:56 +00006827 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006828 return;
6829 }
6830}
6831
6832AudioFlinger::EffectHandle::~EffectHandle()
6833{
Steve Block71f2cf12011-10-20 11:56:00 +01006834 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006835 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01006836 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006837}
6838
6839status_t AudioFlinger::EffectHandle::enable()
6840{
Steve Block71f2cf12011-10-20 11:56:00 +01006841 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006842 if (!mHasControl) return INVALID_OPERATION;
6843 if (mEffect == 0) return DEAD_OBJECT;
6844
Eric Laurent6752ec82011-08-10 10:37:50 -07006845 if (mEnabled) {
6846 return NO_ERROR;
6847 }
6848
Eric Laurentf82fccd2011-07-27 19:49:51 -07006849 mEnabled = true;
6850
6851 sp<ThreadBase> thread = mEffect->thread().promote();
6852 if (thread != 0) {
6853 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6854 }
6855
6856 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6857 if (mEffect->suspended()) {
6858 return NO_ERROR;
6859 }
6860
Eric Laurent6752ec82011-08-10 10:37:50 -07006861 status_t status = mEffect->setEnabled(true);
6862 if (status != NO_ERROR) {
6863 if (thread != 0) {
6864 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6865 }
6866 mEnabled = false;
6867 }
6868 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006869}
6870
6871status_t AudioFlinger::EffectHandle::disable()
6872{
Steve Block71f2cf12011-10-20 11:56:00 +01006873 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006874 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006875 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006876
Eric Laurent6752ec82011-08-10 10:37:50 -07006877 if (!mEnabled) {
6878 return NO_ERROR;
6879 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006880 mEnabled = false;
6881
6882 if (mEffect->suspended()) {
6883 return NO_ERROR;
6884 }
6885
6886 status_t status = mEffect->setEnabled(false);
6887
6888 sp<ThreadBase> thread = mEffect->thread().promote();
6889 if (thread != 0) {
6890 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6891 }
6892
6893 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006894}
6895
6896void AudioFlinger::EffectHandle::disconnect()
6897{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006898 disconnect(true);
6899}
6900
6901void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6902{
Steve Block71f2cf12011-10-20 11:56:00 +01006903 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006904 if (mEffect == 0) {
6905 return;
6906 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006907 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006908
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006909 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006910 sp<ThreadBase> thread = mEffect->thread().promote();
6911 if (thread != 0) {
6912 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6913 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006914 }
6915
Eric Laurent65b65452010-06-01 23:49:17 -07006916 // release sp on module => module destructor can be called now
6917 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006918 if (mClient != 0) {
Glenn Kasten3694ec12012-01-27 16:47:15 -08006919 if (mCblk != NULL) {
Glenn Kastend9d68dc2012-02-03 10:24:48 -08006920 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006921 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6922 }
Glenn Kastenf31d0502012-01-25 15:27:15 -08006923 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten803a86a2012-01-25 14:28:29 -08006924 // Client destructor must run with AudioFlinger mutex locked
Eric Laurent65b65452010-06-01 23:49:17 -07006925 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6926 mClient.clear();
6927 }
6928}
6929
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006930status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6931 uint32_t cmdSize,
6932 void *pCmdData,
6933 uint32_t *replySize,
6934 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006935{
Steve Block71f2cf12011-10-20 11:56:00 +01006936// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006937// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006938
6939 // only get parameter command is permitted for applications not controlling the effect
6940 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6941 return INVALID_OPERATION;
6942 }
6943 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006944 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006945
6946 // handle commands that are not forwarded transparently to effect engine
6947 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6948 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6949 // no risk to block the whole media server process or mixer threads is we are stuck here
6950 Mutex::Autolock _l(mCblk->lock);
6951 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6952 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6953 mCblk->serverIndex = 0;
6954 mCblk->clientIndex = 0;
6955 return BAD_VALUE;
6956 }
6957 status_t status = NO_ERROR;
6958 while (mCblk->serverIndex < mCblk->clientIndex) {
6959 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006960 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006961 int *p = (int *)(mBuffer + mCblk->serverIndex);
6962 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006963 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block8564c8d2012-01-05 23:22:43 +00006964 ALOGW("command(): invalid parameter block size");
Eric Laurent53334cd2010-06-23 17:38:20 -07006965 break;
6966 }
Eric Laurent65b65452010-06-01 23:49:17 -07006967 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006968 if (param->psize == 0 || param->vsize == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006969 ALOGW("command(): null parameter or value size");
Eric Laurent53334cd2010-06-23 17:38:20 -07006970 mCblk->serverIndex += size;
6971 continue;
6972 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006973 uint32_t psize = sizeof(effect_param_t) +
6974 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6975 param->vsize;
6976 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6977 psize,
6978 p,
6979 &rsize,
6980 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006981 // stop at first error encountered
6982 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006983 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006984 *(int *)pReplyData = reply;
6985 break;
6986 } else if (reply != NO_ERROR) {
6987 *(int *)pReplyData = reply;
6988 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006989 }
6990 mCblk->serverIndex += size;
6991 }
6992 mCblk->serverIndex = 0;
6993 mCblk->clientIndex = 0;
6994 return status;
6995 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006996 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006997 return enable();
6998 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006999 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007000 return disable();
7001 }
7002
7003 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7004}
7005
Eric Laurentf82fccd2011-07-27 19:49:51 -07007006void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07007007{
Steve Block71f2cf12011-10-20 11:56:00 +01007008 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07007009
7010 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007011 mEnabled = enabled;
7012
Eric Laurent65b65452010-06-01 23:49:17 -07007013 if (signal && mEffectClient != 0) {
7014 mEffectClient->controlStatusChanged(hasControl);
7015 }
7016}
7017
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007018void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7019 uint32_t cmdSize,
7020 void *pCmdData,
7021 uint32_t replySize,
7022 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007023{
7024 if (mEffectClient != 0) {
7025 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7026 }
7027}
7028
7029
7030
7031void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7032{
7033 if (mEffectClient != 0) {
7034 mEffectClient->enableStatusChanged(enabled);
7035 }
7036}
7037
7038status_t AudioFlinger::EffectHandle::onTransact(
7039 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7040{
7041 return BnEffect::onTransact(code, data, reply, flags);
7042}
7043
7044
7045void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7046{
Glenn Kasten3694ec12012-01-27 16:47:15 -08007047 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Eric Laurent65b65452010-06-01 23:49:17 -07007048
7049 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten706b6182012-01-20 13:44:40 -08007050 (mClient == 0) ? getpid() : mClient->pid(),
Eric Laurent65b65452010-06-01 23:49:17 -07007051 mPriority,
7052 mHasControl,
7053 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007054 mCblk ? mCblk->clientIndex : 0,
7055 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007056 );
7057
7058 if (locked) {
7059 mCblk->lock.unlock();
7060 }
7061}
7062
7063#undef LOG_TAG
7064#define LOG_TAG "AudioFlinger::EffectChain"
7065
7066AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7067 int sessionId)
Eric Laurentf9c361d2011-11-11 15:42:52 -08007068 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007069 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7070 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007071{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007072 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007073 sp<ThreadBase> thread = mThread.promote();
7074 if (thread == 0) {
7075 return;
7076 }
7077 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7078 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007079}
7080
7081AudioFlinger::EffectChain::~EffectChain()
7082{
7083 if (mOwnInBuffer) {
7084 delete mInBuffer;
7085 }
7086
7087}
7088
Eric Laurentf82fccd2011-07-27 19:49:51 -07007089// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007090sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007091{
Eric Laurent65b65452010-06-01 23:49:17 -07007092 size_t size = mEffects.size();
7093
7094 for (size_t i = 0; i < size; i++) {
7095 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007096 return mEffects[i];
Eric Laurent65b65452010-06-01 23:49:17 -07007097 }
7098 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007099 return 0;
Eric Laurent65b65452010-06-01 23:49:17 -07007100}
7101
Eric Laurentf82fccd2011-07-27 19:49:51 -07007102// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007103sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007104{
Eric Laurent65b65452010-06-01 23:49:17 -07007105 size_t size = mEffects.size();
7106
7107 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007108 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7109 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007110 return mEffects[i];
Eric Laurent65b65452010-06-01 23:49:17 -07007111 }
7112 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007113 return 0;
Eric Laurent65b65452010-06-01 23:49:17 -07007114}
7115
Eric Laurentf82fccd2011-07-27 19:49:51 -07007116// getEffectFromType_l() must be called with ThreadBase::mLock held
7117sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7118 const effect_uuid_t *type)
7119{
Eric Laurentf82fccd2011-07-27 19:49:51 -07007120 size_t size = mEffects.size();
7121
7122 for (size_t i = 0; i < size; i++) {
7123 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007124 return mEffects[i];
Eric Laurentf82fccd2011-07-27 19:49:51 -07007125 }
7126 }
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007127 return 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007128}
7129
Eric Laurent65b65452010-06-01 23:49:17 -07007130// Must be called with EffectChain::mLock locked
7131void AudioFlinger::EffectChain::process_l()
7132{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007133 sp<ThreadBase> thread = mThread.promote();
7134 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007135 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007136 return;
7137 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007138 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7139 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007140 // always process effects unless no more tracks are on the session and the effect tail
7141 // has been rendered
7142 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007143 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007144 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007145
Eric Laurentf9c361d2011-11-11 15:42:52 -08007146 if (!tracksOnSession && mTailBufferCount == 0) {
7147 doProcess = false;
7148 }
7149
7150 if (activeTrackCnt() == 0) {
7151 // if no track is active and the effect tail has not been rendered,
7152 // the input buffer must be cleared here as the mixer process will not do it
7153 if (tracksOnSession || mTailBufferCount > 0) {
7154 size_t numSamples = thread->frameCount() * thread->channelCount();
7155 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7156 if (mTailBufferCount > 0) {
7157 mTailBufferCount--;
7158 }
7159 }
7160 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007161 }
7162
Eric Laurent65b65452010-06-01 23:49:17 -07007163 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007164 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007165 for (size_t i = 0; i < size; i++) {
7166 mEffects[i]->process();
7167 }
Eric Laurent65b65452010-06-01 23:49:17 -07007168 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007169 for (size_t i = 0; i < size; i++) {
7170 mEffects[i]->updateState();
7171 }
Eric Laurent65b65452010-06-01 23:49:17 -07007172}
7173
Eric Laurent76c40f72010-07-15 12:50:15 -07007174// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007175status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007176{
7177 effect_descriptor_t desc = effect->desc();
7178 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7179
7180 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007181 effect->setChain(this);
7182 sp<ThreadBase> thread = mThread.promote();
7183 if (thread == 0) {
7184 return NO_INIT;
7185 }
7186 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007187
7188 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7189 // Auxiliary effects are inserted at the beginning of mEffects vector as
7190 // they are processed first and accumulated in chain input buffer
7191 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007192
Eric Laurent65b65452010-06-01 23:49:17 -07007193 // the input buffer for auxiliary effect contains mono samples in
7194 // 32 bit format. This is to avoid saturation in AudoMixer
7195 // accumulation stage. Saturation is done in EffectModule::process() before
7196 // calling the process in effect engine
7197 size_t numSamples = thread->frameCount();
7198 int32_t *buffer = new int32_t[numSamples];
7199 memset(buffer, 0, numSamples * sizeof(int32_t));
7200 effect->setInBuffer((int16_t *)buffer);
7201 // auxiliary effects output samples to chain input buffer for further processing
7202 // by insert effects
7203 effect->setOutBuffer(mInBuffer);
7204 } else {
7205 // Insert effects are inserted at the end of mEffects vector as they are processed
7206 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007207 // Insert effect order as a function of indicated preference:
7208 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7209 // another effect is present
7210 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7211 // last effect claiming first position
7212 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7213 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007214 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007215 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7216 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007217
7218 int size = (int)mEffects.size();
7219 int idx_insert = size;
7220 int idx_insert_first = -1;
7221 int idx_insert_last = -1;
7222
7223 for (int i = 0; i < size; i++) {
7224 effect_descriptor_t d = mEffects[i]->desc();
7225 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7226 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7227 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7228 // check invalid effect chaining combinations
7229 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007230 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block8564c8d2012-01-05 23:22:43 +00007231 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007232 return INVALID_OPERATION;
7233 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007234 // remember position of first insert effect and by default
7235 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007236 if (idx_insert == size) {
7237 idx_insert = i;
7238 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007239 // remember position of last insert effect claiming
7240 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007241 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7242 idx_insert_first = i;
7243 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007244 // remember position of first insert effect claiming
7245 // last position
7246 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7247 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007248 idx_insert_last = i;
7249 }
7250 }
7251 }
7252
Eric Laurent53334cd2010-06-23 17:38:20 -07007253 // modify idx_insert from first position if needed
7254 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7255 if (idx_insert_last != -1) {
7256 idx_insert = idx_insert_last;
7257 } else {
7258 idx_insert = size;
7259 }
7260 } else {
7261 if (idx_insert_first != -1) {
7262 idx_insert = idx_insert_first + 1;
7263 }
Eric Laurent65b65452010-06-01 23:49:17 -07007264 }
7265
7266 // always read samples from chain input buffer
7267 effect->setInBuffer(mInBuffer);
7268
7269 // if last effect in the chain, output samples to chain
7270 // output buffer, otherwise to chain input buffer
7271 if (idx_insert == size) {
7272 if (idx_insert != 0) {
7273 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7274 mEffects[idx_insert-1]->configure();
7275 }
7276 effect->setOutBuffer(mOutBuffer);
7277 } else {
7278 effect->setOutBuffer(mInBuffer);
7279 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007280 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007281
Steve Block71f2cf12011-10-20 11:56:00 +01007282 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007283 }
7284 effect->configure();
7285 return NO_ERROR;
7286}
7287
Eric Laurent76c40f72010-07-15 12:50:15 -07007288// removeEffect_l() must be called with PlaybackThread::mLock held
7289size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007290{
7291 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007292 int size = (int)mEffects.size();
7293 int i;
7294 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7295
7296 for (i = 0; i < size; i++) {
7297 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007298 // calling stop here will remove pre-processing effect from the audio HAL.
7299 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7300 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007301 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7302 mEffects[i]->state() == EffectModule::STOPPING) {
7303 mEffects[i]->stop();
7304 }
Eric Laurent65b65452010-06-01 23:49:17 -07007305 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7306 delete[] effect->inBuffer();
7307 } else {
7308 if (i == size - 1 && i != 0) {
7309 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7310 mEffects[i - 1]->configure();
7311 }
7312 }
7313 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007314 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007315 break;
7316 }
7317 }
Eric Laurent65b65452010-06-01 23:49:17 -07007318
7319 return mEffects.size();
7320}
7321
Eric Laurent76c40f72010-07-15 12:50:15 -07007322// setDevice_l() must be called with PlaybackThread::mLock held
7323void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007324{
7325 size_t size = mEffects.size();
7326 for (size_t i = 0; i < size; i++) {
7327 mEffects[i]->setDevice(device);
7328 }
7329}
7330
Eric Laurent76c40f72010-07-15 12:50:15 -07007331// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenaccb1142012-01-04 11:00:47 -08007332void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007333{
7334 size_t size = mEffects.size();
7335 for (size_t i = 0; i < size; i++) {
7336 mEffects[i]->setMode(mode);
7337 }
7338}
7339
Eric Laurent76c40f72010-07-15 12:50:15 -07007340// setVolume_l() must be called with PlaybackThread::mLock held
7341bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007342{
7343 uint32_t newLeft = *left;
7344 uint32_t newRight = *right;
7345 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007346 int ctrlIdx = -1;
7347 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007348
Eric Laurent76c40f72010-07-15 12:50:15 -07007349 // first update volume controller
7350 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007351 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007352 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7353 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007354 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007355 break;
7356 }
7357 }
7358
7359 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007360 if (hasControl) {
7361 *left = mNewLeftVolume;
7362 *right = mNewRightVolume;
7363 }
7364 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007365 }
7366
7367 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007368 mLeftVolume = newLeft;
7369 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007370
7371 // second get volume update from volume controller
7372 if (ctrlIdx >= 0) {
7373 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007374 mNewLeftVolume = newLeft;
7375 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007376 }
7377 // then indicate volume to all other effects in chain.
7378 // Pass altered volume to effects before volume controller
7379 // and requested volume to effects after controller
7380 uint32_t lVol = newLeft;
7381 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007382
Eric Laurent65b65452010-06-01 23:49:17 -07007383 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007384 if ((int)i == ctrlIdx) continue;
7385 // this also works for ctrlIdx == -1 when there is no volume controller
7386 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007387 lVol = *left;
7388 rVol = *right;
7389 }
7390 mEffects[i]->setVolume(&lVol, &rVol, false);
7391 }
7392 *left = newLeft;
7393 *right = newRight;
7394
7395 return hasControl;
7396}
7397
Eric Laurent65b65452010-06-01 23:49:17 -07007398status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7399{
7400 const size_t SIZE = 256;
7401 char buffer[SIZE];
7402 String8 result;
7403
7404 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7405 result.append(buffer);
7406
7407 bool locked = tryLock(mLock);
7408 // failed to lock - AudioFlinger is probably deadlocked
7409 if (!locked) {
7410 result.append("\tCould not lock mutex:\n");
7411 }
7412
Eric Laurent76c40f72010-07-15 12:50:15 -07007413 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7414 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007415 mEffects.size(),
7416 (uint32_t)mInBuffer,
7417 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007418 mActiveTrackCnt);
7419 result.append(buffer);
7420 write(fd, result.string(), result.size());
7421
7422 for (size_t i = 0; i < mEffects.size(); ++i) {
7423 sp<EffectModule> effect = mEffects[i];
7424 if (effect != 0) {
7425 effect->dump(fd, args);
7426 }
7427 }
7428
7429 if (locked) {
7430 mLock.unlock();
7431 }
7432
7433 return NO_ERROR;
7434}
7435
Eric Laurentf82fccd2011-07-27 19:49:51 -07007436// must be called with ThreadBase::mLock held
7437void AudioFlinger::EffectChain::setEffectSuspended_l(
7438 const effect_uuid_t *type, bool suspend)
7439{
7440 sp<SuspendedEffectDesc> desc;
7441 // use effect type UUID timelow as key as there is no real risk of identical
7442 // timeLow fields among effect type UUIDs.
7443 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7444 if (suspend) {
7445 if (index >= 0) {
7446 desc = mSuspendedEffects.valueAt(index);
7447 } else {
7448 desc = new SuspendedEffectDesc();
7449 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7450 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007451 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007452 }
7453 if (desc->mRefCount++ == 0) {
7454 sp<EffectModule> effect = getEffectIfEnabled(type);
7455 if (effect != 0) {
7456 desc->mEffect = effect;
7457 effect->setSuspended(true);
7458 effect->setEnabled(false);
7459 }
7460 }
7461 } else {
7462 if (index < 0) {
7463 return;
7464 }
7465 desc = mSuspendedEffects.valueAt(index);
7466 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007467 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007468 desc->mRefCount = 1;
7469 }
7470 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007471 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007472 if (desc->mEffect != 0) {
7473 sp<EffectModule> effect = desc->mEffect.promote();
7474 if (effect != 0) {
7475 effect->setSuspended(false);
7476 sp<EffectHandle> handle = effect->controlHandle();
7477 if (handle != 0) {
7478 effect->setEnabled(handle->enabled());
7479 }
7480 }
7481 desc->mEffect.clear();
7482 }
7483 mSuspendedEffects.removeItemsAt(index);
7484 }
7485 }
7486}
7487
7488// must be called with ThreadBase::mLock held
7489void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7490{
7491 sp<SuspendedEffectDesc> desc;
7492
7493 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7494 if (suspend) {
7495 if (index >= 0) {
7496 desc = mSuspendedEffects.valueAt(index);
7497 } else {
7498 desc = new SuspendedEffectDesc();
7499 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007500 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007501 }
7502 if (desc->mRefCount++ == 0) {
Glenn Kasten97040262012-01-30 12:56:03 -08007503 Vector< sp<EffectModule> > effects;
7504 getSuspendEligibleEffects(effects);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007505 for (size_t i = 0; i < effects.size(); i++) {
7506 setEffectSuspended_l(&effects[i]->desc().type, true);
7507 }
7508 }
7509 } else {
7510 if (index < 0) {
7511 return;
7512 }
7513 desc = mSuspendedEffects.valueAt(index);
7514 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007515 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007516 desc->mRefCount = 1;
7517 }
7518 if (--desc->mRefCount == 0) {
7519 Vector<const effect_uuid_t *> types;
7520 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7521 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7522 continue;
7523 }
7524 types.add(&mSuspendedEffects.valueAt(i)->mType);
7525 }
7526 for (size_t i = 0; i < types.size(); i++) {
7527 setEffectSuspended_l(types[i], false);
7528 }
Steve Block71f2cf12011-10-20 11:56:00 +01007529 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007530 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7531 }
7532 }
7533}
7534
Eric Laurent5e7acae2011-09-23 08:40:41 -07007535
7536// The volume effect is used for automated tests only
7537#ifndef OPENSL_ES_H_
7538static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7539 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7540const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7541#endif //OPENSL_ES_H_
7542
Eric Laurent6752ec82011-08-10 10:37:50 -07007543bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7544{
7545 // auxiliary effects and visualizer are never suspended on output mix
7546 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7547 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007548 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7549 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007550 return false;
7551 }
7552 return true;
7553}
7554
Glenn Kasten97040262012-01-30 12:56:03 -08007555void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurentf82fccd2011-07-27 19:49:51 -07007556{
Glenn Kasten97040262012-01-30 12:56:03 -08007557 effects.clear();
Eric Laurentf82fccd2011-07-27 19:49:51 -07007558 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kasten97040262012-01-30 12:56:03 -08007559 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7560 effects.add(mEffects[i]);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007561 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007562 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007563}
7564
7565sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7566 const effect_uuid_t *type)
7567{
Glenn Kastenc64a6f02012-01-30 13:00:02 -08007568 sp<EffectModule> effect = getEffectFromType_l(type);
7569 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007570}
7571
7572void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7573 bool enabled)
7574{
7575 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7576 if (enabled) {
7577 if (index < 0) {
7578 // if the effect is not suspend check if all effects are suspended
7579 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7580 if (index < 0) {
7581 return;
7582 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007583 if (!isEffectEligibleForSuspend(effect->desc())) {
7584 return;
7585 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007586 setEffectSuspended_l(&effect->desc().type, enabled);
7587 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007588 if (index < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007589 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurent6752ec82011-08-10 10:37:50 -07007590 return;
7591 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007592 }
Steve Block71f2cf12011-10-20 11:56:00 +01007593 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007594 effect->desc().type.timeLow);
7595 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7596 // if effect is requested to suspended but was not yet enabled, supend it now.
7597 if (desc->mEffect == 0) {
7598 desc->mEffect = effect;
7599 effect->setEnabled(false);
7600 effect->setSuspended(true);
7601 }
7602 } else {
7603 if (index < 0) {
7604 return;
7605 }
Steve Block71f2cf12011-10-20 11:56:00 +01007606 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007607 effect->desc().type.timeLow);
7608 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7609 desc->mEffect.clear();
7610 effect->setSuspended(false);
7611 }
7612}
7613
Eric Laurent65b65452010-06-01 23:49:17 -07007614#undef LOG_TAG
7615#define LOG_TAG "AudioFlinger"
7616
Eric Laurenta553c252009-07-17 12:17:14 -07007617// ----------------------------------------------------------------------------
7618
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007619status_t AudioFlinger::onTransact(
7620 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7621{
7622 return BnAudioFlinger::onTransact(code, data, reply, flags);
7623}
7624
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007625}; // namespace android