blob: 990a7e2a29b2232172f4d93643e97ae8c57a2603 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Eric Laurent7d850f22010-07-09 13:34:17 -070020//#define LOG_NDEBUG 0
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070021
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9b3f1522011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian07952722009-05-19 19:08:10 -070028#include <binder/IServiceManager.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070029#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070030#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurentae29b762011-03-28 18:37:07 -070034#include <utils/Atomic.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035
Dima Zavin24fc2fb2011-04-19 22:30:36 -070036#include <cutils/bitops.h>
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080037#include <cutils/properties.h>
Glenn Kastene80a4cc2011-12-15 09:51:17 -080038#include <cutils/compiler.h>
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080039
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040#include <media/AudioTrack.h>
41#include <media/AudioRecord.h>
Gloria Wang9b3f1522011-02-24 14:51:45 -080042#include <media/IMediaPlayerService.h>
Glenn Kasten26f260a2012-01-03 15:28:29 -080043#include <media/IMediaDeathNotifier.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044
45#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070046#include <private/media/AudioEffectShared.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070047
Dima Zavin34bb4192011-05-11 14:15:23 -070048#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070049#include <hardware/audio.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070050
51#include "AudioMixer.h"
52#include "AudioFlinger.h"
53
Eric Laurent53334cd2010-06-23 17:38:20 -070054#include <media/EffectsFactoryApi.h>
Eric Laurent5cc05262011-06-24 07:01:31 -070055#include <audio_effects/effect_visualizer.h>
Eric Laurent6639b552011-08-01 09:52:20 -070056#include <audio_effects/effect_ns.h>
57#include <audio_effects/effect_aec.h>
Eric Laurent65b65452010-06-01 23:49:17 -070058
Glenn Kasten490909d2011-12-15 09:52:39 -080059#include <audio_utils/primitives.h>
60
Glenn Kastenda494f92011-07-08 15:26:12 -070061#include <cpustats/ThreadCpuUsage.h>
Eric Laurent6dbdc402011-07-22 09:04:31 -070062#include <powermanager/PowerManager.h>
Glenn Kastenda494f92011-07-08 15:26:12 -070063// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
64
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065// ----------------------------------------------------------------------------
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
Eric Laurent8ed6ed02010-07-13 04:45:46 -070067
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070068namespace android {
69
Glenn Kasten62de3db2011-12-12 09:04:45 -080070static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
71static const char kHardwareLockedString[] = "Hardware lock is taken\n";
The Android Open Source Project10592532009-03-18 17:39:46 -070072
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080073//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070074static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070075static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070076
77// retry counts for buffer fill timeout
78// 50 * ~20msecs = 1 second
79static const int8_t kMaxTrackRetries = 50;
80static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080081// allow less retry attempts on direct output thread.
82// direct outputs can be a scarce resource in audio hardware and should
83// be released as quickly as possible.
84static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070085
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070086static const int kDumpLockRetries = 50;
Glenn Kastencbfe2e12011-12-13 11:04:14 -080087static const int kDumpLockSleepUs = 20000;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070088
Glenn Kastencbfe2e12011-12-13 11:04:14 -080089// don't warn about blocked writes or record buffer overflows more often than this
90static const nsecs_t kWarningThrottleNs = seconds(5);
Dave Sparksd0ac8c02009-09-30 03:09:03 -070091
Eric Laurent464d5b32011-06-17 21:29:58 -070092// RecordThread loop sleep time upon application overrun or audio HAL read error
93static const int kRecordThreadSleepUs = 5000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
Glenn Kastencbfe2e12011-12-13 11:04:14 -080095// maximum time to wait for setParameters to complete
96static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent5f37be32011-09-13 11:40:21 -070097
Eric Laurentf1f5fc82011-11-22 18:50:29 -080098// minimum sleep time for the mixer thread loop when tracks are active but in underrun
99static const uint32_t kMinThreadSleepTimeUs = 5000;
100// maximum divider applied to the active sleep time in the mixer thread loop
101static const uint32_t kMaxThreadSleepTimeShift = 2;
102
103
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700104// ----------------------------------------------------------------------------
105
106static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700107 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
108 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block3762c312012-01-06 19:20:56 +0000109 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700110 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700111}
112
113static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700114 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
115 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block3762c312012-01-06 19:20:56 +0000116 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700117 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700118}
119
Gloria Wang9b3f1522011-02-24 14:51:45 -0800120// To collect the amplifier usage
121static void addBatteryData(uint32_t params) {
Glenn Kasten26f260a2012-01-03 15:28:29 -0800122 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
123 if (service == NULL) {
124 // it already logged
Gloria Wang9b3f1522011-02-24 14:51:45 -0800125 return;
126 }
127
128 service->addBatteryData(params);
129}
130
Dima Zavin31f188892011-04-18 16:57:27 -0700131static int load_audio_interface(const char *if_name, const hw_module_t **mod,
132 audio_hw_device_t **dev)
133{
134 int rc;
135
136 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
137 if (rc)
138 goto out;
139
140 rc = audio_hw_device_open(*mod, dev);
Steve Block3762c312012-01-06 19:20:56 +0000141 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin31f188892011-04-18 16:57:27 -0700142 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
143 if (rc)
144 goto out;
145
146 return 0;
147
148out:
149 *mod = NULL;
150 *dev = NULL;
151 return rc;
152}
153
Glenn Kasten62de3db2011-12-12 09:04:45 -0800154static const char * const audio_interfaces[] = {
Dima Zavin31f188892011-04-18 16:57:27 -0700155 "primary",
156 "a2dp",
157 "usb",
158};
159#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
160
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700161// ----------------------------------------------------------------------------
162
163AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 : BnAudioFlinger(),
Glenn Kastenc434c902011-12-13 11:53:26 -0800165 mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700166 mBtNrecIsOff(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700167{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700168}
169
170void AudioFlinger::onFirstRef()
171{
Dima Zavin31f188892011-04-18 16:57:27 -0700172 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700173
Eric Laurent01635942011-01-18 18:39:02 -0800174 Mutex::Autolock _l(mLock);
175
Dima Zavin31f188892011-04-18 16:57:27 -0700176 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700177 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700178
Dima Zavin31f188892011-04-18 16:57:27 -0700179 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
180 const hw_module_t *mod;
181 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700182
Dima Zavin31f188892011-04-18 16:57:27 -0700183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184 if (rc)
185 continue;
186
Steve Block6215d3f2012-01-04 20:05:49 +0000187 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin31f188892011-04-18 16:57:27 -0700188 mod->name, mod->id);
189 mAudioHwDevs.push(dev);
190
191 if (!mPrimaryHardwareDev) {
192 mPrimaryHardwareDev = dev;
Steve Block6215d3f2012-01-04 20:05:49 +0000193 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700194 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700195 }
196 }
Eric Laurenta553c252009-07-17 12:17:14 -0700197
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700198 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700199
Dima Zavin31f188892011-04-18 16:57:27 -0700200 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
Steve Block3762c312012-01-06 19:20:56 +0000201 ALOGE("Primary audio interface not found");
Dima Zavin31f188892011-04-18 16:57:27 -0700202 return;
203 }
204
205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
206 audio_hw_device_t *dev = mAudioHwDevs[i];
207
208 mHardwareStatus = AUDIO_HW_INIT;
209 rc = dev->init_check(dev);
210 if (rc == 0) {
211 AutoMutex lock(mHardwareLock);
212
213 mMode = AUDIO_MODE_NORMAL;
214 mHardwareStatus = AUDIO_HW_SET_MODE;
215 dev->set_mode(dev, mMode);
216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
217 dev->set_master_volume(dev, 1.0f);
218 mHardwareStatus = AUDIO_HW_IDLE;
219 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700220 }
221}
222
Dima Zavin2986f5b2011-04-19 19:04:32 -0700223status_t AudioFlinger::initCheck() const
224{
225 Mutex::Autolock _l(mLock);
226 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
227 return NO_INIT;
228 return NO_ERROR;
229}
230
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700231AudioFlinger::~AudioFlinger()
232{
Dima Zavin31f188892011-04-18 16:57:27 -0700233 int num_devs = mAudioHwDevs.size();
234
Eric Laurent7954c462009-08-28 10:39:03 -0700235 while (!mRecordThreads.isEmpty()) {
236 // closeInput() will remove first entry from mRecordThreads
237 closeInput(mRecordThreads.keyAt(0));
238 }
239 while (!mPlaybackThreads.isEmpty()) {
240 // closeOutput() will remove first entry from mPlaybackThreads
241 closeOutput(mPlaybackThreads.keyAt(0));
242 }
Dima Zavin31f188892011-04-18 16:57:27 -0700243
244 for (int i = 0; i < num_devs; i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700247 }
Dima Zavin31f188892011-04-18 16:57:27 -0700248 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800249}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800250
Dima Zavin31f188892011-04-18 16:57:27 -0700251audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
252{
253 /* first matching HW device is returned */
254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
255 audio_hw_device_t *dev = mAudioHwDevs[i];
256 if ((dev->get_supported_devices(dev) & devices) == devices)
257 return dev;
258 }
259 return NULL;
260}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700261
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700262status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
263{
264 const size_t SIZE = 256;
265 char buffer[SIZE];
266 String8 result;
267
268 result.append("Clients:\n");
269 for (size_t i = 0; i < mClients.size(); ++i) {
270 wp<Client> wClient = mClients.valueAt(i);
271 if (wClient != 0) {
272 sp<Client> client = wClient.promote();
273 if (client != 0) {
274 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
275 result.append(buffer);
276 }
277 }
278 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700279
280 result.append("Global session refs:\n");
281 result.append(" session pid cnt\n");
282 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
283 AudioSessionRef *r = mAudioSessionRefs[i];
284 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
285 result.append(buffer);
286 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700287 write(fd, result.string(), result.size());
288 return NO_ERROR;
289}
290
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700291
292status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
293{
294 const size_t SIZE = 256;
295 char buffer[SIZE];
296 String8 result;
Glenn Kastena934c2c2012-01-04 11:02:33 -0800297 hardware_call_state hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700298
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700299 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700300 result.append(buffer);
301 write(fd, result.string(), result.size());
302 return NO_ERROR;
303}
304
305status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
306{
307 const size_t SIZE = 256;
308 char buffer[SIZE];
309 String8 result;
310 snprintf(buffer, SIZE, "Permission Denial: "
311 "can't dump AudioFlinger from pid=%d, uid=%d\n",
312 IPCThreadState::self()->getCallingPid(),
313 IPCThreadState::self()->getCallingUid());
314 result.append(buffer);
315 write(fd, result.string(), result.size());
316 return NO_ERROR;
317}
318
The Android Open Source Project10592532009-03-18 17:39:46 -0700319static bool tryLock(Mutex& mutex)
320{
321 bool locked = false;
322 for (int i = 0; i < kDumpLockRetries; ++i) {
323 if (mutex.tryLock() == NO_ERROR) {
324 locked = true;
325 break;
326 }
Glenn Kastencbfe2e12011-12-13 11:04:14 -0800327 usleep(kDumpLockSleepUs);
The Android Open Source Project10592532009-03-18 17:39:46 -0700328 }
329 return locked;
330}
331
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700332status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
333{
334 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
335 dumpPermissionDenial(fd, args);
336 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700337 // get state of hardware lock
338 bool hardwareLocked = tryLock(mHardwareLock);
339 if (!hardwareLocked) {
340 String8 result(kHardwareLockedString);
341 write(fd, result.string(), result.size());
342 } else {
343 mHardwareLock.unlock();
344 }
345
346 bool locked = tryLock(mLock);
347
348 // failed to lock - AudioFlinger is probably deadlocked
349 if (!locked) {
350 String8 result(kDeadlockedString);
351 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700352 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700353
354 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700355 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356
Eric Laurenta553c252009-07-17 12:17:14 -0700357 // dump playback threads
358 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700359 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700360 }
361
362 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700363 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700364 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366
Dima Zavin31f188892011-04-18 16:57:27 -0700367 // dump all hardware devs
368 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
369 audio_hw_device_t *dev = mAudioHwDevs[i];
370 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700371 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700372 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700373 }
374 return NO_ERROR;
375}
376
Eric Laurenta553c252009-07-17 12:17:14 -0700377
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700378// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379
380
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700381sp<IAudioTrack> AudioFlinger::createTrack(
382 pid_t pid,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800383 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700384 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700385 uint32_t format,
386 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800387 int frameCount,
388 uint32_t flags,
389 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700390 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700391 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800392 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700393{
Eric Laurenta553c252009-07-17 12:17:14 -0700394 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700395 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700396 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800397 wp<Client> wclient;
398 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700399 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700400
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700401 if (streamType >= AUDIO_STREAM_CNT) {
Steve Block3762c312012-01-06 19:20:56 +0000402 ALOGE("createTrack() invalid stream type %d", streamType);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800403 lStatus = BAD_VALUE;
404 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700405 }
406
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800407 {
408 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700409 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700410 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700411 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +0000412 ALOGE("unknown output thread");
Eric Laurenta553c252009-07-17 12:17:14 -0700413 lStatus = BAD_VALUE;
414 goto Exit;
415 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800416
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800417 wclient = mClients.valueFor(pid);
418
419 if (wclient != NULL) {
420 client = wclient.promote();
421 } else {
422 client = new Client(this, pid);
423 mClients.add(pid, client);
424 }
Eric Laurent65b65452010-06-01 23:49:17 -0700425
Steve Block71f2cf12011-10-20 11:56:00 +0100426 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700427 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700428 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700429 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
430 if (mPlaybackThreads.keyAt(i) != output) {
431 // prevent same audio session on different output threads
432 uint32_t sessions = t->hasAudioSession(*sessionId);
433 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block3762c312012-01-06 19:20:56 +0000434 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent493941b2010-07-28 01:32:47 -0700435 lStatus = BAD_VALUE;
436 goto Exit;
437 }
438 // check if an effect with same session ID is waiting for a track to be created
439 if (sessions & PlaybackThread::EFFECT_SESSION) {
440 effectThread = t.get();
441 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700442 }
443 }
Eric Laurent65b65452010-06-01 23:49:17 -0700444 lSessionId = *sessionId;
445 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700446 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700447 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700448 if (sessionId != NULL) {
449 *sessionId = lSessionId;
450 }
451 }
Steve Block71f2cf12011-10-20 11:56:00 +0100452 ALOGV("createTrack() lSessionId: %d", lSessionId);
Eric Laurent65b65452010-06-01 23:49:17 -0700453
Eric Laurenta553c252009-07-17 12:17:14 -0700454 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700455 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700456
457 // move effect chain to this output thread if an effect on same session was waiting
458 // for a track to be created
459 if (lStatus == NO_ERROR && effectThread != NULL) {
460 Mutex::Autolock _dl(thread->mLock);
461 Mutex::Autolock _sl(effectThread->mLock);
462 moveEffectChain_l(lSessionId, effectThread, thread, true);
463 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700464 }
465 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800466 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700467 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700468 // remove local strong reference to Client before deleting the Track so that the Client
469 // destructor is called by the TrackBase destructor with mLock held
470 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700471 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800472 }
473
474Exit:
475 if(status) {
476 *status = lStatus;
477 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700478 return trackHandle;
479}
480
Eric Laurentddb78e72009-07-28 08:44:33 -0700481uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700482{
Eric Laurenta553c252009-07-17 12:17:14 -0700483 Mutex::Autolock _l(mLock);
484 PlaybackThread *thread = checkPlaybackThread_l(output);
485 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000486 ALOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700487 return 0;
488 }
489 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700490}
491
Eric Laurentddb78e72009-07-28 08:44:33 -0700492int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700493{
Eric Laurenta553c252009-07-17 12:17:14 -0700494 Mutex::Autolock _l(mLock);
495 PlaybackThread *thread = checkPlaybackThread_l(output);
496 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000497 ALOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700498 return 0;
499 }
500 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700501}
502
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700503uint32_t AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700504{
Eric Laurenta553c252009-07-17 12:17:14 -0700505 Mutex::Autolock _l(mLock);
506 PlaybackThread *thread = checkPlaybackThread_l(output);
507 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000508 ALOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700509 return 0;
510 }
511 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700512}
513
Eric Laurentddb78e72009-07-28 08:44:33 -0700514size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700515{
Eric Laurenta553c252009-07-17 12:17:14 -0700516 Mutex::Autolock _l(mLock);
517 PlaybackThread *thread = checkPlaybackThread_l(output);
518 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000519 ALOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700520 return 0;
521 }
522 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700523}
524
Eric Laurentddb78e72009-07-28 08:44:33 -0700525uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800526{
Eric Laurenta553c252009-07-17 12:17:14 -0700527 Mutex::Autolock _l(mLock);
528 PlaybackThread *thread = checkPlaybackThread_l(output);
529 if (thread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000530 ALOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700531 return 0;
532 }
533 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800534}
535
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700536status_t AudioFlinger::setMasterVolume(float value)
537{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700538 status_t ret = initCheck();
539 if (ret != NO_ERROR) {
540 return ret;
541 }
542
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700543 // check calling permissions
544 if (!settingsAllowed()) {
545 return PERMISSION_DENIED;
546 }
547
548 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800549 { // scope for the lock
550 AutoMutex lock(mHardwareLock);
551 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700552 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800553 value = 1.0f;
554 }
555 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700556 }
Eric Laurenta553c252009-07-17 12:17:14 -0700557
Eric Laurent01635942011-01-18 18:39:02 -0800558 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700559 mMasterVolume = value;
560 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700561 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700562
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700563 return NO_ERROR;
564}
565
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700566status_t AudioFlinger::setMode(int mode)
567{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700568 status_t ret = initCheck();
569 if (ret != NO_ERROR) {
570 return ret;
571 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700572
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700573 // check calling permissions
574 if (!settingsAllowed()) {
575 return PERMISSION_DENIED;
576 }
Glenn Kasten01aaf2c2012-01-06 16:47:31 -0800577 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block8564c8d2012-01-05 23:22:43 +0000578 ALOGW("Illegal value: setMode(%d)", mode);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700579 return BAD_VALUE;
580 }
581
Eric Laurent53334cd2010-06-23 17:38:20 -0700582 { // scope for the lock
583 AutoMutex lock(mHardwareLock);
584 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700585 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700586 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800587 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700588
589 if (NO_ERROR == ret) {
590 Mutex::Autolock _l(mLock);
591 mMode = mode;
592 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
593 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700594 }
595
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700596 return ret;
597}
598
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700599status_t AudioFlinger::setMicMute(bool state)
600{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700601 status_t ret = initCheck();
602 if (ret != NO_ERROR) {
603 return ret;
604 }
605
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700606 // check calling permissions
607 if (!settingsAllowed()) {
608 return PERMISSION_DENIED;
609 }
610
611 AutoMutex lock(mHardwareLock);
612 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700613 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700614 mHardwareStatus = AUDIO_HW_IDLE;
615 return ret;
616}
617
618bool AudioFlinger::getMicMute() const
619{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700620 status_t ret = initCheck();
621 if (ret != NO_ERROR) {
622 return false;
623 }
624
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700625 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700626 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700627 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700628 mHardwareStatus = AUDIO_HW_IDLE;
629 return state;
630}
631
632status_t AudioFlinger::setMasterMute(bool muted)
633{
634 // check calling permissions
635 if (!settingsAllowed()) {
636 return PERMISSION_DENIED;
637 }
Eric Laurenta553c252009-07-17 12:17:14 -0700638
Eric Laurent01635942011-01-18 18:39:02 -0800639 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700640 mMasterMute = muted;
641 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700642 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700643
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700644 return NO_ERROR;
645}
646
647float AudioFlinger::masterVolume() const
648{
Eric Laurenta553c252009-07-17 12:17:14 -0700649 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700650}
651
652bool AudioFlinger::masterMute() const
653{
Eric Laurenta553c252009-07-17 12:17:14 -0700654 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700655}
656
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800657status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700658{
659 // check calling permissions
660 if (!settingsAllowed()) {
661 return PERMISSION_DENIED;
662 }
663
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700664 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block3762c312012-01-06 19:20:56 +0000665 ALOGE("setStreamVolume() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700666 return BAD_VALUE;
667 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800668
Eric Laurenta553c252009-07-17 12:17:14 -0700669 AutoMutex lock(mLock);
670 PlaybackThread *thread = NULL;
671 if (output) {
672 thread = checkPlaybackThread_l(output);
673 if (thread == NULL) {
674 return BAD_VALUE;
675 }
676 }
677
Eric Laurenta553c252009-07-17 12:17:14 -0700678 mStreamTypes[stream].volume = value;
679
680 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700681 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700682 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700683 }
Eric Laurenta553c252009-07-17 12:17:14 -0700684 } else {
685 thread->setStreamVolume(stream, value);
686 }
Eric Laurentef028272009-04-21 07:56:33 -0700687
Eric Laurent415f3e22009-10-21 08:14:22 -0700688 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700689}
690
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800691status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700692{
693 // check calling permissions
694 if (!settingsAllowed()) {
695 return PERMISSION_DENIED;
696 }
697
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700698 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
699 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block3762c312012-01-06 19:20:56 +0000700 ALOGE("setStreamMute() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700701 return BAD_VALUE;
702 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700703
Eric Laurent01635942011-01-18 18:39:02 -0800704 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700705 mStreamTypes[stream].mute = muted;
706 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700707 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700709 return NO_ERROR;
710}
711
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800712float AudioFlinger::streamVolume(audio_stream_type_t stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700713{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700714 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700715 return 0.0f;
716 }
Eric Laurenta553c252009-07-17 12:17:14 -0700717
718 AutoMutex lock(mLock);
719 float volume;
720 if (output) {
721 PlaybackThread *thread = checkPlaybackThread_l(output);
722 if (thread == NULL) {
723 return 0.0f;
724 }
725 volume = thread->streamVolume(stream);
726 } else {
727 volume = mStreamTypes[stream].volume;
728 }
729
Eric Laurentef028272009-04-21 07:56:33 -0700730 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700731}
732
Glenn Kastenbc1d77b2012-01-12 16:38:12 -0800733bool AudioFlinger::streamMute(audio_stream_type_t stream) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700734{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700735 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700736 return true;
737 }
Eric Laurenta553c252009-07-17 12:17:14 -0700738
739 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700740}
741
Eric Laurentddb78e72009-07-28 08:44:33 -0700742status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700743{
Eric Laurenta553c252009-07-17 12:17:14 -0700744 status_t result;
745
Steve Block71f2cf12011-10-20 11:56:00 +0100746 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700747 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
748 // check calling permissions
749 if (!settingsAllowed()) {
750 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800751 }
Eric Laurenta553c252009-07-17 12:17:14 -0700752
753 // ioHandle == 0 means the parameters are global to the audio hardware interface
754 if (ioHandle == 0) {
755 AutoMutex lock(mHardwareLock);
756 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700757 status_t final_result = NO_ERROR;
758 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
759 audio_hw_device_t *dev = mAudioHwDevs[i];
760 result = dev->set_parameters(dev, keyValuePairs.string());
761 final_result = result ?: final_result;
762 }
Eric Laurenta553c252009-07-17 12:17:14 -0700763 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent6639b552011-08-01 09:52:20 -0700764 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
765 AudioParameter param = AudioParameter(keyValuePairs);
766 String8 value;
767 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
768 Mutex::Autolock _l(mLock);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700769 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
770 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent6639b552011-08-01 09:52:20 -0700771 for (size_t i = 0; i < mRecordThreads.size(); i++) {
772 sp<RecordThread> thread = mRecordThreads.valueAt(i);
773 RecordThread::RecordTrack *track = thread->track();
774 if (track != NULL) {
775 audio_devices_t device = (audio_devices_t)(
776 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700777 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700778 thread->setEffectSuspended(FX_IID_AEC,
779 suspend,
780 track->sessionId());
781 thread->setEffectSuspended(FX_IID_NS,
782 suspend,
783 track->sessionId());
784 }
785 }
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700786 mBtNrecIsOff = btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700787 }
788 }
Dima Zavin31f188892011-04-18 16:57:27 -0700789 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700790 }
791
Eric Laurentb7d94602009-09-29 11:12:57 -0700792 // hold a strong ref on thread in case closeOutput() or closeInput() is called
793 // and the thread is exited once the lock is released
794 sp<ThreadBase> thread;
795 {
796 Mutex::Autolock _l(mLock);
797 thread = checkPlaybackThread_l(ioHandle);
798 if (thread == NULL) {
799 thread = checkRecordThread_l(ioHandle);
Eric Laurent464d5b32011-06-17 21:29:58 -0700800 } else if (thread.get() == primaryPlaybackThread_l()) {
801 // indicate output device change to all input threads for pre processing
802 AudioParameter param = AudioParameter(keyValuePairs);
803 int value;
804 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
805 for (size_t i = 0; i < mRecordThreads.size(); i++) {
806 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
807 }
808 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700809 }
Eric Laurenta553c252009-07-17 12:17:14 -0700810 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700811 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800812 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800813 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700814 }
Eric Laurenta553c252009-07-17 12:17:14 -0700815 return BAD_VALUE;
816}
817
Eric Laurentddb78e72009-07-28 08:44:33 -0700818String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700819{
Steve Block71f2cf12011-10-20 11:56:00 +0100820// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700821// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
822
823 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700824 String8 out_s8;
825
Dima Zavin31f188892011-04-18 16:57:27 -0700826 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
827 audio_hw_device_t *dev = mAudioHwDevs[i];
828 char *s = dev->get_parameters(dev, keys.string());
829 out_s8 += String8(s);
830 free(s);
831 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700832 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700833 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700834
835 Mutex::Autolock _l(mLock);
836
Eric Laurenta553c252009-07-17 12:17:14 -0700837 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
838 if (playbackThread != NULL) {
839 return playbackThread->getParameters(keys);
840 }
841 RecordThread *recordThread = checkRecordThread_l(ioHandle);
842 if (recordThread != NULL) {
843 return recordThread->getParameters(keys);
844 }
845 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700846}
847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
849{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700850 status_t ret = initCheck();
851 if (ret != NO_ERROR) {
852 return 0;
853 }
854
Dima Zavin31f188892011-04-18 16:57:27 -0700855 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856}
857
Eric Laurent47d0a922010-02-26 02:47:27 -0800858unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
859{
860 if (ioHandle == 0) {
861 return 0;
862 }
863
864 Mutex::Autolock _l(mLock);
865
866 RecordThread *recordThread = checkRecordThread_l(ioHandle);
867 if (recordThread != NULL) {
868 return recordThread->getInputFramesLost();
869 }
870 return 0;
871}
872
Eric Laurent415f3e22009-10-21 08:14:22 -0700873status_t AudioFlinger::setVoiceVolume(float value)
874{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700875 status_t ret = initCheck();
876 if (ret != NO_ERROR) {
877 return ret;
878 }
879
Eric Laurent415f3e22009-10-21 08:14:22 -0700880 // check calling permissions
881 if (!settingsAllowed()) {
882 return PERMISSION_DENIED;
883 }
884
885 AutoMutex lock(mHardwareLock);
886 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700887 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700888 mHardwareStatus = AUDIO_HW_IDLE;
889
890 return ret;
891}
892
Eric Laurent0986e792010-01-19 17:37:09 -0800893status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
894{
895 status_t status;
896
897 Mutex::Autolock _l(mLock);
898
899 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
900 if (playbackThread != NULL) {
901 return playbackThread->getRenderPosition(halFrames, dspFrames);
902 }
903
904 return BAD_VALUE;
905}
906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
908{
Eric Laurenta553c252009-07-17 12:17:14 -0700909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 Mutex::Autolock _l(mLock);
911
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700912 int pid = IPCThreadState::self()->getCallingPid();
913 if (mNotificationClients.indexOfKey(pid) < 0) {
914 sp<NotificationClient> notificationClient = new NotificationClient(this,
915 client,
916 pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100917 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700918
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700919 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700920
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700921 sp<IBinder> binder = client->asBinder();
922 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700924 // the config change is always sent from playback or record threads to avoid deadlock
925 // with AudioSystem::gLock
926 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
927 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
928 }
Eric Laurenta553c252009-07-17 12:17:14 -0700929
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700930 for (size_t i = 0; i < mRecordThreads.size(); i++) {
931 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 }
933 }
934}
935
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700936void AudioFlinger::removeNotificationClient(pid_t pid)
937{
938 Mutex::Autolock _l(mLock);
939
940 int index = mNotificationClients.indexOfKey(pid);
941 if (index >= 0) {
942 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100943 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700944 mNotificationClients.removeItem(pid);
945 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700946
Steve Block71f2cf12011-10-20 11:56:00 +0100947 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700948 int num = mAudioSessionRefs.size();
949 bool removed = false;
950 for (int i = 0; i< num; i++) {
951 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +0100952 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700953 if (ref->pid == pid) {
Steve Block71f2cf12011-10-20 11:56:00 +0100954 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700955 mAudioSessionRefs.removeAt(i);
956 delete ref;
957 removed = true;
958 i--;
959 num--;
960 }
961 }
962 if (removed) {
963 purgeStaleEffects_l();
964 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700965}
966
Eric Laurent296a0ec2009-09-15 07:10:12 -0700967// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700968void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
969{
Eric Laurent49f02be2009-11-19 09:00:56 -0800970 size_t size = mNotificationClients.size();
971 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700972 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700973 }
974}
975
Eric Laurentb9481d82009-09-17 05:12:56 -0700976// removeClient_l() must be called with AudioFlinger::mLock held
977void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700978{
Steve Block71f2cf12011-10-20 11:56:00 +0100979 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 -0700980 mClients.removeItem(pid);
981}
982
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700983
Eric Laurenta553c252009-07-17 12:17:14 -0700984// ----------------------------------------------------------------------------
985
Eric Laurent464d5b32011-06-17 21:29:58 -0700986AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Eric Laurenta553c252009-07-17 12:17:14 -0700987 : Thread(false),
988 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent6dbdc402011-07-22 09:04:31 -0700989 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
990 mDevice(device)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700991{
Eric Laurent6dbdc402011-07-22 09:04:31 -0700992 mDeathRecipient = new PMDeathRecipient(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993}
994
Eric Laurenta553c252009-07-17 12:17:14 -0700995AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700997 mParamCond.broadcast();
Eric Laurent6dbdc402011-07-22 09:04:31 -0700998 // do not lock the mutex in destructor
999 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -07001000 if (mPowerManager != 0) {
1001 sp<IBinder> binder = mPowerManager->asBinder();
1002 binder->unlinkToDeath(mDeathRecipient);
1003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004}
1005
Eric Laurenta553c252009-07-17 12:17:14 -07001006void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001007{
Glenn Kastene5fb2632011-12-14 10:28:06 -08001008 // keep a strong ref on ourself so that we won't get
Eric Laurenta553c252009-07-17 12:17:14 -07001009 // destroyed in the middle of requestExitAndWait()
1010 sp <ThreadBase> strongMe = this;
1011
Steve Block71f2cf12011-10-20 11:56:00 +01001012 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001013 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08001014 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001015 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001016 requestExit();
1017 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001018 }
Eric Laurenta553c252009-07-17 12:17:14 -07001019 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001020}
Eric Laurenta553c252009-07-17 12:17:14 -07001021
1022uint32_t AudioFlinger::ThreadBase::sampleRate() const
1023{
1024 return mSampleRate;
1025}
1026
1027int AudioFlinger::ThreadBase::channelCount() const
1028{
Eric Laurentb0a01472010-05-14 05:45:46 -07001029 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07001030}
1031
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001032uint32_t AudioFlinger::ThreadBase::format() const
Eric Laurenta553c252009-07-17 12:17:14 -07001033{
1034 return mFormat;
1035}
1036
1037size_t AudioFlinger::ThreadBase::frameCount() const
1038{
1039 return mFrameCount;
1040}
1041
1042status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1043{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001044 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001045
Steve Block71f2cf12011-10-20 11:56:00 +01001046 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001047 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001048
Eric Laurent8fce46a2009-08-04 09:45:33 -07001049 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001050 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001051 // wait condition with timeout in case the thread loop has exited
1052 // before the request could be processed
Glenn Kastencbfe2e12011-12-13 11:04:14 -08001053 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001054 status = mParamStatus;
1055 mWaitWorkCV.signal();
1056 } else {
1057 status = TIMED_OUT;
1058 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001059 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001060}
1061
1062void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1063{
1064 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001065 sendConfigEvent_l(event, param);
1066}
1067
1068// sendConfigEvent_l() must be called with ThreadBase::mLock held
1069void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1070{
Glenn Kasten4b220f02011-12-13 11:50:00 -08001071 ConfigEvent configEvent;
1072 configEvent.mEvent = event;
1073 configEvent.mParam = param;
Eric Laurenta553c252009-07-17 12:17:14 -07001074 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001075 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001076 mWaitWorkCV.signal();
1077}
1078
1079void AudioFlinger::ThreadBase::processConfigEvents()
1080{
1081 mLock.lock();
1082 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001083 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kasten4b220f02011-12-13 11:50:00 -08001084 ConfigEvent configEvent = mConfigEvents[0];
Eric Laurenta553c252009-07-17 12:17:14 -07001085 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001086 // release mLock before locking AudioFlinger mLock: lock order is always
1087 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001088 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001089 mAudioFlinger->mLock.lock();
Glenn Kasten4b220f02011-12-13 11:50:00 -08001090 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001091 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001092 mLock.lock();
1093 }
1094 mLock.unlock();
1095}
1096
Eric Laurent3fdb1262009-11-07 00:01:32 -08001097status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1098{
1099 const size_t SIZE = 256;
1100 char buffer[SIZE];
1101 String8 result;
1102
1103 bool locked = tryLock(mLock);
1104 if (!locked) {
1105 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1106 write(fd, buffer, strlen(buffer));
1107 }
1108
1109 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1110 result.append(buffer);
1111 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1112 result.append(buffer);
1113 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1114 result.append(buffer);
1115 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1116 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001117 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1118 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001119 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1120 result.append(buffer);
1121 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1122 result.append(buffer);
1123
1124 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1125 result.append(buffer);
1126 result.append(" Index Command");
1127 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1128 snprintf(buffer, SIZE, "\n %02d ", i);
1129 result.append(buffer);
1130 result.append(mNewParameters[i]);
1131 }
1132
1133 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1134 result.append(buffer);
1135 snprintf(buffer, SIZE, " Index event param\n");
1136 result.append(buffer);
1137 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kasten4b220f02011-12-13 11:50:00 -08001138 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001139 result.append(buffer);
1140 }
1141 result.append("\n");
1142
1143 write(fd, result.string(), result.size());
1144
1145 if (locked) {
1146 mLock.unlock();
1147 }
1148 return NO_ERROR;
1149}
1150
Eric Laurent1345d332011-07-24 17:49:51 -07001151status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1152{
1153 const size_t SIZE = 256;
1154 char buffer[SIZE];
1155 String8 result;
1156
1157 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1158 write(fd, buffer, strlen(buffer));
1159
1160 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1161 sp<EffectChain> chain = mEffectChains[i];
1162 if (chain != 0) {
1163 chain->dump(fd, args);
1164 }
1165 }
1166 return NO_ERROR;
1167}
1168
Eric Laurent6dbdc402011-07-22 09:04:31 -07001169void AudioFlinger::ThreadBase::acquireWakeLock()
1170{
1171 Mutex::Autolock _l(mLock);
1172 acquireWakeLock_l();
1173}
1174
1175void AudioFlinger::ThreadBase::acquireWakeLock_l()
1176{
1177 if (mPowerManager == 0) {
1178 // use checkService() to avoid blocking if power service is not up yet
1179 sp<IBinder> binder =
1180 defaultServiceManager()->checkService(String16("power"));
1181 if (binder == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00001182 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001183 } else {
1184 mPowerManager = interface_cast<IPowerManager>(binder);
1185 binder->linkToDeath(mDeathRecipient);
1186 }
1187 }
1188 if (mPowerManager != 0) {
1189 sp<IBinder> binder = new BBinder();
1190 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1191 binder,
1192 String16(mName));
1193 if (status == NO_ERROR) {
1194 mWakeLockToken = binder;
1195 }
Steve Block71f2cf12011-10-20 11:56:00 +01001196 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001197 }
1198}
1199
1200void AudioFlinger::ThreadBase::releaseWakeLock()
1201{
1202 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001203 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001204}
1205
1206void AudioFlinger::ThreadBase::releaseWakeLock_l()
1207{
1208 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001209 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001210 if (mPowerManager != 0) {
1211 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1212 }
1213 mWakeLockToken.clear();
1214 }
1215}
1216
1217void AudioFlinger::ThreadBase::clearPowerManager()
1218{
1219 Mutex::Autolock _l(mLock);
1220 releaseWakeLock_l();
1221 mPowerManager.clear();
1222}
1223
1224void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1225{
1226 sp<ThreadBase> thread = mThread.promote();
1227 if (thread != 0) {
1228 thread->clearPowerManager();
1229 }
Steve Block8564c8d2012-01-05 23:22:43 +00001230 ALOGW("power manager service died !!!");
Eric Laurent6dbdc402011-07-22 09:04:31 -07001231}
Eric Laurent1345d332011-07-24 17:49:51 -07001232
Eric Laurentf82fccd2011-07-27 19:49:51 -07001233void AudioFlinger::ThreadBase::setEffectSuspended(
1234 const effect_uuid_t *type, bool suspend, int sessionId)
1235{
1236 Mutex::Autolock _l(mLock);
1237 setEffectSuspended_l(type, suspend, sessionId);
1238}
1239
1240void AudioFlinger::ThreadBase::setEffectSuspended_l(
1241 const effect_uuid_t *type, bool suspend, int sessionId)
1242{
1243 sp<EffectChain> chain;
1244 chain = getEffectChain_l(sessionId);
1245 if (chain != 0) {
1246 if (type != NULL) {
1247 chain->setEffectSuspended_l(type, suspend);
1248 } else {
1249 chain->setEffectSuspendedAll_l(suspend);
1250 }
1251 }
1252
1253 updateSuspendedSessions_l(type, suspend, sessionId);
1254}
1255
1256void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1257{
1258 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1259 if (index < 0) {
1260 return;
1261 }
1262
1263 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1264 mSuspendedSessions.editValueAt(index);
1265
1266 for (size_t i = 0; i < sessionEffects.size(); i++) {
1267 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1268 for (int j = 0; j < desc->mRefCount; j++) {
1269 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1270 chain->setEffectSuspendedAll_l(true);
1271 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001272 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001273 desc->mType.timeLow);
1274 chain->setEffectSuspended_l(&desc->mType, true);
1275 }
1276 }
1277 }
1278}
1279
Eric Laurentf82fccd2011-07-27 19:49:51 -07001280void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1281 bool suspend,
1282 int sessionId)
1283{
1284 int index = mSuspendedSessions.indexOfKey(sessionId);
1285
1286 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1287
1288 if (suspend) {
1289 if (index >= 0) {
1290 sessionEffects = mSuspendedSessions.editValueAt(index);
1291 } else {
1292 mSuspendedSessions.add(sessionId, sessionEffects);
1293 }
1294 } else {
1295 if (index < 0) {
1296 return;
1297 }
1298 sessionEffects = mSuspendedSessions.editValueAt(index);
1299 }
1300
1301
1302 int key = EffectChain::kKeyForSuspendAll;
1303 if (type != NULL) {
1304 key = type->timeLow;
1305 }
1306 index = sessionEffects.indexOfKey(key);
1307
1308 sp <SuspendedSessionDesc> desc;
1309 if (suspend) {
1310 if (index >= 0) {
1311 desc = sessionEffects.valueAt(index);
1312 } else {
1313 desc = new SuspendedSessionDesc();
1314 if (type != NULL) {
1315 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1316 }
1317 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001318 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001319 }
1320 desc->mRefCount++;
1321 } else {
1322 if (index < 0) {
1323 return;
1324 }
1325 desc = sessionEffects.valueAt(index);
1326 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001327 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001328 sessionEffects.removeItemsAt(index);
1329 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001330 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001331 sessionId);
1332 mSuspendedSessions.removeItem(sessionId);
1333 }
1334 }
1335 }
1336 if (!sessionEffects.isEmpty()) {
1337 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1338 }
1339}
1340
1341void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1342 bool enabled,
1343 int sessionId)
1344{
1345 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001346 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1347}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001348
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001349void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1350 bool enabled,
1351 int sessionId)
1352{
Eric Laurent6752ec82011-08-10 10:37:50 -07001353 if (mType != RECORD) {
1354 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1355 // another session. This gives the priority to well behaved effect control panels
1356 // and applications not using global effects.
1357 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1358 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1359 }
1360 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001361
1362 sp<EffectChain> chain = getEffectChain_l(sessionId);
1363 if (chain != 0) {
1364 chain->checkSuspendOnEffectEnabled(effect, enabled);
1365 }
1366}
1367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368// ----------------------------------------------------------------------------
1369
Eric Laurent464d5b32011-06-17 21:29:58 -07001370AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1371 AudioStreamOut* output,
1372 int id,
1373 uint32_t device)
1374 : ThreadBase(audioFlinger, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08001375 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent464d5b32011-06-17 21:29:58 -07001376 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001378 snprintf(mName, kNameLength, "AudioOut_%d", id);
1379
Eric Laurenta553c252009-07-17 12:17:14 -07001380 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381
Eric Laurenta553c252009-07-17 12:17:14 -07001382 mMasterVolume = mAudioFlinger->masterVolume();
1383 mMasterMute = mAudioFlinger->masterMute();
1384
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001385 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1386 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1387 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001388 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1389 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent05ce0942011-08-30 10:18:54 -07001390 mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392}
1393
Eric Laurenta553c252009-07-17 12:17:14 -07001394AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395{
1396 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397}
1398
Eric Laurenta553c252009-07-17 12:17:14 -07001399status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400{
1401 dumpInternals(fd, args);
1402 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001403 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 return NO_ERROR;
1405}
1406
Eric Laurenta553c252009-07-17 12:17:14 -07001407status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408{
1409 const size_t SIZE = 256;
1410 char buffer[SIZE];
1411 String8 result;
1412
Eric Laurenta553c252009-07-17 12:17:14 -07001413 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001415 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 -08001416 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001417 sp<Track> track = mTracks[i];
1418 if (track != 0) {
1419 track->dump(buffer, SIZE);
1420 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 }
1422 }
1423
Eric Laurenta553c252009-07-17 12:17:14 -07001424 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001426 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 -08001427 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001428 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 if (wTrack != 0) {
1430 sp<Track> track = wTrack.promote();
1431 if (track != 0) {
1432 track->dump(buffer, SIZE);
1433 result.append(buffer);
1434 }
1435 }
1436 }
1437 write(fd, result.string(), result.size());
1438 return NO_ERROR;
1439}
1440
Eric Laurenta553c252009-07-17 12:17:14 -07001441status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442{
1443 const size_t SIZE = 256;
1444 char buffer[SIZE];
1445 String8 result;
1446
Eric Laurent3fdb1262009-11-07 00:01:32 -08001447 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 result.append(buffer);
1449 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1450 result.append(buffer);
1451 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1452 result.append(buffer);
1453 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1454 result.append(buffer);
1455 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1456 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001457 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1458 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001459 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1460 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001462
1463 dumpBase(fd, args);
1464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 return NO_ERROR;
1466}
1467
1468// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001469status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470{
Eric Laurent828b9772011-08-07 16:32:26 -07001471 status_t status = initCheck();
1472 if (status == NO_ERROR) {
Steve Block6215d3f2012-01-04 20:05:49 +00001473 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurent828b9772011-08-07 16:32:26 -07001474 } else {
Steve Block3762c312012-01-06 19:20:56 +00001475 ALOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
Eric Laurent828b9772011-08-07 16:32:26 -07001477 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478}
1479
Eric Laurenta553c252009-07-17 12:17:14 -07001480void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001482 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483}
1484
Eric Laurenta553c252009-07-17 12:17:14 -07001485// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1486sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 const sp<AudioFlinger::Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001488 audio_stream_type_t streamType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001490 uint32_t format,
1491 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 int frameCount,
1493 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001494 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 status_t *status)
1496{
1497 sp<Track> track;
1498 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001499
1500 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001501 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1502 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block3762c312012-01-06 19:20:56 +00001503 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001504 "for output %p with format %d",
1505 sampleRate, format, channelMask, mOutput, mFormat);
1506 lStatus = BAD_VALUE;
1507 goto Exit;
1508 }
Eric Laurenta553c252009-07-17 12:17:14 -07001509 }
1510 } else {
1511 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1512 if (sampleRate > mSampleRate*2) {
Steve Block3762c312012-01-06 19:20:56 +00001513 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Eric Laurenta553c252009-07-17 12:17:14 -07001514 lStatus = BAD_VALUE;
1515 goto Exit;
1516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 }
1518
Eric Laurent464d5b32011-06-17 21:29:58 -07001519 lStatus = initCheck();
1520 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00001521 ALOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001522 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 }
1524
Eric Laurenta553c252009-07-17 12:17:14 -07001525 { // scope for mLock
1526 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001527
1528 // all tracks in same audio session must share the same routing strategy otherwise
1529 // conflicts will happen when tracks are moved from one output to another by audio policy
1530 // manager
1531 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001532 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001533 for (size_t i = 0; i < mTracks.size(); ++i) {
1534 sp<Track> t = mTracks[i];
1535 if (t != 0) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001536 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1537 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block3762c312012-01-06 19:20:56 +00001538 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001539 strategy, actual);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001540 lStatus = BAD_VALUE;
1541 goto Exit;
1542 }
1543 }
1544 }
1545
Eric Laurenta553c252009-07-17 12:17:14 -07001546 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001547 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001548 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001549 lStatus = NO_MEMORY;
1550 goto Exit;
1551 }
1552 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001553
1554 sp<EffectChain> chain = getEffectChain_l(sessionId);
1555 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001556 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001557 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001558 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001559 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001560 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001561
1562 // invalidate track immediately if the stream type was moved to another thread since
1563 // createTrack() was called by the client process.
1564 if (!mStreamTypes[streamType].valid) {
Steve Block8564c8d2012-01-05 23:22:43 +00001565 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07001566 this, streamType);
1567 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1568 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001569 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001570 lStatus = NO_ERROR;
1571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572Exit:
1573 if(status) {
1574 *status = lStatus;
1575 }
1576 return track;
1577}
1578
Eric Laurenta553c252009-07-17 12:17:14 -07001579uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580{
Eric Laurent828b9772011-08-07 16:32:26 -07001581 Mutex::Autolock _l(mLock);
1582 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001583 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001584 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 return 0;
1586 }
1587}
1588
Eric Laurenta553c252009-07-17 12:17:14 -07001589status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590{
1591 mMasterVolume = value;
1592 return NO_ERROR;
1593}
1594
Eric Laurenta553c252009-07-17 12:17:14 -07001595status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596{
1597 mMasterMute = muted;
1598 return NO_ERROR;
1599}
1600
Eric Laurenta553c252009-07-17 12:17:14 -07001601float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602{
1603 return mMasterVolume;
1604}
1605
Eric Laurenta553c252009-07-17 12:17:14 -07001606bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607{
1608 return mMasterMute;
1609}
1610
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001611status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612{
1613 mStreamTypes[stream].volume = value;
1614 return NO_ERROR;
1615}
1616
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001617status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618{
1619 mStreamTypes[stream].mute = muted;
1620 return NO_ERROR;
1621}
1622
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001623float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624{
1625 return mStreamTypes[stream].volume;
1626}
1627
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08001628bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629{
1630 return mStreamTypes[stream].mute;
1631}
1632
Eric Laurenta553c252009-07-17 12:17:14 -07001633// addTrack_l() must be called with ThreadBase::mLock held
1634status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635{
1636 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001637
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001638 // set retry count for buffer fill
1639 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001640 if (mActiveTracks.indexOf(track) < 0) {
1641 // the track is newly added, make sure it fills up all its
1642 // buffers before playing. This is to ensure the client will
1643 // effectively get the latency it requested.
1644 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001645 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001646 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001647 if (track->mainBuffer() != mMixBuffer) {
1648 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1649 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001650 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001651 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001652 }
1653 }
1654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001656 }
Eric Laurenta553c252009-07-17 12:17:14 -07001657
Steve Block71f2cf12011-10-20 11:56:00 +01001658 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001659 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660
1661 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001662}
1663
Eric Laurenta553c252009-07-17 12:17:14 -07001664// destroyTrack_l() must be called with ThreadBase::mLock held
1665void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001666{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001667 track->mState = TrackBase::TERMINATED;
1668 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001669 removeTrack_l(track);
1670 }
1671}
1672
1673void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1674{
1675 mTracks.remove(track);
1676 deleteTrackName_l(track->name());
1677 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1678 if (chain != 0) {
1679 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001680 }
1681}
1682
Eric Laurenta553c252009-07-17 12:17:14 -07001683String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001684{
Eric Laurent828b9772011-08-07 16:32:26 -07001685 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001686 char *s;
1687
Eric Laurent828b9772011-08-07 16:32:26 -07001688 Mutex::Autolock _l(mLock);
1689 if (initCheck() != NO_ERROR) {
1690 return out_s8;
1691 }
1692
Dima Zavin31f188892011-04-18 16:57:27 -07001693 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001694 out_s8 = String8(s);
1695 free(s);
1696 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001697}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001698
Eric Laurent828b9772011-08-07 16:32:26 -07001699// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001700void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001701 AudioSystem::OutputDescriptor desc;
1702 void *param2 = 0;
1703
Steve Block71f2cf12011-10-20 11:56:00 +01001704 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001705
1706 switch (event) {
1707 case AudioSystem::OUTPUT_OPENED:
1708 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001709 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001710 desc.samplingRate = mSampleRate;
1711 desc.format = mFormat;
1712 desc.frameCount = mFrameCount;
1713 desc.latency = latency();
1714 param2 = &desc;
1715 break;
1716
1717 case AudioSystem::STREAM_CONFIG_CHANGED:
1718 param2 = &param;
1719 case AudioSystem::OUTPUT_CLOSED:
1720 default:
1721 break;
1722 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001723 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001724}
1725
1726void AudioFlinger::PlaybackThread::readOutputParameters()
1727{
Dima Zavin31f188892011-04-18 16:57:27 -07001728 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001729 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1730 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001731 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1732 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1733 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001734
Eric Laurenta553c252009-07-17 12:17:14 -07001735 // FIXME - Current mixer implementation only supports stereo output: Always
1736 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001737 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001738 mMixBuffer = new int16_t[mFrameCount * 2];
1739 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001740
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001741 // force reconfiguration of effect chains and engines to take new buffer size and audio
1742 // parameters into account
1743 // Note that mLock is not held when readOutputParameters() is called from the constructor
1744 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1745 // matter.
1746 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1747 Vector< sp<EffectChain> > effectChains = mEffectChains;
1748 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001749 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001750 }
Eric Laurenta553c252009-07-17 12:17:14 -07001751}
1752
Eric Laurent0986e792010-01-19 17:37:09 -08001753status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1754{
1755 if (halFrames == 0 || dspFrames == 0) {
1756 return BAD_VALUE;
1757 }
Eric Laurent828b9772011-08-07 16:32:26 -07001758 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001759 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001760 return INVALID_OPERATION;
1761 }
Dima Zavin31f188892011-04-18 16:57:27 -07001762 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001763
Dima Zavin31f188892011-04-18 16:57:27 -07001764 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001765}
1766
Eric Laurent493941b2010-07-28 01:32:47 -07001767uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001768{
1769 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001770 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001771 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001772 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001773 }
1774
1775 for (size_t i = 0; i < mTracks.size(); ++i) {
1776 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001777 if (sessionId == track->sessionId() &&
1778 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001779 result |= TRACK_SESSION;
1780 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001781 }
1782 }
1783
Eric Laurent493941b2010-07-28 01:32:47 -07001784 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001785}
1786
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001787uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1788{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001789 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001790 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001791 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1792 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001793 }
1794 for (size_t i = 0; i < mTracks.size(); i++) {
1795 sp<Track> track = mTracks[i];
1796 if (sessionId == track->sessionId() &&
1797 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001798 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001799 }
1800 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001801 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001802}
1803
Eric Laurent53334cd2010-06-23 17:38:20 -07001804
Eric Laurent828b9772011-08-07 16:32:26 -07001805AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1806{
1807 Mutex::Autolock _l(mLock);
1808 return mOutput;
1809}
1810
1811AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1812{
1813 Mutex::Autolock _l(mLock);
1814 AudioStreamOut *output = mOutput;
1815 mOutput = NULL;
1816 return output;
1817}
1818
1819// this method must always be called either with ThreadBase mLock held or inside the thread loop
1820audio_stream_t* AudioFlinger::PlaybackThread::stream()
1821{
1822 if (mOutput == NULL) {
1823 return NULL;
1824 }
1825 return &mOutput->stream->common;
1826}
1827
Eric Laurent44331692011-12-05 09:47:19 -08001828uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1829{
1830 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1831 // decoding and transfer time. So sleeping for half of the latency would likely cause
1832 // underruns
1833 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1834 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1835 } else {
1836 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1837 }
1838}
1839
Eric Laurenta553c252009-07-17 12:17:14 -07001840// ----------------------------------------------------------------------------
1841
Dima Zavin31f188892011-04-18 16:57:27 -07001842AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001843 : PlaybackThread(audioFlinger, output, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08001844 mAudioMixer(NULL)
Eric Laurenta553c252009-07-17 12:17:14 -07001845{
Eric Laurent464d5b32011-06-17 21:29:58 -07001846 mType = ThreadBase::MIXER;
Eric Laurenta553c252009-07-17 12:17:14 -07001847 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1848
1849 // FIXME - Current mixer implementation only supports stereo output
1850 if (mChannelCount == 1) {
Steve Block3762c312012-01-06 19:20:56 +00001851 ALOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001853}
1854
Eric Laurenta553c252009-07-17 12:17:14 -07001855AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001856{
Eric Laurenta553c252009-07-17 12:17:14 -07001857 delete mAudioMixer;
1858}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859
Eric Laurenta553c252009-07-17 12:17:14 -07001860bool AudioFlinger::MixerThread::threadLoop()
1861{
Eric Laurenta553c252009-07-17 12:17:14 -07001862 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001863 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001864 nsecs_t standbyTime = systemTime();
1865 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001866 // FIXME: Relaxed timing because of a certain device that can't meet latency
1867 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001868 // increase threshold again due to low power audio mode. The way this warning threshold is
1869 // calculated and its usefulness should be reconsidered anyway.
1870 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001871 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001872 bool longStandbyExit = false;
1873 uint32_t activeSleepTime = activeSleepTimeUs();
1874 uint32_t idleSleepTime = idleSleepTimeUs();
1875 uint32_t sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001876 uint32_t sleepTimeShift = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001877 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001878#ifdef DEBUG_CPU_USAGE
1879 ThreadCpuUsage cpu;
1880 const CentralTendencyStatistics& stats = cpu.statistics();
1881#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882
Eric Laurent6dbdc402011-07-22 09:04:31 -07001883 acquireWakeLock();
1884
Eric Laurenta553c252009-07-17 12:17:14 -07001885 while (!exitPending())
1886 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001887#ifdef DEBUG_CPU_USAGE
1888 cpu.sampleAndEnable();
1889 unsigned n = stats.n();
1890 // cpu.elapsed() is expensive, so don't call it every loop
1891 if ((n & 127) == 1) {
1892 long long elapsed = cpu.elapsed();
1893 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1894 double perLoop = elapsed / (double) n;
1895 double perLoop100 = perLoop * 0.01;
1896 double mean = stats.mean();
1897 double stddev = stats.stddev();
1898 double minimum = stats.minimum();
1899 double maximum = stats.maximum();
1900 cpu.resetStatistics();
Steve Block6215d3f2012-01-04 20:05:49 +00001901 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 -07001902 elapsed * .000000001, n, perLoop * .000001,
1903 mean * .001,
1904 stddev * .001,
1905 minimum * .001,
1906 maximum * .001,
1907 mean / perLoop100,
1908 stddev / perLoop100,
1909 minimum / perLoop100,
1910 maximum / perLoop100);
1911 }
1912 }
1913#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001914 processConfigEvents();
1915
Eric Laurent059b4be2009-11-09 23:32:22 -08001916 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001917 { // scope for mLock
1918
1919 Mutex::Autolock _l(mLock);
1920
1921 if (checkForNewParameters_l()) {
1922 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001923 // FIXME: Relaxed timing because of a certain device that can't meet latency
1924 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001925 // increase threshold again due to low power audio mode. The way this warning
1926 // threshold is calculated and its usefulness should be reconsidered anyway.
1927 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001928 activeSleepTime = activeSleepTimeUs();
1929 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001930 }
1931
1932 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1933
1934 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001935 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1936 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001937 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01001938 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001939 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001940 mStandby = true;
1941 mBytesWritten = 0;
1942 }
1943
1944 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1945 // we're about to wait, flush the binder command buffer
1946 IPCThreadState::self()->flushCommands();
1947
1948 if (exitPending()) break;
1949
Eric Laurent6dbdc402011-07-22 09:04:31 -07001950 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001951 // wait until we have something to do...
Steve Block71f2cf12011-10-20 11:56:00 +01001952 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07001953 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01001954 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001955 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001956
1957 if (mMasterMute == false) {
1958 char value[PROPERTY_VALUE_MAX];
1959 property_get("ro.audio.silent", value, "0");
1960 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00001961 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07001962 setMasterMute(true);
1963 }
1964 }
1965
1966 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001967 sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001968 sleepTimeShift = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001969 continue;
1970 }
1971 }
1972
Eric Laurent059b4be2009-11-09 23:32:22 -08001973 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001974
1975 // prevent any changes in effect chain list and in each effect chain
1976 // during mixing and effect process as the audio buffers could be deleted
1977 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001978 lockEffectChains_l(effectChains);
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08001979 }
Eric Laurenta553c252009-07-17 12:17:14 -07001980
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001981 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001982 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001983 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001984 sleepTime = 0;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001985 // increase sleep time progressively when application underrun condition clears
1986 if (sleepTimeShift > 0) {
1987 sleepTimeShift--;
1988 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07001989 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001990 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001991 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001992 // If no tracks are ready, sleep once for the duration of an output
1993 // buffer size, then write 0s to the output
1994 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001995 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001996 sleepTime = activeSleepTime >> sleepTimeShift;
1997 if (sleepTime < kMinThreadSleepTimeUs) {
1998 sleepTime = kMinThreadSleepTimeUs;
1999 }
2000 // reduce sleep time in case of consecutive application underruns to avoid
2001 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2002 // duration we would end up writing less data than needed by the audio HAL if
2003 // the condition persists.
2004 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2005 sleepTimeShift++;
2006 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002007 } else {
2008 sleepTime = idleSleepTime;
2009 }
2010 } else if (mBytesWritten != 0 ||
2011 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002012 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002013 sleepTime = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01002014 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07002015 }
Eric Laurent65b65452010-06-01 23:49:17 -07002016 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07002017 }
2018
2019 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002020 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002021 }
2022 // sleepTime == 0 means we must write to audio hardware
2023 if (sleepTime == 0) {
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08002024 for (size_t i = 0; i < effectChains.size(); i ++) {
2025 effectChains[i]->process_l();
2026 }
2027 // enable changes in effect chain
2028 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002029 mLastWriteTime = systemTime();
2030 mInWrite = true;
2031 mBytesWritten += mixBufferSize;
2032
Dima Zavin31f188892011-04-18 16:57:27 -07002033 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002034 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002035 mNumWrites++;
2036 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002037 nsecs_t now = systemTime();
2038 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07002039 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002040 mNumDelayedWrites++;
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002041 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00002042 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002043 ns2ms(delta), mNumDelayedWrites, this);
2044 lastWarning = now;
2045 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002046 if (mStandby) {
2047 longStandbyExit = true;
2048 }
Eric Laurenta553c252009-07-17 12:17:14 -07002049 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002050 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002051 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002052 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002053 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002054 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002055 }
2056
2057 // finally let go of all our tracks, without the lock held
2058 // since we can't guarantee the destructors won't acquire that
2059 // same lock.
2060 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002061
2062 // Effect chains will be actually deleted here if they were removed from
2063 // mEffectChains list during mixing or effects processing
2064 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002065 }
2066
2067 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002068 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002069 }
Eric Laurenta553c252009-07-17 12:17:14 -07002070
Eric Laurent6dbdc402011-07-22 09:04:31 -07002071 releaseWakeLock();
2072
Steve Block71f2cf12011-10-20 11:56:00 +01002073 ALOGV("MixerThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002074 return false;
2075}
2076
2077// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08002078uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002079{
2080
Eric Laurent059b4be2009-11-09 23:32:22 -08002081 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002082 // find out which tracks need to be processed
2083 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002084 size_t mixedTracks = 0;
2085 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002086
2087 float masterVolume = mMasterVolume;
2088 bool masterMute = mMasterMute;
2089
Eric Laurent8cc93b92010-08-11 05:20:11 -07002090 if (masterMute) {
2091 masterVolume = 0;
2092 }
Eric Laurent65b65452010-06-01 23:49:17 -07002093 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002094 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002095 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002096 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002097 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002098 masterVolume = (float)((v + (1 << 23)) >> 24);
2099 chain.clear();
2100 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002101
Eric Laurenta553c252009-07-17 12:17:14 -07002102 for (size_t i=0 ; i<count ; i++) {
2103 sp<Track> t = activeTracks[i].promote();
2104 if (t == 0) continue;
2105
Glenn Kasten68deb152011-12-19 15:06:39 -08002106 // this const just means the local variable doesn't change
Eric Laurenta553c252009-07-17 12:17:14 -07002107 Track* const track = t.get();
2108 audio_track_cblk_t* cblk = track->cblk();
2109
2110 // The first time a track is added we wait
2111 // for all its buffers to be filled before processing it
Glenn Kasten68deb152011-12-19 15:06:39 -08002112 int name = track->name();
Eric Laurent8a04fe02011-11-08 18:10:16 -08002113 // make sure that we have enough frames to mix one full buffer.
2114 // enforce this condition only once to enable draining the buffer in case the client
2115 // app does not call stop() and relies on underrun to stop:
2116 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2117 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002118 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002119 if (!track->isStopped() && !track->isPausing() &&
2120 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002121 if (t->sampleRate() == (int)mSampleRate) {
2122 minFrames = mFrameCount;
2123 } else {
Eric Laurent72dafb22011-12-22 16:08:41 -08002124 // +1 for rounding and +1 for additional sample needed for interpolation
2125 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2126 // add frames already consumed but not yet released by the resampler
2127 // because cblk->framesReady() will include these frames
2128 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2129 // the minimum track buffer size is normally twice the number of frames necessary
2130 // to fill one buffer and the resampler should not leave more than one buffer worth
2131 // of unreleased frames after each pass, but just in case...
Steve Blockec193de2012-01-09 18:35:44 +00002132 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002133 }
2134 }
2135 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002136 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002137 {
Glenn Kasten68deb152011-12-19 15:06:39 -08002138 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002139
Eric Laurent65b65452010-06-01 23:49:17 -07002140 mixedTracks++;
2141
2142 // track->mainBuffer() != mMixBuffer means there is an effect chain
2143 // connected to the track
2144 chain.clear();
2145 if (track->mainBuffer() != mMixBuffer) {
2146 chain = getEffectChain_l(track->sessionId());
2147 // Delegate volume control to effect in track effect chain if needed
2148 if (chain != 0) {
2149 tracksWithEffect++;
2150 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00002151 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten68deb152011-12-19 15:06:39 -08002152 name, track->sessionId());
Eric Laurent65b65452010-06-01 23:49:17 -07002153 }
2154 }
2155
2156
2157 int param = AudioMixer::VOLUME;
2158 if (track->mFillingUpStatus == Track::FS_FILLED) {
2159 // no ramp for the first volume setting
2160 track->mFillingUpStatus = Track::FS_ACTIVE;
2161 if (track->mState == TrackBase::RESUMING) {
2162 track->mState = TrackBase::ACTIVE;
2163 param = AudioMixer::RAMP_VOLUME;
2164 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002165 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002166 } else if (cblk->server != 0) {
2167 // If the track is stopped before the first frame was mixed,
2168 // do not apply ramp
2169 param = AudioMixer::RAMP_VOLUME;
2170 }
2171
Eric Laurenta553c252009-07-17 12:17:14 -07002172 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002173 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002174 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002175 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002176 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002177 if (track->isPausing()) {
2178 track->setPaused();
2179 }
2180 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002181
Glenn Kasten871c16c2010-03-05 12:18:01 -08002182 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002183 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002184 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002185 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2186 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07002187
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002188 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002189 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002190 // Delegate volume control to effect in track effect chain if needed
2191 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2192 // Do not ramp volume if volume is controlled by effect
2193 param = AudioMixer::VOLUME;
2194 track->mHasVolumeController = true;
2195 } else {
2196 // force no volume ramp when volume controller was just disabled or removed
2197 // from effect chain to avoid volume spike
2198 if (track->mHasVolumeController) {
2199 param = AudioMixer::VOLUME;
2200 }
2201 track->mHasVolumeController = false;
2202 }
2203
2204 // Convert volumes from 8.24 to 4.12 format
2205 int16_t left, right, aux;
2206 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2207 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2208 left = int16_t(v_clamped);
2209 v_clamped = (vr + (1 << 11)) >> 12;
2210 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2211 right = int16_t(v_clamped);
2212
2213 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2214 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002215
Eric Laurent65b65452010-06-01 23:49:17 -07002216 // XXX: these things DON'T need to be done each time
Glenn Kasten68deb152011-12-19 15:06:39 -08002217 mAudioMixer->setBufferProvider(name, track);
2218 mAudioMixer->enable(name);
Eric Laurent65b65452010-06-01 23:49:17 -07002219
Glenn Kasten68deb152011-12-19 15:06:39 -08002220 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2221 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2222 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002223 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002224 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002225 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002226 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002227 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002228 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002229 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002230 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002231 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002232 name,
Eric Laurenta553c252009-07-17 12:17:14 -07002233 AudioMixer::RESAMPLE,
2234 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002235 (void *)(cblk->sampleRate));
2236 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002237 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002238 AudioMixer::TRACK,
2239 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2240 mAudioMixer->setParameter(
Glenn Kasten68deb152011-12-19 15:06:39 -08002241 name,
Eric Laurent65b65452010-06-01 23:49:17 -07002242 AudioMixer::TRACK,
2243 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002244
2245 // reset retry count
2246 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08002247 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002248 } else {
Glenn Kasten68deb152011-12-19 15:06:39 -08002249 //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 -07002250 if (track->isStopped()) {
2251 track->reset();
2252 }
2253 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2254 // We have consumed all the buffers of this track.
2255 // Remove it from the list of active tracks.
2256 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002257 } else {
2258 // No buffers for this track. Give it a few chances to
2259 // fill a buffer, then remove it from active list.
2260 if (--(track->mRetryCount) <= 0) {
Glenn Kasten68deb152011-12-19 15:06:39 -08002261 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002262 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002263 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002264 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -08002265 } else if (mixerStatus != MIXER_TRACKS_READY) {
2266 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002267 }
Eric Laurenta553c252009-07-17 12:17:14 -07002268 }
Glenn Kasten68deb152011-12-19 15:06:39 -08002269 mAudioMixer->disable(name);
Eric Laurenta553c252009-07-17 12:17:14 -07002270 }
2271 }
2272
2273 // remove all the tracks that need to be...
2274 count = tracksToRemove->size();
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002275 if (CC_UNLIKELY(count)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002276 for (size_t i=0 ; i<count ; i++) {
2277 const sp<Track>& track = tracksToRemove->itemAt(i);
2278 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002279 if (track->mainBuffer() != mMixBuffer) {
2280 chain = getEffectChain_l(track->sessionId());
2281 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002282 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002283 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002284 }
2285 }
Eric Laurenta553c252009-07-17 12:17:14 -07002286 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002287 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002288 }
2289 }
2290 }
2291
Eric Laurent65b65452010-06-01 23:49:17 -07002292 // mix buffer must be cleared if all tracks are connected to an
2293 // effect chain as in this case the mixer will not write to
2294 // mix buffer and track effects will accumulate into it
2295 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2296 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2297 }
2298
Eric Laurent059b4be2009-11-09 23:32:22 -08002299 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002300}
2301
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002302void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002303{
Steve Block71f2cf12011-10-20 11:56:00 +01002304 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002305 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002306 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002307
Eric Laurenta553c252009-07-17 12:17:14 -07002308 size_t size = mTracks.size();
2309 for (size_t i = 0; i < size; i++) {
2310 sp<Track> t = mTracks[i];
2311 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002312 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002313 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002314 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002315 }
2316}
Eric Laurenta553c252009-07-17 12:17:14 -07002317
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08002318void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent05ce0942011-08-30 10:18:54 -07002319{
Steve Block71f2cf12011-10-20 11:56:00 +01002320 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002321 this, streamType, valid);
2322 Mutex::Autolock _l(mLock);
2323
2324 mStreamTypes[streamType].valid = valid;
2325}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326
Eric Laurenta553c252009-07-17 12:17:14 -07002327// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002328int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002329{
2330 return mAudioMixer->getTrackName();
2331}
2332
Eric Laurenta553c252009-07-17 12:17:14 -07002333// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002334void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335{
Steve Block71f2cf12011-10-20 11:56:00 +01002336 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 mAudioMixer->deleteTrackName(name);
2338}
2339
Eric Laurenta553c252009-07-17 12:17:14 -07002340// checkForNewParameters_l() must be called with ThreadBase::mLock held
2341bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342{
Eric Laurenta553c252009-07-17 12:17:14 -07002343 bool reconfig = false;
2344
Eric Laurent8fce46a2009-08-04 09:45:33 -07002345 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002346 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002347 String8 keyValuePair = mNewParameters[0];
2348 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002349 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002350
Eric Laurenta553c252009-07-17 12:17:14 -07002351 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2352 reconfig = true;
2353 }
2354 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002355 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002356 status = BAD_VALUE;
2357 } else {
2358 reconfig = true;
2359 }
2360 }
2361 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002362 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002363 status = BAD_VALUE;
2364 } else {
2365 reconfig = true;
2366 }
2367 }
2368 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2369 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastene5fb2632011-12-14 10:28:06 -08002370 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07002371 // if frame count is changed after track creation
2372 if (!mTracks.isEmpty()) {
2373 status = INVALID_OPERATION;
2374 } else {
2375 reconfig = true;
2376 }
2377 }
Eric Laurent65b65452010-06-01 23:49:17 -07002378 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002379 // when changing the audio output device, call addBatteryData to notify
2380 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002381 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002382 uint32_t params = 0;
2383 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002384 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002385 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2386 }
2387
2388 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002389 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002390 // check if any other device (except speaker) is on
2391 if (value & deviceWithoutSpeaker ) {
2392 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2393 }
2394
2395 if (params != 0) {
2396 addBatteryData(params);
2397 }
2398 }
2399
Eric Laurent65b65452010-06-01 23:49:17 -07002400 // forward device change to effects that have requested to be
2401 // aware of attached audio device.
2402 mDevice = (uint32_t)value;
2403 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002404 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002405 }
2406 }
2407
Eric Laurenta553c252009-07-17 12:17:14 -07002408 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002409 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002410 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002411 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002412 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002413 mStandby = true;
2414 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002415 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002416 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002417 }
2418 if (status == NO_ERROR && reconfig) {
2419 delete mAudioMixer;
2420 readOutputParameters();
2421 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2422 for (size_t i = 0; i < mTracks.size() ; i++) {
2423 int name = getTrackName_l();
2424 if (name < 0) break;
2425 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002426 // limit track sample rate to 2 x new output sample rate
2427 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2428 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2429 }
Eric Laurenta553c252009-07-17 12:17:14 -07002430 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002431 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002432 }
2433 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002434
2435 mNewParameters.removeAt(0);
2436
Eric Laurenta553c252009-07-17 12:17:14 -07002437 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002438 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002439 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2440 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002441 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002442 }
2443 return reconfig;
2444}
2445
2446status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2447{
2448 const size_t SIZE = 256;
2449 char buffer[SIZE];
2450 String8 result;
2451
2452 PlaybackThread::dumpInternals(fd, args);
2453
2454 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2455 result.append(buffer);
2456 write(fd, result.string(), result.size());
2457 return NO_ERROR;
2458}
2459
Eric Laurent059b4be2009-11-09 23:32:22 -08002460uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2461{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002462 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002463}
2464
Eric Laurent8448a792010-08-18 18:13:17 -07002465uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2466{
2467 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2468}
2469
Eric Laurenta553c252009-07-17 12:17:14 -07002470// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002471AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002472 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002473{
Eric Laurent464d5b32011-06-17 21:29:58 -07002474 mType = ThreadBase::DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -07002475}
2476
2477AudioFlinger::DirectOutputThread::~DirectOutputThread()
2478{
2479}
2480
Eric Laurent65b65452010-06-01 23:49:17 -07002481static inline
2482int32_t mul(int16_t in, int16_t v)
2483{
2484#if defined(__arm__) && !defined(__thumb__)
2485 int32_t out;
2486 asm( "smulbb %[out], %[in], %[v] \n"
2487 : [out]"=r"(out)
2488 : [in]"%r"(in), [v]"r"(v)
2489 : );
2490 return out;
2491#else
2492 return in * int32_t(v);
2493#endif
2494}
2495
2496void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2497{
2498 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002499 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002500 return;
2501 }
2502
2503 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002504 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002505 size_t count = mFrameCount * mChannelCount;
2506 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2507 int16_t *dst = mMixBuffer + count-1;
2508 while(count--) {
2509 *dst-- = (int16_t)(*src--^0x80) << 8;
2510 }
2511 }
2512
2513 size_t frameCount = mFrameCount;
2514 int16_t *out = mMixBuffer;
2515 if (ramp) {
2516 if (mChannelCount == 1) {
2517 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2518 int32_t vlInc = d / (int32_t)frameCount;
2519 int32_t vl = ((int32_t)mLeftVolShort << 16);
2520 do {
2521 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2522 out++;
2523 vl += vlInc;
2524 } while (--frameCount);
2525
2526 } else {
2527 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2528 int32_t vlInc = d / (int32_t)frameCount;
2529 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2530 int32_t vrInc = d / (int32_t)frameCount;
2531 int32_t vl = ((int32_t)mLeftVolShort << 16);
2532 int32_t vr = ((int32_t)mRightVolShort << 16);
2533 do {
2534 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2535 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2536 out += 2;
2537 vl += vlInc;
2538 vr += vrInc;
2539 } while (--frameCount);
2540 }
2541 } else {
2542 if (mChannelCount == 1) {
2543 do {
2544 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2545 out++;
2546 } while (--frameCount);
2547 } else {
2548 do {
2549 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2550 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2551 out += 2;
2552 } while (--frameCount);
2553 }
2554 }
2555
2556 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002557 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002558 size_t count = mFrameCount * mChannelCount;
2559 int16_t *src = mMixBuffer;
2560 uint8_t *dst = (uint8_t *)mMixBuffer;
2561 while(count--) {
2562 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2563 }
2564 }
2565
2566 mLeftVolShort = leftVol;
2567 mRightVolShort = rightVol;
2568}
2569
Eric Laurenta553c252009-07-17 12:17:14 -07002570bool AudioFlinger::DirectOutputThread::threadLoop()
2571{
Eric Laurent059b4be2009-11-09 23:32:22 -08002572 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002573 sp<Track> trackToRemove;
2574 sp<Track> activeTrack;
2575 nsecs_t standbyTime = systemTime();
2576 int8_t *curBuf;
2577 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002578 uint32_t activeSleepTime = activeSleepTimeUs();
2579 uint32_t idleSleepTime = idleSleepTimeUs();
2580 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002581 // use shorter standby delay as on normal output to release
2582 // hardware resources as soon as possible
2583 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002584
Eric Laurent6dbdc402011-07-22 09:04:31 -07002585 acquireWakeLock();
2586
Eric Laurenta553c252009-07-17 12:17:14 -07002587 while (!exitPending())
2588 {
Eric Laurent65b65452010-06-01 23:49:17 -07002589 bool rampVolume;
2590 uint16_t leftVol;
2591 uint16_t rightVol;
2592 Vector< sp<EffectChain> > effectChains;
2593
Eric Laurenta553c252009-07-17 12:17:14 -07002594 processConfigEvents();
2595
Eric Laurent059b4be2009-11-09 23:32:22 -08002596 mixerStatus = MIXER_IDLE;
2597
Eric Laurenta553c252009-07-17 12:17:14 -07002598 { // scope for the mLock
2599
2600 Mutex::Autolock _l(mLock);
2601
2602 if (checkForNewParameters_l()) {
2603 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002604 activeSleepTime = activeSleepTimeUs();
2605 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002606 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002607 }
2608
2609 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002610 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2611 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002612 // wait until we have something to do...
2613 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01002614 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002615 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002616 mStandby = true;
2617 mBytesWritten = 0;
2618 }
2619
2620 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2621 // we're about to wait, flush the binder command buffer
2622 IPCThreadState::self()->flushCommands();
2623
2624 if (exitPending()) break;
2625
Eric Laurent6dbdc402011-07-22 09:04:31 -07002626 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002627 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002628 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002629 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002630 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002631
2632 if (mMasterMute == false) {
2633 char value[PROPERTY_VALUE_MAX];
2634 property_get("ro.audio.silent", value, "0");
2635 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00002636 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07002637 setMasterMute(true);
2638 }
2639 }
2640
Eric Laurentef9500f2010-03-11 14:47:00 -08002641 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002642 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002643 continue;
2644 }
2645 }
2646
Eric Laurent65b65452010-06-01 23:49:17 -07002647 effectChains = mEffectChains;
2648
Eric Laurenta553c252009-07-17 12:17:14 -07002649 // find out which tracks need to be processed
2650 if (mActiveTracks.size() != 0) {
2651 sp<Track> t = mActiveTracks[0].promote();
2652 if (t == 0) continue;
2653
2654 Track* const track = t.get();
2655 audio_track_cblk_t* cblk = track->cblk();
2656
2657 // The first time a track is added we wait
2658 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002659 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002660 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002661 {
Steve Block71f2cf12011-10-20 11:56:00 +01002662 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002663
Eric Laurent65b65452010-06-01 23:49:17 -07002664 if (track->mFillingUpStatus == Track::FS_FILLED) {
2665 track->mFillingUpStatus = Track::FS_ACTIVE;
2666 mLeftVolFloat = mRightVolFloat = 0;
2667 mLeftVolShort = mRightVolShort = 0;
2668 if (track->mState == TrackBase::RESUMING) {
2669 track->mState = TrackBase::ACTIVE;
2670 rampVolume = true;
2671 }
2672 } else if (cblk->server != 0) {
2673 // If the track is stopped before the first frame was mixed,
2674 // do not apply ramp
2675 rampVolume = true;
2676 }
Eric Laurenta553c252009-07-17 12:17:14 -07002677 // compute volume for this track
2678 float left, right;
2679 if (track->isMuted() || mMasterMute || track->isPausing() ||
2680 mStreamTypes[track->type()].mute) {
2681 left = right = 0;
2682 if (track->isPausing()) {
2683 track->setPaused();
2684 }
2685 } else {
2686 float typeVolume = mStreamTypes[track->type()].volume;
2687 float v = mMasterVolume * typeVolume;
2688 float v_clamped = v * cblk->volume[0];
2689 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2690 left = v_clamped/MAX_GAIN;
2691 v_clamped = v * cblk->volume[1];
2692 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2693 right = v_clamped/MAX_GAIN;
2694 }
2695
Eric Laurent65b65452010-06-01 23:49:17 -07002696 if (left != mLeftVolFloat || right != mRightVolFloat) {
2697 mLeftVolFloat = left;
2698 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002699
Eric Laurent65b65452010-06-01 23:49:17 -07002700 // If audio HAL implements volume control,
2701 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002702 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002703 left = 1.0f;
2704 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002705 }
Eric Laurent65b65452010-06-01 23:49:17 -07002706
2707 // Convert volumes from float to 8.24
2708 uint32_t vl = (uint32_t)(left * (1 << 24));
2709 uint32_t vr = (uint32_t)(right * (1 << 24));
2710
2711 // Delegate volume control to effect in track effect chain if needed
2712 // only one effect chain can be present on DirectOutputThread, so if
2713 // there is one, the track is connected to it
2714 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002715 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002716 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002717 rampVolume = false;
2718 }
2719 }
2720
2721 // Convert volumes from 8.24 to 4.12 format
2722 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2723 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2724 leftVol = (uint16_t)v_clamped;
2725 v_clamped = (vr + (1 << 11)) >> 12;
2726 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2727 rightVol = (uint16_t)v_clamped;
2728 } else {
2729 leftVol = mLeftVolShort;
2730 rightVol = mRightVolShort;
2731 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002732 }
2733
2734 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002735 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002736 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002737 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002738 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002739 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002740 if (track->isStopped()) {
2741 track->reset();
2742 }
2743 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2744 // We have consumed all the buffers of this track.
2745 // Remove it from the list of active tracks.
2746 trackToRemove = track;
2747 } else {
2748 // No buffers for this track. Give it a few chances to
2749 // fill a buffer, then remove it from active list.
2750 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002751 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurenta553c252009-07-17 12:17:14 -07002752 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002753 } else {
2754 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002755 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002756 }
Eric Laurenta553c252009-07-17 12:17:14 -07002757 }
2758 }
2759
2760 // remove all the tracks that need to be...
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002761 if (CC_UNLIKELY(trackToRemove != 0)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002762 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002763 if (!effectChains.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01002764 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002765 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002766 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002767 }
Eric Laurenta553c252009-07-17 12:17:14 -07002768 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002769 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002770 }
2771 }
Eric Laurent65b65452010-06-01 23:49:17 -07002772
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002773 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002774 }
2775
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002776 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002777 AudioBufferProvider::Buffer buffer;
2778 size_t frameCount = mFrameCount;
2779 curBuf = (int8_t *)mMixBuffer;
2780 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002781 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002782 buffer.frameCount = frameCount;
2783 activeTrack->getNextBuffer(&buffer);
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002784 if (CC_UNLIKELY(buffer.raw == NULL)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002785 memset(curBuf, 0, frameCount * mFrameSize);
2786 break;
2787 }
2788 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2789 frameCount -= buffer.frameCount;
2790 curBuf += buffer.frameCount * mFrameSize;
2791 activeTrack->releaseBuffer(&buffer);
2792 }
2793 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002794 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002795 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002796 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002797 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2798 sleepTime = activeSleepTime;
2799 } else {
2800 sleepTime = idleSleepTime;
2801 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002802 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002803 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002804 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002805 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002806 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002807
Eric Laurentf69a3f82009-09-22 00:35:48 -07002808 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002809 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002810 }
2811 // sleepTime == 0 means we must write to audio hardware
2812 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002813 if (mixerStatus == MIXER_TRACKS_READY) {
2814 applyVolume(leftVol, rightVol, rampVolume);
2815 }
2816 for (size_t i = 0; i < effectChains.size(); i ++) {
2817 effectChains[i]->process_l();
2818 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002819 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002820
Eric Laurentf69a3f82009-09-22 00:35:48 -07002821 mLastWriteTime = systemTime();
2822 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002823 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002824 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002825 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002826 mNumWrites++;
2827 mInWrite = false;
2828 mStandby = false;
2829 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002830 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002831 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002832 }
2833
2834 // finally let go of removed track, without the lock held
2835 // since we can't guarantee the destructors won't acquire that
2836 // same lock.
2837 trackToRemove.clear();
2838 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002839
2840 // Effect chains will be actually deleted here if they were removed from
2841 // mEffectChains list during mixing or effects processing
2842 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002843 }
2844
2845 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002846 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002847 }
Eric Laurenta553c252009-07-17 12:17:14 -07002848
Eric Laurent6dbdc402011-07-22 09:04:31 -07002849 releaseWakeLock();
2850
Steve Block71f2cf12011-10-20 11:56:00 +01002851 ALOGV("DirectOutputThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002852 return false;
2853}
2854
2855// getTrackName_l() must be called with ThreadBase::mLock held
2856int AudioFlinger::DirectOutputThread::getTrackName_l()
2857{
2858 return 0;
2859}
2860
2861// deleteTrackName_l() must be called with ThreadBase::mLock held
2862void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2863{
2864}
2865
2866// checkForNewParameters_l() must be called with ThreadBase::mLock held
2867bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2868{
2869 bool reconfig = false;
2870
Eric Laurent8fce46a2009-08-04 09:45:33 -07002871 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002872 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002873 String8 keyValuePair = mNewParameters[0];
2874 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002875 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002876
Eric Laurenta553c252009-07-17 12:17:14 -07002877 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2878 // do not accept frame count changes if tracks are open as the track buffer
2879 // size depends on frame count and correct behavior would not be garantied
2880 // if frame count is changed after track creation
2881 if (!mTracks.isEmpty()) {
2882 status = INVALID_OPERATION;
2883 } else {
2884 reconfig = true;
2885 }
2886 }
2887 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002888 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002889 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002890 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002891 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002892 mStandby = true;
2893 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002894 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002895 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002896 }
2897 if (status == NO_ERROR && reconfig) {
2898 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002899 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002900 }
2901 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002902
2903 mNewParameters.removeAt(0);
2904
Eric Laurenta553c252009-07-17 12:17:14 -07002905 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002906 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002907 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2908 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002909 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002910 }
2911 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002912}
2913
Eric Laurent059b4be2009-11-09 23:32:22 -08002914uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002915{
2916 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002917 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08002918 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08002919 } else {
2920 time = 10000;
2921 }
2922 return time;
2923}
2924
2925uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2926{
2927 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002928 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002929 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002930 } else {
2931 time = 10000;
2932 }
2933 return time;
2934}
2935
Eric Laurent8448a792010-08-18 18:13:17 -07002936uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2937{
2938 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002939 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002940 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2941 } else {
2942 time = 10000;
2943 }
2944 return time;
2945}
2946
2947
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002948// ----------------------------------------------------------------------------
2949
Eric Laurent49f02be2009-11-19 09:00:56 -08002950AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002951 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002952{
Eric Laurent464d5b32011-06-17 21:29:58 -07002953 mType = ThreadBase::DUPLICATING;
Eric Laurenta553c252009-07-17 12:17:14 -07002954 addOutputTrack(mainThread);
2955}
2956
2957AudioFlinger::DuplicatingThread::~DuplicatingThread()
2958{
Eric Laurent0a080292009-12-07 10:53:10 -08002959 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2960 mOutputTracks[i]->destroy();
2961 }
Eric Laurenta553c252009-07-17 12:17:14 -07002962 mOutputTracks.clear();
2963}
2964
2965bool AudioFlinger::DuplicatingThread::threadLoop()
2966{
Eric Laurenta553c252009-07-17 12:17:14 -07002967 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002968 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002969 nsecs_t standbyTime = systemTime();
2970 size_t mixBufferSize = mFrameCount*mFrameSize;
2971 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002972 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002973 uint32_t activeSleepTime = activeSleepTimeUs();
2974 uint32_t idleSleepTime = idleSleepTimeUs();
2975 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002976 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002977
Eric Laurent6dbdc402011-07-22 09:04:31 -07002978 acquireWakeLock();
2979
Eric Laurenta553c252009-07-17 12:17:14 -07002980 while (!exitPending())
2981 {
2982 processConfigEvents();
2983
Eric Laurent059b4be2009-11-09 23:32:22 -08002984 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002985 { // scope for the mLock
2986
2987 Mutex::Autolock _l(mLock);
2988
2989 if (checkForNewParameters_l()) {
2990 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002991 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002992 activeSleepTime = activeSleepTimeUs();
2993 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002994 }
2995
2996 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2997
2998 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2999 outputTracks.add(mOutputTracks[i]);
3000 }
3001
3002 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003003 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3004 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003005 if (!mStandby) {
3006 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07003007 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07003008 }
3009 mStandby = true;
3010 mBytesWritten = 0;
3011 }
3012
3013 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3014 // we're about to wait, flush the binder command buffer
3015 IPCThreadState::self()->flushCommands();
3016 outputTracks.clear();
3017
3018 if (exitPending()) break;
3019
Eric Laurent6dbdc402011-07-22 09:04:31 -07003020 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01003021 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07003022 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01003023 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07003024 acquireWakeLock_l();
3025
Eric Laurenta553c252009-07-17 12:17:14 -07003026 if (mMasterMute == false) {
3027 char value[PROPERTY_VALUE_MAX];
3028 property_get("ro.audio.silent", value, "0");
3029 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00003030 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07003031 setMasterMute(true);
3032 }
3033 }
3034
3035 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08003036 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07003037 continue;
3038 }
3039 }
3040
Eric Laurent059b4be2009-11-09 23:32:22 -08003041 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07003042
3043 // prevent any changes in effect chain list and in each effect chain
3044 // during mixing and effect process as the audio buffers could be deleted
3045 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003046 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003047 }
Eric Laurenta553c252009-07-17 12:17:14 -07003048
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003049 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003050 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003051 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003052 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003053 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003054 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003055 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003056 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003057 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003058 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003059 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003060 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3061 sleepTime = activeSleepTime;
3062 } else {
3063 sleepTime = idleSleepTime;
3064 }
Eric Laurent62443f52009-10-05 20:29:18 -07003065 } else if (mBytesWritten != 0) {
3066 // flush remaining overflow buffers in output tracks
3067 for (size_t i = 0; i < outputTracks.size(); i++) {
3068 if (outputTracks[i]->isActive()) {
3069 sleepTime = 0;
3070 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003071 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003072 break;
3073 }
3074 }
Eric Laurenta553c252009-07-17 12:17:14 -07003075 }
3076 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003077
3078 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003079 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003080 }
3081 // sleepTime == 0 means we must write to audio hardware
3082 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003083 for (size_t i = 0; i < effectChains.size(); i ++) {
3084 effectChains[i]->process_l();
3085 }
3086 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003087 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003088
Eric Laurent62443f52009-10-05 20:29:18 -07003089 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003090 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003091 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003092 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003093 mStandby = false;
3094 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003095 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003096 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003097 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003098 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003099 }
3100
3101 // finally let go of all our tracks, without the lock held
3102 // since we can't guarantee the destructors won't acquire that
3103 // same lock.
3104 tracksToRemove.clear();
3105 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003106
3107 // Effect chains will be actually deleted here if they were removed from
3108 // mEffectChains list during mixing or effects processing
3109 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003110 }
3111
Eric Laurent6dbdc402011-07-22 09:04:31 -07003112 releaseWakeLock();
3113
Eric Laurenta553c252009-07-17 12:17:14 -07003114 return false;
3115}
3116
3117void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3118{
3119 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3120 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003121 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003122 mSampleRate,
3123 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003124 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003125 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003126 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003127 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003128 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003129 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003130 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003131 }
Eric Laurenta553c252009-07-17 12:17:14 -07003132}
3133
3134void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3135{
3136 Mutex::Autolock _l(mLock);
3137 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3138 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003139 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003140 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003141 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003142 return;
3143 }
3144 }
Steve Block71f2cf12011-10-20 11:56:00 +01003145 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003146}
3147
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003148void AudioFlinger::DuplicatingThread::updateWaitTime()
3149{
3150 mWaitTimeMs = UINT_MAX;
3151 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3152 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3153 if (strong != NULL) {
3154 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3155 if (waitTimeMs < mWaitTimeMs) {
3156 mWaitTimeMs = waitTimeMs;
3157 }
3158 }
3159 }
3160}
3161
3162
3163bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3164{
3165 for (size_t i = 0; i < outputTracks.size(); i++) {
3166 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3167 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003168 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003169 return false;
3170 }
3171 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3172 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003173 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003174 return false;
3175 }
3176 }
3177 return true;
3178}
3179
3180uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3181{
3182 return (mWaitTimeMs * 1000) / 2;
3183}
3184
Eric Laurenta553c252009-07-17 12:17:14 -07003185// ----------------------------------------------------------------------------
3186
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003187// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003188AudioFlinger::ThreadBase::TrackBase::TrackBase(
3189 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003190 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003191 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003192 uint32_t format,
3193 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003194 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003196 const sp<IMemory>& sharedBuffer,
3197 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003198 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003199 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003200 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07003201 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003202 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003203 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003204 mClientTid(-1),
3205 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003206 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3207 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003208{
Steve Block71f2cf12011-10-20 11:56:00 +01003209 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003210
Steve Block5baa3a62011-12-20 16:23:08 +00003211 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003212 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003213 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003214 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3215 if (sharedBuffer == 0) {
3216 size += bufferSize;
3217 }
3218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 if (client != NULL) {
3220 mCblkMemory = client->heap()->allocate(size);
3221 if (mCblkMemory != 0) {
3222 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3223 if (mCblk) { // construct the shared structure in-place.
3224 new(mCblk) audio_track_cblk_t();
3225 // clear all buffers
3226 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003227 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003228 mChannelCount = channelCount;
3229 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 if (sharedBuffer == 0) {
3231 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3232 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3233 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003234 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003235 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 } else {
3237 mBuffer = sharedBuffer->pointer();
3238 }
3239 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241 } else {
Steve Block3762c312012-01-06 19:20:56 +00003242 ALOGE("not enough memory for AudioTrack size=%u", size);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003243 client->heap()->dump("AudioTrack");
3244 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 } else {
3247 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenc95ca2c2012-01-06 15:03:11 -08003248 // construct the shared structure in-place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 new(mCblk) audio_track_cblk_t();
3250 // clear all buffers
3251 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003252 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003253 mChannelCount = channelCount;
3254 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3256 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3257 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003258 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003259 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003262}
3263
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003264AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003265{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07003267 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3268 if (mClient == NULL) {
3269 delete mCblk;
3270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003272 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07003273 if (mClient != NULL) {
3274 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3275 mClient.clear();
3276 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003277}
3278
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003279void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003280{
Glenn Kastenc434c902011-12-13 11:53:26 -08003281 buffer->raw = NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003282 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003283 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003284 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003285}
3286
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003287bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003288 bool result;
3289 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003290
3291 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003292 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003293 ALOGV("stepServer failed acquiring cblk mutex");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003294 mFlags |= STEPSERVER_FAILED;
3295 }
3296 return result;
3297}
3298
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003299void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003300 audio_track_cblk_t* cblk = this->cblk();
3301
3302 cblk->user = 0;
3303 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003304 cblk->userBase = 0;
3305 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block71f2cf12011-10-20 11:56:00 +01003307 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003308}
3309
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003310sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003311{
3312 return mCblkMemory;
3313}
3314
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003315int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003316 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003317}
3318
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003319int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003320 return (const int)mChannelCount;
3321}
3322
3323uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3324 return mChannelMask;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003325}
3326
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003327void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003328 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07003329 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3330 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003331
3332 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003333 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3334 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
Steve Block3762c312012-01-06 19:20:56 +00003335 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 -07003336 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003337 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003338 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003339 return 0;
3340 }
3341
3342 return bufferStart;
3343}
3344
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003345// ----------------------------------------------------------------------------
3346
Eric Laurenta553c252009-07-17 12:17:14 -07003347// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3348AudioFlinger::PlaybackThread::Track::Track(
3349 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003350 const sp<Client>& client,
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08003351 audio_stream_type_t streamType,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003352 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003353 uint32_t format,
3354 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003355 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003356 const sp<IMemory>& sharedBuffer,
3357 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003358 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003359 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3360 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003361{
Eric Laurent8a77a992009-09-09 05:16:08 -07003362 if (mCblk != NULL) {
3363 sp<ThreadBase> baseThread = thread.promote();
3364 if (baseThread != 0) {
3365 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3366 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003367 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003368 }
Steve Block71f2cf12011-10-20 11:56:00 +01003369 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003370 if (mName < 0) {
Steve Block3762c312012-01-06 19:20:56 +00003371 ALOGE("no more track names available");
Eric Laurent8a77a992009-09-09 05:16:08 -07003372 }
3373 mVolume[0] = 1.0f;
3374 mVolume[1] = 1.0f;
3375 mStreamType = streamType;
3376 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3377 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003378 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003379 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003380}
3381
Eric Laurenta553c252009-07-17 12:17:14 -07003382AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003383{
Steve Block71f2cf12011-10-20 11:56:00 +01003384 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003385 sp<ThreadBase> thread = mThread.promote();
3386 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003387 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003388 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003389 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003390}
3391
Eric Laurenta553c252009-07-17 12:17:14 -07003392void AudioFlinger::PlaybackThread::Track::destroy()
3393{
3394 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3395 // by removing it from mTracks vector, so there is a risk that this Tracks's
3396 // desctructor is called. As the destructor needs to lock mLock,
3397 // we must acquire a strong reference on this Track before locking mLock
3398 // here so that the destructor is called only when exiting this function.
3399 // On the other hand, as long as Track::destroy() is only called by
3400 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3401 // this Track with its member mTrack.
3402 sp<Track> keep(this);
3403 { // scope for mLock
3404 sp<ThreadBase> thread = mThread.promote();
3405 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003406 if (!isOutputTrack()) {
3407 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003408 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003409 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003410 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003411
3412 // to track the speaker usage
3413 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003414 }
3415 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003416 }
Eric Laurenta553c252009-07-17 12:17:14 -07003417 Mutex::Autolock _l(thread->mLock);
3418 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3419 playbackThread->destroyTrack_l(this);
3420 }
3421 }
3422}
3423
3424void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003425{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003426 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 -07003427 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003429 mStreamType,
3430 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003431 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003432 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003433 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003434 mState,
3435 mMute,
3436 mFillingUpStatus,
3437 mCblk->sampleRate,
3438 mCblk->volume[0],
3439 mCblk->volume[1],
3440 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003441 mCblk->user,
3442 (int)mMainBuffer,
3443 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003444}
3445
Eric Laurenta553c252009-07-17 12:17:14 -07003446status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003447{
3448 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003449 uint32_t framesReady;
3450 uint32_t framesReq = buffer->frameCount;
3451
3452 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003453 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3454 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003455 ALOGV("stepServer recovered");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003456 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3457 }
3458
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003459 framesReady = cblk->framesReady();
3460
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003461 if (CC_LIKELY(framesReady)) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003462 uint32_t s = cblk->server;
3463 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3464
3465 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3466 if (framesReq > framesReady) {
3467 framesReq = framesReady;
3468 }
3469 if (s + framesReq > bufferEnd) {
3470 framesReq = bufferEnd - s;
3471 }
3472
3473 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003474 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003475
3476 buffer->frameCount = framesReq;
3477 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003478 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003479
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003480getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003481 buffer->raw = NULL;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003482 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003483 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 -07003484 return NOT_ENOUGH_DATA;
3485}
3486
Eric Laurenta553c252009-07-17 12:17:14 -07003487bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003488 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003489
3490 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003491 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003492 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003493 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003494 return true;
3495 }
3496 return false;
3497}
3498
Eric Laurenta553c252009-07-17 12:17:14 -07003499status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003500{
Eric Laurent49f02be2009-11-19 09:00:56 -08003501 status_t status = NO_ERROR;
Steve Block71f2cf12011-10-20 11:56:00 +01003502 ALOGV("start(%d), calling thread %d session %d",
Eric Laurent0d7e0482010-07-19 06:24:46 -07003503 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003504 sp<ThreadBase> thread = mThread.promote();
3505 if (thread != 0) {
3506 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003507 int state = mState;
3508 // here the track could be either new, or restarted
3509 // in both cases "unstop" the track
3510 if (mState == PAUSED) {
3511 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003512 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003513 } else {
3514 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003515 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003516 }
3517
3518 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3519 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003520 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003521 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003522 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003523 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003524
3525 // to track the speaker usage
3526 if (status == NO_ERROR) {
3527 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3528 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003529 }
3530 if (status == NO_ERROR) {
3531 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3532 playbackThread->addTrack_l(this);
3533 } else {
3534 mState = state;
3535 }
3536 } else {
3537 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003538 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003539 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003540}
3541
Eric Laurenta553c252009-07-17 12:17:14 -07003542void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003543{
Steve Block71f2cf12011-10-20 11:56:00 +01003544 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003545 sp<ThreadBase> thread = mThread.promote();
3546 if (thread != 0) {
3547 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003548 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003549 if (mState > STOPPED) {
3550 mState = STOPPED;
3551 // If the track is not active (PAUSED and buffers full), flush buffers
3552 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3553 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3554 reset();
3555 }
Steve Block71f2cf12011-10-20 11:56:00 +01003556 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003557 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003558 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3559 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003560 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003561 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003562 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003563 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003564
3565 // to track the speaker usage
3566 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003567 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003568 }
3569}
3570
Eric Laurenta553c252009-07-17 12:17:14 -07003571void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003572{
Steve Block71f2cf12011-10-20 11:56:00 +01003573 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003574 sp<ThreadBase> thread = mThread.promote();
3575 if (thread != 0) {
3576 Mutex::Autolock _l(thread->mLock);
3577 if (mState == ACTIVE || mState == RESUMING) {
3578 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003579 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003580 if (!isOutputTrack()) {
3581 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003582 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003583 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003584 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003585 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003586
3587 // to track the speaker usage
3588 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003589 }
Eric Laurenta553c252009-07-17 12:17:14 -07003590 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003591 }
3592}
3593
Eric Laurenta553c252009-07-17 12:17:14 -07003594void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003595{
Steve Block71f2cf12011-10-20 11:56:00 +01003596 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003597 sp<ThreadBase> thread = mThread.promote();
3598 if (thread != 0) {
3599 Mutex::Autolock _l(thread->mLock);
3600 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3601 return;
3602 }
3603 // No point remaining in PAUSED state after a flush => go to
3604 // STOPPED state
3605 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003606
Eric Laurentae29b762011-03-28 18:37:07 -07003607 // do not reset the track if it is still in the process of being stopped or paused.
3608 // this will be done by prepareTracks_l() when the track is stopped.
3609 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3610 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3611 reset();
3612 }
Eric Laurenta553c252009-07-17 12:17:14 -07003613 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003614}
3615
Eric Laurenta553c252009-07-17 12:17:14 -07003616void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003617{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003618 // Do not reset twice to avoid discarding data written just after a flush and before
3619 // the audioflinger thread detects the track is stopped.
3620 if (!mResetDone) {
3621 TrackBase::reset();
3622 // Force underrun condition to avoid false underrun callback until first data is
3623 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003624 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3625 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003626 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003627 mResetDone = true;
3628 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003629}
3630
Eric Laurenta553c252009-07-17 12:17:14 -07003631void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003632{
3633 mMute = muted;
3634}
3635
Eric Laurenta553c252009-07-17 12:17:14 -07003636void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003637{
3638 mVolume[0] = left;
3639 mVolume[1] = right;
3640}
3641
Eric Laurent65b65452010-06-01 23:49:17 -07003642status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3643{
3644 status_t status = DEAD_OBJECT;
3645 sp<ThreadBase> thread = mThread.promote();
3646 if (thread != 0) {
3647 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3648 status = playbackThread->attachAuxEffect(this, EffectId);
3649 }
3650 return status;
3651}
3652
3653void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3654{
3655 mAuxEffectId = EffectId;
3656 mAuxBuffer = buffer;
3657}
3658
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003659// ----------------------------------------------------------------------------
3660
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003661// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003662AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3663 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003666 uint32_t format,
3667 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003669 uint32_t flags,
3670 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003671 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003672 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003673 mOverflow(false)
3674{
Eric Laurent8a77a992009-09-09 05:16:08 -07003675 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003676 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003677 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003678 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003679 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003680 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003681 } else {
3682 mCblk->frameSize = sizeof(int8_t);
3683 }
3684 }
Eric Laurenta553c252009-07-17 12:17:14 -07003685}
3686
3687AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688{
Eric Laurent49f02be2009-11-19 09:00:56 -08003689 sp<ThreadBase> thread = mThread.promote();
3690 if (thread != 0) {
3691 AudioSystem::releaseInput(thread->id());
3692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693}
3694
Eric Laurenta553c252009-07-17 12:17:14 -07003695status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696{
3697 audio_track_cblk_t* cblk = this->cblk();
3698 uint32_t framesAvail;
3699 uint32_t framesReq = buffer->frameCount;
3700
3701 // Check if last stepServer failed, try to step now
3702 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3703 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003704 ALOGV("stepServer recovered");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3706 }
3707
3708 framesAvail = cblk->framesAvailable_l();
3709
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003710 if (CC_LIKELY(framesAvail)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003711 uint32_t s = cblk->server;
3712 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3713
3714 if (framesReq > framesAvail) {
3715 framesReq = framesAvail;
3716 }
3717 if (s + framesReq > bufferEnd) {
3718 framesReq = bufferEnd - s;
3719 }
3720
3721 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003722 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723
3724 buffer->frameCount = framesReq;
3725 return NO_ERROR;
3726 }
3727
3728getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003729 buffer->raw = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 buffer->frameCount = 0;
3731 return NOT_ENOUGH_DATA;
3732}
3733
Eric Laurenta553c252009-07-17 12:17:14 -07003734status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735{
Eric Laurenta553c252009-07-17 12:17:14 -07003736 sp<ThreadBase> thread = mThread.promote();
3737 if (thread != 0) {
3738 RecordThread *recordThread = (RecordThread *)thread.get();
3739 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003740 } else {
3741 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743}
3744
Eric Laurenta553c252009-07-17 12:17:14 -07003745void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746{
Eric Laurenta553c252009-07-17 12:17:14 -07003747 sp<ThreadBase> thread = mThread.promote();
3748 if (thread != 0) {
3749 RecordThread *recordThread = (RecordThread *)thread.get();
3750 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003751 TrackBase::reset();
3752 // Force overerrun condition to avoid false overrun callback until first data is
3753 // read from buffer
3754 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756}
3757
Eric Laurent3fdb1262009-11-07 00:01:32 -08003758void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3759{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003760 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003761 (mClient == NULL) ? getpid() : mClient->pid(),
3762 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003763 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003764 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003765 mFrameCount,
3766 mState,
3767 mCblk->sampleRate,
3768 mCblk->server,
3769 mCblk->user);
3770}
3771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772
3773// ----------------------------------------------------------------------------
3774
Eric Laurenta553c252009-07-17 12:17:14 -07003775AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3776 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003777 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003779 uint32_t format,
3780 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003782 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003783 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784{
Eric Laurenta553c252009-07-17 12:17:14 -07003785
3786 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003787 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003788 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003789 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3790 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3791 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003792 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01003793 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003794 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3795 mCblk, mBuffer, mCblk->buffers,
3796 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003797 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003798 ALOGW("Error creating output track on thread %p", playbackThread);
Eric Laurent6c30a712009-08-10 23:22:32 -07003799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800}
3801
Eric Laurenta553c252009-07-17 12:17:14 -07003802AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003803{
Eric Laurent6c30a712009-08-10 23:22:32 -07003804 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805}
3806
Eric Laurenta553c252009-07-17 12:17:14 -07003807status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808{
3809 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003810 if (status != NO_ERROR) {
3811 return status;
3812 }
3813
3814 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 mRetryCount = 127;
3816 return status;
3817}
3818
Eric Laurenta553c252009-07-17 12:17:14 -07003819void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820{
3821 Track::stop();
3822 clearBufferQueue();
3823 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003824 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825}
3826
Eric Laurenta553c252009-07-17 12:17:14 -07003827bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828{
3829 Buffer *pInBuffer;
3830 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003831 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003832 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 inBuffer.frameCount = frames;
3834 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003835
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003836 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003837
Eric Laurent62443f52009-10-05 20:29:18 -07003838 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003839 start();
3840 sp<ThreadBase> thread = mThread.promote();
3841 if (thread != 0) {
3842 MixerThread *mixerThread = (MixerThread *)thread.get();
3843 if (mCblk->frameCount > frames){
3844 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3845 uint32_t startFrames = (mCblk->frameCount - frames);
3846 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003847 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003848 pInBuffer->frameCount = startFrames;
3849 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003850 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003851 mBufferQueue.add(pInBuffer);
3852 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003853 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Eric Laurenta553c252009-07-17 12:17:14 -07003854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 }
Eric Laurenta553c252009-07-17 12:17:14 -07003856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 }
3858
Eric Laurenta553c252009-07-17 12:17:14 -07003859 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 // First write pending buffers, then new data
3861 if (mBufferQueue.size()) {
3862 pInBuffer = mBufferQueue.itemAt(0);
3863 } else {
3864 pInBuffer = &inBuffer;
3865 }
Eric Laurenta553c252009-07-17 12:17:14 -07003866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 if (pInBuffer->frameCount == 0) {
3868 break;
3869 }
Eric Laurenta553c252009-07-17 12:17:14 -07003870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871 if (mOutBuffer.frameCount == 0) {
3872 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003873 nsecs_t startTime = systemTime();
3874 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01003875 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003876 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 break;
3878 }
Eric Laurenta553c252009-07-17 12:17:14 -07003879 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003880 if (waitTimeLeftMs >= waitTimeMs) {
3881 waitTimeLeftMs -= waitTimeMs;
3882 } else {
3883 waitTimeLeftMs = 0;
3884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 }
Eric Laurenta553c252009-07-17 12:17:14 -07003886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003888 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 mCblk->stepUser(outFrames);
3890 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003891 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003893 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 if (pInBuffer->frameCount == 0) {
3896 if (mBufferQueue.size()) {
3897 mBufferQueue.removeAt(0);
3898 delete [] pInBuffer->mBuffer;
3899 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01003900 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 -08003901 } else {
3902 break;
3903 }
3904 }
3905 }
Eric Laurenta553c252009-07-17 12:17:14 -07003906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 // If we could not write all frames, allocate a buffer and queue it for next time.
3908 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003909 sp<ThreadBase> thread = mThread.promote();
3910 if (thread != 0 && !thread->standby()) {
3911 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3912 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003913 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003914 pInBuffer->frameCount = inBuffer.frameCount;
3915 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003916 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003917 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01003918 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003919 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00003920 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 }
3923 }
Eric Laurenta553c252009-07-17 12:17:14 -07003924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003926 // 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 -08003927 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003928 if (frames == 0 && mBufferQueue.size() == 0) {
3929 if (mCblk->user < mCblk->frameCount) {
3930 frames = mCblk->frameCount - mCblk->user;
3931 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003932 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003933 pInBuffer->frameCount = frames;
3934 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003935 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003936 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003937 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003938 stop();
3939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 }
3941
Eric Laurenta553c252009-07-17 12:17:14 -07003942 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943}
3944
Eric Laurenta553c252009-07-17 12:17:14 -07003945status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946{
3947 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 status_t result;
3949 audio_track_cblk_t* cblk = mCblk;
3950 uint32_t framesReq = buffer->frameCount;
3951
Steve Block71f2cf12011-10-20 11:56:00 +01003952// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 uint32_t framesAvail = cblk->framesAvailable();
3956
Eric Laurenta553c252009-07-17 12:17:14 -07003957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003959 Mutex::Autolock _l(cblk->lock);
3960 goto start_loop_here;
3961 while (framesAvail == 0) {
3962 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003963 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01003964 ALOGV("Not active and NO_MORE_BUFFERS");
Eric Laurenta553c252009-07-17 12:17:14 -07003965 return AudioTrack::NO_MORE_BUFFERS;
3966 }
3967 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3968 if (result != NO_ERROR) {
3969 return AudioTrack::NO_MORE_BUFFERS;
3970 }
3971 // read the server count again
3972 start_loop_here:
3973 framesAvail = cblk->framesAvailable_l();
3974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 }
3976
Eric Laurenta553c252009-07-17 12:17:14 -07003977// if (framesAvail < framesReq) {
3978// return AudioTrack::NO_MORE_BUFFERS;
3979// }
3980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 if (framesReq > framesAvail) {
3982 framesReq = framesAvail;
3983 }
3984
3985 uint32_t u = cblk->user;
3986 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3987
3988 if (u + framesReq > bufferEnd) {
3989 framesReq = bufferEnd - u;
3990 }
3991
3992 buffer->frameCount = framesReq;
3993 buffer->raw = (void *)cblk->buffer(u);
3994 return NO_ERROR;
3995}
3996
3997
Eric Laurenta553c252009-07-17 12:17:14 -07003998void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999{
4000 size_t size = mBufferQueue.size();
4001 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 for (size_t i = 0; i < size; i++) {
4004 pBuffer = mBufferQueue.itemAt(i);
4005 delete [] pBuffer->mBuffer;
4006 delete pBuffer;
4007 }
4008 mBufferQueue.clear();
4009}
4010
4011// ----------------------------------------------------------------------------
4012
4013AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4014 : RefBase(),
4015 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08004016 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 mPid(pid)
4018{
4019 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4020}
4021
Eric Laurentb9481d82009-09-17 05:12:56 -07004022// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023AudioFlinger::Client::~Client()
4024{
Eric Laurentb9481d82009-09-17 05:12:56 -07004025 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026}
4027
4028const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4029{
4030 return mMemoryDealer;
4031}
4032
4033// ----------------------------------------------------------------------------
4034
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004035AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4036 const sp<IAudioFlingerClient>& client,
4037 pid_t pid)
4038 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4039{
4040}
4041
4042AudioFlinger::NotificationClient::~NotificationClient()
4043{
4044 mClient.clear();
4045}
4046
4047void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4048{
4049 sp<NotificationClient> keep(this);
4050 {
4051 mAudioFlinger->removeNotificationClient(mPid);
4052 }
4053}
4054
4055// ----------------------------------------------------------------------------
4056
Eric Laurenta553c252009-07-17 12:17:14 -07004057AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004058 : BnAudioTrack(),
4059 mTrack(track)
4060{
4061}
4062
4063AudioFlinger::TrackHandle::~TrackHandle() {
4064 // just stop the track on deletion, associated resources
4065 // will be freed from the main thread once all pending buffers have
4066 // been played. Unless it's not in the active track list, in which
4067 // case we free everything now...
4068 mTrack->destroy();
4069}
4070
4071status_t AudioFlinger::TrackHandle::start() {
4072 return mTrack->start();
4073}
4074
4075void AudioFlinger::TrackHandle::stop() {
4076 mTrack->stop();
4077}
4078
4079void AudioFlinger::TrackHandle::flush() {
4080 mTrack->flush();
4081}
4082
4083void AudioFlinger::TrackHandle::mute(bool e) {
4084 mTrack->mute(e);
4085}
4086
4087void AudioFlinger::TrackHandle::pause() {
4088 mTrack->pause();
4089}
4090
4091void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4092 mTrack->setVolume(left, right);
4093}
4094
4095sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4096 return mTrack->getCblk();
4097}
4098
Eric Laurent65b65452010-06-01 23:49:17 -07004099status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4100{
4101 return mTrack->attachAuxEffect(EffectId);
4102}
4103
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004104status_t AudioFlinger::TrackHandle::onTransact(
4105 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4106{
4107 return BnAudioTrack::onTransact(code, data, reply, flags);
4108}
4109
4110// ----------------------------------------------------------------------------
4111
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004112sp<IAudioRecord> AudioFlinger::openRecord(
4113 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07004114 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004115 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004116 uint32_t format,
4117 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004118 int frameCount,
4119 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004120 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004121 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004122{
Eric Laurenta553c252009-07-17 12:17:14 -07004123 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004124 sp<RecordHandle> recordHandle;
4125 sp<Client> client;
4126 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004127 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004128 RecordThread *thread;
4129 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004130 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004131
4132 // check calling permissions
4133 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004134 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004135 goto Exit;
4136 }
4137
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004138 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004139 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004140 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004141 thread = checkRecordThread_l(input);
4142 if (thread == NULL) {
4143 lStatus = BAD_VALUE;
4144 goto Exit;
4145 }
4146
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004147 wclient = mClients.valueFor(pid);
4148 if (wclient != NULL) {
4149 client = wclient.promote();
4150 } else {
4151 client = new Client(this, pid);
4152 mClients.add(pid, client);
4153 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004154
Eric Laurent65b65452010-06-01 23:49:17 -07004155 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004156 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004157 lSessionId = *sessionId;
4158 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004159 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004160 if (sessionId != NULL) {
4161 *sessionId = lSessionId;
4162 }
4163 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004164 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004165 recordTrack = thread->createRecordTrack_l(client,
4166 sampleRate,
4167 format,
4168 channelMask,
4169 frameCount,
4170 flags,
4171 lSessionId,
4172 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004173 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004174 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004175 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4176 // destructor is called by the TrackBase destructor with mLock held
4177 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179 goto Exit;
4180 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004181
4182 // return to handle to client
4183 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004184 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004185
4186Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004187 if (status) {
4188 *status = lStatus;
4189 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004190 return recordHandle;
4191}
4192
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004193// ----------------------------------------------------------------------------
4194
Eric Laurenta553c252009-07-17 12:17:14 -07004195AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004196 : BnAudioRecord(),
4197 mRecordTrack(recordTrack)
4198{
4199}
4200
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004201AudioFlinger::RecordHandle::~RecordHandle() {
4202 stop();
4203}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004204
4205status_t AudioFlinger::RecordHandle::start() {
Steve Block71f2cf12011-10-20 11:56:00 +01004206 ALOGV("RecordHandle::start()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004207 return mRecordTrack->start();
4208}
4209
4210void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004211 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004212 mRecordTrack->stop();
4213}
4214
4215sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4216 return mRecordTrack->getCblk();
4217}
4218
4219status_t AudioFlinger::RecordHandle::onTransact(
4220 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4221{
4222 return BnAudioRecord::onTransact(code, data, reply, flags);
4223}
4224
4225// ----------------------------------------------------------------------------
4226
Eric Laurent464d5b32011-06-17 21:29:58 -07004227AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4228 AudioStreamIn *input,
4229 uint32_t sampleRate,
4230 uint32_t channels,
4231 int id,
4232 uint32_t device) :
4233 ThreadBase(audioFlinger, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08004234 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004235{
Eric Laurent464d5b32011-06-17 21:29:58 -07004236 mType = ThreadBase::RECORD;
Eric Laurent6dbdc402011-07-22 09:04:31 -07004237
4238 snprintf(mName, kNameLength, "AudioIn_%d", id);
4239
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004240 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07004241 mReqSampleRate = sampleRate;
4242 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004243}
4244
Eric Laurenta553c252009-07-17 12:17:14 -07004245
4246AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004247{
Eric Laurenta553c252009-07-17 12:17:14 -07004248 delete[] mRsmpInBuffer;
Glenn Kastenc434c902011-12-13 11:53:26 -08004249 if (mResampler != NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004250 delete mResampler;
4251 delete[] mRsmpOutBuffer;
4252 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004253}
4254
Eric Laurenta553c252009-07-17 12:17:14 -07004255void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004256{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004257 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004258}
Eric Laurent49f02be2009-11-19 09:00:56 -08004259
Eric Laurent828b9772011-08-07 16:32:26 -07004260status_t AudioFlinger::RecordThread::readyToRun()
4261{
4262 status_t status = initCheck();
Steve Block8564c8d2012-01-05 23:22:43 +00004263 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurent828b9772011-08-07 16:32:26 -07004264 return status;
4265}
4266
Eric Laurenta553c252009-07-17 12:17:14 -07004267bool AudioFlinger::RecordThread::threadLoop()
4268{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004269 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004270 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004271 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004272
Eric Laurent4712baa2010-09-30 16:12:31 -07004273 nsecs_t lastWarning = 0;
4274
Eric Laurent6dbdc402011-07-22 09:04:31 -07004275 acquireWakeLock();
4276
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004277 // start recording
4278 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004279
Eric Laurenta553c252009-07-17 12:17:14 -07004280 processConfigEvents();
4281
4282 { // scope for mLock
4283 Mutex::Autolock _l(mLock);
4284 checkForNewParameters_l();
4285 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4286 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004287 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004288 mStandby = true;
4289 }
4290
4291 if (exitPending()) break;
4292
Eric Laurent6dbdc402011-07-22 09:04:31 -07004293 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004294 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004295 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004296 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004297 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004298 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004299 continue;
4300 }
4301 if (mActiveTrack != 0) {
4302 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004303 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004304 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004305 mStandby = true;
4306 }
Eric Laurenta553c252009-07-17 12:17:14 -07004307 mActiveTrack.clear();
4308 mStartStopCond.broadcast();
4309 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004310 if (mReqChannelCount != mActiveTrack->channelCount()) {
4311 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004312 mStartStopCond.broadcast();
4313 } else if (mBytesRead != 0) {
4314 // record start succeeds only if first read from audio input
4315 // succeeds
4316 if (mBytesRead > 0) {
4317 mActiveTrack->mState = TrackBase::ACTIVE;
4318 } else {
4319 mActiveTrack.clear();
4320 }
4321 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004322 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004323 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004324 }
Eric Laurenta553c252009-07-17 12:17:14 -07004325 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004326 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004327 }
4328
4329 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004330 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4331 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004332 unlockEffectChains(effectChains);
4333 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004334 continue;
4335 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004336 for (size_t i = 0; i < effectChains.size(); i ++) {
4337 effectChains[i]->process_l();
4338 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004339
Eric Laurenta553c252009-07-17 12:17:14 -07004340 buffer.frameCount = mFrameCount;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004341 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004342 size_t framesOut = buffer.frameCount;
Glenn Kastenc434c902011-12-13 11:53:26 -08004343 if (mResampler == NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004344 // no resampling
4345 while (framesOut) {
4346 size_t framesIn = mFrameCount - mRsmpInIndex;
4347 if (framesIn) {
4348 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4349 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4350 if (framesIn > framesOut)
4351 framesIn = framesOut;
4352 mRsmpInIndex += framesIn;
4353 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004354 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004355 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004356 memcpy(dst, src, framesIn * mFrameSize);
4357 } else {
4358 int16_t *src16 = (int16_t *)src;
4359 int16_t *dst16 = (int16_t *)dst;
4360 if (mChannelCount == 1) {
4361 while (framesIn--) {
4362 *dst16++ = *src16;
4363 *dst16++ = *src16++;
4364 }
4365 } else {
4366 while (framesIn--) {
4367 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4368 src16 += 2;
4369 }
4370 }
4371 }
4372 }
4373 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004374 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004375 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004376 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004377 framesOut = 0;
4378 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004379 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004380 mRsmpInIndex = 0;
4381 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004382 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004383 ALOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004384 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004385 // Force input into standby so that it tries to
4386 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004387 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004388 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004389 }
Eric Laurenta553c252009-07-17 12:17:14 -07004390 mRsmpInIndex = mFrameCount;
4391 framesOut = 0;
4392 buffer.frameCount = 0;
4393 }
4394 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004395 }
4396 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004397 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004398
Eric Laurenta553c252009-07-17 12:17:14 -07004399 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4400 // alter output frame count as if we were expecting stereo samples
4401 if (mChannelCount == 1 && mReqChannelCount == 1) {
4402 framesOut >>= 1;
4403 }
4404 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4405 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4406 // are 32 bit aligned which should be always true.
4407 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten490909d2011-12-15 09:52:39 -08004408 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004409 // the resampler always outputs stereo samples: do post stereo to mono conversion
4410 int16_t *src = (int16_t *)mRsmpOutBuffer;
4411 int16_t *dst = buffer.i16;
4412 while (framesOut--) {
4413 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4414 src += 2;
4415 }
4416 } else {
Glenn Kasten490909d2011-12-15 09:52:39 -08004417 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004418 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004419
Eric Laurenta553c252009-07-17 12:17:14 -07004420 }
4421 mActiveTrack->releaseBuffer(&buffer);
4422 mActiveTrack->overflow();
4423 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004424 // client isn't retrieving buffers fast enough
4425 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004426 if (!mActiveTrack->setOverflow()) {
4427 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004428 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block8564c8d2012-01-05 23:22:43 +00004429 ALOGW("RecordThread: buffer overflow");
Eric Laurent4712baa2010-09-30 16:12:31 -07004430 lastWarning = now;
4431 }
4432 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004433 // Release the processor for a while before asking for a new buffer.
4434 // This will give the application more chance to read from the buffer and
4435 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004436 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004437 }
4438 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004439 // enable changes in effect chain
4440 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004441 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004442 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004443
Eric Laurenta553c252009-07-17 12:17:14 -07004444 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004445 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004446 }
Eric Laurenta553c252009-07-17 12:17:14 -07004447 mActiveTrack.clear();
4448
Eric Laurent49f02be2009-11-19 09:00:56 -08004449 mStartStopCond.broadcast();
4450
Eric Laurent6dbdc402011-07-22 09:04:31 -07004451 releaseWakeLock();
4452
Steve Block71f2cf12011-10-20 11:56:00 +01004453 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004454 return false;
4455}
4456
Eric Laurent464d5b32011-06-17 21:29:58 -07004457
4458sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4459 const sp<AudioFlinger::Client>& client,
4460 uint32_t sampleRate,
4461 int format,
4462 int channelMask,
4463 int frameCount,
4464 uint32_t flags,
4465 int sessionId,
4466 status_t *status)
4467{
4468 sp<RecordTrack> track;
4469 status_t lStatus;
4470
4471 lStatus = initCheck();
4472 if (lStatus != NO_ERROR) {
Steve Block3762c312012-01-06 19:20:56 +00004473 ALOGE("Audio driver not initialized.");
Eric Laurent464d5b32011-06-17 21:29:58 -07004474 goto Exit;
4475 }
4476
4477 { // scope for mLock
4478 Mutex::Autolock _l(mLock);
4479
4480 track = new RecordTrack(this, client, sampleRate,
4481 format, channelMask, frameCount, flags, sessionId);
4482
4483 if (track->getCblk() == NULL) {
4484 lStatus = NO_MEMORY;
4485 goto Exit;
4486 }
4487
4488 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004489 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4490 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004491 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004492 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4493 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004494 }
4495 lStatus = NO_ERROR;
4496
4497Exit:
4498 if (status) {
4499 *status = lStatus;
4500 }
4501 return track;
4502}
4503
Eric Laurenta553c252009-07-17 12:17:14 -07004504status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004505{
Steve Block71f2cf12011-10-20 11:56:00 +01004506 ALOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004507 sp <ThreadBase> strongMe = this;
4508 status_t status = NO_ERROR;
4509 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004510 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004511 if (mActiveTrack != 0) {
4512 if (recordTrack != mActiveTrack.get()) {
4513 status = -EBUSY;
4514 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004515 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004516 }
4517 return status;
4518 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004519
Eric Laurent49f02be2009-11-19 09:00:56 -08004520 recordTrack->mState = TrackBase::IDLE;
4521 mActiveTrack = recordTrack;
4522 mLock.unlock();
4523 status_t status = AudioSystem::startInput(mId);
4524 mLock.lock();
4525 if (status != NO_ERROR) {
4526 mActiveTrack.clear();
4527 return status;
4528 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004529 mRsmpInIndex = mFrameCount;
4530 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004531 if (mResampler != NULL) {
4532 mResampler->reset();
4533 }
4534 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004535 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004536 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004537 mWaitWorkCV.signal();
4538 // do not wait for mStartStopCond if exiting
4539 if (mExiting) {
4540 mActiveTrack.clear();
4541 status = INVALID_OPERATION;
4542 goto startError;
4543 }
4544 mStartStopCond.wait(mLock);
4545 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01004546 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004547 status = BAD_VALUE;
4548 goto startError;
4549 }
Steve Block71f2cf12011-10-20 11:56:00 +01004550 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004551 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004552 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004553startError:
4554 AudioSystem::stopInput(mId);
4555 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004556}
4557
Eric Laurenta553c252009-07-17 12:17:14 -07004558void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01004559 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004560 sp <ThreadBase> strongMe = this;
4561 {
Glenn Kasten325ee1c2012-01-05 15:41:56 -08004562 AutoMutex lock(mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08004563 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4564 mActiveTrack->mState = TrackBase::PAUSING;
4565 // do not wait for mStartStopCond if exiting
4566 if (mExiting) {
4567 return;
4568 }
4569 mStartStopCond.wait(mLock);
4570 // if we have been restarted, recordTrack == mActiveTrack.get() here
4571 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4572 mLock.unlock();
4573 AudioSystem::stopInput(mId);
4574 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01004575 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004576 }
4577 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004578 }
4579}
4580
Eric Laurenta553c252009-07-17 12:17:14 -07004581status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582{
4583 const size_t SIZE = 256;
4584 char buffer[SIZE];
4585 String8 result;
4586 pid_t pid = 0;
4587
Eric Laurent3fdb1262009-11-07 00:01:32 -08004588 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4589 result.append(buffer);
4590
4591 if (mActiveTrack != 0) {
4592 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004593 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004594 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004596
4597 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4598 result.append(buffer);
4599 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4600 result.append(buffer);
Glenn Kastenc434c902011-12-13 11:53:26 -08004601 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Eric Laurent3fdb1262009-11-07 00:01:32 -08004602 result.append(buffer);
4603 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4604 result.append(buffer);
4605 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4606 result.append(buffer);
4607
4608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 } else {
4610 result.append("No record client\n");
4611 }
4612 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004613
4614 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004615 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617 return NO_ERROR;
4618}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004619
Eric Laurenta553c252009-07-17 12:17:14 -07004620status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4621{
4622 size_t framesReq = buffer->frameCount;
4623 size_t framesReady = mFrameCount - mRsmpInIndex;
4624 int channelCount;
4625
4626 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004627 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004628 if (mBytesRead < 0) {
Steve Block3762c312012-01-06 19:20:56 +00004629 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004630 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004631 // Force input into standby so that it tries to
4632 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004633 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004634 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004635 }
Glenn Kastenc434c902011-12-13 11:53:26 -08004636 buffer->raw = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004637 buffer->frameCount = 0;
4638 return NOT_ENOUGH_DATA;
4639 }
4640 mRsmpInIndex = 0;
4641 framesReady = mFrameCount;
4642 }
4643
4644 if (framesReq > framesReady) {
4645 framesReq = framesReady;
4646 }
4647
4648 if (mChannelCount == 1 && mReqChannelCount == 2) {
4649 channelCount = 1;
4650 } else {
4651 channelCount = 2;
4652 }
4653 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4654 buffer->frameCount = framesReq;
4655 return NO_ERROR;
4656}
4657
4658void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4659{
4660 mRsmpInIndex += buffer->frameCount;
4661 buffer->frameCount = 0;
4662}
4663
4664bool AudioFlinger::RecordThread::checkForNewParameters_l()
4665{
4666 bool reconfig = false;
4667
Eric Laurent8fce46a2009-08-04 09:45:33 -07004668 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004669 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004670 String8 keyValuePair = mNewParameters[0];
4671 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004672 int value;
4673 int reqFormat = mFormat;
4674 int reqSamplingRate = mReqSampleRate;
4675 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004676
Eric Laurenta553c252009-07-17 12:17:14 -07004677 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4678 reqSamplingRate = value;
4679 reconfig = true;
4680 }
4681 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4682 reqFormat = value;
4683 reconfig = true;
4684 }
4685 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004686 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004687 reconfig = true;
4688 }
4689 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4690 // do not accept frame count changes if tracks are open as the track buffer
4691 // size depends on frame count and correct behavior would not be garantied
4692 // if frame count is changed after track creation
4693 if (mActiveTrack != 0) {
4694 status = INVALID_OPERATION;
4695 } else {
4696 reconfig = true;
4697 }
4698 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004699 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4700 // forward device change to effects that have requested to be
4701 // aware of attached audio device.
4702 for (size_t i = 0; i < mEffectChains.size(); i++) {
4703 mEffectChains[i]->setDevice_l(value);
4704 }
4705 // store input device and output device but do not forward output device to audio HAL.
4706 // Note that status is ignored by the caller for output device
4707 // (see AudioFlinger::setParameters()
4708 if (value & AUDIO_DEVICE_OUT_ALL) {
4709 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4710 status = BAD_VALUE;
4711 } else {
4712 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004713 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4714 if (mTrack != NULL) {
4715 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004716 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004717 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4718 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4719 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004720 }
4721 mDevice |= (uint32_t)value;
4722 }
Eric Laurenta553c252009-07-17 12:17:14 -07004723 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004724 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004725 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004726 mInput->stream->common.standby(&mInput->stream->common);
4727 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004728 }
4729 if (reconfig) {
4730 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004731 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004732 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004733 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4734 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004735 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004736 status = NO_ERROR;
4737 }
4738 if (status == NO_ERROR) {
4739 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004740 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004741 }
4742 }
4743 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004744
4745 mNewParameters.removeAt(0);
4746
Eric Laurenta553c252009-07-17 12:17:14 -07004747 mParamStatus = status;
4748 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004749 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4750 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004751 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07004752 }
4753 return reconfig;
4754}
4755
4756String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4757{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004758 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004759 String8 out_s8 = String8();
4760
4761 Mutex::Autolock _l(mLock);
4762 if (initCheck() != NO_ERROR) {
4763 return out_s8;
4764 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004765
Dima Zavin31f188892011-04-18 16:57:27 -07004766 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004767 out_s8 = String8(s);
4768 free(s);
4769 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004770}
4771
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004772void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004773 AudioSystem::OutputDescriptor desc;
4774 void *param2 = 0;
4775
4776 switch (event) {
4777 case AudioSystem::INPUT_OPENED:
4778 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004779 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004780 desc.samplingRate = mSampleRate;
4781 desc.format = mFormat;
4782 desc.frameCount = mFrameCount;
4783 desc.latency = 0;
4784 param2 = &desc;
4785 break;
4786
4787 case AudioSystem::INPUT_CLOSED:
4788 default:
4789 break;
4790 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004791 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004792}
4793
4794void AudioFlinger::RecordThread::readInputParameters()
4795{
4796 if (mRsmpInBuffer) delete mRsmpInBuffer;
4797 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4798 if (mResampler) delete mResampler;
Glenn Kastenc434c902011-12-13 11:53:26 -08004799 mResampler = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004800
Dima Zavin31f188892011-04-18 16:57:27 -07004801 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004802 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4803 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004804 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4805 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4806 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004807 mFrameCount = mInputBytes / mFrameSize;
4808 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4809
4810 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4811 {
4812 int channelCount;
4813 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4814 // stereo to mono post process as the resampler always outputs stereo.
4815 if (mChannelCount == 1 && mReqChannelCount == 2) {
4816 channelCount = 1;
4817 } else {
4818 channelCount = 2;
4819 }
4820 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4821 mResampler->setSampleRate(mSampleRate);
4822 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4823 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4824
4825 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4826 if (mChannelCount == 1 && mReqChannelCount == 1) {
4827 mFrameCount >>= 1;
4828 }
4829
4830 }
4831 mRsmpInIndex = mFrameCount;
4832}
4833
Eric Laurent47d0a922010-02-26 02:47:27 -08004834unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4835{
Eric Laurent828b9772011-08-07 16:32:26 -07004836 Mutex::Autolock _l(mLock);
4837 if (initCheck() != NO_ERROR) {
4838 return 0;
4839 }
4840
Dima Zavin31f188892011-04-18 16:57:27 -07004841 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004842}
4843
Eric Laurent464d5b32011-06-17 21:29:58 -07004844uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4845{
4846 Mutex::Autolock _l(mLock);
4847 uint32_t result = 0;
4848 if (getEffectChain_l(sessionId) != 0) {
4849 result = EFFECT_SESSION;
4850 }
4851
4852 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4853 result |= TRACK_SESSION;
4854 }
4855
4856 return result;
4857}
4858
Eric Laurent6639b552011-08-01 09:52:20 -07004859AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4860{
4861 Mutex::Autolock _l(mLock);
4862 return mTrack;
4863}
4864
Eric Laurent828b9772011-08-07 16:32:26 -07004865AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4866{
4867 Mutex::Autolock _l(mLock);
4868 return mInput;
4869}
4870
4871AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4872{
4873 Mutex::Autolock _l(mLock);
4874 AudioStreamIn *input = mInput;
4875 mInput = NULL;
4876 return input;
4877}
4878
4879// this method must always be called either with ThreadBase mLock held or inside the thread loop
4880audio_stream_t* AudioFlinger::RecordThread::stream()
4881{
4882 if (mInput == NULL) {
4883 return NULL;
4884 }
4885 return &mInput->stream->common;
4886}
4887
4888
Eric Laurenta553c252009-07-17 12:17:14 -07004889// ----------------------------------------------------------------------------
4890
Eric Laurentddb78e72009-07-28 08:44:33 -07004891int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004892 uint32_t *pSamplingRate,
4893 uint32_t *pFormat,
4894 uint32_t *pChannels,
4895 uint32_t *pLatencyMs,
4896 uint32_t flags)
4897{
4898 status_t status;
4899 PlaybackThread *thread = NULL;
4900 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4901 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4902 uint32_t format = pFormat ? *pFormat : 0;
4903 uint32_t channels = pChannels ? *pChannels : 0;
4904 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004905 audio_stream_out_t *outStream;
4906 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004907
Steve Block71f2cf12011-10-20 11:56:00 +01004908 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07004909 pDevices ? *pDevices : 0,
4910 samplingRate,
4911 format,
4912 channels,
4913 flags);
4914
4915 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004916 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004917 }
Dima Zavin31f188892011-04-18 16:57:27 -07004918
Eric Laurenta553c252009-07-17 12:17:14 -07004919 Mutex::Autolock _l(mLock);
4920
Dima Zavin31f188892011-04-18 16:57:27 -07004921 outHwDev = findSuitableHwDev_l(*pDevices);
4922 if (outHwDev == NULL)
4923 return 0;
4924
4925 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4926 &channels, &samplingRate, &outStream);
Steve Block71f2cf12011-10-20 11:56:00 +01004927 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004928 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004929 samplingRate,
4930 format,
4931 channels,
4932 status);
4933
4934 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004935 if (outStream != NULL) {
4936 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent464d5b32011-06-17 21:29:58 -07004937 int id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004938
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004939 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4940 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4941 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004942 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004943 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004944 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004945 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004946 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004947 }
Eric Laurent65b65452010-06-01 23:49:17 -07004948 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004949
4950 if (pSamplingRate) *pSamplingRate = samplingRate;
4951 if (pFormat) *pFormat = format;
4952 if (pChannels) *pChannels = channels;
4953 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004954
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004955 // notify client processes of the new output creation
4956 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004957 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004958 }
4959
Eric Laurent9cc489a22009-12-05 05:20:01 -08004960 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004961}
4962
Eric Laurentddb78e72009-07-28 08:44:33 -07004963int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004964{
4965 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004966 MixerThread *thread1 = checkMixerThread_l(output1);
4967 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004968
Eric Laurentddb78e72009-07-28 08:44:33 -07004969 if (thread1 == NULL || thread2 == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00004970 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004971 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004972 }
4973
Eric Laurent464d5b32011-06-17 21:29:58 -07004974 int id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004975 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004976 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004977 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004978 // notify client processes of the new output creation
4979 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004980 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004981}
4982
Eric Laurentddb78e72009-07-28 08:44:33 -07004983status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004984{
Eric Laurent49018a52009-08-04 08:37:05 -07004985 // keep strong reference on the playback thread so that
4986 // it is not destroyed while exit() is executed
4987 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004988 {
4989 Mutex::Autolock _l(mLock);
4990 thread = checkPlaybackThread_l(output);
4991 if (thread == NULL) {
4992 return BAD_VALUE;
4993 }
4994
Steve Block71f2cf12011-10-20 11:56:00 +01004995 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004996
Eric Laurent464d5b32011-06-17 21:29:58 -07004997 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07004998 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004999 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005000 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07005001 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07005002 }
5003 }
5004 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07005005 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005006 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005007 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07005008 }
5009 thread->exit();
5010
Eric Laurent464d5b32011-06-17 21:29:58 -07005011 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07005012 AudioStreamOut *out = thread->clearOutput();
5013 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005014 out->hwDev->close_output_stream(out->hwDev, out->stream);
5015 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005016 }
Eric Laurenta553c252009-07-17 12:17:14 -07005017 return NO_ERROR;
5018}
5019
Eric Laurentddb78e72009-07-28 08:44:33 -07005020status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005021{
5022 Mutex::Autolock _l(mLock);
5023 PlaybackThread *thread = checkPlaybackThread_l(output);
5024
5025 if (thread == NULL) {
5026 return BAD_VALUE;
5027 }
5028
Steve Block71f2cf12011-10-20 11:56:00 +01005029 ALOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005030 thread->suspend();
5031
5032 return NO_ERROR;
5033}
5034
Eric Laurentddb78e72009-07-28 08:44:33 -07005035status_t AudioFlinger::restoreOutput(int 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("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005045
5046 thread->restore();
5047
5048 return NO_ERROR;
5049}
5050
Eric Laurentddb78e72009-07-28 08:44:33 -07005051int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005052 uint32_t *pSamplingRate,
5053 uint32_t *pFormat,
5054 uint32_t *pChannels,
5055 uint32_t acoustics)
5056{
5057 status_t status;
5058 RecordThread *thread = NULL;
5059 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5060 uint32_t format = pFormat ? *pFormat : 0;
5061 uint32_t channels = pChannels ? *pChannels : 0;
5062 uint32_t reqSamplingRate = samplingRate;
5063 uint32_t reqFormat = format;
5064 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005065 audio_stream_in_t *inStream;
5066 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005067
5068 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005069 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005070 }
Dima Zavin31f188892011-04-18 16:57:27 -07005071
Eric Laurenta553c252009-07-17 12:17:14 -07005072 Mutex::Autolock _l(mLock);
5073
Dima Zavin31f188892011-04-18 16:57:27 -07005074 inHwDev = findSuitableHwDev_l(*pDevices);
5075 if (inHwDev == NULL)
5076 return 0;
5077
5078 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5079 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005080 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005081 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005082 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005083 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005084 samplingRate,
5085 format,
5086 channels,
5087 acoustics,
5088 status);
5089
5090 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5091 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5092 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005093 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005094 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005095 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005096 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005097 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin31f188892011-04-18 16:57:27 -07005098 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5099 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005100 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005101 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005102 }
5103
Dima Zavin31f188892011-04-18 16:57:27 -07005104 if (inStream != NULL) {
5105 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5106
Eric Laurent464d5b32011-06-17 21:29:58 -07005107 int id = nextUniqueId();
5108 // Start record thread
5109 // RecorThread require both input and output device indication to forward to audio
5110 // pre processing modules
5111 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5112 thread = new RecordThread(this,
5113 input,
5114 reqSamplingRate,
5115 reqChannels,
5116 id,
5117 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005118 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005119 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005120 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5121 if (pFormat) *pFormat = format;
5122 if (pChannels) *pChannels = reqChannels;
5123
Dima Zavin31f188892011-04-18 16:57:27 -07005124 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005125
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005126 // notify client processes of the new input creation
5127 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005128 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005129 }
5130
Eric Laurent9cc489a22009-12-05 05:20:01 -08005131 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005132}
5133
Eric Laurentddb78e72009-07-28 08:44:33 -07005134status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07005135{
Eric Laurent49018a52009-08-04 08:37:05 -07005136 // keep strong reference on the record thread so that
5137 // it is not destroyed while exit() is executed
5138 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005139 {
5140 Mutex::Autolock _l(mLock);
5141 thread = checkRecordThread_l(input);
5142 if (thread == NULL) {
5143 return BAD_VALUE;
5144 }
5145
Steve Block71f2cf12011-10-20 11:56:00 +01005146 ALOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07005147 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005148 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005149 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005150 }
5151 thread->exit();
5152
Eric Laurent828b9772011-08-07 16:32:26 -07005153 AudioStreamIn *in = thread->clearInput();
5154 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005155 in->hwDev->close_input_stream(in->hwDev, in->stream);
5156 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005157
Eric Laurenta553c252009-07-17 12:17:14 -07005158 return NO_ERROR;
5159}
5160
Glenn Kastenbc1d77b2012-01-12 16:38:12 -08005161status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005162{
5163 Mutex::Autolock _l(mLock);
5164 MixerThread *dstThread = checkMixerThread_l(output);
5165 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005166 ALOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005167 return BAD_VALUE;
5168 }
5169
Steve Block71f2cf12011-10-20 11:56:00 +01005170 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005171 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005172
Eric Laurent05ce0942011-08-30 10:18:54 -07005173 dstThread->setStreamValid(stream, true);
5174
Eric Laurenta553c252009-07-17 12:17:14 -07005175 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005176 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005177 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005178 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005179 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005180 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005181 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005182 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005183 }
Eric Laurentd069f322009-09-01 05:56:26 -07005184
Eric Laurenta553c252009-07-17 12:17:14 -07005185 return NO_ERROR;
5186}
5187
Eric Laurent65b65452010-06-01 23:49:17 -07005188
5189int AudioFlinger::newAudioSessionId()
5190{
Eric Laurent464d5b32011-06-17 21:29:58 -07005191 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005192}
5193
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005194void AudioFlinger::acquireAudioSessionId(int audioSession)
5195{
5196 Mutex::Autolock _l(mLock);
5197 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005198 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005199 int num = mAudioSessionRefs.size();
5200 for (int i = 0; i< num; i++) {
5201 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5202 if (ref->sessionid == audioSession && ref->pid == caller) {
5203 ref->cnt++;
Steve Block71f2cf12011-10-20 11:56:00 +01005204 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005205 return;
5206 }
5207 }
5208 AudioSessionRef *ref = new AudioSessionRef();
5209 ref->sessionid = audioSession;
5210 ref->pid = caller;
5211 ref->cnt = 1;
5212 mAudioSessionRefs.push(ref);
Steve Block71f2cf12011-10-20 11:56:00 +01005213 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005214}
5215
5216void AudioFlinger::releaseAudioSessionId(int audioSession)
5217{
5218 Mutex::Autolock _l(mLock);
5219 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005220 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005221 int num = mAudioSessionRefs.size();
5222 for (int i = 0; i< num; i++) {
5223 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5224 if (ref->sessionid == audioSession && ref->pid == caller) {
5225 ref->cnt--;
Steve Block71f2cf12011-10-20 11:56:00 +01005226 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005227 if (ref->cnt == 0) {
5228 mAudioSessionRefs.removeAt(i);
5229 delete ref;
5230 purgeStaleEffects_l();
5231 }
5232 return;
5233 }
5234 }
Steve Block8564c8d2012-01-05 23:22:43 +00005235 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005236}
5237
5238void AudioFlinger::purgeStaleEffects_l() {
5239
Steve Block71f2cf12011-10-20 11:56:00 +01005240 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005241
5242 Vector< sp<EffectChain> > chains;
5243
5244 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5245 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5246 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5247 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005248 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5249 chains.push(ec);
5250 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005251 }
5252 }
5253 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5254 sp<RecordThread> t = mRecordThreads.valueAt(i);
5255 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5256 sp<EffectChain> ec = t->mEffectChains[j];
5257 chains.push(ec);
5258 }
5259 }
5260
5261 for (size_t i = 0; i < chains.size(); i++) {
5262 sp<EffectChain> ec = chains[i];
5263 int sessionid = ec->sessionId();
5264 sp<ThreadBase> t = ec->mThread.promote();
5265 if (t == 0) {
5266 continue;
5267 }
5268 size_t numsessionrefs = mAudioSessionRefs.size();
5269 bool found = false;
5270 for (size_t k = 0; k < numsessionrefs; k++) {
5271 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5272 if (ref->sessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005273 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005274 sessionid, ref->pid, ref->cnt);
5275 found = true;
5276 break;
5277 }
5278 }
5279 if (!found) {
5280 // remove all effects from the chain
5281 while (ec->mEffects.size()) {
5282 sp<EffectModule> effect = ec->mEffects[0];
5283 effect->unPin();
5284 Mutex::Autolock _l (t->mLock);
5285 t->removeEffect_l(effect);
5286 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5287 sp<EffectHandle> handle = effect->mHandles[j].promote();
5288 if (handle != 0) {
5289 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005290 if (handle->mHasControl && handle->mEnabled) {
5291 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5292 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005293 }
5294 }
5295 AudioSystem::unregisterEffect(effect->id());
5296 }
5297 }
5298 }
5299 return;
5300}
5301
Eric Laurenta553c252009-07-17 12:17:14 -07005302// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005303AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005304{
5305 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005306 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5307 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005308 }
Eric Laurenta553c252009-07-17 12:17:14 -07005309 return thread;
5310}
5311
5312// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005313AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005314{
5315 PlaybackThread *thread = checkPlaybackThread_l(output);
5316 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005317 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005318 thread = NULL;
5319 }
5320 }
5321 return (MixerThread *)thread;
5322}
5323
5324// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005325AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005326{
5327 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005328 if (mRecordThreads.indexOfKey(input) >= 0) {
5329 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005330 }
Eric Laurenta553c252009-07-17 12:17:14 -07005331 return thread;
5332}
5333
Eric Laurent464d5b32011-06-17 21:29:58 -07005334uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005335{
Eric Laurent464d5b32011-06-17 21:29:58 -07005336 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005337}
5338
Eric Laurent464d5b32011-06-17 21:29:58 -07005339AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5340{
5341 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5342 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005343 AudioStreamOut *output = thread->getOutput();
5344 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005345 return thread;
5346 }
5347 }
5348 return NULL;
5349}
5350
5351uint32_t AudioFlinger::primaryOutputDevice_l()
5352{
5353 PlaybackThread *thread = primaryPlaybackThread_l();
5354
5355 if (thread == NULL) {
5356 return 0;
5357 }
5358
5359 return thread->device();
5360}
5361
5362
Eric Laurent65b65452010-06-01 23:49:17 -07005363// ----------------------------------------------------------------------------
5364// Effect management
5365// ----------------------------------------------------------------------------
5366
5367
Eric Laurent65b65452010-06-01 23:49:17 -07005368status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5369{
5370 Mutex::Autolock _l(mLock);
5371 return EffectQueryNumberEffects(numEffects);
5372}
5373
Eric Laurent53334cd2010-06-23 17:38:20 -07005374status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07005375{
5376 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005377 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005378}
5379
5380status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5381{
5382 Mutex::Autolock _l(mLock);
5383 return EffectGetDescriptor(pUuid, descriptor);
5384}
5385
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005386
Eric Laurent65b65452010-06-01 23:49:17 -07005387sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5388 effect_descriptor_t *pDesc,
5389 const sp<IEffectClient>& effectClient,
5390 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005391 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005392 int sessionId,
5393 status_t *status,
5394 int *id,
5395 int *enabled)
5396{
5397 status_t lStatus = NO_ERROR;
5398 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005399 effect_descriptor_t desc;
5400 sp<Client> client;
5401 wp<Client> wclient;
5402
Steve Block71f2cf12011-10-20 11:56:00 +01005403 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005404 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005405
5406 if (pDesc == NULL) {
5407 lStatus = BAD_VALUE;
5408 goto Exit;
5409 }
5410
Eric Laurent98c92592010-09-23 16:10:16 -07005411 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005412 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005413 lStatus = PERMISSION_DENIED;
5414 goto Exit;
5415 }
5416
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005417 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005418 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005419 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005420 lStatus = PERMISSION_DENIED;
5421 goto Exit;
5422 }
5423
Eric Laurent464d5b32011-06-17 21:29:58 -07005424 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005425 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005426 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005427 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005428 lStatus = BAD_VALUE;
5429 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005430 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005431 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005432 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005433 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005434 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005435 }
5436 }
5437
Eric Laurent65b65452010-06-01 23:49:17 -07005438 {
5439 Mutex::Autolock _l(mLock);
5440
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005441
Eric Laurent65b65452010-06-01 23:49:17 -07005442 if (!EffectIsNullUuid(&pDesc->uuid)) {
5443 // if uuid is specified, request effect descriptor
5444 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5445 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005446 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005447 goto Exit;
5448 }
5449 } else {
5450 // if uuid is not specified, look for an available implementation
5451 // of the required type in effect factory
5452 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005453 ALOGW("createEffect() no effect type");
Eric Laurent65b65452010-06-01 23:49:17 -07005454 lStatus = BAD_VALUE;
5455 goto Exit;
5456 }
5457 uint32_t numEffects = 0;
5458 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005459 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005460 bool found = false;
5461
5462 lStatus = EffectQueryNumberEffects(&numEffects);
5463 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005464 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005465 goto Exit;
5466 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005467 for (uint32_t i = 0; i < numEffects; i++) {
5468 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005469 if (lStatus < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005470 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005471 continue;
5472 }
5473 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5474 // If matching type found save effect descriptor. If the session is
5475 // 0 and the effect is not auxiliary, continue enumeration in case
5476 // an auxiliary version of this effect type is available
5477 found = true;
5478 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005479 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005480 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5481 break;
5482 }
5483 }
5484 }
5485 if (!found) {
5486 lStatus = BAD_VALUE;
Steve Block8564c8d2012-01-05 23:22:43 +00005487 ALOGW("createEffect() effect not found");
Eric Laurent65b65452010-06-01 23:49:17 -07005488 goto Exit;
5489 }
5490 // For same effect type, chose auxiliary version over insert version if
5491 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005492 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005493 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5494 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5495 }
5496 }
5497
5498 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005499 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005500 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5501 lStatus = INVALID_OPERATION;
5502 goto Exit;
5503 }
5504
Eric Laurentf82fccd2011-07-27 19:49:51 -07005505 // check recording permission for visualizer
5506 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5507 !recordingAllowed()) {
5508 lStatus = PERMISSION_DENIED;
5509 goto Exit;
5510 }
5511
Eric Laurent65b65452010-06-01 23:49:17 -07005512 // return effect descriptor
5513 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5514
5515 // If output is not specified try to find a matching audio session ID in one of the
5516 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005517 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5518 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005519 // Note: io is never 0 when creating an effect on an input
5520 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005521 // look for the thread where the specified audio session is present
5522 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5523 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005524 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005525 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005526 }
Eric Laurent65b65452010-06-01 23:49:17 -07005527 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005528 if (io == 0) {
5529 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5530 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5531 io = mRecordThreads.keyAt(i);
5532 break;
5533 }
5534 }
5535 }
Eric Laurent98c92592010-09-23 16:10:16 -07005536 // If no output thread contains the requested session ID, default to
5537 // first output. The effect chain will be moved to the correct output
5538 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005539 if (io == 0 && mPlaybackThreads.size()) {
5540 io = mPlaybackThreads.keyAt(0);
5541 }
Steve Block71f2cf12011-10-20 11:56:00 +01005542 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005543 }
5544 ThreadBase *thread = checkRecordThread_l(io);
5545 if (thread == NULL) {
5546 thread = checkPlaybackThread_l(io);
5547 if (thread == NULL) {
Steve Block3762c312012-01-06 19:20:56 +00005548 ALOGE("createEffect() unknown output thread");
Eric Laurent464d5b32011-06-17 21:29:58 -07005549 lStatus = BAD_VALUE;
5550 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005551 }
Eric Laurent65b65452010-06-01 23:49:17 -07005552 }
Eric Laurent98c92592010-09-23 16:10:16 -07005553
Eric Laurent65b65452010-06-01 23:49:17 -07005554 wclient = mClients.valueFor(pid);
5555
5556 if (wclient != NULL) {
5557 client = wclient.promote();
5558 } else {
5559 client = new Client(this, pid);
5560 mClients.add(pid, client);
5561 }
5562
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005563 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005564 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5565 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005566 if (handle != 0 && id != NULL) {
5567 *id = handle->id();
5568 }
5569 }
5570
5571Exit:
5572 if(status) {
5573 *status = lStatus;
5574 }
5575 return handle;
5576}
5577
Eric Laurentf82fccd2011-07-27 19:49:51 -07005578status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005579{
Steve Block71f2cf12011-10-20 11:56:00 +01005580 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005581 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005582 Mutex::Autolock _l(mLock);
5583 if (srcOutput == dstOutput) {
Steve Block8564c8d2012-01-05 23:22:43 +00005584 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005585 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005586 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005587 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5588 if (srcThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005589 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005590 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005591 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005592 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5593 if (dstThread == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00005594 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005595 return BAD_VALUE;
5596 }
5597
5598 Mutex::Autolock _dl(dstThread->mLock);
5599 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005600 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005601
Eric Laurent53334cd2010-06-23 17:38:20 -07005602 return NO_ERROR;
5603}
5604
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005605// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005606status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005607 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005608 AudioFlinger::PlaybackThread *dstThread,
5609 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005610{
Steve Block71f2cf12011-10-20 11:56:00 +01005611 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005612 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005613
Eric Laurentf82fccd2011-07-27 19:49:51 -07005614 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005615 if (chain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005616 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005617 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005618 return INVALID_OPERATION;
5619 }
5620
Eric Laurent493941b2010-07-28 01:32:47 -07005621 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005622 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005623 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005624 // removed.
5625 srcThread->removeEffectChain_l(chain);
5626
5627 // transfer all effects one by one so that new effect chain is created on new thread with
5628 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005629 int dstOutput = dstThread->id();
5630 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005631 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005632 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5633 while (effect != 0) {
5634 srcThread->removeEffect_l(effect);
5635 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005636 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5637 if (effect->state() == EffectModule::ACTIVE ||
5638 effect->state() == EffectModule::STOPPING) {
5639 effect->start();
5640 }
Eric Laurent493941b2010-07-28 01:32:47 -07005641 // if the move request is not received from audio policy manager, the effect must be
5642 // re-registered with the new strategy and output
5643 if (dstChain == 0) {
5644 dstChain = effect->chain().promote();
5645 if (dstChain == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005646 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent493941b2010-07-28 01:32:47 -07005647 srcThread->addEffect_l(effect);
5648 return NO_INIT;
5649 }
5650 strategy = dstChain->strategy();
5651 }
5652 if (reRegister) {
5653 AudioSystem::unregisterEffect(effect->id());
5654 AudioSystem::registerEffect(&effect->desc(),
5655 dstOutput,
5656 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005657 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005658 effect->id());
5659 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005660 effect = chain->getEffectFromId_l(0);
5661 }
5662
5663 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005664}
5665
Eric Laurent464d5b32011-06-17 21:29:58 -07005666
Eric Laurent65b65452010-06-01 23:49:17 -07005667// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005668sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005669 const sp<AudioFlinger::Client>& client,
5670 const sp<IEffectClient>& effectClient,
5671 int32_t priority,
5672 int sessionId,
5673 effect_descriptor_t *desc,
5674 int *enabled,
5675 status_t *status
5676 )
5677{
5678 sp<EffectModule> effect;
5679 sp<EffectHandle> handle;
5680 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005681 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005682 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005683 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005684 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005685
Eric Laurent464d5b32011-06-17 21:29:58 -07005686 lStatus = initCheck();
5687 if (lStatus != NO_ERROR) {
Steve Block8564c8d2012-01-05 23:22:43 +00005688 ALOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005689 goto Exit;
5690 }
5691
5692 // Do not allow effects with session ID 0 on direct output or duplicating threads
5693 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005694 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block8564c8d2012-01-05 23:22:43 +00005695 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005696 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005697 lStatus = BAD_VALUE;
5698 goto Exit;
5699 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005700 // Only Pre processor effects are allowed on input threads and only on input threads
5701 if ((mType == RECORD &&
5702 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5703 (mType != RECORD &&
5704 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block8564c8d2012-01-05 23:22:43 +00005705 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005706 desc->name, desc->flags, mType);
5707 lStatus = BAD_VALUE;
5708 goto Exit;
5709 }
Eric Laurent65b65452010-06-01 23:49:17 -07005710
Steve Block71f2cf12011-10-20 11:56:00 +01005711 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005712
5713 { // scope for mLock
5714 Mutex::Autolock _l(mLock);
5715
5716 // check for existing effect chain with the requested audio session
5717 chain = getEffectChain_l(sessionId);
5718 if (chain == 0) {
5719 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005720 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005721 chain = new EffectChain(this, sessionId);
5722 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005723 chain->setStrategy(getStrategyForSession_l(sessionId));
5724 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005725 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005726 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005727 }
5728
Steve Block71f2cf12011-10-20 11:56:00 +01005729 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005730
5731 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005732 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005733 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005734 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005735 if (lStatus != NO_ERROR) {
5736 goto Exit;
5737 }
5738 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005739 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005740 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005741 lStatus = effect->status();
5742 if (lStatus != NO_ERROR) {
5743 goto Exit;
5744 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005745 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005746 if (lStatus != NO_ERROR) {
5747 goto Exit;
5748 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005749 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005750
5751 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005752 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005753 }
5754 // create effect handle and connect it to effect module
5755 handle = new EffectHandle(effect, client, effectClient, priority);
5756 lStatus = effect->addHandle(handle);
5757 if (enabled) {
5758 *enabled = (int)effect->isEnabled();
5759 }
5760 }
5761
5762Exit:
5763 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005764 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005765 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005766 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005767 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005768 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005769 AudioSystem::unregisterEffect(effect->id());
5770 }
5771 if (chainCreated) {
5772 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005773 }
Eric Laurent65b65452010-06-01 23:49:17 -07005774 handle.clear();
5775 }
5776
5777 if(status) {
5778 *status = lStatus;
5779 }
5780 return handle;
5781}
5782
Eric Laurent464d5b32011-06-17 21:29:58 -07005783sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5784{
5785 sp<EffectModule> effect;
5786
5787 sp<EffectChain> chain = getEffectChain_l(sessionId);
5788 if (chain != 0) {
5789 effect = chain->getEffectFromId_l(effectId);
5790 }
5791 return effect;
5792}
5793
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005794// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5795// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005796status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005797{
5798 // check for existing effect chain with the requested audio session
5799 int sessionId = effect->sessionId();
5800 sp<EffectChain> chain = getEffectChain_l(sessionId);
5801 bool chainCreated = false;
5802
5803 if (chain == 0) {
5804 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005805 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005806 chain = new EffectChain(this, sessionId);
5807 addEffectChain_l(chain);
5808 chain->setStrategy(getStrategyForSession_l(sessionId));
5809 chainCreated = true;
5810 }
Steve Block71f2cf12011-10-20 11:56:00 +01005811 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005812
5813 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00005814 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005815 this, effect->desc().name, chain.get());
5816 return BAD_VALUE;
5817 }
5818
5819 status_t status = chain->addEffect_l(effect);
5820 if (status != NO_ERROR) {
5821 if (chainCreated) {
5822 removeEffectChain_l(chain);
5823 }
5824 return status;
5825 }
5826
5827 effect->setDevice(mDevice);
5828 effect->setMode(mAudioFlinger->getMode());
5829 return NO_ERROR;
5830}
5831
Eric Laurent464d5b32011-06-17 21:29:58 -07005832void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005833
Steve Block71f2cf12011-10-20 11:56:00 +01005834 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005835 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005836 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5837 detachAuxEffect_l(effect->id());
5838 }
5839
5840 sp<EffectChain> chain = effect->chain().promote();
5841 if (chain != 0) {
5842 // remove effect chain if removing last effect
5843 if (chain->removeEffect_l(effect) == 0) {
5844 removeEffectChain_l(chain);
5845 }
5846 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00005847 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005848 }
5849}
5850
Eric Laurent464d5b32011-06-17 21:29:58 -07005851void AudioFlinger::ThreadBase::lockEffectChains_l(
5852 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5853{
5854 effectChains = mEffectChains;
5855 for (size_t i = 0; i < mEffectChains.size(); i++) {
5856 mEffectChains[i]->lock();
5857 }
5858}
5859
5860void AudioFlinger::ThreadBase::unlockEffectChains(
5861 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5862{
5863 for (size_t i = 0; i < effectChains.size(); i++) {
5864 effectChains[i]->unlock();
5865 }
5866}
5867
5868sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5869{
5870 Mutex::Autolock _l(mLock);
5871 return getEffectChain_l(sessionId);
5872}
5873
5874sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5875{
5876 sp<EffectChain> chain;
5877
5878 size_t size = mEffectChains.size();
5879 for (size_t i = 0; i < size; i++) {
5880 if (mEffectChains[i]->sessionId() == sessionId) {
5881 chain = mEffectChains[i];
5882 break;
5883 }
5884 }
5885 return chain;
5886}
5887
5888void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5889{
5890 Mutex::Autolock _l(mLock);
5891 size_t size = mEffectChains.size();
5892 for (size_t i = 0; i < size; i++) {
5893 mEffectChains[i]->setMode_l(mode);
5894 }
5895}
5896
5897void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005898 const wp<EffectHandle>& handle,
5899 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005900
Eric Laurent53334cd2010-06-23 17:38:20 -07005901 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01005902 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005903 // delete the effect module if removing last handle on it
5904 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005905 if (!effect->isPinned() || unpiniflast) {
5906 removeEffect_l(effect);
5907 AudioSystem::unregisterEffect(effect->id());
5908 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005909 }
5910}
5911
Eric Laurent65b65452010-06-01 23:49:17 -07005912status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5913{
5914 int session = chain->sessionId();
5915 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005916 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005917
Steve Block71f2cf12011-10-20 11:56:00 +01005918 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005919 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005920 // Only one effect chain can be present in direct output thread and it uses
5921 // the mix buffer as input
5922 if (mType != DIRECT) {
5923 size_t numSamples = mFrameCount * mChannelCount;
5924 buffer = new int16_t[numSamples];
5925 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01005926 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005927 ownsBuffer = true;
5928 }
Eric Laurent65b65452010-06-01 23:49:17 -07005929
Eric Laurent53334cd2010-06-23 17:38:20 -07005930 // Attach all tracks with same session ID to this chain.
5931 for (size_t i = 0; i < mTracks.size(); ++i) {
5932 sp<Track> track = mTracks[i];
5933 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005934 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07005935 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005936 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005937 }
5938 }
5939
5940 // indicate all active tracks in the chain
5941 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5942 sp<Track> track = mActiveTracks[i].promote();
5943 if (track == 0) continue;
5944 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005945 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005946 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005947 }
Eric Laurent65b65452010-06-01 23:49:17 -07005948 }
5949 }
5950
Eric Laurent53334cd2010-06-23 17:38:20 -07005951 chain->setInBuffer(buffer, ownsBuffer);
5952 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005953 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005954 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005955 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5956 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005957 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005958 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5959 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005960 // Effect chain for other sessions are inserted at beginning of effect
5961 // chains list to be processed before output mix effects. Relative order between other
5962 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005963 size_t size = mEffectChains.size();
5964 size_t i = 0;
5965 for (i = 0; i < size; i++) {
5966 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005967 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005968 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005969 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005970
5971 return NO_ERROR;
5972}
5973
5974size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5975{
5976 int session = chain->sessionId();
5977
Steve Block71f2cf12011-10-20 11:56:00 +01005978 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005979
5980 for (size_t i = 0; i < mEffectChains.size(); i++) {
5981 if (chain == mEffectChains[i]) {
5982 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005983 // detach all active tracks from the chain
5984 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5985 sp<Track> track = mActiveTracks[i].promote();
5986 if (track == 0) continue;
5987 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005988 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07005989 chain.get(), session);
5990 chain->decActiveTrackCnt();
5991 }
5992 }
5993
Eric Laurent65b65452010-06-01 23:49:17 -07005994 // detach all tracks with same session ID from this chain
5995 for (size_t i = 0; i < mTracks.size(); ++i) {
5996 sp<Track> track = mTracks[i];
5997 if (session == track->sessionId()) {
5998 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005999 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07006000 }
6001 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006002 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006003 }
6004 }
6005 return mEffectChains.size();
6006}
6007
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006008status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6009 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006010{
6011 Mutex::Autolock _l(mLock);
6012 return attachAuxEffect_l(track, EffectId);
6013}
6014
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006015status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6016 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006017{
6018 status_t status = NO_ERROR;
6019
6020 if (EffectId == 0) {
6021 track->setAuxBuffer(0, NULL);
6022 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006023 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6024 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006025 if (effect != 0) {
6026 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6027 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6028 } else {
6029 status = INVALID_OPERATION;
6030 }
6031 } else {
6032 status = BAD_VALUE;
6033 }
6034 }
6035 return status;
6036}
6037
6038void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6039{
6040 for (size_t i = 0; i < mTracks.size(); ++i) {
6041 sp<Track> track = mTracks[i];
6042 if (track->auxEffectId() == effectId) {
6043 attachAuxEffect_l(track, 0);
6044 }
6045 }
6046}
6047
Eric Laurent464d5b32011-06-17 21:29:58 -07006048status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6049{
6050 // only one chain per input thread
6051 if (mEffectChains.size() != 0) {
6052 return INVALID_OPERATION;
6053 }
Steve Block71f2cf12011-10-20 11:56:00 +01006054 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006055
6056 chain->setInBuffer(NULL);
6057 chain->setOutBuffer(NULL);
6058
Eric Laurentf82fccd2011-07-27 19:49:51 -07006059 checkSuspendOnAddEffectChain_l(chain);
6060
Eric Laurent464d5b32011-06-17 21:29:58 -07006061 mEffectChains.add(chain);
6062
6063 return NO_ERROR;
6064}
6065
6066size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6067{
Steve Block71f2cf12011-10-20 11:56:00 +01006068 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block8564c8d2012-01-05 23:22:43 +00006069 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent464d5b32011-06-17 21:29:58 -07006070 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6071 chain.get(), mEffectChains.size(), this);
6072 if (mEffectChains.size() == 1) {
6073 mEffectChains.removeAt(0);
6074 }
6075 return 0;
6076}
6077
Eric Laurent65b65452010-06-01 23:49:17 -07006078// ----------------------------------------------------------------------------
6079// EffectModule implementation
6080// ----------------------------------------------------------------------------
6081
6082#undef LOG_TAG
6083#define LOG_TAG "AudioFlinger::EffectModule"
6084
6085AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6086 const wp<AudioFlinger::EffectChain>& chain,
6087 effect_descriptor_t *desc,
6088 int id,
6089 int sessionId)
6090 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006091 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006092{
Steve Block71f2cf12011-10-20 11:56:00 +01006093 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006094 int lStatus;
6095 sp<ThreadBase> thread = mThread.promote();
6096 if (thread == 0) {
6097 return;
6098 }
Eric Laurent65b65452010-06-01 23:49:17 -07006099
6100 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6101
6102 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006103 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006104
Eric Laurent65b65452010-06-01 23:49:17 -07006105 if (mStatus != NO_ERROR) {
6106 return;
6107 }
6108 lStatus = init();
6109 if (lStatus < 0) {
6110 mStatus = lStatus;
6111 goto Error;
6112 }
6113
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006114 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6115 mPinned = true;
6116 }
Steve Block71f2cf12011-10-20 11:56:00 +01006117 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006118 return;
6119Error:
6120 EffectRelease(mEffectInterface);
6121 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006122 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006123}
6124
6125AudioFlinger::EffectModule::~EffectModule()
6126{
Steve Block71f2cf12011-10-20 11:56:00 +01006127 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006128 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006129 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6130 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6131 sp<ThreadBase> thread = mThread.promote();
6132 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006133 audio_stream_t *stream = thread->stream();
6134 if (stream != NULL) {
6135 stream->remove_audio_effect(stream, mEffectInterface);
6136 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006137 }
6138 }
Eric Laurent65b65452010-06-01 23:49:17 -07006139 // release effect engine
6140 EffectRelease(mEffectInterface);
6141 }
6142}
6143
6144status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6145{
6146 status_t status;
6147
6148 Mutex::Autolock _l(mLock);
6149 // First handle in mHandles has highest priority and controls the effect module
6150 int priority = handle->priority();
6151 size_t size = mHandles.size();
6152 sp<EffectHandle> h;
6153 size_t i;
6154 for (i = 0; i < size; i++) {
6155 h = mHandles[i].promote();
6156 if (h == 0) continue;
6157 if (h->priority() <= priority) break;
6158 }
6159 // if inserted in first place, move effect control from previous owner to this handle
6160 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006161 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006162 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006163 enabled = h->enabled();
6164 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006165 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006166 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006167 status = NO_ERROR;
6168 } else {
6169 status = ALREADY_EXISTS;
6170 }
Steve Block71f2cf12011-10-20 11:56:00 +01006171 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006172 mHandles.insertAt(handle, i);
6173 return status;
6174}
6175
6176size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6177{
6178 Mutex::Autolock _l(mLock);
6179 size_t size = mHandles.size();
6180 size_t i;
6181 for (i = 0; i < size; i++) {
6182 if (mHandles[i] == handle) break;
6183 }
6184 if (i == size) {
6185 return size;
6186 }
Steve Block71f2cf12011-10-20 11:56:00 +01006187 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006188
6189 bool enabled = false;
6190 EffectHandle *hdl = handle.unsafe_get();
6191 if (hdl) {
Steve Block71f2cf12011-10-20 11:56:00 +01006192 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006193 enabled = hdl->enabled();
6194 }
Eric Laurent65b65452010-06-01 23:49:17 -07006195 mHandles.removeAt(i);
6196 size = mHandles.size();
6197 // if removed from first place, move effect control from this handle to next in line
6198 if (i == 0 && size != 0) {
6199 sp<EffectHandle> h = mHandles[0].promote();
6200 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006201 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006202 }
6203 }
6204
Eric Laurent21b5c472011-07-26 20:54:46 -07006205 // Prevent calls to process() and other functions on effect interface from now on.
6206 // The effect engine will be released by the destructor when the last strong reference on
6207 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006208 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006209 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006210 }
6211
Eric Laurent65b65452010-06-01 23:49:17 -07006212 return size;
6213}
6214
Eric Laurentf82fccd2011-07-27 19:49:51 -07006215sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6216{
6217 Mutex::Autolock _l(mLock);
6218 sp<EffectHandle> handle;
6219 if (mHandles.size() != 0) {
6220 handle = mHandles[0].promote();
6221 }
6222 return handle;
6223}
6224
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006225void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006226{
Steve Block71f2cf12011-10-20 11:56:00 +01006227 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006228 // keep a strong reference on this EffectModule to avoid calling the
6229 // destructor before we exit
6230 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006231 {
6232 sp<ThreadBase> thread = mThread.promote();
6233 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006234 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006235 }
6236 }
6237}
6238
Eric Laurent7d850f22010-07-09 13:34:17 -07006239void AudioFlinger::EffectModule::updateState() {
6240 Mutex::Autolock _l(mLock);
6241
6242 switch (mState) {
6243 case RESTART:
6244 reset_l();
6245 // FALL THROUGH
6246
6247 case STARTING:
6248 // clear auxiliary effect input buffer for next accumulation
6249 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6250 memset(mConfig.inputCfg.buffer.raw,
6251 0,
6252 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6253 }
6254 start_l();
6255 mState = ACTIVE;
6256 break;
6257 case STOPPING:
6258 stop_l();
6259 mDisableWaitCnt = mMaxDisableWaitCnt;
6260 mState = STOPPED;
6261 break;
6262 case STOPPED:
6263 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6264 // turn off sequence.
6265 if (--mDisableWaitCnt == 0) {
6266 reset_l();
6267 mState = IDLE;
6268 }
6269 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006270 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006271 break;
6272 }
6273}
6274
Eric Laurent65b65452010-06-01 23:49:17 -07006275void AudioFlinger::EffectModule::process()
6276{
6277 Mutex::Autolock _l(mLock);
6278
Eric Laurent21b5c472011-07-26 20:54:46 -07006279 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006280 mConfig.inputCfg.buffer.raw == NULL ||
6281 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006282 return;
6283 }
6284
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006285 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006286 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6287 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten490909d2011-12-15 09:52:39 -08006288 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Eric Laurent65b65452010-06-01 23:49:17 -07006289 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006290 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006291 }
6292
Eric Laurent65b65452010-06-01 23:49:17 -07006293 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006294 int ret = (*mEffectInterface)->process(mEffectInterface,
6295 &mConfig.inputCfg.buffer,
6296 &mConfig.outputCfg.buffer);
6297
6298 // force transition to IDLE state when engine is ready
6299 if (mState == STOPPED && ret == -ENODATA) {
6300 mDisableWaitCnt = 1;
6301 }
Eric Laurent65b65452010-06-01 23:49:17 -07006302
6303 // clear auxiliary effect input buffer for next accumulation
6304 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006305 memset(mConfig.inputCfg.buffer.raw, 0,
6306 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006307 }
6308 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006309 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6310 // If an insert effect is idle and input buffer is different from output buffer,
6311 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006312 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006313 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006314 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6315 int16_t *in = mConfig.inputCfg.buffer.s16;
6316 int16_t *out = mConfig.outputCfg.buffer.s16;
6317 for (size_t i = 0; i < frameCnt; i++) {
6318 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006319 }
Eric Laurent65b65452010-06-01 23:49:17 -07006320 }
6321 }
6322}
6323
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006324void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006325{
6326 if (mEffectInterface == NULL) {
6327 return;
6328 }
6329 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6330}
6331
6332status_t AudioFlinger::EffectModule::configure()
6333{
6334 uint32_t channels;
6335 if (mEffectInterface == NULL) {
6336 return NO_INIT;
6337 }
6338
6339 sp<ThreadBase> thread = mThread.promote();
6340 if (thread == 0) {
6341 return DEAD_OBJECT;
6342 }
6343
6344 // TODO: handle configuration of effects replacing track process
6345 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006346 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006347 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006348 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006349 }
6350
6351 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006352 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006353 } else {
6354 mConfig.inputCfg.channels = channels;
6355 }
6356 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006357 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6358 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006359 mConfig.inputCfg.samplingRate = thread->sampleRate();
6360 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6361 mConfig.inputCfg.bufferProvider.cookie = NULL;
6362 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6363 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6364 mConfig.outputCfg.bufferProvider.cookie = NULL;
6365 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6366 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6367 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6368 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006369 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006370 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006371 // - in other sessions:
6372 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6373 // other effect: overwrites output buffer: input buffer == output buffer
6374 // Auxiliary effect:
6375 // accumulates in output buffer: input buffer != output buffer
6376 // Therefore: accumulate <=> input buffer != output buffer
6377 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6378 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6379 } else {
6380 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6381 }
6382 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6383 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6384 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6385 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6386
Steve Block71f2cf12011-10-20 11:56:00 +01006387 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006388 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6389
Eric Laurent65b65452010-06-01 23:49:17 -07006390 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006391 uint32_t size = sizeof(int);
6392 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent4abf8822011-12-16 15:30:36 -08006393 EFFECT_CMD_SET_CONFIG,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006394 sizeof(effect_config_t),
6395 &mConfig,
6396 &size,
6397 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006398 if (status == 0) {
6399 status = cmdStatus;
6400 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006401
6402 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6403 (1000 * mConfig.outputCfg.buffer.frameCount);
6404
Eric Laurent65b65452010-06-01 23:49:17 -07006405 return status;
6406}
6407
6408status_t AudioFlinger::EffectModule::init()
6409{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006410 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006411 if (mEffectInterface == NULL) {
6412 return NO_INIT;
6413 }
6414 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006415 uint32_t size = sizeof(status_t);
6416 status_t status = (*mEffectInterface)->command(mEffectInterface,
6417 EFFECT_CMD_INIT,
6418 0,
6419 NULL,
6420 &size,
6421 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006422 if (status == 0) {
6423 status = cmdStatus;
6424 }
6425 return status;
6426}
6427
Eric Laurent6fccbd02011-10-05 17:42:25 -07006428status_t AudioFlinger::EffectModule::start()
6429{
6430 Mutex::Autolock _l(mLock);
6431 return start_l();
6432}
6433
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006434status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006435{
6436 if (mEffectInterface == NULL) {
6437 return NO_INIT;
6438 }
6439 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006440 uint32_t size = sizeof(status_t);
6441 status_t status = (*mEffectInterface)->command(mEffectInterface,
6442 EFFECT_CMD_ENABLE,
6443 0,
6444 NULL,
6445 &size,
6446 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006447 if (status == 0) {
6448 status = cmdStatus;
6449 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006450 if (status == 0 &&
6451 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6452 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6453 sp<ThreadBase> thread = mThread.promote();
6454 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006455 audio_stream_t *stream = thread->stream();
6456 if (stream != NULL) {
6457 stream->add_audio_effect(stream, mEffectInterface);
6458 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006459 }
6460 }
Eric Laurent65b65452010-06-01 23:49:17 -07006461 return status;
6462}
6463
Eric Laurent21b5c472011-07-26 20:54:46 -07006464status_t AudioFlinger::EffectModule::stop()
6465{
6466 Mutex::Autolock _l(mLock);
6467 return stop_l();
6468}
6469
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006470status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006471{
6472 if (mEffectInterface == NULL) {
6473 return NO_INIT;
6474 }
6475 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006476 uint32_t size = sizeof(status_t);
6477 status_t status = (*mEffectInterface)->command(mEffectInterface,
6478 EFFECT_CMD_DISABLE,
6479 0,
6480 NULL,
6481 &size,
6482 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006483 if (status == 0) {
6484 status = cmdStatus;
6485 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006486 if (status == 0 &&
6487 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6488 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6489 sp<ThreadBase> thread = mThread.promote();
6490 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006491 audio_stream_t *stream = thread->stream();
6492 if (stream != NULL) {
6493 stream->remove_audio_effect(stream, mEffectInterface);
6494 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006495 }
6496 }
Eric Laurent65b65452010-06-01 23:49:17 -07006497 return status;
6498}
6499
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006500status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6501 uint32_t cmdSize,
6502 void *pCmdData,
6503 uint32_t *replySize,
6504 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006505{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006506 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006507// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006508
Eric Laurent21b5c472011-07-26 20:54:46 -07006509 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006510 return NO_INIT;
6511 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006512 status_t status = (*mEffectInterface)->command(mEffectInterface,
6513 cmdCode,
6514 cmdSize,
6515 pCmdData,
6516 replySize,
6517 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006518 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006519 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006520 for (size_t i = 1; i < mHandles.size(); i++) {
6521 sp<EffectHandle> h = mHandles[i].promote();
6522 if (h != 0) {
6523 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6524 }
6525 }
6526 }
6527 return status;
6528}
6529
6530status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6531{
Eric Laurent6752ec82011-08-10 10:37:50 -07006532
Eric Laurent65b65452010-06-01 23:49:17 -07006533 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006534 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006535
6536 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006537 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6538 if (enabled && status != NO_ERROR) {
6539 return status;
6540 }
6541
Eric Laurent65b65452010-06-01 23:49:17 -07006542 switch (mState) {
6543 // going from disabled to enabled
6544 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006545 mState = STARTING;
6546 break;
6547 case STOPPED:
6548 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006549 break;
6550 case STOPPING:
6551 mState = ACTIVE;
6552 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006553
6554 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006555 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006556 mState = STOPPED;
6557 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006558 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006559 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006560 break;
6561 case ACTIVE:
6562 mState = STOPPING;
6563 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006564 case DESTROYED:
6565 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006566 }
6567 for (size_t i = 1; i < mHandles.size(); i++) {
6568 sp<EffectHandle> h = mHandles[i].promote();
6569 if (h != 0) {
6570 h->setEnabled(enabled);
6571 }
6572 }
6573 }
6574 return NO_ERROR;
6575}
6576
6577bool AudioFlinger::EffectModule::isEnabled()
6578{
6579 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006580 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006581 case STARTING:
6582 case ACTIVE:
6583 return true;
6584 case IDLE:
6585 case STOPPING:
6586 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006587 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006588 default:
6589 return false;
6590 }
6591}
6592
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006593bool AudioFlinger::EffectModule::isProcessEnabled()
6594{
6595 switch (mState) {
6596 case RESTART:
6597 case ACTIVE:
6598 case STOPPING:
6599 case STOPPED:
6600 return true;
6601 case IDLE:
6602 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006603 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006604 default:
6605 return false;
6606 }
6607}
6608
Eric Laurent65b65452010-06-01 23:49:17 -07006609status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6610{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006611 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006612 status_t status = NO_ERROR;
6613
6614 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6615 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006616 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006617 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6618 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006619 status_t cmdStatus;
6620 uint32_t volume[2];
6621 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006622 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006623 volume[0] = *left;
6624 volume[1] = *right;
6625 if (controller) {
6626 pVolume = volume;
6627 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006628 status = (*mEffectInterface)->command(mEffectInterface,
6629 EFFECT_CMD_SET_VOLUME,
6630 size,
6631 volume,
6632 &size,
6633 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006634 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6635 *left = volume[0];
6636 *right = volume[1];
6637 }
6638 }
6639 return status;
6640}
6641
6642status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6643{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006644 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006645 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006646 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6647 // audio pre processing modules on RecordThread can receive both output and
6648 // input device indication in the same call
6649 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6650 if (dev) {
6651 status_t cmdStatus;
6652 uint32_t size = sizeof(status_t);
6653
6654 status = (*mEffectInterface)->command(mEffectInterface,
6655 EFFECT_CMD_SET_DEVICE,
6656 sizeof(uint32_t),
6657 &dev,
6658 &size,
6659 &cmdStatus);
6660 if (status == NO_ERROR) {
6661 status = cmdStatus;
6662 }
6663 }
6664 dev = device & AUDIO_DEVICE_IN_ALL;
6665 if (dev) {
6666 status_t cmdStatus;
6667 uint32_t size = sizeof(status_t);
6668
6669 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6670 EFFECT_CMD_SET_INPUT_DEVICE,
6671 sizeof(uint32_t),
6672 &dev,
6673 &size,
6674 &cmdStatus);
6675 if (status2 == NO_ERROR) {
6676 status2 = cmdStatus;
6677 }
6678 if (status == NO_ERROR) {
6679 status = status2;
6680 }
Eric Laurent65b65452010-06-01 23:49:17 -07006681 }
6682 }
6683 return status;
6684}
6685
Eric Laurent53334cd2010-06-23 17:38:20 -07006686status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6687{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006688 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006689 status_t status = NO_ERROR;
6690 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006691 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006692 uint32_t size = sizeof(status_t);
6693 status = (*mEffectInterface)->command(mEffectInterface,
6694 EFFECT_CMD_SET_AUDIO_MODE,
6695 sizeof(int),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006696 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006697 &size,
6698 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006699 if (status == NO_ERROR) {
6700 status = cmdStatus;
6701 }
6702 }
6703 return status;
6704}
6705
Eric Laurentf82fccd2011-07-27 19:49:51 -07006706void AudioFlinger::EffectModule::setSuspended(bool suspended)
6707{
6708 Mutex::Autolock _l(mLock);
6709 mSuspended = suspended;
6710}
Glenn Kasten1dce8412012-01-04 11:01:11 -08006711
6712bool AudioFlinger::EffectModule::suspended() const
Eric Laurentf82fccd2011-07-27 19:49:51 -07006713{
6714 Mutex::Autolock _l(mLock);
6715 return mSuspended;
6716}
6717
Eric Laurent65b65452010-06-01 23:49:17 -07006718status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6719{
6720 const size_t SIZE = 256;
6721 char buffer[SIZE];
6722 String8 result;
6723
6724 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6725 result.append(buffer);
6726
6727 bool locked = tryLock(mLock);
6728 // failed to lock - AudioFlinger is probably deadlocked
6729 if (!locked) {
6730 result.append("\t\tCould not lock Fx mutex:\n");
6731 }
6732
6733 result.append("\t\tSession Status State Engine:\n");
6734 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6735 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6736 result.append(buffer);
6737
6738 result.append("\t\tDescriptor:\n");
6739 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6740 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6741 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6742 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6743 result.append(buffer);
6744 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6745 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6746 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6747 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6748 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006749 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006750 mDescriptor.apiVersion,
6751 mDescriptor.flags);
6752 result.append(buffer);
6753 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6754 mDescriptor.name);
6755 result.append(buffer);
6756 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6757 mDescriptor.implementor);
6758 result.append(buffer);
6759
6760 result.append("\t\t- Input configuration:\n");
6761 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6762 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6763 (uint32_t)mConfig.inputCfg.buffer.raw,
6764 mConfig.inputCfg.buffer.frameCount,
6765 mConfig.inputCfg.samplingRate,
6766 mConfig.inputCfg.channels,
6767 mConfig.inputCfg.format);
6768 result.append(buffer);
6769
6770 result.append("\t\t- Output configuration:\n");
6771 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6772 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6773 (uint32_t)mConfig.outputCfg.buffer.raw,
6774 mConfig.outputCfg.buffer.frameCount,
6775 mConfig.outputCfg.samplingRate,
6776 mConfig.outputCfg.channels,
6777 mConfig.outputCfg.format);
6778 result.append(buffer);
6779
6780 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6781 result.append(buffer);
6782 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6783 for (size_t i = 0; i < mHandles.size(); ++i) {
6784 sp<EffectHandle> handle = mHandles[i].promote();
6785 if (handle != 0) {
6786 handle->dump(buffer, SIZE);
6787 result.append(buffer);
6788 }
6789 }
6790
6791 result.append("\n");
6792
6793 write(fd, result.string(), result.length());
6794
6795 if (locked) {
6796 mLock.unlock();
6797 }
6798
6799 return NO_ERROR;
6800}
6801
6802// ----------------------------------------------------------------------------
6803// EffectHandle implementation
6804// ----------------------------------------------------------------------------
6805
6806#undef LOG_TAG
6807#define LOG_TAG "AudioFlinger::EffectHandle"
6808
6809AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6810 const sp<AudioFlinger::Client>& client,
6811 const sp<IEffectClient>& effectClient,
6812 int32_t priority)
6813 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006814 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006815 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006816{
Steve Block71f2cf12011-10-20 11:56:00 +01006817 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006818
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006819 if (client == 0) {
6820 return;
6821 }
Eric Laurent65b65452010-06-01 23:49:17 -07006822 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6823 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6824 if (mCblkMemory != 0) {
6825 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6826
6827 if (mCblk) {
6828 new(mCblk) effect_param_cblk_t();
6829 mBuffer = (uint8_t *)mCblk + bufOffset;
6830 }
6831 } else {
Steve Block3762c312012-01-06 19:20:56 +00006832 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006833 return;
6834 }
6835}
6836
6837AudioFlinger::EffectHandle::~EffectHandle()
6838{
Steve Block71f2cf12011-10-20 11:56:00 +01006839 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006840 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01006841 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006842}
6843
6844status_t AudioFlinger::EffectHandle::enable()
6845{
Steve Block71f2cf12011-10-20 11:56:00 +01006846 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006847 if (!mHasControl) return INVALID_OPERATION;
6848 if (mEffect == 0) return DEAD_OBJECT;
6849
Eric Laurent6752ec82011-08-10 10:37:50 -07006850 if (mEnabled) {
6851 return NO_ERROR;
6852 }
6853
Eric Laurentf82fccd2011-07-27 19:49:51 -07006854 mEnabled = true;
6855
6856 sp<ThreadBase> thread = mEffect->thread().promote();
6857 if (thread != 0) {
6858 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6859 }
6860
6861 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6862 if (mEffect->suspended()) {
6863 return NO_ERROR;
6864 }
6865
Eric Laurent6752ec82011-08-10 10:37:50 -07006866 status_t status = mEffect->setEnabled(true);
6867 if (status != NO_ERROR) {
6868 if (thread != 0) {
6869 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6870 }
6871 mEnabled = false;
6872 }
6873 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006874}
6875
6876status_t AudioFlinger::EffectHandle::disable()
6877{
Steve Block71f2cf12011-10-20 11:56:00 +01006878 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006879 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006880 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006881
Eric Laurent6752ec82011-08-10 10:37:50 -07006882 if (!mEnabled) {
6883 return NO_ERROR;
6884 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006885 mEnabled = false;
6886
6887 if (mEffect->suspended()) {
6888 return NO_ERROR;
6889 }
6890
6891 status_t status = mEffect->setEnabled(false);
6892
6893 sp<ThreadBase> thread = mEffect->thread().promote();
6894 if (thread != 0) {
6895 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6896 }
6897
6898 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006899}
6900
6901void AudioFlinger::EffectHandle::disconnect()
6902{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006903 disconnect(true);
6904}
6905
6906void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6907{
Steve Block71f2cf12011-10-20 11:56:00 +01006908 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006909 if (mEffect == 0) {
6910 return;
6911 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006912 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006913
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006914 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006915 sp<ThreadBase> thread = mEffect->thread().promote();
6916 if (thread != 0) {
6917 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6918 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006919 }
6920
Eric Laurent65b65452010-06-01 23:49:17 -07006921 // release sp on module => module destructor can be called now
6922 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006923 if (mClient != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006924 if (mCblk) {
6925 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6926 }
6927 mCblkMemory.clear(); // and free the shared memory
Eric Laurent65b65452010-06-01 23:49:17 -07006928 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6929 mClient.clear();
6930 }
6931}
6932
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006933status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6934 uint32_t cmdSize,
6935 void *pCmdData,
6936 uint32_t *replySize,
6937 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006938{
Steve Block71f2cf12011-10-20 11:56:00 +01006939// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006940// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006941
6942 // only get parameter command is permitted for applications not controlling the effect
6943 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6944 return INVALID_OPERATION;
6945 }
6946 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006947 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006948
6949 // handle commands that are not forwarded transparently to effect engine
6950 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6951 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6952 // no risk to block the whole media server process or mixer threads is we are stuck here
6953 Mutex::Autolock _l(mCblk->lock);
6954 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6955 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6956 mCblk->serverIndex = 0;
6957 mCblk->clientIndex = 0;
6958 return BAD_VALUE;
6959 }
6960 status_t status = NO_ERROR;
6961 while (mCblk->serverIndex < mCblk->clientIndex) {
6962 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006963 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006964 int *p = (int *)(mBuffer + mCblk->serverIndex);
6965 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006966 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block8564c8d2012-01-05 23:22:43 +00006967 ALOGW("command(): invalid parameter block size");
Eric Laurent53334cd2010-06-23 17:38:20 -07006968 break;
6969 }
Eric Laurent65b65452010-06-01 23:49:17 -07006970 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006971 if (param->psize == 0 || param->vsize == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00006972 ALOGW("command(): null parameter or value size");
Eric Laurent53334cd2010-06-23 17:38:20 -07006973 mCblk->serverIndex += size;
6974 continue;
6975 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006976 uint32_t psize = sizeof(effect_param_t) +
6977 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6978 param->vsize;
6979 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6980 psize,
6981 p,
6982 &rsize,
6983 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006984 // stop at first error encountered
6985 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006986 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006987 *(int *)pReplyData = reply;
6988 break;
6989 } else if (reply != NO_ERROR) {
6990 *(int *)pReplyData = reply;
6991 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006992 }
6993 mCblk->serverIndex += size;
6994 }
6995 mCblk->serverIndex = 0;
6996 mCblk->clientIndex = 0;
6997 return status;
6998 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006999 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007000 return enable();
7001 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07007002 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07007003 return disable();
7004 }
7005
7006 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7007}
7008
7009sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7010 return mCblkMemory;
7011}
7012
Eric Laurentf82fccd2011-07-27 19:49:51 -07007013void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07007014{
Steve Block71f2cf12011-10-20 11:56:00 +01007015 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07007016
7017 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007018 mEnabled = enabled;
7019
Eric Laurent65b65452010-06-01 23:49:17 -07007020 if (signal && mEffectClient != 0) {
7021 mEffectClient->controlStatusChanged(hasControl);
7022 }
7023}
7024
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007025void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7026 uint32_t cmdSize,
7027 void *pCmdData,
7028 uint32_t replySize,
7029 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007030{
7031 if (mEffectClient != 0) {
7032 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7033 }
7034}
7035
7036
7037
7038void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7039{
7040 if (mEffectClient != 0) {
7041 mEffectClient->enableStatusChanged(enabled);
7042 }
7043}
7044
7045status_t AudioFlinger::EffectHandle::onTransact(
7046 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7047{
7048 return BnEffect::onTransact(code, data, reply, flags);
7049}
7050
7051
7052void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7053{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007054 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Eric Laurent65b65452010-06-01 23:49:17 -07007055
7056 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7057 (mClient == NULL) ? getpid() : mClient->pid(),
7058 mPriority,
7059 mHasControl,
7060 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007061 mCblk ? mCblk->clientIndex : 0,
7062 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007063 );
7064
7065 if (locked) {
7066 mCblk->lock.unlock();
7067 }
7068}
7069
7070#undef LOG_TAG
7071#define LOG_TAG "AudioFlinger::EffectChain"
7072
7073AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7074 int sessionId)
Eric Laurentf9c361d2011-11-11 15:42:52 -08007075 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007076 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7077 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007078{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007079 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007080 sp<ThreadBase> thread = mThread.promote();
7081 if (thread == 0) {
7082 return;
7083 }
7084 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7085 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007086}
7087
7088AudioFlinger::EffectChain::~EffectChain()
7089{
7090 if (mOwnInBuffer) {
7091 delete mInBuffer;
7092 }
7093
7094}
7095
Eric Laurentf82fccd2011-07-27 19:49:51 -07007096// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007097sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007098{
7099 sp<EffectModule> effect;
7100 size_t size = mEffects.size();
7101
7102 for (size_t i = 0; i < size; i++) {
7103 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7104 effect = mEffects[i];
7105 break;
7106 }
7107 }
7108 return effect;
7109}
7110
Eric Laurentf82fccd2011-07-27 19:49:51 -07007111// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007112sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007113{
7114 sp<EffectModule> effect;
7115 size_t size = mEffects.size();
7116
7117 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007118 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7119 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07007120 effect = mEffects[i];
7121 break;
7122 }
7123 }
7124 return effect;
7125}
7126
Eric Laurentf82fccd2011-07-27 19:49:51 -07007127// getEffectFromType_l() must be called with ThreadBase::mLock held
7128sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7129 const effect_uuid_t *type)
7130{
7131 sp<EffectModule> effect;
7132 size_t size = mEffects.size();
7133
7134 for (size_t i = 0; i < size; i++) {
7135 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7136 effect = mEffects[i];
7137 break;
7138 }
7139 }
7140 return effect;
7141}
7142
Eric Laurent65b65452010-06-01 23:49:17 -07007143// Must be called with EffectChain::mLock locked
7144void AudioFlinger::EffectChain::process_l()
7145{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007146 sp<ThreadBase> thread = mThread.promote();
7147 if (thread == 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007148 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007149 return;
7150 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007151 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7152 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007153 // always process effects unless no more tracks are on the session and the effect tail
7154 // has been rendered
7155 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007156 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007157 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007158
Eric Laurentf9c361d2011-11-11 15:42:52 -08007159 if (!tracksOnSession && mTailBufferCount == 0) {
7160 doProcess = false;
7161 }
7162
7163 if (activeTrackCnt() == 0) {
7164 // if no track is active and the effect tail has not been rendered,
7165 // the input buffer must be cleared here as the mixer process will not do it
7166 if (tracksOnSession || mTailBufferCount > 0) {
7167 size_t numSamples = thread->frameCount() * thread->channelCount();
7168 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7169 if (mTailBufferCount > 0) {
7170 mTailBufferCount--;
7171 }
7172 }
7173 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007174 }
7175
Eric Laurent65b65452010-06-01 23:49:17 -07007176 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007177 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007178 for (size_t i = 0; i < size; i++) {
7179 mEffects[i]->process();
7180 }
Eric Laurent65b65452010-06-01 23:49:17 -07007181 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007182 for (size_t i = 0; i < size; i++) {
7183 mEffects[i]->updateState();
7184 }
Eric Laurent65b65452010-06-01 23:49:17 -07007185}
7186
Eric Laurent76c40f72010-07-15 12:50:15 -07007187// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007188status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007189{
7190 effect_descriptor_t desc = effect->desc();
7191 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7192
7193 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007194 effect->setChain(this);
7195 sp<ThreadBase> thread = mThread.promote();
7196 if (thread == 0) {
7197 return NO_INIT;
7198 }
7199 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007200
7201 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7202 // Auxiliary effects are inserted at the beginning of mEffects vector as
7203 // they are processed first and accumulated in chain input buffer
7204 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007205
Eric Laurent65b65452010-06-01 23:49:17 -07007206 // the input buffer for auxiliary effect contains mono samples in
7207 // 32 bit format. This is to avoid saturation in AudoMixer
7208 // accumulation stage. Saturation is done in EffectModule::process() before
7209 // calling the process in effect engine
7210 size_t numSamples = thread->frameCount();
7211 int32_t *buffer = new int32_t[numSamples];
7212 memset(buffer, 0, numSamples * sizeof(int32_t));
7213 effect->setInBuffer((int16_t *)buffer);
7214 // auxiliary effects output samples to chain input buffer for further processing
7215 // by insert effects
7216 effect->setOutBuffer(mInBuffer);
7217 } else {
7218 // Insert effects are inserted at the end of mEffects vector as they are processed
7219 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007220 // Insert effect order as a function of indicated preference:
7221 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7222 // another effect is present
7223 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7224 // last effect claiming first position
7225 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7226 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007227 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007228 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7229 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007230
7231 int size = (int)mEffects.size();
7232 int idx_insert = size;
7233 int idx_insert_first = -1;
7234 int idx_insert_last = -1;
7235
7236 for (int i = 0; i < size; i++) {
7237 effect_descriptor_t d = mEffects[i]->desc();
7238 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7239 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7240 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7241 // check invalid effect chaining combinations
7242 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007243 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block8564c8d2012-01-05 23:22:43 +00007244 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007245 return INVALID_OPERATION;
7246 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007247 // remember position of first insert effect and by default
7248 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007249 if (idx_insert == size) {
7250 idx_insert = i;
7251 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007252 // remember position of last insert effect claiming
7253 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007254 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7255 idx_insert_first = i;
7256 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007257 // remember position of first insert effect claiming
7258 // last position
7259 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7260 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007261 idx_insert_last = i;
7262 }
7263 }
7264 }
7265
Eric Laurent53334cd2010-06-23 17:38:20 -07007266 // modify idx_insert from first position if needed
7267 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7268 if (idx_insert_last != -1) {
7269 idx_insert = idx_insert_last;
7270 } else {
7271 idx_insert = size;
7272 }
7273 } else {
7274 if (idx_insert_first != -1) {
7275 idx_insert = idx_insert_first + 1;
7276 }
Eric Laurent65b65452010-06-01 23:49:17 -07007277 }
7278
7279 // always read samples from chain input buffer
7280 effect->setInBuffer(mInBuffer);
7281
7282 // if last effect in the chain, output samples to chain
7283 // output buffer, otherwise to chain input buffer
7284 if (idx_insert == size) {
7285 if (idx_insert != 0) {
7286 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7287 mEffects[idx_insert-1]->configure();
7288 }
7289 effect->setOutBuffer(mOutBuffer);
7290 } else {
7291 effect->setOutBuffer(mInBuffer);
7292 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007293 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007294
Steve Block71f2cf12011-10-20 11:56:00 +01007295 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007296 }
7297 effect->configure();
7298 return NO_ERROR;
7299}
7300
Eric Laurent76c40f72010-07-15 12:50:15 -07007301// removeEffect_l() must be called with PlaybackThread::mLock held
7302size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007303{
7304 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007305 int size = (int)mEffects.size();
7306 int i;
7307 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7308
7309 for (i = 0; i < size; i++) {
7310 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007311 // calling stop here will remove pre-processing effect from the audio HAL.
7312 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7313 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007314 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7315 mEffects[i]->state() == EffectModule::STOPPING) {
7316 mEffects[i]->stop();
7317 }
Eric Laurent65b65452010-06-01 23:49:17 -07007318 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7319 delete[] effect->inBuffer();
7320 } else {
7321 if (i == size - 1 && i != 0) {
7322 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7323 mEffects[i - 1]->configure();
7324 }
7325 }
7326 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007327 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007328 break;
7329 }
7330 }
Eric Laurent65b65452010-06-01 23:49:17 -07007331
7332 return mEffects.size();
7333}
7334
Eric Laurent76c40f72010-07-15 12:50:15 -07007335// setDevice_l() must be called with PlaybackThread::mLock held
7336void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007337{
7338 size_t size = mEffects.size();
7339 for (size_t i = 0; i < size; i++) {
7340 mEffects[i]->setDevice(device);
7341 }
7342}
7343
Eric Laurent76c40f72010-07-15 12:50:15 -07007344// setMode_l() must be called with PlaybackThread::mLock held
7345void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007346{
7347 size_t size = mEffects.size();
7348 for (size_t i = 0; i < size; i++) {
7349 mEffects[i]->setMode(mode);
7350 }
7351}
7352
Eric Laurent76c40f72010-07-15 12:50:15 -07007353// setVolume_l() must be called with PlaybackThread::mLock held
7354bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007355{
7356 uint32_t newLeft = *left;
7357 uint32_t newRight = *right;
7358 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007359 int ctrlIdx = -1;
7360 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007361
Eric Laurent76c40f72010-07-15 12:50:15 -07007362 // first update volume controller
7363 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007364 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007365 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7366 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007367 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007368 break;
7369 }
7370 }
7371
7372 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007373 if (hasControl) {
7374 *left = mNewLeftVolume;
7375 *right = mNewRightVolume;
7376 }
7377 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007378 }
7379
7380 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007381 mLeftVolume = newLeft;
7382 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007383
7384 // second get volume update from volume controller
7385 if (ctrlIdx >= 0) {
7386 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007387 mNewLeftVolume = newLeft;
7388 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007389 }
7390 // then indicate volume to all other effects in chain.
7391 // Pass altered volume to effects before volume controller
7392 // and requested volume to effects after controller
7393 uint32_t lVol = newLeft;
7394 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007395
Eric Laurent65b65452010-06-01 23:49:17 -07007396 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007397 if ((int)i == ctrlIdx) continue;
7398 // this also works for ctrlIdx == -1 when there is no volume controller
7399 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007400 lVol = *left;
7401 rVol = *right;
7402 }
7403 mEffects[i]->setVolume(&lVol, &rVol, false);
7404 }
7405 *left = newLeft;
7406 *right = newRight;
7407
7408 return hasControl;
7409}
7410
Eric Laurent65b65452010-06-01 23:49:17 -07007411status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7412{
7413 const size_t SIZE = 256;
7414 char buffer[SIZE];
7415 String8 result;
7416
7417 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7418 result.append(buffer);
7419
7420 bool locked = tryLock(mLock);
7421 // failed to lock - AudioFlinger is probably deadlocked
7422 if (!locked) {
7423 result.append("\tCould not lock mutex:\n");
7424 }
7425
Eric Laurent76c40f72010-07-15 12:50:15 -07007426 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7427 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007428 mEffects.size(),
7429 (uint32_t)mInBuffer,
7430 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007431 mActiveTrackCnt);
7432 result.append(buffer);
7433 write(fd, result.string(), result.size());
7434
7435 for (size_t i = 0; i < mEffects.size(); ++i) {
7436 sp<EffectModule> effect = mEffects[i];
7437 if (effect != 0) {
7438 effect->dump(fd, args);
7439 }
7440 }
7441
7442 if (locked) {
7443 mLock.unlock();
7444 }
7445
7446 return NO_ERROR;
7447}
7448
Eric Laurentf82fccd2011-07-27 19:49:51 -07007449// must be called with ThreadBase::mLock held
7450void AudioFlinger::EffectChain::setEffectSuspended_l(
7451 const effect_uuid_t *type, bool suspend)
7452{
7453 sp<SuspendedEffectDesc> desc;
7454 // use effect type UUID timelow as key as there is no real risk of identical
7455 // timeLow fields among effect type UUIDs.
7456 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7457 if (suspend) {
7458 if (index >= 0) {
7459 desc = mSuspendedEffects.valueAt(index);
7460 } else {
7461 desc = new SuspendedEffectDesc();
7462 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7463 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007464 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007465 }
7466 if (desc->mRefCount++ == 0) {
7467 sp<EffectModule> effect = getEffectIfEnabled(type);
7468 if (effect != 0) {
7469 desc->mEffect = effect;
7470 effect->setSuspended(true);
7471 effect->setEnabled(false);
7472 }
7473 }
7474 } else {
7475 if (index < 0) {
7476 return;
7477 }
7478 desc = mSuspendedEffects.valueAt(index);
7479 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007480 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007481 desc->mRefCount = 1;
7482 }
7483 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007484 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007485 if (desc->mEffect != 0) {
7486 sp<EffectModule> effect = desc->mEffect.promote();
7487 if (effect != 0) {
7488 effect->setSuspended(false);
7489 sp<EffectHandle> handle = effect->controlHandle();
7490 if (handle != 0) {
7491 effect->setEnabled(handle->enabled());
7492 }
7493 }
7494 desc->mEffect.clear();
7495 }
7496 mSuspendedEffects.removeItemsAt(index);
7497 }
7498 }
7499}
7500
7501// must be called with ThreadBase::mLock held
7502void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7503{
7504 sp<SuspendedEffectDesc> desc;
7505
7506 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7507 if (suspend) {
7508 if (index >= 0) {
7509 desc = mSuspendedEffects.valueAt(index);
7510 } else {
7511 desc = new SuspendedEffectDesc();
7512 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007513 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007514 }
7515 if (desc->mRefCount++ == 0) {
7516 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7517 for (size_t i = 0; i < effects.size(); i++) {
7518 setEffectSuspended_l(&effects[i]->desc().type, true);
7519 }
7520 }
7521 } else {
7522 if (index < 0) {
7523 return;
7524 }
7525 desc = mSuspendedEffects.valueAt(index);
7526 if (desc->mRefCount <= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007527 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007528 desc->mRefCount = 1;
7529 }
7530 if (--desc->mRefCount == 0) {
7531 Vector<const effect_uuid_t *> types;
7532 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7533 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7534 continue;
7535 }
7536 types.add(&mSuspendedEffects.valueAt(i)->mType);
7537 }
7538 for (size_t i = 0; i < types.size(); i++) {
7539 setEffectSuspended_l(types[i], false);
7540 }
Steve Block71f2cf12011-10-20 11:56:00 +01007541 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007542 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7543 }
7544 }
7545}
7546
Eric Laurent5e7acae2011-09-23 08:40:41 -07007547
7548// The volume effect is used for automated tests only
7549#ifndef OPENSL_ES_H_
7550static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7551 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7552const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7553#endif //OPENSL_ES_H_
7554
Eric Laurent6752ec82011-08-10 10:37:50 -07007555bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7556{
7557 // auxiliary effects and visualizer are never suspended on output mix
7558 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7559 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007560 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7561 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007562 return false;
7563 }
7564 return true;
7565}
7566
Eric Laurentf82fccd2011-07-27 19:49:51 -07007567Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7568{
7569 Vector< sp<EffectModule> > effects;
7570 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007571 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07007572 continue;
7573 }
7574 effects.add(mEffects[i]);
7575 }
7576 return effects;
7577}
7578
7579sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7580 const effect_uuid_t *type)
7581{
7582 sp<EffectModule> effect;
7583 effect = getEffectFromType_l(type);
7584 if (effect != 0 && !effect->isEnabled()) {
7585 effect.clear();
7586 }
7587 return effect;
7588}
7589
7590void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7591 bool enabled)
7592{
7593 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7594 if (enabled) {
7595 if (index < 0) {
7596 // if the effect is not suspend check if all effects are suspended
7597 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7598 if (index < 0) {
7599 return;
7600 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007601 if (!isEffectEligibleForSuspend(effect->desc())) {
7602 return;
7603 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007604 setEffectSuspended_l(&effect->desc().type, enabled);
7605 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007606 if (index < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00007607 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurent6752ec82011-08-10 10:37:50 -07007608 return;
7609 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007610 }
Steve Block71f2cf12011-10-20 11:56:00 +01007611 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007612 effect->desc().type.timeLow);
7613 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7614 // if effect is requested to suspended but was not yet enabled, supend it now.
7615 if (desc->mEffect == 0) {
7616 desc->mEffect = effect;
7617 effect->setEnabled(false);
7618 effect->setSuspended(true);
7619 }
7620 } else {
7621 if (index < 0) {
7622 return;
7623 }
Steve Block71f2cf12011-10-20 11:56:00 +01007624 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007625 effect->desc().type.timeLow);
7626 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7627 desc->mEffect.clear();
7628 effect->setSuspended(false);
7629 }
7630}
7631
Eric Laurent65b65452010-06-01 23:49:17 -07007632#undef LOG_TAG
7633#define LOG_TAG "AudioFlinger"
7634
Eric Laurenta553c252009-07-17 12:17:14 -07007635// ----------------------------------------------------------------------------
7636
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007637status_t AudioFlinger::onTransact(
7638 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7639{
7640 return BnAudioFlinger::onTransact(code, data, reply, flags);
7641}
7642
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007643}; // namespace android