blob: b22c3ea5c5d2e2a6702bb3058ac49696dbae0f91 [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>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070043
44#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070045#include <private/media/AudioEffectShared.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070046
Dima Zavin34bb4192011-05-11 14:15:23 -070047#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070048#include <hardware/audio.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070049
50#include "AudioMixer.h"
51#include "AudioFlinger.h"
52
Eric Laurent53334cd2010-06-23 17:38:20 -070053#include <media/EffectsFactoryApi.h>
Eric Laurent5cc05262011-06-24 07:01:31 -070054#include <audio_effects/effect_visualizer.h>
Eric Laurent6639b552011-08-01 09:52:20 -070055#include <audio_effects/effect_ns.h>
56#include <audio_effects/effect_aec.h>
Eric Laurent65b65452010-06-01 23:49:17 -070057
Glenn Kasten490909d2011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Glenn Kastenda494f92011-07-08 15:26:12 -070060#include <cpustats/ThreadCpuUsage.h>
Eric Laurent6dbdc402011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kastenda494f92011-07-08 15:26:12 -070062// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
63
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064// ----------------------------------------------------------------------------
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
Eric Laurent8ed6ed02010-07-13 04:45:46 -070066
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070067namespace android {
68
Glenn Kasten62de3db2011-12-12 09:04:45 -080069static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
70static const char kHardwareLockedString[] = "Hardware lock is taken\n";
The Android Open Source Project10592532009-03-18 17:39:46 -070071
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080072//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070073static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070074static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070075
76// retry counts for buffer fill timeout
77// 50 * ~20msecs = 1 second
78static const int8_t kMaxTrackRetries = 50;
79static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080080// allow less retry attempts on direct output thread.
81// direct outputs can be a scarce resource in audio hardware and should
82// be released as quickly as possible.
83static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070084
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070085static const int kDumpLockRetries = 50;
Glenn Kastencbfe2e12011-12-13 11:04:14 -080086static const int kDumpLockSleepUs = 20000;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070087
Glenn Kastencbfe2e12011-12-13 11:04:14 -080088// don't warn about blocked writes or record buffer overflows more often than this
89static const nsecs_t kWarningThrottleNs = seconds(5);
Dave Sparksd0ac8c02009-09-30 03:09:03 -070090
Eric Laurent464d5b32011-06-17 21:29:58 -070091// RecordThread loop sleep time upon application overrun or audio HAL read error
92static const int kRecordThreadSleepUs = 5000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
Glenn Kastencbfe2e12011-12-13 11:04:14 -080094// maximum time to wait for setParameters to complete
95static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent5f37be32011-09-13 11:40:21 -070096
Eric Laurentf1f5fc82011-11-22 18:50:29 -080097// minimum sleep time for the mixer thread loop when tracks are active but in underrun
98static const uint32_t kMinThreadSleepTimeUs = 5000;
99// maximum divider applied to the active sleep time in the mixer thread loop
100static const uint32_t kMaxThreadSleepTimeShift = 2;
101
102
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700103// ----------------------------------------------------------------------------
104
105static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700106 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
107 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
108 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
109 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700110}
111
112static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700113 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
114 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
115 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
116 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700117}
118
Gloria Wang9b3f1522011-02-24 14:51:45 -0800119// To collect the amplifier usage
120static void addBatteryData(uint32_t params) {
121 sp<IBinder> binder =
122 defaultServiceManager()->getService(String16("media.player"));
123 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
124 if (service.get() == NULL) {
125 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
126 return;
127 }
128
129 service->addBatteryData(params);
130}
131
Dima Zavin31f188892011-04-18 16:57:27 -0700132static int load_audio_interface(const char *if_name, const hw_module_t **mod,
133 audio_hw_device_t **dev)
134{
135 int rc;
136
137 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
138 if (rc)
139 goto out;
140
141 rc = audio_hw_device_open(*mod, dev);
142 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
143 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
144 if (rc)
145 goto out;
146
147 return 0;
148
149out:
150 *mod = NULL;
151 *dev = NULL;
152 return rc;
153}
154
Glenn Kasten62de3db2011-12-12 09:04:45 -0800155static const char * const audio_interfaces[] = {
Dima Zavin31f188892011-04-18 16:57:27 -0700156 "primary",
157 "a2dp",
158 "usb",
159};
160#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
161
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700162// ----------------------------------------------------------------------------
163
164AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 : BnAudioFlinger(),
Glenn Kastenc434c902011-12-13 11:53:26 -0800166 mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700167 mBtNrecIsOff(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700168{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700169}
170
171void AudioFlinger::onFirstRef()
172{
Dima Zavin31f188892011-04-18 16:57:27 -0700173 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700174
Eric Laurent01635942011-01-18 18:39:02 -0800175 Mutex::Autolock _l(mLock);
176
Dima Zavin31f188892011-04-18 16:57:27 -0700177 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700178 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700179
Dima Zavin31f188892011-04-18 16:57:27 -0700180 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
181 const hw_module_t *mod;
182 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700183
Dima Zavin31f188892011-04-18 16:57:27 -0700184 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
185 if (rc)
186 continue;
187
188 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
189 mod->name, mod->id);
190 mAudioHwDevs.push(dev);
191
192 if (!mPrimaryHardwareDev) {
193 mPrimaryHardwareDev = dev;
194 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700195 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700196 }
197 }
Eric Laurenta553c252009-07-17 12:17:14 -0700198
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700199 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700200
Dima Zavin31f188892011-04-18 16:57:27 -0700201 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
202 LOGE("Primary audio interface not found");
203 return;
204 }
205
206 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
207 audio_hw_device_t *dev = mAudioHwDevs[i];
208
209 mHardwareStatus = AUDIO_HW_INIT;
210 rc = dev->init_check(dev);
211 if (rc == 0) {
212 AutoMutex lock(mHardwareLock);
213
214 mMode = AUDIO_MODE_NORMAL;
215 mHardwareStatus = AUDIO_HW_SET_MODE;
216 dev->set_mode(dev, mMode);
217 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
218 dev->set_master_volume(dev, 1.0f);
219 mHardwareStatus = AUDIO_HW_IDLE;
220 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700221 }
222}
223
Dima Zavin2986f5b2011-04-19 19:04:32 -0700224status_t AudioFlinger::initCheck() const
225{
226 Mutex::Autolock _l(mLock);
227 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
228 return NO_INIT;
229 return NO_ERROR;
230}
231
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700232AudioFlinger::~AudioFlinger()
233{
Dima Zavin31f188892011-04-18 16:57:27 -0700234 int num_devs = mAudioHwDevs.size();
235
Eric Laurent7954c462009-08-28 10:39:03 -0700236 while (!mRecordThreads.isEmpty()) {
237 // closeInput() will remove first entry from mRecordThreads
238 closeInput(mRecordThreads.keyAt(0));
239 }
240 while (!mPlaybackThreads.isEmpty()) {
241 // closeOutput() will remove first entry from mPlaybackThreads
242 closeOutput(mPlaybackThreads.keyAt(0));
243 }
Dima Zavin31f188892011-04-18 16:57:27 -0700244
245 for (int i = 0; i < num_devs; i++) {
246 audio_hw_device_t *dev = mAudioHwDevs[i];
247 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700248 }
Dima Zavin31f188892011-04-18 16:57:27 -0700249 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800250}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800251
Dima Zavin31f188892011-04-18 16:57:27 -0700252audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
253{
254 /* first matching HW device is returned */
255 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
256 audio_hw_device_t *dev = mAudioHwDevs[i];
257 if ((dev->get_supported_devices(dev) & devices) == devices)
258 return dev;
259 }
260 return NULL;
261}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700262
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700263status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
264{
265 const size_t SIZE = 256;
266 char buffer[SIZE];
267 String8 result;
268
269 result.append("Clients:\n");
270 for (size_t i = 0; i < mClients.size(); ++i) {
271 wp<Client> wClient = mClients.valueAt(i);
272 if (wClient != 0) {
273 sp<Client> client = wClient.promote();
274 if (client != 0) {
275 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
276 result.append(buffer);
277 }
278 }
279 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700280
281 result.append("Global session refs:\n");
282 result.append(" session pid cnt\n");
283 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
284 AudioSessionRef *r = mAudioSessionRefs[i];
285 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
286 result.append(buffer);
287 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700288 write(fd, result.string(), result.size());
289 return NO_ERROR;
290}
291
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700292
293status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
294{
295 const size_t SIZE = 256;
296 char buffer[SIZE];
297 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700298 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700299
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700300 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700301 result.append(buffer);
302 write(fd, result.string(), result.size());
303 return NO_ERROR;
304}
305
306status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
307{
308 const size_t SIZE = 256;
309 char buffer[SIZE];
310 String8 result;
311 snprintf(buffer, SIZE, "Permission Denial: "
312 "can't dump AudioFlinger from pid=%d, uid=%d\n",
313 IPCThreadState::self()->getCallingPid(),
314 IPCThreadState::self()->getCallingUid());
315 result.append(buffer);
316 write(fd, result.string(), result.size());
317 return NO_ERROR;
318}
319
The Android Open Source Project10592532009-03-18 17:39:46 -0700320static bool tryLock(Mutex& mutex)
321{
322 bool locked = false;
323 for (int i = 0; i < kDumpLockRetries; ++i) {
324 if (mutex.tryLock() == NO_ERROR) {
325 locked = true;
326 break;
327 }
Glenn Kastencbfe2e12011-12-13 11:04:14 -0800328 usleep(kDumpLockSleepUs);
The Android Open Source Project10592532009-03-18 17:39:46 -0700329 }
330 return locked;
331}
332
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700333status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
334{
335 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
336 dumpPermissionDenial(fd, args);
337 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700338 // get state of hardware lock
339 bool hardwareLocked = tryLock(mHardwareLock);
340 if (!hardwareLocked) {
341 String8 result(kHardwareLockedString);
342 write(fd, result.string(), result.size());
343 } else {
344 mHardwareLock.unlock();
345 }
346
347 bool locked = tryLock(mLock);
348
349 // failed to lock - AudioFlinger is probably deadlocked
350 if (!locked) {
351 String8 result(kDeadlockedString);
352 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700353 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700354
355 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700356 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357
Eric Laurenta553c252009-07-17 12:17:14 -0700358 // dump playback threads
359 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700360 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700361 }
362
363 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700364 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700365 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367
Dima Zavin31f188892011-04-18 16:57:27 -0700368 // dump all hardware devs
369 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
370 audio_hw_device_t *dev = mAudioHwDevs[i];
371 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700372 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700373 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700374 }
375 return NO_ERROR;
376}
377
Eric Laurenta553c252009-07-17 12:17:14 -0700378
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700379// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380
381
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700382sp<IAudioTrack> AudioFlinger::createTrack(
383 pid_t pid,
384 int streamType,
385 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700386 uint32_t format,
387 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800388 int frameCount,
389 uint32_t flags,
390 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700391 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700392 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800393 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700394{
Eric Laurenta553c252009-07-17 12:17:14 -0700395 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700396 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700397 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800398 wp<Client> wclient;
399 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700400 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700401
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700402 if (streamType >= AUDIO_STREAM_CNT) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -0700403 LOGE("createTrack() invalid stream type %d", streamType);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800404 lStatus = BAD_VALUE;
405 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700406 }
407
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800408 {
409 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700410 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700411 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700412 if (thread == NULL) {
413 LOGE("unknown output thread");
414 lStatus = BAD_VALUE;
415 goto Exit;
416 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800417
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800418 wclient = mClients.valueFor(pid);
419
420 if (wclient != NULL) {
421 client = wclient.promote();
422 } else {
423 client = new Client(this, pid);
424 mClients.add(pid, client);
425 }
Eric Laurent65b65452010-06-01 23:49:17 -0700426
Steve Block71f2cf12011-10-20 11:56:00 +0100427 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700428 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700429 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700430 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
431 if (mPlaybackThreads.keyAt(i) != output) {
432 // prevent same audio session on different output threads
433 uint32_t sessions = t->hasAudioSession(*sessionId);
434 if (sessions & PlaybackThread::TRACK_SESSION) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -0700435 LOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent493941b2010-07-28 01:32:47 -0700436 lStatus = BAD_VALUE;
437 goto Exit;
438 }
439 // check if an effect with same session ID is waiting for a track to be created
440 if (sessions & PlaybackThread::EFFECT_SESSION) {
441 effectThread = t.get();
442 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700443 }
444 }
Eric Laurent65b65452010-06-01 23:49:17 -0700445 lSessionId = *sessionId;
446 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700447 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700448 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700449 if (sessionId != NULL) {
450 *sessionId = lSessionId;
451 }
452 }
Steve Block71f2cf12011-10-20 11:56:00 +0100453 ALOGV("createTrack() lSessionId: %d", lSessionId);
Eric Laurent65b65452010-06-01 23:49:17 -0700454
Eric Laurenta553c252009-07-17 12:17:14 -0700455 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700456 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700457
458 // move effect chain to this output thread if an effect on same session was waiting
459 // for a track to be created
460 if (lStatus == NO_ERROR && effectThread != NULL) {
461 Mutex::Autolock _dl(thread->mLock);
462 Mutex::Autolock _sl(effectThread->mLock);
463 moveEffectChain_l(lSessionId, effectThread, thread, true);
464 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700465 }
466 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800467 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700468 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700469 // remove local strong reference to Client before deleting the Track so that the Client
470 // destructor is called by the TrackBase destructor with mLock held
471 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700472 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800473 }
474
475Exit:
476 if(status) {
477 *status = lStatus;
478 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700479 return trackHandle;
480}
481
Eric Laurentddb78e72009-07-28 08:44:33 -0700482uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700483{
Eric Laurenta553c252009-07-17 12:17:14 -0700484 Mutex::Autolock _l(mLock);
485 PlaybackThread *thread = checkPlaybackThread_l(output);
486 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700487 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700488 return 0;
489 }
490 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700491}
492
Eric Laurentddb78e72009-07-28 08:44:33 -0700493int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700494{
Eric Laurenta553c252009-07-17 12:17:14 -0700495 Mutex::Autolock _l(mLock);
496 PlaybackThread *thread = checkPlaybackThread_l(output);
497 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700498 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700499 return 0;
500 }
501 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700502}
503
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700504uint32_t AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700505{
Eric Laurenta553c252009-07-17 12:17:14 -0700506 Mutex::Autolock _l(mLock);
507 PlaybackThread *thread = checkPlaybackThread_l(output);
508 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700509 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700510 return 0;
511 }
512 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700513}
514
Eric Laurentddb78e72009-07-28 08:44:33 -0700515size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700516{
Eric Laurenta553c252009-07-17 12:17:14 -0700517 Mutex::Autolock _l(mLock);
518 PlaybackThread *thread = checkPlaybackThread_l(output);
519 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700520 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700521 return 0;
522 }
523 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700524}
525
Eric Laurentddb78e72009-07-28 08:44:33 -0700526uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800527{
Eric Laurenta553c252009-07-17 12:17:14 -0700528 Mutex::Autolock _l(mLock);
529 PlaybackThread *thread = checkPlaybackThread_l(output);
530 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700531 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700532 return 0;
533 }
534 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800535}
536
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700537status_t AudioFlinger::setMasterVolume(float value)
538{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700539 status_t ret = initCheck();
540 if (ret != NO_ERROR) {
541 return ret;
542 }
543
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700544 // check calling permissions
545 if (!settingsAllowed()) {
546 return PERMISSION_DENIED;
547 }
548
549 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800550 { // scope for the lock
551 AutoMutex lock(mHardwareLock);
552 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700553 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800554 value = 1.0f;
555 }
556 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700557 }
Eric Laurenta553c252009-07-17 12:17:14 -0700558
Eric Laurent01635942011-01-18 18:39:02 -0800559 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700560 mMasterVolume = value;
561 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700562 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700563
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700564 return NO_ERROR;
565}
566
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700567status_t AudioFlinger::setMode(int mode)
568{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700569 status_t ret = initCheck();
570 if (ret != NO_ERROR) {
571 return ret;
572 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700573
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700574 // check calling permissions
575 if (!settingsAllowed()) {
576 return PERMISSION_DENIED;
577 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700578 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700579 LOGW("Illegal value: setMode(%d)", mode);
580 return BAD_VALUE;
581 }
582
Eric Laurent53334cd2010-06-23 17:38:20 -0700583 { // scope for the lock
584 AutoMutex lock(mHardwareLock);
585 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700586 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700587 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800588 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700589
590 if (NO_ERROR == ret) {
591 Mutex::Autolock _l(mLock);
592 mMode = mode;
593 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
594 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700595 }
596
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700597 return ret;
598}
599
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700600status_t AudioFlinger::setMicMute(bool state)
601{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700602 status_t ret = initCheck();
603 if (ret != NO_ERROR) {
604 return ret;
605 }
606
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700607 // check calling permissions
608 if (!settingsAllowed()) {
609 return PERMISSION_DENIED;
610 }
611
612 AutoMutex lock(mHardwareLock);
613 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700614 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700615 mHardwareStatus = AUDIO_HW_IDLE;
616 return ret;
617}
618
619bool AudioFlinger::getMicMute() const
620{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700621 status_t ret = initCheck();
622 if (ret != NO_ERROR) {
623 return false;
624 }
625
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700626 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700627 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700628 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700629 mHardwareStatus = AUDIO_HW_IDLE;
630 return state;
631}
632
633status_t AudioFlinger::setMasterMute(bool muted)
634{
635 // check calling permissions
636 if (!settingsAllowed()) {
637 return PERMISSION_DENIED;
638 }
Eric Laurenta553c252009-07-17 12:17:14 -0700639
Eric Laurent01635942011-01-18 18:39:02 -0800640 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700641 mMasterMute = muted;
642 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700643 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700644
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700645 return NO_ERROR;
646}
647
648float AudioFlinger::masterVolume() const
649{
Eric Laurenta553c252009-07-17 12:17:14 -0700650 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700651}
652
653bool AudioFlinger::masterMute() const
654{
Eric Laurenta553c252009-07-17 12:17:14 -0700655 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700656}
657
Eric Laurentddb78e72009-07-28 08:44:33 -0700658status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700659{
660 // check calling permissions
661 if (!settingsAllowed()) {
662 return PERMISSION_DENIED;
663 }
664
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700665 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -0700666 LOGE("setStreamVolume() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700667 return BAD_VALUE;
668 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800669
Eric Laurenta553c252009-07-17 12:17:14 -0700670 AutoMutex lock(mLock);
671 PlaybackThread *thread = NULL;
672 if (output) {
673 thread = checkPlaybackThread_l(output);
674 if (thread == NULL) {
675 return BAD_VALUE;
676 }
677 }
678
Eric Laurenta553c252009-07-17 12:17:14 -0700679 mStreamTypes[stream].volume = value;
680
681 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700682 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700683 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700684 }
Eric Laurenta553c252009-07-17 12:17:14 -0700685 } else {
686 thread->setStreamVolume(stream, value);
687 }
Eric Laurentef028272009-04-21 07:56:33 -0700688
Eric Laurent415f3e22009-10-21 08:14:22 -0700689 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700690}
691
692status_t AudioFlinger::setStreamMute(int stream, bool muted)
693{
694 // check calling permissions
695 if (!settingsAllowed()) {
696 return PERMISSION_DENIED;
697 }
698
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700699 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
700 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -0700701 LOGE("setStreamMute() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700702 return BAD_VALUE;
703 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700704
Eric Laurent01635942011-01-18 18:39:02 -0800705 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700706 mStreamTypes[stream].mute = muted;
707 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700708 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700710 return NO_ERROR;
711}
712
Eric Laurentddb78e72009-07-28 08:44:33 -0700713float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700714{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700715 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700716 return 0.0f;
717 }
Eric Laurenta553c252009-07-17 12:17:14 -0700718
719 AutoMutex lock(mLock);
720 float volume;
721 if (output) {
722 PlaybackThread *thread = checkPlaybackThread_l(output);
723 if (thread == NULL) {
724 return 0.0f;
725 }
726 volume = thread->streamVolume(stream);
727 } else {
728 volume = mStreamTypes[stream].volume;
729 }
730
Eric Laurentef028272009-04-21 07:56:33 -0700731 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700732}
733
734bool AudioFlinger::streamMute(int stream) const
735{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700736 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700737 return true;
738 }
Eric Laurenta553c252009-07-17 12:17:14 -0700739
740 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700741}
742
Eric Laurentddb78e72009-07-28 08:44:33 -0700743status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700744{
Eric Laurenta553c252009-07-17 12:17:14 -0700745 status_t result;
746
Steve Block71f2cf12011-10-20 11:56:00 +0100747 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700748 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
749 // check calling permissions
750 if (!settingsAllowed()) {
751 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800752 }
Eric Laurenta553c252009-07-17 12:17:14 -0700753
754 // ioHandle == 0 means the parameters are global to the audio hardware interface
755 if (ioHandle == 0) {
756 AutoMutex lock(mHardwareLock);
757 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700758 status_t final_result = NO_ERROR;
759 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
760 audio_hw_device_t *dev = mAudioHwDevs[i];
761 result = dev->set_parameters(dev, keyValuePairs.string());
762 final_result = result ?: final_result;
763 }
Eric Laurenta553c252009-07-17 12:17:14 -0700764 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent6639b552011-08-01 09:52:20 -0700765 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
766 AudioParameter param = AudioParameter(keyValuePairs);
767 String8 value;
768 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
769 Mutex::Autolock _l(mLock);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700770 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
771 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent6639b552011-08-01 09:52:20 -0700772 for (size_t i = 0; i < mRecordThreads.size(); i++) {
773 sp<RecordThread> thread = mRecordThreads.valueAt(i);
774 RecordThread::RecordTrack *track = thread->track();
775 if (track != NULL) {
776 audio_devices_t device = (audio_devices_t)(
777 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700778 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700779 thread->setEffectSuspended(FX_IID_AEC,
780 suspend,
781 track->sessionId());
782 thread->setEffectSuspended(FX_IID_NS,
783 suspend,
784 track->sessionId());
785 }
786 }
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700787 mBtNrecIsOff = btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700788 }
789 }
Dima Zavin31f188892011-04-18 16:57:27 -0700790 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700791 }
792
Eric Laurentb7d94602009-09-29 11:12:57 -0700793 // hold a strong ref on thread in case closeOutput() or closeInput() is called
794 // and the thread is exited once the lock is released
795 sp<ThreadBase> thread;
796 {
797 Mutex::Autolock _l(mLock);
798 thread = checkPlaybackThread_l(ioHandle);
799 if (thread == NULL) {
800 thread = checkRecordThread_l(ioHandle);
Eric Laurent464d5b32011-06-17 21:29:58 -0700801 } else if (thread.get() == primaryPlaybackThread_l()) {
802 // indicate output device change to all input threads for pre processing
803 AudioParameter param = AudioParameter(keyValuePairs);
804 int value;
805 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
806 for (size_t i = 0; i < mRecordThreads.size(); i++) {
807 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
808 }
809 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700810 }
Eric Laurenta553c252009-07-17 12:17:14 -0700811 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700812 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800813 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800814 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700815 }
Eric Laurenta553c252009-07-17 12:17:14 -0700816 return BAD_VALUE;
817}
818
Eric Laurentddb78e72009-07-28 08:44:33 -0700819String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700820{
Steve Block71f2cf12011-10-20 11:56:00 +0100821// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700822// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
823
824 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700825 String8 out_s8;
826
Dima Zavin31f188892011-04-18 16:57:27 -0700827 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
828 audio_hw_device_t *dev = mAudioHwDevs[i];
829 char *s = dev->get_parameters(dev, keys.string());
830 out_s8 += String8(s);
831 free(s);
832 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700833 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700834 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700835
836 Mutex::Autolock _l(mLock);
837
Eric Laurenta553c252009-07-17 12:17:14 -0700838 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
839 if (playbackThread != NULL) {
840 return playbackThread->getParameters(keys);
841 }
842 RecordThread *recordThread = checkRecordThread_l(ioHandle);
843 if (recordThread != NULL) {
844 return recordThread->getParameters(keys);
845 }
846 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700847}
848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
850{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700851 status_t ret = initCheck();
852 if (ret != NO_ERROR) {
853 return 0;
854 }
855
Dima Zavin31f188892011-04-18 16:57:27 -0700856 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857}
858
Eric Laurent47d0a922010-02-26 02:47:27 -0800859unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
860{
861 if (ioHandle == 0) {
862 return 0;
863 }
864
865 Mutex::Autolock _l(mLock);
866
867 RecordThread *recordThread = checkRecordThread_l(ioHandle);
868 if (recordThread != NULL) {
869 return recordThread->getInputFramesLost();
870 }
871 return 0;
872}
873
Eric Laurent415f3e22009-10-21 08:14:22 -0700874status_t AudioFlinger::setVoiceVolume(float value)
875{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700876 status_t ret = initCheck();
877 if (ret != NO_ERROR) {
878 return ret;
879 }
880
Eric Laurent415f3e22009-10-21 08:14:22 -0700881 // check calling permissions
882 if (!settingsAllowed()) {
883 return PERMISSION_DENIED;
884 }
885
886 AutoMutex lock(mHardwareLock);
887 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700888 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700889 mHardwareStatus = AUDIO_HW_IDLE;
890
891 return ret;
892}
893
Eric Laurent0986e792010-01-19 17:37:09 -0800894status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
895{
896 status_t status;
897
898 Mutex::Autolock _l(mLock);
899
900 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
901 if (playbackThread != NULL) {
902 return playbackThread->getRenderPosition(halFrames, dspFrames);
903 }
904
905 return BAD_VALUE;
906}
907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
909{
Eric Laurenta553c252009-07-17 12:17:14 -0700910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 Mutex::Autolock _l(mLock);
912
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700913 int pid = IPCThreadState::self()->getCallingPid();
914 if (mNotificationClients.indexOfKey(pid) < 0) {
915 sp<NotificationClient> notificationClient = new NotificationClient(this,
916 client,
917 pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100918 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700919
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700920 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700921
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700922 sp<IBinder> binder = client->asBinder();
923 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700925 // the config change is always sent from playback or record threads to avoid deadlock
926 // with AudioSystem::gLock
927 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
928 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
929 }
Eric Laurenta553c252009-07-17 12:17:14 -0700930
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700931 for (size_t i = 0; i < mRecordThreads.size(); i++) {
932 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 }
934 }
935}
936
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700937void AudioFlinger::removeNotificationClient(pid_t pid)
938{
939 Mutex::Autolock _l(mLock);
940
941 int index = mNotificationClients.indexOfKey(pid);
942 if (index >= 0) {
943 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100944 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700945 mNotificationClients.removeItem(pid);
946 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700947
Steve Block71f2cf12011-10-20 11:56:00 +0100948 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700949 int num = mAudioSessionRefs.size();
950 bool removed = false;
951 for (int i = 0; i< num; i++) {
952 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +0100953 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700954 if (ref->pid == pid) {
Steve Block71f2cf12011-10-20 11:56:00 +0100955 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700956 mAudioSessionRefs.removeAt(i);
957 delete ref;
958 removed = true;
959 i--;
960 num--;
961 }
962 }
963 if (removed) {
964 purgeStaleEffects_l();
965 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700966}
967
Eric Laurent296a0ec2009-09-15 07:10:12 -0700968// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700969void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
970{
Eric Laurent49f02be2009-11-19 09:00:56 -0800971 size_t size = mNotificationClients.size();
972 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700973 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700974 }
975}
976
Eric Laurentb9481d82009-09-17 05:12:56 -0700977// removeClient_l() must be called with AudioFlinger::mLock held
978void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700979{
Steve Block71f2cf12011-10-20 11:56:00 +0100980 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700981 mClients.removeItem(pid);
982}
983
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700984
Eric Laurenta553c252009-07-17 12:17:14 -0700985// ----------------------------------------------------------------------------
986
Eric Laurent464d5b32011-06-17 21:29:58 -0700987AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Eric Laurenta553c252009-07-17 12:17:14 -0700988 : Thread(false),
989 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent6dbdc402011-07-22 09:04:31 -0700990 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
991 mDevice(device)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700992{
Eric Laurent6dbdc402011-07-22 09:04:31 -0700993 mDeathRecipient = new PMDeathRecipient(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994}
995
Eric Laurenta553c252009-07-17 12:17:14 -0700996AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700998 mParamCond.broadcast();
Eric Laurent6dbdc402011-07-22 09:04:31 -0700999 // do not lock the mutex in destructor
1000 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -07001001 if (mPowerManager != 0) {
1002 sp<IBinder> binder = mPowerManager->asBinder();
1003 binder->unlinkToDeath(mDeathRecipient);
1004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005}
1006
Eric Laurenta553c252009-07-17 12:17:14 -07001007void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001008{
Glenn Kastene5fb2632011-12-14 10:28:06 -08001009 // keep a strong ref on ourself so that we won't get
Eric Laurenta553c252009-07-17 12:17:14 -07001010 // destroyed in the middle of requestExitAndWait()
1011 sp <ThreadBase> strongMe = this;
1012
Steve Block71f2cf12011-10-20 11:56:00 +01001013 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001014 {
1015 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001016 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001017 requestExit();
1018 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001019 }
Eric Laurenta553c252009-07-17 12:17:14 -07001020 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001021}
Eric Laurenta553c252009-07-17 12:17:14 -07001022
1023uint32_t AudioFlinger::ThreadBase::sampleRate() const
1024{
1025 return mSampleRate;
1026}
1027
1028int AudioFlinger::ThreadBase::channelCount() const
1029{
Eric Laurentb0a01472010-05-14 05:45:46 -07001030 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07001031}
1032
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001033uint32_t AudioFlinger::ThreadBase::format() const
Eric Laurenta553c252009-07-17 12:17:14 -07001034{
1035 return mFormat;
1036}
1037
1038size_t AudioFlinger::ThreadBase::frameCount() const
1039{
1040 return mFrameCount;
1041}
1042
1043status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1044{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001045 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001046
Steve Block71f2cf12011-10-20 11:56:00 +01001047 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001048 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001049
Eric Laurent8fce46a2009-08-04 09:45:33 -07001050 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001051 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001052 // wait condition with timeout in case the thread loop has exited
1053 // before the request could be processed
Glenn Kastencbfe2e12011-12-13 11:04:14 -08001054 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001055 status = mParamStatus;
1056 mWaitWorkCV.signal();
1057 } else {
1058 status = TIMED_OUT;
1059 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001060 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001061}
1062
1063void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1064{
1065 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001066 sendConfigEvent_l(event, param);
1067}
1068
1069// sendConfigEvent_l() must be called with ThreadBase::mLock held
1070void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1071{
Glenn Kasten4b220f02011-12-13 11:50:00 -08001072 ConfigEvent configEvent;
1073 configEvent.mEvent = event;
1074 configEvent.mParam = param;
Eric Laurenta553c252009-07-17 12:17:14 -07001075 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001076 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001077 mWaitWorkCV.signal();
1078}
1079
1080void AudioFlinger::ThreadBase::processConfigEvents()
1081{
1082 mLock.lock();
1083 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001084 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kasten4b220f02011-12-13 11:50:00 -08001085 ConfigEvent configEvent = mConfigEvents[0];
Eric Laurenta553c252009-07-17 12:17:14 -07001086 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001087 // release mLock before locking AudioFlinger mLock: lock order is always
1088 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001089 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001090 mAudioFlinger->mLock.lock();
Glenn Kasten4b220f02011-12-13 11:50:00 -08001091 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001092 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001093 mLock.lock();
1094 }
1095 mLock.unlock();
1096}
1097
Eric Laurent3fdb1262009-11-07 00:01:32 -08001098status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1099{
1100 const size_t SIZE = 256;
1101 char buffer[SIZE];
1102 String8 result;
1103
1104 bool locked = tryLock(mLock);
1105 if (!locked) {
1106 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1107 write(fd, buffer, strlen(buffer));
1108 }
1109
1110 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1111 result.append(buffer);
1112 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1113 result.append(buffer);
1114 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1115 result.append(buffer);
1116 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1117 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001118 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1119 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001120 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1121 result.append(buffer);
1122 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1123 result.append(buffer);
1124
1125 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1126 result.append(buffer);
1127 result.append(" Index Command");
1128 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1129 snprintf(buffer, SIZE, "\n %02d ", i);
1130 result.append(buffer);
1131 result.append(mNewParameters[i]);
1132 }
1133
1134 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1135 result.append(buffer);
1136 snprintf(buffer, SIZE, " Index event param\n");
1137 result.append(buffer);
1138 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kasten4b220f02011-12-13 11:50:00 -08001139 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001140 result.append(buffer);
1141 }
1142 result.append("\n");
1143
1144 write(fd, result.string(), result.size());
1145
1146 if (locked) {
1147 mLock.unlock();
1148 }
1149 return NO_ERROR;
1150}
1151
Eric Laurent1345d332011-07-24 17:49:51 -07001152status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1153{
1154 const size_t SIZE = 256;
1155 char buffer[SIZE];
1156 String8 result;
1157
1158 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1159 write(fd, buffer, strlen(buffer));
1160
1161 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1162 sp<EffectChain> chain = mEffectChains[i];
1163 if (chain != 0) {
1164 chain->dump(fd, args);
1165 }
1166 }
1167 return NO_ERROR;
1168}
1169
Eric Laurent6dbdc402011-07-22 09:04:31 -07001170void AudioFlinger::ThreadBase::acquireWakeLock()
1171{
1172 Mutex::Autolock _l(mLock);
1173 acquireWakeLock_l();
1174}
1175
1176void AudioFlinger::ThreadBase::acquireWakeLock_l()
1177{
1178 if (mPowerManager == 0) {
1179 // use checkService() to avoid blocking if power service is not up yet
1180 sp<IBinder> binder =
1181 defaultServiceManager()->checkService(String16("power"));
1182 if (binder == 0) {
1183 LOGW("Thread %s cannot connect to the power manager service", mName);
1184 } else {
1185 mPowerManager = interface_cast<IPowerManager>(binder);
1186 binder->linkToDeath(mDeathRecipient);
1187 }
1188 }
1189 if (mPowerManager != 0) {
1190 sp<IBinder> binder = new BBinder();
1191 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1192 binder,
1193 String16(mName));
1194 if (status == NO_ERROR) {
1195 mWakeLockToken = binder;
1196 }
Steve Block71f2cf12011-10-20 11:56:00 +01001197 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001198 }
1199}
1200
1201void AudioFlinger::ThreadBase::releaseWakeLock()
1202{
1203 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001204 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001205}
1206
1207void AudioFlinger::ThreadBase::releaseWakeLock_l()
1208{
1209 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001210 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001211 if (mPowerManager != 0) {
1212 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1213 }
1214 mWakeLockToken.clear();
1215 }
1216}
1217
1218void AudioFlinger::ThreadBase::clearPowerManager()
1219{
1220 Mutex::Autolock _l(mLock);
1221 releaseWakeLock_l();
1222 mPowerManager.clear();
1223}
1224
1225void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1226{
1227 sp<ThreadBase> thread = mThread.promote();
1228 if (thread != 0) {
1229 thread->clearPowerManager();
1230 }
1231 LOGW("power manager service died !!!");
1232}
Eric Laurent1345d332011-07-24 17:49:51 -07001233
Eric Laurentf82fccd2011-07-27 19:49:51 -07001234void AudioFlinger::ThreadBase::setEffectSuspended(
1235 const effect_uuid_t *type, bool suspend, int sessionId)
1236{
1237 Mutex::Autolock _l(mLock);
1238 setEffectSuspended_l(type, suspend, sessionId);
1239}
1240
1241void AudioFlinger::ThreadBase::setEffectSuspended_l(
1242 const effect_uuid_t *type, bool suspend, int sessionId)
1243{
1244 sp<EffectChain> chain;
1245 chain = getEffectChain_l(sessionId);
1246 if (chain != 0) {
1247 if (type != NULL) {
1248 chain->setEffectSuspended_l(type, suspend);
1249 } else {
1250 chain->setEffectSuspendedAll_l(suspend);
1251 }
1252 }
1253
1254 updateSuspendedSessions_l(type, suspend, sessionId);
1255}
1256
1257void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1258{
1259 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1260 if (index < 0) {
1261 return;
1262 }
1263
1264 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1265 mSuspendedSessions.editValueAt(index);
1266
1267 for (size_t i = 0; i < sessionEffects.size(); i++) {
1268 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1269 for (int j = 0; j < desc->mRefCount; j++) {
1270 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1271 chain->setEffectSuspendedAll_l(true);
1272 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001273 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001274 desc->mType.timeLow);
1275 chain->setEffectSuspended_l(&desc->mType, true);
1276 }
1277 }
1278 }
1279}
1280
Eric Laurentf82fccd2011-07-27 19:49:51 -07001281void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1282 bool suspend,
1283 int sessionId)
1284{
1285 int index = mSuspendedSessions.indexOfKey(sessionId);
1286
1287 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1288
1289 if (suspend) {
1290 if (index >= 0) {
1291 sessionEffects = mSuspendedSessions.editValueAt(index);
1292 } else {
1293 mSuspendedSessions.add(sessionId, sessionEffects);
1294 }
1295 } else {
1296 if (index < 0) {
1297 return;
1298 }
1299 sessionEffects = mSuspendedSessions.editValueAt(index);
1300 }
1301
1302
1303 int key = EffectChain::kKeyForSuspendAll;
1304 if (type != NULL) {
1305 key = type->timeLow;
1306 }
1307 index = sessionEffects.indexOfKey(key);
1308
1309 sp <SuspendedSessionDesc> desc;
1310 if (suspend) {
1311 if (index >= 0) {
1312 desc = sessionEffects.valueAt(index);
1313 } else {
1314 desc = new SuspendedSessionDesc();
1315 if (type != NULL) {
1316 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1317 }
1318 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001319 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001320 }
1321 desc->mRefCount++;
1322 } else {
1323 if (index < 0) {
1324 return;
1325 }
1326 desc = sessionEffects.valueAt(index);
1327 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001328 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001329 sessionEffects.removeItemsAt(index);
1330 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001331 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001332 sessionId);
1333 mSuspendedSessions.removeItem(sessionId);
1334 }
1335 }
1336 }
1337 if (!sessionEffects.isEmpty()) {
1338 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1339 }
1340}
1341
1342void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1343 bool enabled,
1344 int sessionId)
1345{
1346 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001347 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1348}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001349
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001350void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1351 bool enabled,
1352 int sessionId)
1353{
Eric Laurent6752ec82011-08-10 10:37:50 -07001354 if (mType != RECORD) {
1355 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1356 // another session. This gives the priority to well behaved effect control panels
1357 // and applications not using global effects.
1358 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1359 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1360 }
1361 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001362
1363 sp<EffectChain> chain = getEffectChain_l(sessionId);
1364 if (chain != 0) {
1365 chain->checkSuspendOnEffectEnabled(effect, enabled);
1366 }
1367}
1368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369// ----------------------------------------------------------------------------
1370
Eric Laurent464d5b32011-06-17 21:29:58 -07001371AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1372 AudioStreamOut* output,
1373 int id,
1374 uint32_t device)
1375 : ThreadBase(audioFlinger, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08001376 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent464d5b32011-06-17 21:29:58 -07001377 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001379 snprintf(mName, kNameLength, "AudioOut_%d", id);
1380
Eric Laurenta553c252009-07-17 12:17:14 -07001381 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382
Eric Laurenta553c252009-07-17 12:17:14 -07001383 mMasterVolume = mAudioFlinger->masterVolume();
1384 mMasterMute = mAudioFlinger->masterMute();
1385
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001386 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurenta553c252009-07-17 12:17:14 -07001387 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1388 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent05ce0942011-08-30 10:18:54 -07001389 mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391}
1392
Eric Laurenta553c252009-07-17 12:17:14 -07001393AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394{
1395 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396}
1397
Eric Laurenta553c252009-07-17 12:17:14 -07001398status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399{
1400 dumpInternals(fd, args);
1401 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001402 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 return NO_ERROR;
1404}
1405
Eric Laurenta553c252009-07-17 12:17:14 -07001406status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407{
1408 const size_t SIZE = 256;
1409 char buffer[SIZE];
1410 String8 result;
1411
Eric Laurenta553c252009-07-17 12:17:14 -07001412 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001414 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001416 sp<Track> track = mTracks[i];
1417 if (track != 0) {
1418 track->dump(buffer, SIZE);
1419 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421 }
1422
Eric Laurenta553c252009-07-17 12:17:14 -07001423 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001425 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001427 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 if (wTrack != 0) {
1429 sp<Track> track = wTrack.promote();
1430 if (track != 0) {
1431 track->dump(buffer, SIZE);
1432 result.append(buffer);
1433 }
1434 }
1435 }
1436 write(fd, result.string(), result.size());
1437 return NO_ERROR;
1438}
1439
Eric Laurenta553c252009-07-17 12:17:14 -07001440status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441{
1442 const size_t SIZE = 256;
1443 char buffer[SIZE];
1444 String8 result;
1445
Eric Laurent3fdb1262009-11-07 00:01:32 -08001446 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 result.append(buffer);
1448 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1449 result.append(buffer);
1450 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1451 result.append(buffer);
1452 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1453 result.append(buffer);
1454 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1455 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001456 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1457 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001458 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1459 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001461
1462 dumpBase(fd, args);
1463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 return NO_ERROR;
1465}
1466
1467// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001468status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469{
Eric Laurent828b9772011-08-07 16:32:26 -07001470 status_t status = initCheck();
1471 if (status == NO_ERROR) {
1472 LOGI("AudioFlinger's thread %p ready to run", this);
1473 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 LOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 }
Eric Laurent828b9772011-08-07 16:32:26 -07001476 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477}
1478
Eric Laurenta553c252009-07-17 12:17:14 -07001479void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001481 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482}
1483
Eric Laurenta553c252009-07-17 12:17:14 -07001484// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1485sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 const sp<AudioFlinger::Client>& client,
1487 int streamType,
1488 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001489 uint32_t format,
1490 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 int frameCount,
1492 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001493 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 status_t *status)
1495{
1496 sp<Track> track;
1497 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001498
1499 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001500 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1501 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1502 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1503 "for output %p with format %d",
1504 sampleRate, format, channelMask, mOutput, mFormat);
1505 lStatus = BAD_VALUE;
1506 goto Exit;
1507 }
Eric Laurenta553c252009-07-17 12:17:14 -07001508 }
1509 } else {
1510 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1511 if (sampleRate > mSampleRate*2) {
1512 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1513 lStatus = BAD_VALUE;
1514 goto Exit;
1515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517
Eric Laurent464d5b32011-06-17 21:29:58 -07001518 lStatus = initCheck();
1519 if (lStatus != NO_ERROR) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001520 LOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001521 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 }
1523
Eric Laurenta553c252009-07-17 12:17:14 -07001524 { // scope for mLock
1525 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001526
1527 // all tracks in same audio session must share the same routing strategy otherwise
1528 // conflicts will happen when tracks are moved from one output to another by audio policy
1529 // manager
1530 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001531 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001532 for (size_t i = 0; i < mTracks.size(); ++i) {
1533 sp<Track> t = mTracks[i];
1534 if (t != 0) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001535 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1536 if (sessionId == t->sessionId() && strategy != actual) {
1537 LOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1538 strategy, actual);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001539 lStatus = BAD_VALUE;
1540 goto Exit;
1541 }
1542 }
1543 }
1544
Eric Laurenta553c252009-07-17 12:17:14 -07001545 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001546 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001547 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001548 lStatus = NO_MEMORY;
1549 goto Exit;
1550 }
1551 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001552
1553 sp<EffectChain> chain = getEffectChain_l(sessionId);
1554 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001555 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001556 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001557 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001558 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001559 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001560
1561 // invalidate track immediately if the stream type was moved to another thread since
1562 // createTrack() was called by the client process.
1563 if (!mStreamTypes[streamType].valid) {
1564 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1565 this, streamType);
1566 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1567 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001568 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001569 lStatus = NO_ERROR;
1570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571Exit:
1572 if(status) {
1573 *status = lStatus;
1574 }
1575 return track;
1576}
1577
Eric Laurenta553c252009-07-17 12:17:14 -07001578uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579{
Eric Laurent828b9772011-08-07 16:32:26 -07001580 Mutex::Autolock _l(mLock);
1581 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001582 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001583 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 return 0;
1585 }
1586}
1587
Eric Laurenta553c252009-07-17 12:17:14 -07001588status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589{
1590 mMasterVolume = value;
1591 return NO_ERROR;
1592}
1593
Eric Laurenta553c252009-07-17 12:17:14 -07001594status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595{
1596 mMasterMute = muted;
1597 return NO_ERROR;
1598}
1599
Eric Laurenta553c252009-07-17 12:17:14 -07001600float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601{
1602 return mMasterVolume;
1603}
1604
Eric Laurenta553c252009-07-17 12:17:14 -07001605bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606{
1607 return mMasterMute;
1608}
1609
Eric Laurenta553c252009-07-17 12:17:14 -07001610status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611{
1612 mStreamTypes[stream].volume = value;
1613 return NO_ERROR;
1614}
1615
Eric Laurenta553c252009-07-17 12:17:14 -07001616status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617{
1618 mStreamTypes[stream].mute = muted;
1619 return NO_ERROR;
1620}
1621
Eric Laurenta553c252009-07-17 12:17:14 -07001622float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623{
1624 return mStreamTypes[stream].volume;
1625}
1626
Eric Laurenta553c252009-07-17 12:17:14 -07001627bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628{
1629 return mStreamTypes[stream].mute;
1630}
1631
Eric Laurenta553c252009-07-17 12:17:14 -07001632// addTrack_l() must be called with ThreadBase::mLock held
1633status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634{
1635 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001636
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001637 // set retry count for buffer fill
1638 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001639 if (mActiveTracks.indexOf(track) < 0) {
1640 // the track is newly added, make sure it fills up all its
1641 // buffers before playing. This is to ensure the client will
1642 // effectively get the latency it requested.
1643 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001644 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001645 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001646 if (track->mainBuffer() != mMixBuffer) {
1647 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1648 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001649 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001650 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001651 }
1652 }
1653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001655 }
Eric Laurenta553c252009-07-17 12:17:14 -07001656
Steve Block71f2cf12011-10-20 11:56:00 +01001657 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001658 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659
1660 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001661}
1662
Eric Laurenta553c252009-07-17 12:17:14 -07001663// destroyTrack_l() must be called with ThreadBase::mLock held
1664void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001665{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001666 track->mState = TrackBase::TERMINATED;
1667 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001668 removeTrack_l(track);
1669 }
1670}
1671
1672void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1673{
1674 mTracks.remove(track);
1675 deleteTrackName_l(track->name());
1676 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1677 if (chain != 0) {
1678 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001679 }
1680}
1681
Eric Laurenta553c252009-07-17 12:17:14 -07001682String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001683{
Eric Laurent828b9772011-08-07 16:32:26 -07001684 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001685 char *s;
1686
Eric Laurent828b9772011-08-07 16:32:26 -07001687 Mutex::Autolock _l(mLock);
1688 if (initCheck() != NO_ERROR) {
1689 return out_s8;
1690 }
1691
Dima Zavin31f188892011-04-18 16:57:27 -07001692 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001693 out_s8 = String8(s);
1694 free(s);
1695 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001696}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001697
Eric Laurent828b9772011-08-07 16:32:26 -07001698// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001699void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001700 AudioSystem::OutputDescriptor desc;
1701 void *param2 = 0;
1702
Steve Block71f2cf12011-10-20 11:56:00 +01001703 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001704
1705 switch (event) {
1706 case AudioSystem::OUTPUT_OPENED:
1707 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001708 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001709 desc.samplingRate = mSampleRate;
1710 desc.format = mFormat;
1711 desc.frameCount = mFrameCount;
1712 desc.latency = latency();
1713 param2 = &desc;
1714 break;
1715
1716 case AudioSystem::STREAM_CONFIG_CHANGED:
1717 param2 = &param;
1718 case AudioSystem::OUTPUT_CLOSED:
1719 default:
1720 break;
1721 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001722 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001723}
1724
1725void AudioFlinger::PlaybackThread::readOutputParameters()
1726{
Dima Zavin31f188892011-04-18 16:57:27 -07001727 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001728 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1729 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001730 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1731 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1732 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001733
Eric Laurenta553c252009-07-17 12:17:14 -07001734 // FIXME - Current mixer implementation only supports stereo output: Always
1735 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001736 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001737 mMixBuffer = new int16_t[mFrameCount * 2];
1738 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001739
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001740 // force reconfiguration of effect chains and engines to take new buffer size and audio
1741 // parameters into account
1742 // Note that mLock is not held when readOutputParameters() is called from the constructor
1743 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1744 // matter.
1745 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1746 Vector< sp<EffectChain> > effectChains = mEffectChains;
1747 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001748 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001749 }
Eric Laurenta553c252009-07-17 12:17:14 -07001750}
1751
Eric Laurent0986e792010-01-19 17:37:09 -08001752status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1753{
1754 if (halFrames == 0 || dspFrames == 0) {
1755 return BAD_VALUE;
1756 }
Eric Laurent828b9772011-08-07 16:32:26 -07001757 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001758 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001759 return INVALID_OPERATION;
1760 }
Dima Zavin31f188892011-04-18 16:57:27 -07001761 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001762
Dima Zavin31f188892011-04-18 16:57:27 -07001763 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001764}
1765
Eric Laurent493941b2010-07-28 01:32:47 -07001766uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001767{
1768 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001769 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001770 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001771 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001772 }
1773
1774 for (size_t i = 0; i < mTracks.size(); ++i) {
1775 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001776 if (sessionId == track->sessionId() &&
1777 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001778 result |= TRACK_SESSION;
1779 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001780 }
1781 }
1782
Eric Laurent493941b2010-07-28 01:32:47 -07001783 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001784}
1785
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001786uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1787{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001788 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001789 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001790 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1791 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001792 }
1793 for (size_t i = 0; i < mTracks.size(); i++) {
1794 sp<Track> track = mTracks[i];
1795 if (sessionId == track->sessionId() &&
1796 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001797 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001798 }
1799 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001800 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001801}
1802
Eric Laurent53334cd2010-06-23 17:38:20 -07001803
Eric Laurent828b9772011-08-07 16:32:26 -07001804AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1805{
1806 Mutex::Autolock _l(mLock);
1807 return mOutput;
1808}
1809
1810AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1811{
1812 Mutex::Autolock _l(mLock);
1813 AudioStreamOut *output = mOutput;
1814 mOutput = NULL;
1815 return output;
1816}
1817
1818// this method must always be called either with ThreadBase mLock held or inside the thread loop
1819audio_stream_t* AudioFlinger::PlaybackThread::stream()
1820{
1821 if (mOutput == NULL) {
1822 return NULL;
1823 }
1824 return &mOutput->stream->common;
1825}
1826
Eric Laurent44331692011-12-05 09:47:19 -08001827uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1828{
1829 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1830 // decoding and transfer time. So sleeping for half of the latency would likely cause
1831 // underruns
1832 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1833 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1834 } else {
1835 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1836 }
1837}
1838
Eric Laurenta553c252009-07-17 12:17:14 -07001839// ----------------------------------------------------------------------------
1840
Dima Zavin31f188892011-04-18 16:57:27 -07001841AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001842 : PlaybackThread(audioFlinger, output, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08001843 mAudioMixer(NULL)
Eric Laurenta553c252009-07-17 12:17:14 -07001844{
Eric Laurent464d5b32011-06-17 21:29:58 -07001845 mType = ThreadBase::MIXER;
Eric Laurenta553c252009-07-17 12:17:14 -07001846 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1847
1848 // FIXME - Current mixer implementation only supports stereo output
1849 if (mChannelCount == 1) {
1850 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001852}
1853
Eric Laurenta553c252009-07-17 12:17:14 -07001854AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001855{
Eric Laurenta553c252009-07-17 12:17:14 -07001856 delete mAudioMixer;
1857}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858
Eric Laurenta553c252009-07-17 12:17:14 -07001859bool AudioFlinger::MixerThread::threadLoop()
1860{
Eric Laurenta553c252009-07-17 12:17:14 -07001861 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001862 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001863 nsecs_t standbyTime = systemTime();
1864 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001865 // FIXME: Relaxed timing because of a certain device that can't meet latency
1866 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001867 // increase threshold again due to low power audio mode. The way this warning threshold is
1868 // calculated and its usefulness should be reconsidered anyway.
1869 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001870 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001871 bool longStandbyExit = false;
1872 uint32_t activeSleepTime = activeSleepTimeUs();
1873 uint32_t idleSleepTime = idleSleepTimeUs();
1874 uint32_t sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001875 uint32_t sleepTimeShift = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001876 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001877#ifdef DEBUG_CPU_USAGE
1878 ThreadCpuUsage cpu;
1879 const CentralTendencyStatistics& stats = cpu.statistics();
1880#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881
Eric Laurent6dbdc402011-07-22 09:04:31 -07001882 acquireWakeLock();
1883
Eric Laurenta553c252009-07-17 12:17:14 -07001884 while (!exitPending())
1885 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001886#ifdef DEBUG_CPU_USAGE
1887 cpu.sampleAndEnable();
1888 unsigned n = stats.n();
1889 // cpu.elapsed() is expensive, so don't call it every loop
1890 if ((n & 127) == 1) {
1891 long long elapsed = cpu.elapsed();
1892 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1893 double perLoop = elapsed / (double) n;
1894 double perLoop100 = perLoop * 0.01;
1895 double mean = stats.mean();
1896 double stddev = stats.stddev();
1897 double minimum = stats.minimum();
1898 double maximum = stats.maximum();
1899 cpu.resetStatistics();
1900 LOGI("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",
1901 elapsed * .000000001, n, perLoop * .000001,
1902 mean * .001,
1903 stddev * .001,
1904 minimum * .001,
1905 maximum * .001,
1906 mean / perLoop100,
1907 stddev / perLoop100,
1908 minimum / perLoop100,
1909 maximum / perLoop100);
1910 }
1911 }
1912#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001913 processConfigEvents();
1914
Eric Laurent059b4be2009-11-09 23:32:22 -08001915 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001916 { // scope for mLock
1917
1918 Mutex::Autolock _l(mLock);
1919
1920 if (checkForNewParameters_l()) {
1921 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001922 // FIXME: Relaxed timing because of a certain device that can't meet latency
1923 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001924 // increase threshold again due to low power audio mode. The way this warning
1925 // threshold is calculated and its usefulness should be reconsidered anyway.
1926 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001927 activeSleepTime = activeSleepTimeUs();
1928 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001929 }
1930
1931 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1932
1933 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001934 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1935 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07001936 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01001937 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001938 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001939 mStandby = true;
1940 mBytesWritten = 0;
1941 }
1942
1943 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1944 // we're about to wait, flush the binder command buffer
1945 IPCThreadState::self()->flushCommands();
1946
1947 if (exitPending()) break;
1948
Eric Laurent6dbdc402011-07-22 09:04:31 -07001949 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001950 // wait until we have something to do...
Steve Block71f2cf12011-10-20 11:56:00 +01001951 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07001952 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01001953 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001954 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001955
1956 if (mMasterMute == false) {
1957 char value[PROPERTY_VALUE_MAX];
1958 property_get("ro.audio.silent", value, "0");
1959 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00001960 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07001961 setMasterMute(true);
1962 }
1963 }
1964
1965 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001966 sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001967 sleepTimeShift = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001968 continue;
1969 }
1970 }
1971
Eric Laurent059b4be2009-11-09 23:32:22 -08001972 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001973
1974 // prevent any changes in effect chain list and in each effect chain
1975 // during mixing and effect process as the audio buffers could be deleted
1976 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001977 lockEffectChains_l(effectChains);
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08001978 }
Eric Laurenta553c252009-07-17 12:17:14 -07001979
Glenn Kastene80a4cc2011-12-15 09:51:17 -08001980 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001981 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001982 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001983 sleepTime = 0;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001984 // increase sleep time progressively when application underrun condition clears
1985 if (sleepTimeShift > 0) {
1986 sleepTimeShift--;
1987 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07001988 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001989 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001990 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001991 // If no tracks are ready, sleep once for the duration of an output
1992 // buffer size, then write 0s to the output
1993 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001994 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001995 sleepTime = activeSleepTime >> sleepTimeShift;
1996 if (sleepTime < kMinThreadSleepTimeUs) {
1997 sleepTime = kMinThreadSleepTimeUs;
1998 }
1999 // reduce sleep time in case of consecutive application underruns to avoid
2000 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2001 // duration we would end up writing less data than needed by the audio HAL if
2002 // the condition persists.
2003 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2004 sleepTimeShift++;
2005 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002006 } else {
2007 sleepTime = idleSleepTime;
2008 }
2009 } else if (mBytesWritten != 0 ||
2010 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002011 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002012 sleepTime = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01002013 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07002014 }
Eric Laurent65b65452010-06-01 23:49:17 -07002015 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07002016 }
2017
2018 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002019 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002020 }
2021 // sleepTime == 0 means we must write to audio hardware
2022 if (sleepTime == 0) {
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08002023 for (size_t i = 0; i < effectChains.size(); i ++) {
2024 effectChains[i]->process_l();
2025 }
2026 // enable changes in effect chain
2027 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002028 mLastWriteTime = systemTime();
2029 mInWrite = true;
2030 mBytesWritten += mixBufferSize;
2031
Dima Zavin31f188892011-04-18 16:57:27 -07002032 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002033 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002034 mNumWrites++;
2035 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002036 nsecs_t now = systemTime();
2037 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07002038 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002039 mNumDelayedWrites++;
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002040 if ((now - lastWarning) > kWarningThrottleNs) {
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002041 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2042 ns2ms(delta), mNumDelayedWrites, this);
2043 lastWarning = now;
2044 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002045 if (mStandby) {
2046 longStandbyExit = true;
2047 }
Eric Laurenta553c252009-07-17 12:17:14 -07002048 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002049 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002050 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002051 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002052 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002053 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002054 }
2055
2056 // finally let go of all our tracks, without the lock held
2057 // since we can't guarantee the destructors won't acquire that
2058 // same lock.
2059 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002060
2061 // Effect chains will be actually deleted here if they were removed from
2062 // mEffectChains list during mixing or effects processing
2063 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002064 }
2065
2066 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002067 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002068 }
Eric Laurenta553c252009-07-17 12:17:14 -07002069
Eric Laurent6dbdc402011-07-22 09:04:31 -07002070 releaseWakeLock();
2071
Steve Block71f2cf12011-10-20 11:56:00 +01002072 ALOGV("MixerThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002073 return false;
2074}
2075
2076// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08002077uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002078{
2079
Eric Laurent059b4be2009-11-09 23:32:22 -08002080 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002081 // find out which tracks need to be processed
2082 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002083 size_t mixedTracks = 0;
2084 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002085
2086 float masterVolume = mMasterVolume;
2087 bool masterMute = mMasterMute;
2088
Eric Laurent8cc93b92010-08-11 05:20:11 -07002089 if (masterMute) {
2090 masterVolume = 0;
2091 }
Eric Laurent65b65452010-06-01 23:49:17 -07002092 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002093 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002094 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002095 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002096 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002097 masterVolume = (float)((v + (1 << 23)) >> 24);
2098 chain.clear();
2099 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002100
Eric Laurenta553c252009-07-17 12:17:14 -07002101 for (size_t i=0 ; i<count ; i++) {
2102 sp<Track> t = activeTracks[i].promote();
2103 if (t == 0) continue;
2104
2105 Track* const track = t.get();
2106 audio_track_cblk_t* cblk = track->cblk();
2107
2108 // The first time a track is added we wait
2109 // for all its buffers to be filled before processing it
2110 mAudioMixer->setActiveTrack(track->name());
Eric Laurent8a04fe02011-11-08 18:10:16 -08002111 // make sure that we have enough frames to mix one full buffer.
2112 // enforce this condition only once to enable draining the buffer in case the client
2113 // app does not call stop() and relies on underrun to stop:
2114 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2115 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002116 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002117 if (!track->isStopped() && !track->isPausing() &&
2118 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002119 if (t->sampleRate() == (int)mSampleRate) {
2120 minFrames = mFrameCount;
2121 } else {
Eric Laurent72dafb22011-12-22 16:08:41 -08002122 // +1 for rounding and +1 for additional sample needed for interpolation
2123 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2124 // add frames already consumed but not yet released by the resampler
2125 // because cblk->framesReady() will include these frames
2126 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2127 // the minimum track buffer size is normally twice the number of frames necessary
2128 // to fill one buffer and the resampler should not leave more than one buffer worth
2129 // of unreleased frames after each pass, but just in case...
2130 LOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002131 }
2132 }
2133 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002134 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002135 {
Steve Block71f2cf12011-10-20 11:56:00 +01002136 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002137
Eric Laurent65b65452010-06-01 23:49:17 -07002138 mixedTracks++;
2139
2140 // track->mainBuffer() != mMixBuffer means there is an effect chain
2141 // connected to the track
2142 chain.clear();
2143 if (track->mainBuffer() != mMixBuffer) {
2144 chain = getEffectChain_l(track->sessionId());
2145 // Delegate volume control to effect in track effect chain if needed
2146 if (chain != 0) {
2147 tracksWithEffect++;
2148 } else {
2149 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2150 track->name(), track->sessionId());
2151 }
2152 }
2153
2154
2155 int param = AudioMixer::VOLUME;
2156 if (track->mFillingUpStatus == Track::FS_FILLED) {
2157 // no ramp for the first volume setting
2158 track->mFillingUpStatus = Track::FS_ACTIVE;
2159 if (track->mState == TrackBase::RESUMING) {
2160 track->mState = TrackBase::ACTIVE;
2161 param = AudioMixer::RAMP_VOLUME;
2162 }
Eric Laurent4bb21c42011-02-28 16:52:51 -08002163 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002164 } else if (cblk->server != 0) {
2165 // If the track is stopped before the first frame was mixed,
2166 // do not apply ramp
2167 param = AudioMixer::RAMP_VOLUME;
2168 }
2169
Eric Laurenta553c252009-07-17 12:17:14 -07002170 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002171 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002172 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002173 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002174 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002175 if (track->isPausing()) {
2176 track->setPaused();
2177 }
2178 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002179
Glenn Kasten871c16c2010-03-05 12:18:01 -08002180 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002181 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002182 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002183 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2184 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07002185
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002186 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002187 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002188 // Delegate volume control to effect in track effect chain if needed
2189 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2190 // Do not ramp volume if volume is controlled by effect
2191 param = AudioMixer::VOLUME;
2192 track->mHasVolumeController = true;
2193 } else {
2194 // force no volume ramp when volume controller was just disabled or removed
2195 // from effect chain to avoid volume spike
2196 if (track->mHasVolumeController) {
2197 param = AudioMixer::VOLUME;
2198 }
2199 track->mHasVolumeController = false;
2200 }
2201
2202 // Convert volumes from 8.24 to 4.12 format
2203 int16_t left, right, aux;
2204 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2205 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2206 left = int16_t(v_clamped);
2207 v_clamped = (vr + (1 << 11)) >> 12;
2208 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2209 right = int16_t(v_clamped);
2210
2211 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2212 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002213
Eric Laurent65b65452010-06-01 23:49:17 -07002214 // XXX: these things DON'T need to be done each time
2215 mAudioMixer->setBufferProvider(track);
Glenn Kastenaf62dbc2011-12-15 14:54:01 -08002216 mAudioMixer->enable();
Eric Laurent65b65452010-06-01 23:49:17 -07002217
2218 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2219 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2220 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002221 mAudioMixer->setParameter(
2222 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002223 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002224 mAudioMixer->setParameter(
2225 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002226 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002227 mAudioMixer->setParameter(
2228 AudioMixer::RESAMPLE,
2229 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002230 (void *)(cblk->sampleRate));
2231 mAudioMixer->setParameter(
2232 AudioMixer::TRACK,
2233 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2234 mAudioMixer->setParameter(
2235 AudioMixer::TRACK,
2236 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002237
2238 // reset retry count
2239 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08002240 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002241 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002242 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07002243 if (track->isStopped()) {
2244 track->reset();
2245 }
2246 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2247 // We have consumed all the buffers of this track.
2248 // Remove it from the list of active tracks.
2249 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002250 } else {
2251 // No buffers for this track. Give it a few chances to
2252 // fill a buffer, then remove it from active list.
2253 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002254 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07002255 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002256 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002257 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -08002258 } else if (mixerStatus != MIXER_TRACKS_READY) {
2259 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002260 }
Eric Laurenta553c252009-07-17 12:17:14 -07002261 }
Glenn Kastenaf62dbc2011-12-15 14:54:01 -08002262 mAudioMixer->disable();
Eric Laurenta553c252009-07-17 12:17:14 -07002263 }
2264 }
2265
2266 // remove all the tracks that need to be...
2267 count = tracksToRemove->size();
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002268 if (CC_UNLIKELY(count)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002269 for (size_t i=0 ; i<count ; i++) {
2270 const sp<Track>& track = tracksToRemove->itemAt(i);
2271 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002272 if (track->mainBuffer() != mMixBuffer) {
2273 chain = getEffectChain_l(track->sessionId());
2274 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002275 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002276 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002277 }
2278 }
Eric Laurenta553c252009-07-17 12:17:14 -07002279 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002280 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002281 }
2282 }
2283 }
2284
Eric Laurent65b65452010-06-01 23:49:17 -07002285 // mix buffer must be cleared if all tracks are connected to an
2286 // effect chain as in this case the mixer will not write to
2287 // mix buffer and track effects will accumulate into it
2288 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2289 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2290 }
2291
Eric Laurent059b4be2009-11-09 23:32:22 -08002292 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002293}
2294
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002295void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002296{
Steve Block71f2cf12011-10-20 11:56:00 +01002297 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002298 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002299 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002300
Eric Laurenta553c252009-07-17 12:17:14 -07002301 size_t size = mTracks.size();
2302 for (size_t i = 0; i < size; i++) {
2303 sp<Track> t = mTracks[i];
2304 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002305 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002306 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002307 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002308 }
2309}
Eric Laurenta553c252009-07-17 12:17:14 -07002310
Eric Laurent05ce0942011-08-30 10:18:54 -07002311void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2312{
Steve Block71f2cf12011-10-20 11:56:00 +01002313 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002314 this, streamType, valid);
2315 Mutex::Autolock _l(mLock);
2316
2317 mStreamTypes[streamType].valid = valid;
2318}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319
Eric Laurenta553c252009-07-17 12:17:14 -07002320// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002321int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322{
2323 return mAudioMixer->getTrackName();
2324}
2325
Eric Laurenta553c252009-07-17 12:17:14 -07002326// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002327void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328{
Steve Block71f2cf12011-10-20 11:56:00 +01002329 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 mAudioMixer->deleteTrackName(name);
2331}
2332
Eric Laurenta553c252009-07-17 12:17:14 -07002333// checkForNewParameters_l() must be called with ThreadBase::mLock held
2334bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335{
Eric Laurenta553c252009-07-17 12:17:14 -07002336 bool reconfig = false;
2337
Eric Laurent8fce46a2009-08-04 09:45:33 -07002338 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002339 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002340 String8 keyValuePair = mNewParameters[0];
2341 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002342 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002343
Eric Laurenta553c252009-07-17 12:17:14 -07002344 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2345 reconfig = true;
2346 }
2347 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002348 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002349 status = BAD_VALUE;
2350 } else {
2351 reconfig = true;
2352 }
2353 }
2354 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002355 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002356 status = BAD_VALUE;
2357 } else {
2358 reconfig = true;
2359 }
2360 }
2361 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2362 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastene5fb2632011-12-14 10:28:06 -08002363 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07002364 // if frame count is changed after track creation
2365 if (!mTracks.isEmpty()) {
2366 status = INVALID_OPERATION;
2367 } else {
2368 reconfig = true;
2369 }
2370 }
Eric Laurent65b65452010-06-01 23:49:17 -07002371 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002372 // when changing the audio output device, call addBatteryData to notify
2373 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002374 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002375 uint32_t params = 0;
2376 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002377 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002378 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2379 }
2380
2381 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002382 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002383 // check if any other device (except speaker) is on
2384 if (value & deviceWithoutSpeaker ) {
2385 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2386 }
2387
2388 if (params != 0) {
2389 addBatteryData(params);
2390 }
2391 }
2392
Eric Laurent65b65452010-06-01 23:49:17 -07002393 // forward device change to effects that have requested to be
2394 // aware of attached audio device.
2395 mDevice = (uint32_t)value;
2396 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002397 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002398 }
2399 }
2400
Eric Laurenta553c252009-07-17 12:17:14 -07002401 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002402 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002403 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002404 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002405 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002406 mStandby = true;
2407 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002408 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002409 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002410 }
2411 if (status == NO_ERROR && reconfig) {
2412 delete mAudioMixer;
2413 readOutputParameters();
2414 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2415 for (size_t i = 0; i < mTracks.size() ; i++) {
2416 int name = getTrackName_l();
2417 if (name < 0) break;
2418 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002419 // limit track sample rate to 2 x new output sample rate
2420 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2421 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2422 }
Eric Laurenta553c252009-07-17 12:17:14 -07002423 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002424 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002425 }
2426 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002427
2428 mNewParameters.removeAt(0);
2429
Eric Laurenta553c252009-07-17 12:17:14 -07002430 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002431 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002432 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2433 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002434 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002435 }
2436 return reconfig;
2437}
2438
2439status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2440{
2441 const size_t SIZE = 256;
2442 char buffer[SIZE];
2443 String8 result;
2444
2445 PlaybackThread::dumpInternals(fd, args);
2446
2447 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2448 result.append(buffer);
2449 write(fd, result.string(), result.size());
2450 return NO_ERROR;
2451}
2452
Eric Laurent059b4be2009-11-09 23:32:22 -08002453uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2454{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002455 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002456}
2457
Eric Laurent8448a792010-08-18 18:13:17 -07002458uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2459{
2460 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2461}
2462
Eric Laurenta553c252009-07-17 12:17:14 -07002463// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002464AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002465 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002466{
Eric Laurent464d5b32011-06-17 21:29:58 -07002467 mType = ThreadBase::DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -07002468}
2469
2470AudioFlinger::DirectOutputThread::~DirectOutputThread()
2471{
2472}
2473
Eric Laurent65b65452010-06-01 23:49:17 -07002474static inline
2475int32_t mul(int16_t in, int16_t v)
2476{
2477#if defined(__arm__) && !defined(__thumb__)
2478 int32_t out;
2479 asm( "smulbb %[out], %[in], %[v] \n"
2480 : [out]"=r"(out)
2481 : [in]"%r"(in), [v]"r"(v)
2482 : );
2483 return out;
2484#else
2485 return in * int32_t(v);
2486#endif
2487}
2488
2489void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2490{
2491 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002492 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002493 return;
2494 }
2495
2496 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002497 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002498 size_t count = mFrameCount * mChannelCount;
2499 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2500 int16_t *dst = mMixBuffer + count-1;
2501 while(count--) {
2502 *dst-- = (int16_t)(*src--^0x80) << 8;
2503 }
2504 }
2505
2506 size_t frameCount = mFrameCount;
2507 int16_t *out = mMixBuffer;
2508 if (ramp) {
2509 if (mChannelCount == 1) {
2510 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2511 int32_t vlInc = d / (int32_t)frameCount;
2512 int32_t vl = ((int32_t)mLeftVolShort << 16);
2513 do {
2514 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2515 out++;
2516 vl += vlInc;
2517 } while (--frameCount);
2518
2519 } else {
2520 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2521 int32_t vlInc = d / (int32_t)frameCount;
2522 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2523 int32_t vrInc = d / (int32_t)frameCount;
2524 int32_t vl = ((int32_t)mLeftVolShort << 16);
2525 int32_t vr = ((int32_t)mRightVolShort << 16);
2526 do {
2527 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2528 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2529 out += 2;
2530 vl += vlInc;
2531 vr += vrInc;
2532 } while (--frameCount);
2533 }
2534 } else {
2535 if (mChannelCount == 1) {
2536 do {
2537 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2538 out++;
2539 } while (--frameCount);
2540 } else {
2541 do {
2542 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2543 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2544 out += 2;
2545 } while (--frameCount);
2546 }
2547 }
2548
2549 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002550 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002551 size_t count = mFrameCount * mChannelCount;
2552 int16_t *src = mMixBuffer;
2553 uint8_t *dst = (uint8_t *)mMixBuffer;
2554 while(count--) {
2555 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2556 }
2557 }
2558
2559 mLeftVolShort = leftVol;
2560 mRightVolShort = rightVol;
2561}
2562
Eric Laurenta553c252009-07-17 12:17:14 -07002563bool AudioFlinger::DirectOutputThread::threadLoop()
2564{
Eric Laurent059b4be2009-11-09 23:32:22 -08002565 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002566 sp<Track> trackToRemove;
2567 sp<Track> activeTrack;
2568 nsecs_t standbyTime = systemTime();
2569 int8_t *curBuf;
2570 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002571 uint32_t activeSleepTime = activeSleepTimeUs();
2572 uint32_t idleSleepTime = idleSleepTimeUs();
2573 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002574 // use shorter standby delay as on normal output to release
2575 // hardware resources as soon as possible
2576 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002577
Eric Laurent6dbdc402011-07-22 09:04:31 -07002578 acquireWakeLock();
2579
Eric Laurenta553c252009-07-17 12:17:14 -07002580 while (!exitPending())
2581 {
Eric Laurent65b65452010-06-01 23:49:17 -07002582 bool rampVolume;
2583 uint16_t leftVol;
2584 uint16_t rightVol;
2585 Vector< sp<EffectChain> > effectChains;
2586
Eric Laurenta553c252009-07-17 12:17:14 -07002587 processConfigEvents();
2588
Eric Laurent059b4be2009-11-09 23:32:22 -08002589 mixerStatus = MIXER_IDLE;
2590
Eric Laurenta553c252009-07-17 12:17:14 -07002591 { // scope for the mLock
2592
2593 Mutex::Autolock _l(mLock);
2594
2595 if (checkForNewParameters_l()) {
2596 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002597 activeSleepTime = activeSleepTimeUs();
2598 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002599 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002600 }
2601
2602 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002603 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2604 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002605 // wait until we have something to do...
2606 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01002607 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002608 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002609 mStandby = true;
2610 mBytesWritten = 0;
2611 }
2612
2613 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2614 // we're about to wait, flush the binder command buffer
2615 IPCThreadState::self()->flushCommands();
2616
2617 if (exitPending()) break;
2618
Eric Laurent6dbdc402011-07-22 09:04:31 -07002619 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002620 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002621 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002622 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002623 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002624
2625 if (mMasterMute == false) {
2626 char value[PROPERTY_VALUE_MAX];
2627 property_get("ro.audio.silent", value, "0");
2628 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00002629 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07002630 setMasterMute(true);
2631 }
2632 }
2633
Eric Laurentef9500f2010-03-11 14:47:00 -08002634 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002635 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002636 continue;
2637 }
2638 }
2639
Eric Laurent65b65452010-06-01 23:49:17 -07002640 effectChains = mEffectChains;
2641
Eric Laurenta553c252009-07-17 12:17:14 -07002642 // find out which tracks need to be processed
2643 if (mActiveTracks.size() != 0) {
2644 sp<Track> t = mActiveTracks[0].promote();
2645 if (t == 0) continue;
2646
2647 Track* const track = t.get();
2648 audio_track_cblk_t* cblk = track->cblk();
2649
2650 // The first time a track is added we wait
2651 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002652 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002653 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002654 {
Steve Block71f2cf12011-10-20 11:56:00 +01002655 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002656
Eric Laurent65b65452010-06-01 23:49:17 -07002657 if (track->mFillingUpStatus == Track::FS_FILLED) {
2658 track->mFillingUpStatus = Track::FS_ACTIVE;
2659 mLeftVolFloat = mRightVolFloat = 0;
2660 mLeftVolShort = mRightVolShort = 0;
2661 if (track->mState == TrackBase::RESUMING) {
2662 track->mState = TrackBase::ACTIVE;
2663 rampVolume = true;
2664 }
2665 } else if (cblk->server != 0) {
2666 // If the track is stopped before the first frame was mixed,
2667 // do not apply ramp
2668 rampVolume = true;
2669 }
Eric Laurenta553c252009-07-17 12:17:14 -07002670 // compute volume for this track
2671 float left, right;
2672 if (track->isMuted() || mMasterMute || track->isPausing() ||
2673 mStreamTypes[track->type()].mute) {
2674 left = right = 0;
2675 if (track->isPausing()) {
2676 track->setPaused();
2677 }
2678 } else {
2679 float typeVolume = mStreamTypes[track->type()].volume;
2680 float v = mMasterVolume * typeVolume;
2681 float v_clamped = v * cblk->volume[0];
2682 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2683 left = v_clamped/MAX_GAIN;
2684 v_clamped = v * cblk->volume[1];
2685 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2686 right = v_clamped/MAX_GAIN;
2687 }
2688
Eric Laurent65b65452010-06-01 23:49:17 -07002689 if (left != mLeftVolFloat || right != mRightVolFloat) {
2690 mLeftVolFloat = left;
2691 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002692
Eric Laurent65b65452010-06-01 23:49:17 -07002693 // If audio HAL implements volume control,
2694 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002695 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002696 left = 1.0f;
2697 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002698 }
Eric Laurent65b65452010-06-01 23:49:17 -07002699
2700 // Convert volumes from float to 8.24
2701 uint32_t vl = (uint32_t)(left * (1 << 24));
2702 uint32_t vr = (uint32_t)(right * (1 << 24));
2703
2704 // Delegate volume control to effect in track effect chain if needed
2705 // only one effect chain can be present on DirectOutputThread, so if
2706 // there is one, the track is connected to it
2707 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002708 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002709 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002710 rampVolume = false;
2711 }
2712 }
2713
2714 // Convert volumes from 8.24 to 4.12 format
2715 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2716 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2717 leftVol = (uint16_t)v_clamped;
2718 v_clamped = (vr + (1 << 11)) >> 12;
2719 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2720 rightVol = (uint16_t)v_clamped;
2721 } else {
2722 leftVol = mLeftVolShort;
2723 rightVol = mRightVolShort;
2724 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002725 }
2726
2727 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002728 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002729 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002730 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002731 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002732 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002733 if (track->isStopped()) {
2734 track->reset();
2735 }
2736 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2737 // We have consumed all the buffers of this track.
2738 // Remove it from the list of active tracks.
2739 trackToRemove = track;
2740 } else {
2741 // No buffers for this track. Give it a few chances to
2742 // fill a buffer, then remove it from active list.
2743 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002744 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurenta553c252009-07-17 12:17:14 -07002745 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002746 } else {
2747 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002748 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002749 }
Eric Laurenta553c252009-07-17 12:17:14 -07002750 }
2751 }
2752
2753 // remove all the tracks that need to be...
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002754 if (CC_UNLIKELY(trackToRemove != 0)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002755 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002756 if (!effectChains.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01002757 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002758 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002759 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002760 }
Eric Laurenta553c252009-07-17 12:17:14 -07002761 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002762 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002763 }
2764 }
Eric Laurent65b65452010-06-01 23:49:17 -07002765
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002766 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002767 }
2768
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002769 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002770 AudioBufferProvider::Buffer buffer;
2771 size_t frameCount = mFrameCount;
2772 curBuf = (int8_t *)mMixBuffer;
2773 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002774 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002775 buffer.frameCount = frameCount;
2776 activeTrack->getNextBuffer(&buffer);
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002777 if (CC_UNLIKELY(buffer.raw == NULL)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002778 memset(curBuf, 0, frameCount * mFrameSize);
2779 break;
2780 }
2781 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2782 frameCount -= buffer.frameCount;
2783 curBuf += buffer.frameCount * mFrameSize;
2784 activeTrack->releaseBuffer(&buffer);
2785 }
2786 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002787 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002788 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002789 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002790 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2791 sleepTime = activeSleepTime;
2792 } else {
2793 sleepTime = idleSleepTime;
2794 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002795 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002796 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002797 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002798 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002799 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002800
Eric Laurentf69a3f82009-09-22 00:35:48 -07002801 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002802 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002803 }
2804 // sleepTime == 0 means we must write to audio hardware
2805 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002806 if (mixerStatus == MIXER_TRACKS_READY) {
2807 applyVolume(leftVol, rightVol, rampVolume);
2808 }
2809 for (size_t i = 0; i < effectChains.size(); i ++) {
2810 effectChains[i]->process_l();
2811 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002812 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002813
Eric Laurentf69a3f82009-09-22 00:35:48 -07002814 mLastWriteTime = systemTime();
2815 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002816 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002817 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002818 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002819 mNumWrites++;
2820 mInWrite = false;
2821 mStandby = false;
2822 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002823 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002824 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002825 }
2826
2827 // finally let go of removed track, without the lock held
2828 // since we can't guarantee the destructors won't acquire that
2829 // same lock.
2830 trackToRemove.clear();
2831 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002832
2833 // Effect chains will be actually deleted here if they were removed from
2834 // mEffectChains list during mixing or effects processing
2835 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002836 }
2837
2838 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002839 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002840 }
Eric Laurenta553c252009-07-17 12:17:14 -07002841
Eric Laurent6dbdc402011-07-22 09:04:31 -07002842 releaseWakeLock();
2843
Steve Block71f2cf12011-10-20 11:56:00 +01002844 ALOGV("DirectOutputThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002845 return false;
2846}
2847
2848// getTrackName_l() must be called with ThreadBase::mLock held
2849int AudioFlinger::DirectOutputThread::getTrackName_l()
2850{
2851 return 0;
2852}
2853
2854// deleteTrackName_l() must be called with ThreadBase::mLock held
2855void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2856{
2857}
2858
2859// checkForNewParameters_l() must be called with ThreadBase::mLock held
2860bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2861{
2862 bool reconfig = false;
2863
Eric Laurent8fce46a2009-08-04 09:45:33 -07002864 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002865 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002866 String8 keyValuePair = mNewParameters[0];
2867 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002868 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002869
Eric Laurenta553c252009-07-17 12:17:14 -07002870 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2871 // do not accept frame count changes if tracks are open as the track buffer
2872 // size depends on frame count and correct behavior would not be garantied
2873 // if frame count is changed after track creation
2874 if (!mTracks.isEmpty()) {
2875 status = INVALID_OPERATION;
2876 } else {
2877 reconfig = true;
2878 }
2879 }
2880 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002881 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002882 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002883 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002884 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002885 mStandby = true;
2886 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002887 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002888 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002889 }
2890 if (status == NO_ERROR && reconfig) {
2891 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002892 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002893 }
2894 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002895
2896 mNewParameters.removeAt(0);
2897
Eric Laurenta553c252009-07-17 12:17:14 -07002898 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002899 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002900 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2901 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002902 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002903 }
2904 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002905}
2906
Eric Laurent059b4be2009-11-09 23:32:22 -08002907uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002908{
2909 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002910 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08002911 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08002912 } else {
2913 time = 10000;
2914 }
2915 return time;
2916}
2917
2918uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2919{
2920 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002921 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002922 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002923 } else {
2924 time = 10000;
2925 }
2926 return time;
2927}
2928
Eric Laurent8448a792010-08-18 18:13:17 -07002929uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2930{
2931 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002932 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002933 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2934 } else {
2935 time = 10000;
2936 }
2937 return time;
2938}
2939
2940
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002941// ----------------------------------------------------------------------------
2942
Eric Laurent49f02be2009-11-19 09:00:56 -08002943AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002944 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002945{
Eric Laurent464d5b32011-06-17 21:29:58 -07002946 mType = ThreadBase::DUPLICATING;
Eric Laurenta553c252009-07-17 12:17:14 -07002947 addOutputTrack(mainThread);
2948}
2949
2950AudioFlinger::DuplicatingThread::~DuplicatingThread()
2951{
Eric Laurent0a080292009-12-07 10:53:10 -08002952 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2953 mOutputTracks[i]->destroy();
2954 }
Eric Laurenta553c252009-07-17 12:17:14 -07002955 mOutputTracks.clear();
2956}
2957
2958bool AudioFlinger::DuplicatingThread::threadLoop()
2959{
Eric Laurenta553c252009-07-17 12:17:14 -07002960 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002961 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002962 nsecs_t standbyTime = systemTime();
2963 size_t mixBufferSize = mFrameCount*mFrameSize;
2964 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002965 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002966 uint32_t activeSleepTime = activeSleepTimeUs();
2967 uint32_t idleSleepTime = idleSleepTimeUs();
2968 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002969 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002970
Eric Laurent6dbdc402011-07-22 09:04:31 -07002971 acquireWakeLock();
2972
Eric Laurenta553c252009-07-17 12:17:14 -07002973 while (!exitPending())
2974 {
2975 processConfigEvents();
2976
Eric Laurent059b4be2009-11-09 23:32:22 -08002977 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002978 { // scope for the mLock
2979
2980 Mutex::Autolock _l(mLock);
2981
2982 if (checkForNewParameters_l()) {
2983 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002984 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002985 activeSleepTime = activeSleepTimeUs();
2986 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002987 }
2988
2989 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2990
2991 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2992 outputTracks.add(mOutputTracks[i]);
2993 }
2994
2995 // put audio hardware into standby after short delay
Glenn Kastene80a4cc2011-12-15 09:51:17 -08002996 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2997 mSuspended)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002998 if (!mStandby) {
2999 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07003000 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07003001 }
3002 mStandby = true;
3003 mBytesWritten = 0;
3004 }
3005
3006 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3007 // we're about to wait, flush the binder command buffer
3008 IPCThreadState::self()->flushCommands();
3009 outputTracks.clear();
3010
3011 if (exitPending()) break;
3012
Eric Laurent6dbdc402011-07-22 09:04:31 -07003013 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01003014 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07003015 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01003016 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07003017 acquireWakeLock_l();
3018
Eric Laurenta553c252009-07-17 12:17:14 -07003019 if (mMasterMute == false) {
3020 char value[PROPERTY_VALUE_MAX];
3021 property_get("ro.audio.silent", value, "0");
3022 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00003023 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07003024 setMasterMute(true);
3025 }
3026 }
3027
3028 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08003029 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07003030 continue;
3031 }
3032 }
3033
Eric Laurent059b4be2009-11-09 23:32:22 -08003034 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07003035
3036 // prevent any changes in effect chain list and in each effect chain
3037 // during mixing and effect process as the audio buffers could be deleted
3038 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003039 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003040 }
Eric Laurenta553c252009-07-17 12:17:14 -07003041
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003042 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003043 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003044 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003045 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003046 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003047 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003048 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003049 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003050 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003051 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003052 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003053 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3054 sleepTime = activeSleepTime;
3055 } else {
3056 sleepTime = idleSleepTime;
3057 }
Eric Laurent62443f52009-10-05 20:29:18 -07003058 } else if (mBytesWritten != 0) {
3059 // flush remaining overflow buffers in output tracks
3060 for (size_t i = 0; i < outputTracks.size(); i++) {
3061 if (outputTracks[i]->isActive()) {
3062 sleepTime = 0;
3063 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003064 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003065 break;
3066 }
3067 }
Eric Laurenta553c252009-07-17 12:17:14 -07003068 }
3069 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003070
3071 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003072 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003073 }
3074 // sleepTime == 0 means we must write to audio hardware
3075 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003076 for (size_t i = 0; i < effectChains.size(); i ++) {
3077 effectChains[i]->process_l();
3078 }
3079 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003080 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003081
Eric Laurent62443f52009-10-05 20:29:18 -07003082 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003083 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003084 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003085 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003086 mStandby = false;
3087 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003088 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003089 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003090 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003091 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003092 }
3093
3094 // finally let go of all our tracks, without the lock held
3095 // since we can't guarantee the destructors won't acquire that
3096 // same lock.
3097 tracksToRemove.clear();
3098 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003099
3100 // Effect chains will be actually deleted here if they were removed from
3101 // mEffectChains list during mixing or effects processing
3102 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003103 }
3104
Eric Laurent6dbdc402011-07-22 09:04:31 -07003105 releaseWakeLock();
3106
Eric Laurenta553c252009-07-17 12:17:14 -07003107 return false;
3108}
3109
3110void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3111{
3112 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3113 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003114 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003115 mSampleRate,
3116 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003117 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003118 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003119 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003120 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003121 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003122 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003123 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003124 }
Eric Laurenta553c252009-07-17 12:17:14 -07003125}
3126
3127void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3128{
3129 Mutex::Autolock _l(mLock);
3130 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3131 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003132 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003133 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003134 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003135 return;
3136 }
3137 }
Steve Block71f2cf12011-10-20 11:56:00 +01003138 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003139}
3140
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003141void AudioFlinger::DuplicatingThread::updateWaitTime()
3142{
3143 mWaitTimeMs = UINT_MAX;
3144 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3145 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3146 if (strong != NULL) {
3147 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3148 if (waitTimeMs < mWaitTimeMs) {
3149 mWaitTimeMs = waitTimeMs;
3150 }
3151 }
3152 }
3153}
3154
3155
3156bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3157{
3158 for (size_t i = 0; i < outputTracks.size(); i++) {
3159 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3160 if (thread == 0) {
3161 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3162 return false;
3163 }
3164 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3165 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003166 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003167 return false;
3168 }
3169 }
3170 return true;
3171}
3172
3173uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3174{
3175 return (mWaitTimeMs * 1000) / 2;
3176}
3177
Eric Laurenta553c252009-07-17 12:17:14 -07003178// ----------------------------------------------------------------------------
3179
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003180// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003181AudioFlinger::ThreadBase::TrackBase::TrackBase(
3182 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003183 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003184 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003185 uint32_t format,
3186 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003187 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003189 const sp<IMemory>& sharedBuffer,
3190 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003191 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003192 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003193 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07003194 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003195 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003196 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003197 mClientTid(-1),
3198 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003199 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3200 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003201{
Steve Block71f2cf12011-10-20 11:56:00 +01003202 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003203
Steve Block5baa3a62011-12-20 16:23:08 +00003204 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003205 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003206 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003207 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3208 if (sharedBuffer == 0) {
3209 size += bufferSize;
3210 }
3211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 if (client != NULL) {
3213 mCblkMemory = client->heap()->allocate(size);
3214 if (mCblkMemory != 0) {
3215 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3216 if (mCblk) { // construct the shared structure in-place.
3217 new(mCblk) audio_track_cblk_t();
3218 // clear all buffers
3219 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003220 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003221 mChannelCount = channelCount;
3222 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 if (sharedBuffer == 0) {
3224 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3225 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3226 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003227 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003228 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 } else {
3230 mBuffer = sharedBuffer->pointer();
3231 }
3232 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 } else {
3235 LOGE("not enough memory for AudioTrack size=%u", size);
3236 client->heap()->dump("AudioTrack");
3237 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 } else {
3240 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3241 if (mCblk) { // construct the shared structure in-place.
3242 new(mCblk) audio_track_cblk_t();
3243 // clear all buffers
3244 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003245 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003246 mChannelCount = channelCount;
3247 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3249 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3250 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003251 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003252 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3254 }
3255 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003256}
3257
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003258AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003259{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07003261 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3262 if (mClient == NULL) {
3263 delete mCblk;
3264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003266 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07003267 if (mClient != NULL) {
3268 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3269 mClient.clear();
3270 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003271}
3272
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003273void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003274{
Glenn Kastenc434c902011-12-13 11:53:26 -08003275 buffer->raw = NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003276 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003277 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003278 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003279}
3280
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003281bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003282 bool result;
3283 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003284
3285 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003286 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003287 ALOGV("stepServer failed acquiring cblk mutex");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003288 mFlags |= STEPSERVER_FAILED;
3289 }
3290 return result;
3291}
3292
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003293void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003294 audio_track_cblk_t* cblk = this->cblk();
3295
3296 cblk->user = 0;
3297 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003298 cblk->userBase = 0;
3299 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block71f2cf12011-10-20 11:56:00 +01003301 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003302}
3303
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003304sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003305{
3306 return mCblkMemory;
3307}
3308
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003309int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003310 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003311}
3312
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003313int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003314 return (const int)mChannelCount;
3315}
3316
3317uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3318 return mChannelMask;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003319}
3320
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003321void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003322 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07003323 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3324 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003325
3326 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003327 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3328 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07003329 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003330 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003331 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003332 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003333 return 0;
3334 }
3335
3336 return bufferStart;
3337}
3338
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003339// ----------------------------------------------------------------------------
3340
Eric Laurenta553c252009-07-17 12:17:14 -07003341// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3342AudioFlinger::PlaybackThread::Track::Track(
3343 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003344 const sp<Client>& client,
3345 int streamType,
3346 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003347 uint32_t format,
3348 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003349 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003350 const sp<IMemory>& sharedBuffer,
3351 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003352 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003353 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3354 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003355{
Eric Laurent8a77a992009-09-09 05:16:08 -07003356 if (mCblk != NULL) {
3357 sp<ThreadBase> baseThread = thread.promote();
3358 if (baseThread != 0) {
3359 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3360 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003361 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003362 }
Steve Block71f2cf12011-10-20 11:56:00 +01003363 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003364 if (mName < 0) {
3365 LOGE("no more track names available");
3366 }
3367 mVolume[0] = 1.0f;
3368 mVolume[1] = 1.0f;
3369 mStreamType = streamType;
3370 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3371 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003372 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003373 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003374}
3375
Eric Laurenta553c252009-07-17 12:17:14 -07003376AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003377{
Steve Block71f2cf12011-10-20 11:56:00 +01003378 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003379 sp<ThreadBase> thread = mThread.promote();
3380 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003381 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003382 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003383 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003384}
3385
Eric Laurenta553c252009-07-17 12:17:14 -07003386void AudioFlinger::PlaybackThread::Track::destroy()
3387{
3388 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3389 // by removing it from mTracks vector, so there is a risk that this Tracks's
3390 // desctructor is called. As the destructor needs to lock mLock,
3391 // we must acquire a strong reference on this Track before locking mLock
3392 // here so that the destructor is called only when exiting this function.
3393 // On the other hand, as long as Track::destroy() is only called by
3394 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3395 // this Track with its member mTrack.
3396 sp<Track> keep(this);
3397 { // scope for mLock
3398 sp<ThreadBase> thread = mThread.promote();
3399 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003400 if (!isOutputTrack()) {
3401 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003402 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003403 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003404 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003405
3406 // to track the speaker usage
3407 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003408 }
3409 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003410 }
Eric Laurenta553c252009-07-17 12:17:14 -07003411 Mutex::Autolock _l(thread->mLock);
3412 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3413 playbackThread->destroyTrack_l(this);
3414 }
3415 }
3416}
3417
3418void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003419{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003420 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 -07003421 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003423 mStreamType,
3424 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003425 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003426 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003427 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003428 mState,
3429 mMute,
3430 mFillingUpStatus,
3431 mCblk->sampleRate,
3432 mCblk->volume[0],
3433 mCblk->volume[1],
3434 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003435 mCblk->user,
3436 (int)mMainBuffer,
3437 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003438}
3439
Eric Laurenta553c252009-07-17 12:17:14 -07003440status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003441{
3442 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003443 uint32_t framesReady;
3444 uint32_t framesReq = buffer->frameCount;
3445
3446 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003447 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3448 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003449 ALOGV("stepServer recovered");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003450 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3451 }
3452
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003453 framesReady = cblk->framesReady();
3454
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003455 if (CC_LIKELY(framesReady)) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003456 uint32_t s = cblk->server;
3457 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3458
3459 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3460 if (framesReq > framesReady) {
3461 framesReq = framesReady;
3462 }
3463 if (s + framesReq > bufferEnd) {
3464 framesReq = bufferEnd - s;
3465 }
3466
3467 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003468 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003469
3470 buffer->frameCount = framesReq;
3471 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003472 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003473
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003474getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003475 buffer->raw = NULL;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003476 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003477 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 -07003478 return NOT_ENOUGH_DATA;
3479}
3480
Eric Laurenta553c252009-07-17 12:17:14 -07003481bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003482 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003483
3484 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003485 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003486 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003487 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003488 return true;
3489 }
3490 return false;
3491}
3492
Eric Laurenta553c252009-07-17 12:17:14 -07003493status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003494{
Eric Laurent49f02be2009-11-19 09:00:56 -08003495 status_t status = NO_ERROR;
Steve Block71f2cf12011-10-20 11:56:00 +01003496 ALOGV("start(%d), calling thread %d session %d",
Eric Laurent0d7e0482010-07-19 06:24:46 -07003497 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003498 sp<ThreadBase> thread = mThread.promote();
3499 if (thread != 0) {
3500 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003501 int state = mState;
3502 // here the track could be either new, or restarted
3503 // in both cases "unstop" the track
3504 if (mState == PAUSED) {
3505 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003506 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003507 } else {
3508 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003509 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003510 }
3511
3512 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3513 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003514 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003515 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003516 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003517 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003518
3519 // to track the speaker usage
3520 if (status == NO_ERROR) {
3521 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3522 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003523 }
3524 if (status == NO_ERROR) {
3525 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3526 playbackThread->addTrack_l(this);
3527 } else {
3528 mState = state;
3529 }
3530 } else {
3531 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003532 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003533 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003534}
3535
Eric Laurenta553c252009-07-17 12:17:14 -07003536void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003537{
Steve Block71f2cf12011-10-20 11:56:00 +01003538 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003539 sp<ThreadBase> thread = mThread.promote();
3540 if (thread != 0) {
3541 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003542 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003543 if (mState > STOPPED) {
3544 mState = STOPPED;
3545 // If the track is not active (PAUSED and buffers full), flush buffers
3546 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3547 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3548 reset();
3549 }
Steve Block71f2cf12011-10-20 11:56:00 +01003550 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003551 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003552 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3553 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003554 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003555 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003556 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003557 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003558
3559 // to track the speaker usage
3560 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003561 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003562 }
3563}
3564
Eric Laurenta553c252009-07-17 12:17:14 -07003565void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003566{
Steve Block71f2cf12011-10-20 11:56:00 +01003567 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003568 sp<ThreadBase> thread = mThread.promote();
3569 if (thread != 0) {
3570 Mutex::Autolock _l(thread->mLock);
3571 if (mState == ACTIVE || mState == RESUMING) {
3572 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003573 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003574 if (!isOutputTrack()) {
3575 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003576 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003577 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003578 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003579 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003580
3581 // to track the speaker usage
3582 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003583 }
Eric Laurenta553c252009-07-17 12:17:14 -07003584 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003585 }
3586}
3587
Eric Laurenta553c252009-07-17 12:17:14 -07003588void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003589{
Steve Block71f2cf12011-10-20 11:56:00 +01003590 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003591 sp<ThreadBase> thread = mThread.promote();
3592 if (thread != 0) {
3593 Mutex::Autolock _l(thread->mLock);
3594 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3595 return;
3596 }
3597 // No point remaining in PAUSED state after a flush => go to
3598 // STOPPED state
3599 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003600
Eric Laurentae29b762011-03-28 18:37:07 -07003601 // do not reset the track if it is still in the process of being stopped or paused.
3602 // this will be done by prepareTracks_l() when the track is stopped.
3603 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3604 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3605 reset();
3606 }
Eric Laurenta553c252009-07-17 12:17:14 -07003607 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003608}
3609
Eric Laurenta553c252009-07-17 12:17:14 -07003610void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003611{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003612 // Do not reset twice to avoid discarding data written just after a flush and before
3613 // the audioflinger thread detects the track is stopped.
3614 if (!mResetDone) {
3615 TrackBase::reset();
3616 // Force underrun condition to avoid false underrun callback until first data is
3617 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003618 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3619 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003620 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003621 mResetDone = true;
3622 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003623}
3624
Eric Laurenta553c252009-07-17 12:17:14 -07003625void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003626{
3627 mMute = muted;
3628}
3629
Eric Laurenta553c252009-07-17 12:17:14 -07003630void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003631{
3632 mVolume[0] = left;
3633 mVolume[1] = right;
3634}
3635
Eric Laurent65b65452010-06-01 23:49:17 -07003636status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3637{
3638 status_t status = DEAD_OBJECT;
3639 sp<ThreadBase> thread = mThread.promote();
3640 if (thread != 0) {
3641 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3642 status = playbackThread->attachAuxEffect(this, EffectId);
3643 }
3644 return status;
3645}
3646
3647void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3648{
3649 mAuxEffectId = EffectId;
3650 mAuxBuffer = buffer;
3651}
3652
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003653// ----------------------------------------------------------------------------
3654
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003655// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003656AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3657 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003660 uint32_t format,
3661 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003663 uint32_t flags,
3664 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003665 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003666 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003667 mOverflow(false)
3668{
Eric Laurent8a77a992009-09-09 05:16:08 -07003669 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003670 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003671 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003672 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003673 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003674 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003675 } else {
3676 mCblk->frameSize = sizeof(int8_t);
3677 }
3678 }
Eric Laurenta553c252009-07-17 12:17:14 -07003679}
3680
3681AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003682{
Eric Laurent49f02be2009-11-19 09:00:56 -08003683 sp<ThreadBase> thread = mThread.promote();
3684 if (thread != 0) {
3685 AudioSystem::releaseInput(thread->id());
3686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687}
3688
Eric Laurenta553c252009-07-17 12:17:14 -07003689status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003690{
3691 audio_track_cblk_t* cblk = this->cblk();
3692 uint32_t framesAvail;
3693 uint32_t framesReq = buffer->frameCount;
3694
3695 // Check if last stepServer failed, try to step now
3696 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3697 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003698 ALOGV("stepServer recovered");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3700 }
3701
3702 framesAvail = cblk->framesAvailable_l();
3703
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003704 if (CC_LIKELY(framesAvail)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 uint32_t s = cblk->server;
3706 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3707
3708 if (framesReq > framesAvail) {
3709 framesReq = framesAvail;
3710 }
3711 if (s + framesReq > bufferEnd) {
3712 framesReq = bufferEnd - s;
3713 }
3714
3715 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003716 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717
3718 buffer->frameCount = framesReq;
3719 return NO_ERROR;
3720 }
3721
3722getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003723 buffer->raw = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 buffer->frameCount = 0;
3725 return NOT_ENOUGH_DATA;
3726}
3727
Eric Laurenta553c252009-07-17 12:17:14 -07003728status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729{
Eric Laurenta553c252009-07-17 12:17:14 -07003730 sp<ThreadBase> thread = mThread.promote();
3731 if (thread != 0) {
3732 RecordThread *recordThread = (RecordThread *)thread.get();
3733 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003734 } else {
3735 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737}
3738
Eric Laurenta553c252009-07-17 12:17:14 -07003739void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740{
Eric Laurenta553c252009-07-17 12:17:14 -07003741 sp<ThreadBase> thread = mThread.promote();
3742 if (thread != 0) {
3743 RecordThread *recordThread = (RecordThread *)thread.get();
3744 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003745 TrackBase::reset();
3746 // Force overerrun condition to avoid false overrun callback until first data is
3747 // read from buffer
3748 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750}
3751
Eric Laurent3fdb1262009-11-07 00:01:32 -08003752void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3753{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003754 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003755 (mClient == NULL) ? getpid() : mClient->pid(),
3756 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003757 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003758 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003759 mFrameCount,
3760 mState,
3761 mCblk->sampleRate,
3762 mCblk->server,
3763 mCblk->user);
3764}
3765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766
3767// ----------------------------------------------------------------------------
3768
Eric Laurenta553c252009-07-17 12:17:14 -07003769AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3770 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003771 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003773 uint32_t format,
3774 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003776 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003777 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778{
Eric Laurenta553c252009-07-17 12:17:14 -07003779
3780 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003781 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003782 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003783 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3784 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3785 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003786 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01003787 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003788 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3789 mCblk, mBuffer, mCblk->buffers,
3790 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003791 } else {
3792 LOGW("Error creating output track on thread %p", playbackThread);
3793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794}
3795
Eric Laurenta553c252009-07-17 12:17:14 -07003796AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797{
Eric Laurent6c30a712009-08-10 23:22:32 -07003798 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799}
3800
Eric Laurenta553c252009-07-17 12:17:14 -07003801status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802{
3803 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003804 if (status != NO_ERROR) {
3805 return status;
3806 }
3807
3808 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 mRetryCount = 127;
3810 return status;
3811}
3812
Eric Laurenta553c252009-07-17 12:17:14 -07003813void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814{
3815 Track::stop();
3816 clearBufferQueue();
3817 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003818 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819}
3820
Eric Laurenta553c252009-07-17 12:17:14 -07003821bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822{
3823 Buffer *pInBuffer;
3824 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003825 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003826 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 inBuffer.frameCount = frames;
3828 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003829
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003830 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003831
Eric Laurent62443f52009-10-05 20:29:18 -07003832 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003833 start();
3834 sp<ThreadBase> thread = mThread.promote();
3835 if (thread != 0) {
3836 MixerThread *mixerThread = (MixerThread *)thread.get();
3837 if (mCblk->frameCount > frames){
3838 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3839 uint32_t startFrames = (mCblk->frameCount - frames);
3840 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003841 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003842 pInBuffer->frameCount = startFrames;
3843 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003844 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003845 mBufferQueue.add(pInBuffer);
3846 } else {
3847 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 }
Eric Laurenta553c252009-07-17 12:17:14 -07003850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 }
3852
Eric Laurenta553c252009-07-17 12:17:14 -07003853 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 // First write pending buffers, then new data
3855 if (mBufferQueue.size()) {
3856 pInBuffer = mBufferQueue.itemAt(0);
3857 } else {
3858 pInBuffer = &inBuffer;
3859 }
Eric Laurenta553c252009-07-17 12:17:14 -07003860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 if (pInBuffer->frameCount == 0) {
3862 break;
3863 }
Eric Laurenta553c252009-07-17 12:17:14 -07003864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 if (mOutBuffer.frameCount == 0) {
3866 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003867 nsecs_t startTime = systemTime();
3868 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01003869 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003870 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871 break;
3872 }
Eric Laurenta553c252009-07-17 12:17:14 -07003873 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003874 if (waitTimeLeftMs >= waitTimeMs) {
3875 waitTimeLeftMs -= waitTimeMs;
3876 } else {
3877 waitTimeLeftMs = 0;
3878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 }
Eric Laurenta553c252009-07-17 12:17:14 -07003880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003882 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 mCblk->stepUser(outFrames);
3884 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003885 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003887 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 if (pInBuffer->frameCount == 0) {
3890 if (mBufferQueue.size()) {
3891 mBufferQueue.removeAt(0);
3892 delete [] pInBuffer->mBuffer;
3893 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01003894 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 -08003895 } else {
3896 break;
3897 }
3898 }
3899 }
Eric Laurenta553c252009-07-17 12:17:14 -07003900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 // If we could not write all frames, allocate a buffer and queue it for next time.
3902 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003903 sp<ThreadBase> thread = mThread.promote();
3904 if (thread != 0 && !thread->standby()) {
3905 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3906 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003907 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003908 pInBuffer->frameCount = inBuffer.frameCount;
3909 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003910 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003911 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01003912 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003913 } else {
3914 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 }
3917 }
Eric Laurenta553c252009-07-17 12:17:14 -07003918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003920 // 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 -08003921 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003922 if (frames == 0 && mBufferQueue.size() == 0) {
3923 if (mCblk->user < mCblk->frameCount) {
3924 frames = mCblk->frameCount - mCblk->user;
3925 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003926 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003927 pInBuffer->frameCount = frames;
3928 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003929 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003930 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003931 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003932 stop();
3933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 }
3935
Eric Laurenta553c252009-07-17 12:17:14 -07003936 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937}
3938
Eric Laurenta553c252009-07-17 12:17:14 -07003939status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940{
3941 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 status_t result;
3943 audio_track_cblk_t* cblk = mCblk;
3944 uint32_t framesReq = buffer->frameCount;
3945
Steve Block71f2cf12011-10-20 11:56:00 +01003946// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 uint32_t framesAvail = cblk->framesAvailable();
3950
Eric Laurenta553c252009-07-17 12:17:14 -07003951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003953 Mutex::Autolock _l(cblk->lock);
3954 goto start_loop_here;
3955 while (framesAvail == 0) {
3956 active = mActive;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08003957 if (CC_UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01003958 ALOGV("Not active and NO_MORE_BUFFERS");
Eric Laurenta553c252009-07-17 12:17:14 -07003959 return AudioTrack::NO_MORE_BUFFERS;
3960 }
3961 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3962 if (result != NO_ERROR) {
3963 return AudioTrack::NO_MORE_BUFFERS;
3964 }
3965 // read the server count again
3966 start_loop_here:
3967 framesAvail = cblk->framesAvailable_l();
3968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 }
3970
Eric Laurenta553c252009-07-17 12:17:14 -07003971// if (framesAvail < framesReq) {
3972// return AudioTrack::NO_MORE_BUFFERS;
3973// }
3974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 if (framesReq > framesAvail) {
3976 framesReq = framesAvail;
3977 }
3978
3979 uint32_t u = cblk->user;
3980 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3981
3982 if (u + framesReq > bufferEnd) {
3983 framesReq = bufferEnd - u;
3984 }
3985
3986 buffer->frameCount = framesReq;
3987 buffer->raw = (void *)cblk->buffer(u);
3988 return NO_ERROR;
3989}
3990
3991
Eric Laurenta553c252009-07-17 12:17:14 -07003992void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993{
3994 size_t size = mBufferQueue.size();
3995 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 for (size_t i = 0; i < size; i++) {
3998 pBuffer = mBufferQueue.itemAt(i);
3999 delete [] pBuffer->mBuffer;
4000 delete pBuffer;
4001 }
4002 mBufferQueue.clear();
4003}
4004
4005// ----------------------------------------------------------------------------
4006
4007AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4008 : RefBase(),
4009 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08004010 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 mPid(pid)
4012{
4013 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4014}
4015
Eric Laurentb9481d82009-09-17 05:12:56 -07004016// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017AudioFlinger::Client::~Client()
4018{
Eric Laurentb9481d82009-09-17 05:12:56 -07004019 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020}
4021
4022const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4023{
4024 return mMemoryDealer;
4025}
4026
4027// ----------------------------------------------------------------------------
4028
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004029AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4030 const sp<IAudioFlingerClient>& client,
4031 pid_t pid)
4032 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4033{
4034}
4035
4036AudioFlinger::NotificationClient::~NotificationClient()
4037{
4038 mClient.clear();
4039}
4040
4041void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4042{
4043 sp<NotificationClient> keep(this);
4044 {
4045 mAudioFlinger->removeNotificationClient(mPid);
4046 }
4047}
4048
4049// ----------------------------------------------------------------------------
4050
Eric Laurenta553c252009-07-17 12:17:14 -07004051AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004052 : BnAudioTrack(),
4053 mTrack(track)
4054{
4055}
4056
4057AudioFlinger::TrackHandle::~TrackHandle() {
4058 // just stop the track on deletion, associated resources
4059 // will be freed from the main thread once all pending buffers have
4060 // been played. Unless it's not in the active track list, in which
4061 // case we free everything now...
4062 mTrack->destroy();
4063}
4064
4065status_t AudioFlinger::TrackHandle::start() {
4066 return mTrack->start();
4067}
4068
4069void AudioFlinger::TrackHandle::stop() {
4070 mTrack->stop();
4071}
4072
4073void AudioFlinger::TrackHandle::flush() {
4074 mTrack->flush();
4075}
4076
4077void AudioFlinger::TrackHandle::mute(bool e) {
4078 mTrack->mute(e);
4079}
4080
4081void AudioFlinger::TrackHandle::pause() {
4082 mTrack->pause();
4083}
4084
4085void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4086 mTrack->setVolume(left, right);
4087}
4088
4089sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4090 return mTrack->getCblk();
4091}
4092
Eric Laurent65b65452010-06-01 23:49:17 -07004093status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4094{
4095 return mTrack->attachAuxEffect(EffectId);
4096}
4097
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004098status_t AudioFlinger::TrackHandle::onTransact(
4099 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4100{
4101 return BnAudioTrack::onTransact(code, data, reply, flags);
4102}
4103
4104// ----------------------------------------------------------------------------
4105
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004106sp<IAudioRecord> AudioFlinger::openRecord(
4107 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07004108 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004109 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004110 uint32_t format,
4111 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004112 int frameCount,
4113 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004114 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004115 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004116{
Eric Laurenta553c252009-07-17 12:17:14 -07004117 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004118 sp<RecordHandle> recordHandle;
4119 sp<Client> client;
4120 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004121 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004122 RecordThread *thread;
4123 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004124 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004125
4126 // check calling permissions
4127 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004128 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004129 goto Exit;
4130 }
4131
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004132 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004133 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004134 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004135 thread = checkRecordThread_l(input);
4136 if (thread == NULL) {
4137 lStatus = BAD_VALUE;
4138 goto Exit;
4139 }
4140
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004141 wclient = mClients.valueFor(pid);
4142 if (wclient != NULL) {
4143 client = wclient.promote();
4144 } else {
4145 client = new Client(this, pid);
4146 mClients.add(pid, client);
4147 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004148
Eric Laurent65b65452010-06-01 23:49:17 -07004149 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004150 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004151 lSessionId = *sessionId;
4152 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004153 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004154 if (sessionId != NULL) {
4155 *sessionId = lSessionId;
4156 }
4157 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004158 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004159 recordTrack = thread->createRecordTrack_l(client,
4160 sampleRate,
4161 format,
4162 channelMask,
4163 frameCount,
4164 flags,
4165 lSessionId,
4166 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004167 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004168 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004169 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4170 // destructor is called by the TrackBase destructor with mLock held
4171 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004173 goto Exit;
4174 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004175
4176 // return to handle to client
4177 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004178 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004179
4180Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004181 if (status) {
4182 *status = lStatus;
4183 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004184 return recordHandle;
4185}
4186
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004187// ----------------------------------------------------------------------------
4188
Eric Laurenta553c252009-07-17 12:17:14 -07004189AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004190 : BnAudioRecord(),
4191 mRecordTrack(recordTrack)
4192{
4193}
4194
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004195AudioFlinger::RecordHandle::~RecordHandle() {
4196 stop();
4197}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004198
4199status_t AudioFlinger::RecordHandle::start() {
Steve Block71f2cf12011-10-20 11:56:00 +01004200 ALOGV("RecordHandle::start()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004201 return mRecordTrack->start();
4202}
4203
4204void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004205 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004206 mRecordTrack->stop();
4207}
4208
4209sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4210 return mRecordTrack->getCblk();
4211}
4212
4213status_t AudioFlinger::RecordHandle::onTransact(
4214 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4215{
4216 return BnAudioRecord::onTransact(code, data, reply, flags);
4217}
4218
4219// ----------------------------------------------------------------------------
4220
Eric Laurent464d5b32011-06-17 21:29:58 -07004221AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4222 AudioStreamIn *input,
4223 uint32_t sampleRate,
4224 uint32_t channels,
4225 int id,
4226 uint32_t device) :
4227 ThreadBase(audioFlinger, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08004228 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004229{
Eric Laurent464d5b32011-06-17 21:29:58 -07004230 mType = ThreadBase::RECORD;
Eric Laurent6dbdc402011-07-22 09:04:31 -07004231
4232 snprintf(mName, kNameLength, "AudioIn_%d", id);
4233
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004234 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07004235 mReqSampleRate = sampleRate;
4236 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004237}
4238
Eric Laurenta553c252009-07-17 12:17:14 -07004239
4240AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004241{
Eric Laurenta553c252009-07-17 12:17:14 -07004242 delete[] mRsmpInBuffer;
Glenn Kastenc434c902011-12-13 11:53:26 -08004243 if (mResampler != NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004244 delete mResampler;
4245 delete[] mRsmpOutBuffer;
4246 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004247}
4248
Eric Laurenta553c252009-07-17 12:17:14 -07004249void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004250{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004251 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004252}
Eric Laurent49f02be2009-11-19 09:00:56 -08004253
Eric Laurent828b9772011-08-07 16:32:26 -07004254status_t AudioFlinger::RecordThread::readyToRun()
4255{
4256 status_t status = initCheck();
4257 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4258 return status;
4259}
4260
Eric Laurenta553c252009-07-17 12:17:14 -07004261bool AudioFlinger::RecordThread::threadLoop()
4262{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004263 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004264 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004265 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004266
Eric Laurent4712baa2010-09-30 16:12:31 -07004267 nsecs_t lastWarning = 0;
4268
Eric Laurent6dbdc402011-07-22 09:04:31 -07004269 acquireWakeLock();
4270
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004271 // start recording
4272 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004273
Eric Laurenta553c252009-07-17 12:17:14 -07004274 processConfigEvents();
4275
4276 { // scope for mLock
4277 Mutex::Autolock _l(mLock);
4278 checkForNewParameters_l();
4279 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4280 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004281 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004282 mStandby = true;
4283 }
4284
4285 if (exitPending()) break;
4286
Eric Laurent6dbdc402011-07-22 09:04:31 -07004287 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004288 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004289 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004290 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004291 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004292 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004293 continue;
4294 }
4295 if (mActiveTrack != 0) {
4296 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004297 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004298 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004299 mStandby = true;
4300 }
Eric Laurenta553c252009-07-17 12:17:14 -07004301 mActiveTrack.clear();
4302 mStartStopCond.broadcast();
4303 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004304 if (mReqChannelCount != mActiveTrack->channelCount()) {
4305 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004306 mStartStopCond.broadcast();
4307 } else if (mBytesRead != 0) {
4308 // record start succeeds only if first read from audio input
4309 // succeeds
4310 if (mBytesRead > 0) {
4311 mActiveTrack->mState = TrackBase::ACTIVE;
4312 } else {
4313 mActiveTrack.clear();
4314 }
4315 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004316 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004317 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004318 }
Eric Laurenta553c252009-07-17 12:17:14 -07004319 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004320 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004321 }
4322
4323 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004324 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4325 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004326 unlockEffectChains(effectChains);
4327 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004328 continue;
4329 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004330 for (size_t i = 0; i < effectChains.size(); i ++) {
4331 effectChains[i]->process_l();
4332 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004333
Eric Laurenta553c252009-07-17 12:17:14 -07004334 buffer.frameCount = mFrameCount;
Glenn Kastene80a4cc2011-12-15 09:51:17 -08004335 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004336 size_t framesOut = buffer.frameCount;
Glenn Kastenc434c902011-12-13 11:53:26 -08004337 if (mResampler == NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004338 // no resampling
4339 while (framesOut) {
4340 size_t framesIn = mFrameCount - mRsmpInIndex;
4341 if (framesIn) {
4342 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4343 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4344 if (framesIn > framesOut)
4345 framesIn = framesOut;
4346 mRsmpInIndex += framesIn;
4347 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004348 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004349 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004350 memcpy(dst, src, framesIn * mFrameSize);
4351 } else {
4352 int16_t *src16 = (int16_t *)src;
4353 int16_t *dst16 = (int16_t *)dst;
4354 if (mChannelCount == 1) {
4355 while (framesIn--) {
4356 *dst16++ = *src16;
4357 *dst16++ = *src16++;
4358 }
4359 } else {
4360 while (framesIn--) {
4361 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4362 src16 += 2;
4363 }
4364 }
4365 }
4366 }
4367 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004368 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004369 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004370 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004371 framesOut = 0;
4372 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004373 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004374 mRsmpInIndex = 0;
4375 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004376 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004377 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004378 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004379 // Force input into standby so that it tries to
4380 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004381 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004382 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004383 }
Eric Laurenta553c252009-07-17 12:17:14 -07004384 mRsmpInIndex = mFrameCount;
4385 framesOut = 0;
4386 buffer.frameCount = 0;
4387 }
4388 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004389 }
4390 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004391 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004392
Eric Laurenta553c252009-07-17 12:17:14 -07004393 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4394 // alter output frame count as if we were expecting stereo samples
4395 if (mChannelCount == 1 && mReqChannelCount == 1) {
4396 framesOut >>= 1;
4397 }
4398 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4399 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4400 // are 32 bit aligned which should be always true.
4401 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten490909d2011-12-15 09:52:39 -08004402 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004403 // the resampler always outputs stereo samples: do post stereo to mono conversion
4404 int16_t *src = (int16_t *)mRsmpOutBuffer;
4405 int16_t *dst = buffer.i16;
4406 while (framesOut--) {
4407 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4408 src += 2;
4409 }
4410 } else {
Glenn Kasten490909d2011-12-15 09:52:39 -08004411 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004412 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004413
Eric Laurenta553c252009-07-17 12:17:14 -07004414 }
4415 mActiveTrack->releaseBuffer(&buffer);
4416 mActiveTrack->overflow();
4417 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004418 // client isn't retrieving buffers fast enough
4419 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004420 if (!mActiveTrack->setOverflow()) {
4421 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004422 if ((now - lastWarning) > kWarningThrottleNs) {
Eric Laurent4712baa2010-09-30 16:12:31 -07004423 LOGW("RecordThread: buffer overflow");
4424 lastWarning = now;
4425 }
4426 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004427 // Release the processor for a while before asking for a new buffer.
4428 // This will give the application more chance to read from the buffer and
4429 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004430 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004431 }
4432 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004433 // enable changes in effect chain
4434 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004435 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004436 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004437
Eric Laurenta553c252009-07-17 12:17:14 -07004438 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004439 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004440 }
Eric Laurenta553c252009-07-17 12:17:14 -07004441 mActiveTrack.clear();
4442
Eric Laurent49f02be2009-11-19 09:00:56 -08004443 mStartStopCond.broadcast();
4444
Eric Laurent6dbdc402011-07-22 09:04:31 -07004445 releaseWakeLock();
4446
Steve Block71f2cf12011-10-20 11:56:00 +01004447 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004448 return false;
4449}
4450
Eric Laurent464d5b32011-06-17 21:29:58 -07004451
4452sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4453 const sp<AudioFlinger::Client>& client,
4454 uint32_t sampleRate,
4455 int format,
4456 int channelMask,
4457 int frameCount,
4458 uint32_t flags,
4459 int sessionId,
4460 status_t *status)
4461{
4462 sp<RecordTrack> track;
4463 status_t lStatus;
4464
4465 lStatus = initCheck();
4466 if (lStatus != NO_ERROR) {
4467 LOGE("Audio driver not initialized.");
4468 goto Exit;
4469 }
4470
4471 { // scope for mLock
4472 Mutex::Autolock _l(mLock);
4473
4474 track = new RecordTrack(this, client, sampleRate,
4475 format, channelMask, frameCount, flags, sessionId);
4476
4477 if (track->getCblk() == NULL) {
4478 lStatus = NO_MEMORY;
4479 goto Exit;
4480 }
4481
4482 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004483 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4484 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004485 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004486 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4487 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004488 }
4489 lStatus = NO_ERROR;
4490
4491Exit:
4492 if (status) {
4493 *status = lStatus;
4494 }
4495 return track;
4496}
4497
Eric Laurenta553c252009-07-17 12:17:14 -07004498status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004499{
Steve Block71f2cf12011-10-20 11:56:00 +01004500 ALOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004501 sp <ThreadBase> strongMe = this;
4502 status_t status = NO_ERROR;
4503 {
4504 AutoMutex lock(&mLock);
4505 if (mActiveTrack != 0) {
4506 if (recordTrack != mActiveTrack.get()) {
4507 status = -EBUSY;
4508 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08004509 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004510 }
4511 return status;
4512 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004513
Eric Laurent49f02be2009-11-19 09:00:56 -08004514 recordTrack->mState = TrackBase::IDLE;
4515 mActiveTrack = recordTrack;
4516 mLock.unlock();
4517 status_t status = AudioSystem::startInput(mId);
4518 mLock.lock();
4519 if (status != NO_ERROR) {
4520 mActiveTrack.clear();
4521 return status;
4522 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08004523 mRsmpInIndex = mFrameCount;
4524 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004525 if (mResampler != NULL) {
4526 mResampler->reset();
4527 }
4528 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004529 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004530 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004531 mWaitWorkCV.signal();
4532 // do not wait for mStartStopCond if exiting
4533 if (mExiting) {
4534 mActiveTrack.clear();
4535 status = INVALID_OPERATION;
4536 goto startError;
4537 }
4538 mStartStopCond.wait(mLock);
4539 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01004540 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004541 status = BAD_VALUE;
4542 goto startError;
4543 }
Steve Block71f2cf12011-10-20 11:56:00 +01004544 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004545 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004546 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004547startError:
4548 AudioSystem::stopInput(mId);
4549 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004550}
4551
Eric Laurenta553c252009-07-17 12:17:14 -07004552void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01004553 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004554 sp <ThreadBase> strongMe = this;
4555 {
4556 AutoMutex lock(&mLock);
4557 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4558 mActiveTrack->mState = TrackBase::PAUSING;
4559 // do not wait for mStartStopCond if exiting
4560 if (mExiting) {
4561 return;
4562 }
4563 mStartStopCond.wait(mLock);
4564 // if we have been restarted, recordTrack == mActiveTrack.get() here
4565 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4566 mLock.unlock();
4567 AudioSystem::stopInput(mId);
4568 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01004569 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004570 }
4571 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004572 }
4573}
4574
Eric Laurenta553c252009-07-17 12:17:14 -07004575status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576{
4577 const size_t SIZE = 256;
4578 char buffer[SIZE];
4579 String8 result;
4580 pid_t pid = 0;
4581
Eric Laurent3fdb1262009-11-07 00:01:32 -08004582 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4583 result.append(buffer);
4584
4585 if (mActiveTrack != 0) {
4586 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004587 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004588 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004589 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004590
4591 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4592 result.append(buffer);
4593 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4594 result.append(buffer);
Glenn Kastenc434c902011-12-13 11:53:26 -08004595 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Eric Laurent3fdb1262009-11-07 00:01:32 -08004596 result.append(buffer);
4597 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4598 result.append(buffer);
4599 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4600 result.append(buffer);
4601
4602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004603 } else {
4604 result.append("No record client\n");
4605 }
4606 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004607
4608 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004609 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611 return NO_ERROR;
4612}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004613
Eric Laurenta553c252009-07-17 12:17:14 -07004614status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4615{
4616 size_t framesReq = buffer->frameCount;
4617 size_t framesReady = mFrameCount - mRsmpInIndex;
4618 int channelCount;
4619
4620 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004621 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004622 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004623 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08004624 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004625 // Force input into standby so that it tries to
4626 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004627 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004628 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a22009-12-05 05:20:01 -08004629 }
Glenn Kastenc434c902011-12-13 11:53:26 -08004630 buffer->raw = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004631 buffer->frameCount = 0;
4632 return NOT_ENOUGH_DATA;
4633 }
4634 mRsmpInIndex = 0;
4635 framesReady = mFrameCount;
4636 }
4637
4638 if (framesReq > framesReady) {
4639 framesReq = framesReady;
4640 }
4641
4642 if (mChannelCount == 1 && mReqChannelCount == 2) {
4643 channelCount = 1;
4644 } else {
4645 channelCount = 2;
4646 }
4647 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4648 buffer->frameCount = framesReq;
4649 return NO_ERROR;
4650}
4651
4652void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4653{
4654 mRsmpInIndex += buffer->frameCount;
4655 buffer->frameCount = 0;
4656}
4657
4658bool AudioFlinger::RecordThread::checkForNewParameters_l()
4659{
4660 bool reconfig = false;
4661
Eric Laurent8fce46a2009-08-04 09:45:33 -07004662 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004663 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004664 String8 keyValuePair = mNewParameters[0];
4665 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004666 int value;
4667 int reqFormat = mFormat;
4668 int reqSamplingRate = mReqSampleRate;
4669 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004670
Eric Laurenta553c252009-07-17 12:17:14 -07004671 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4672 reqSamplingRate = value;
4673 reconfig = true;
4674 }
4675 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4676 reqFormat = value;
4677 reconfig = true;
4678 }
4679 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004680 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004681 reconfig = true;
4682 }
4683 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4684 // do not accept frame count changes if tracks are open as the track buffer
4685 // size depends on frame count and correct behavior would not be garantied
4686 // if frame count is changed after track creation
4687 if (mActiveTrack != 0) {
4688 status = INVALID_OPERATION;
4689 } else {
4690 reconfig = true;
4691 }
4692 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004693 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4694 // forward device change to effects that have requested to be
4695 // aware of attached audio device.
4696 for (size_t i = 0; i < mEffectChains.size(); i++) {
4697 mEffectChains[i]->setDevice_l(value);
4698 }
4699 // store input device and output device but do not forward output device to audio HAL.
4700 // Note that status is ignored by the caller for output device
4701 // (see AudioFlinger::setParameters()
4702 if (value & AUDIO_DEVICE_OUT_ALL) {
4703 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4704 status = BAD_VALUE;
4705 } else {
4706 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004707 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4708 if (mTrack != NULL) {
4709 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004710 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004711 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4712 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4713 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004714 }
4715 mDevice |= (uint32_t)value;
4716 }
Eric Laurenta553c252009-07-17 12:17:14 -07004717 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004718 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004719 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004720 mInput->stream->common.standby(&mInput->stream->common);
4721 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004722 }
4723 if (reconfig) {
4724 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004725 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004726 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004727 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4728 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004729 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004730 status = NO_ERROR;
4731 }
4732 if (status == NO_ERROR) {
4733 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004734 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004735 }
4736 }
4737 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004738
4739 mNewParameters.removeAt(0);
4740
Eric Laurenta553c252009-07-17 12:17:14 -07004741 mParamStatus = status;
4742 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004743 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4744 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004745 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07004746 }
4747 return reconfig;
4748}
4749
4750String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4751{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004752 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004753 String8 out_s8 = String8();
4754
4755 Mutex::Autolock _l(mLock);
4756 if (initCheck() != NO_ERROR) {
4757 return out_s8;
4758 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004759
Dima Zavin31f188892011-04-18 16:57:27 -07004760 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004761 out_s8 = String8(s);
4762 free(s);
4763 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004764}
4765
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004766void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004767 AudioSystem::OutputDescriptor desc;
4768 void *param2 = 0;
4769
4770 switch (event) {
4771 case AudioSystem::INPUT_OPENED:
4772 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004773 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004774 desc.samplingRate = mSampleRate;
4775 desc.format = mFormat;
4776 desc.frameCount = mFrameCount;
4777 desc.latency = 0;
4778 param2 = &desc;
4779 break;
4780
4781 case AudioSystem::INPUT_CLOSED:
4782 default:
4783 break;
4784 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004785 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004786}
4787
4788void AudioFlinger::RecordThread::readInputParameters()
4789{
4790 if (mRsmpInBuffer) delete mRsmpInBuffer;
4791 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4792 if (mResampler) delete mResampler;
Glenn Kastenc434c902011-12-13 11:53:26 -08004793 mResampler = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004794
Dima Zavin31f188892011-04-18 16:57:27 -07004795 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004796 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4797 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004798 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4799 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4800 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004801 mFrameCount = mInputBytes / mFrameSize;
4802 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4803
4804 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4805 {
4806 int channelCount;
4807 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4808 // stereo to mono post process as the resampler always outputs stereo.
4809 if (mChannelCount == 1 && mReqChannelCount == 2) {
4810 channelCount = 1;
4811 } else {
4812 channelCount = 2;
4813 }
4814 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4815 mResampler->setSampleRate(mSampleRate);
4816 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4817 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4818
4819 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4820 if (mChannelCount == 1 && mReqChannelCount == 1) {
4821 mFrameCount >>= 1;
4822 }
4823
4824 }
4825 mRsmpInIndex = mFrameCount;
4826}
4827
Eric Laurent47d0a922010-02-26 02:47:27 -08004828unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4829{
Eric Laurent828b9772011-08-07 16:32:26 -07004830 Mutex::Autolock _l(mLock);
4831 if (initCheck() != NO_ERROR) {
4832 return 0;
4833 }
4834
Dima Zavin31f188892011-04-18 16:57:27 -07004835 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004836}
4837
Eric Laurent464d5b32011-06-17 21:29:58 -07004838uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4839{
4840 Mutex::Autolock _l(mLock);
4841 uint32_t result = 0;
4842 if (getEffectChain_l(sessionId) != 0) {
4843 result = EFFECT_SESSION;
4844 }
4845
4846 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4847 result |= TRACK_SESSION;
4848 }
4849
4850 return result;
4851}
4852
Eric Laurent6639b552011-08-01 09:52:20 -07004853AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4854{
4855 Mutex::Autolock _l(mLock);
4856 return mTrack;
4857}
4858
Eric Laurent828b9772011-08-07 16:32:26 -07004859AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4860{
4861 Mutex::Autolock _l(mLock);
4862 return mInput;
4863}
4864
4865AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4866{
4867 Mutex::Autolock _l(mLock);
4868 AudioStreamIn *input = mInput;
4869 mInput = NULL;
4870 return input;
4871}
4872
4873// this method must always be called either with ThreadBase mLock held or inside the thread loop
4874audio_stream_t* AudioFlinger::RecordThread::stream()
4875{
4876 if (mInput == NULL) {
4877 return NULL;
4878 }
4879 return &mInput->stream->common;
4880}
4881
4882
Eric Laurenta553c252009-07-17 12:17:14 -07004883// ----------------------------------------------------------------------------
4884
Eric Laurentddb78e72009-07-28 08:44:33 -07004885int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004886 uint32_t *pSamplingRate,
4887 uint32_t *pFormat,
4888 uint32_t *pChannels,
4889 uint32_t *pLatencyMs,
4890 uint32_t flags)
4891{
4892 status_t status;
4893 PlaybackThread *thread = NULL;
4894 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4895 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4896 uint32_t format = pFormat ? *pFormat : 0;
4897 uint32_t channels = pChannels ? *pChannels : 0;
4898 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004899 audio_stream_out_t *outStream;
4900 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004901
Steve Block71f2cf12011-10-20 11:56:00 +01004902 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07004903 pDevices ? *pDevices : 0,
4904 samplingRate,
4905 format,
4906 channels,
4907 flags);
4908
4909 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004910 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004911 }
Dima Zavin31f188892011-04-18 16:57:27 -07004912
Eric Laurenta553c252009-07-17 12:17:14 -07004913 Mutex::Autolock _l(mLock);
4914
Dima Zavin31f188892011-04-18 16:57:27 -07004915 outHwDev = findSuitableHwDev_l(*pDevices);
4916 if (outHwDev == NULL)
4917 return 0;
4918
4919 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4920 &channels, &samplingRate, &outStream);
Steve Block71f2cf12011-10-20 11:56:00 +01004921 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004922 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004923 samplingRate,
4924 format,
4925 channels,
4926 status);
4927
4928 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004929 if (outStream != NULL) {
4930 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent464d5b32011-06-17 21:29:58 -07004931 int id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004932
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004933 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4934 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4935 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004936 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004937 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004938 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004939 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004940 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004941 }
Eric Laurent65b65452010-06-01 23:49:17 -07004942 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004943
4944 if (pSamplingRate) *pSamplingRate = samplingRate;
4945 if (pFormat) *pFormat = format;
4946 if (pChannels) *pChannels = channels;
4947 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004948
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004949 // notify client processes of the new output creation
4950 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004951 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004952 }
4953
Eric Laurent9cc489a22009-12-05 05:20:01 -08004954 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004955}
4956
Eric Laurentddb78e72009-07-28 08:44:33 -07004957int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004958{
4959 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004960 MixerThread *thread1 = checkMixerThread_l(output1);
4961 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004962
Eric Laurentddb78e72009-07-28 08:44:33 -07004963 if (thread1 == NULL || thread2 == NULL) {
4964 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4965 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004966 }
4967
Eric Laurent464d5b32011-06-17 21:29:58 -07004968 int id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004969 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004970 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004971 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004972 // notify client processes of the new output creation
4973 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004974 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004975}
4976
Eric Laurentddb78e72009-07-28 08:44:33 -07004977status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004978{
Eric Laurent49018a52009-08-04 08:37:05 -07004979 // keep strong reference on the playback thread so that
4980 // it is not destroyed while exit() is executed
4981 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004982 {
4983 Mutex::Autolock _l(mLock);
4984 thread = checkPlaybackThread_l(output);
4985 if (thread == NULL) {
4986 return BAD_VALUE;
4987 }
4988
Steve Block71f2cf12011-10-20 11:56:00 +01004989 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004990
Eric Laurent464d5b32011-06-17 21:29:58 -07004991 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07004992 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004993 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004994 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004995 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004996 }
4997 }
4998 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004999 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005000 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005001 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07005002 }
5003 thread->exit();
5004
Eric Laurent464d5b32011-06-17 21:29:58 -07005005 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07005006 AudioStreamOut *out = thread->clearOutput();
5007 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005008 out->hwDev->close_output_stream(out->hwDev, out->stream);
5009 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005010 }
Eric Laurenta553c252009-07-17 12:17:14 -07005011 return NO_ERROR;
5012}
5013
Eric Laurentddb78e72009-07-28 08:44:33 -07005014status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005015{
5016 Mutex::Autolock _l(mLock);
5017 PlaybackThread *thread = checkPlaybackThread_l(output);
5018
5019 if (thread == NULL) {
5020 return BAD_VALUE;
5021 }
5022
Steve Block71f2cf12011-10-20 11:56:00 +01005023 ALOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005024 thread->suspend();
5025
5026 return NO_ERROR;
5027}
5028
Eric Laurentddb78e72009-07-28 08:44:33 -07005029status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005030{
5031 Mutex::Autolock _l(mLock);
5032 PlaybackThread *thread = checkPlaybackThread_l(output);
5033
5034 if (thread == NULL) {
5035 return BAD_VALUE;
5036 }
5037
Steve Block71f2cf12011-10-20 11:56:00 +01005038 ALOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005039
5040 thread->restore();
5041
5042 return NO_ERROR;
5043}
5044
Eric Laurentddb78e72009-07-28 08:44:33 -07005045int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005046 uint32_t *pSamplingRate,
5047 uint32_t *pFormat,
5048 uint32_t *pChannels,
5049 uint32_t acoustics)
5050{
5051 status_t status;
5052 RecordThread *thread = NULL;
5053 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5054 uint32_t format = pFormat ? *pFormat : 0;
5055 uint32_t channels = pChannels ? *pChannels : 0;
5056 uint32_t reqSamplingRate = samplingRate;
5057 uint32_t reqFormat = format;
5058 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005059 audio_stream_in_t *inStream;
5060 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005061
5062 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005063 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005064 }
Dima Zavin31f188892011-04-18 16:57:27 -07005065
Eric Laurenta553c252009-07-17 12:17:14 -07005066 Mutex::Autolock _l(mLock);
5067
Dima Zavin31f188892011-04-18 16:57:27 -07005068 inHwDev = findSuitableHwDev_l(*pDevices);
5069 if (inHwDev == NULL)
5070 return 0;
5071
5072 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5073 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005074 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005075 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005076 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005077 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005078 samplingRate,
5079 format,
5080 channels,
5081 acoustics,
5082 status);
5083
5084 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5085 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5086 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005087 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005088 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005089 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005090 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005091 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin31f188892011-04-18 16:57:27 -07005092 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5093 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005094 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005095 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005096 }
5097
Dima Zavin31f188892011-04-18 16:57:27 -07005098 if (inStream != NULL) {
5099 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5100
Eric Laurent464d5b32011-06-17 21:29:58 -07005101 int id = nextUniqueId();
5102 // Start record thread
5103 // RecorThread require both input and output device indication to forward to audio
5104 // pre processing modules
5105 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5106 thread = new RecordThread(this,
5107 input,
5108 reqSamplingRate,
5109 reqChannels,
5110 id,
5111 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005112 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005113 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005114 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5115 if (pFormat) *pFormat = format;
5116 if (pChannels) *pChannels = reqChannels;
5117
Dima Zavin31f188892011-04-18 16:57:27 -07005118 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a22009-12-05 05:20:01 -08005119
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005120 // notify client processes of the new input creation
5121 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005122 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005123 }
5124
Eric Laurent9cc489a22009-12-05 05:20:01 -08005125 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005126}
5127
Eric Laurentddb78e72009-07-28 08:44:33 -07005128status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07005129{
Eric Laurent49018a52009-08-04 08:37:05 -07005130 // keep strong reference on the record thread so that
5131 // it is not destroyed while exit() is executed
5132 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005133 {
5134 Mutex::Autolock _l(mLock);
5135 thread = checkRecordThread_l(input);
5136 if (thread == NULL) {
5137 return BAD_VALUE;
5138 }
5139
Steve Block71f2cf12011-10-20 11:56:00 +01005140 ALOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07005141 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005142 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005143 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005144 }
5145 thread->exit();
5146
Eric Laurent828b9772011-08-07 16:32:26 -07005147 AudioStreamIn *in = thread->clearInput();
5148 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005149 in->hwDev->close_input_stream(in->hwDev, in->stream);
5150 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005151
Eric Laurenta553c252009-07-17 12:17:14 -07005152 return NO_ERROR;
5153}
5154
Eric Laurentddb78e72009-07-28 08:44:33 -07005155status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005156{
5157 Mutex::Autolock _l(mLock);
5158 MixerThread *dstThread = checkMixerThread_l(output);
5159 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005160 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005161 return BAD_VALUE;
5162 }
5163
Steve Block71f2cf12011-10-20 11:56:00 +01005164 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005165 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005166
Eric Laurent05ce0942011-08-30 10:18:54 -07005167 dstThread->setStreamValid(stream, true);
5168
Eric Laurenta553c252009-07-17 12:17:14 -07005169 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005170 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005171 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005172 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005173 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005174 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005175 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005176 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005177 }
Eric Laurentd069f322009-09-01 05:56:26 -07005178
Eric Laurenta553c252009-07-17 12:17:14 -07005179 return NO_ERROR;
5180}
5181
Eric Laurent65b65452010-06-01 23:49:17 -07005182
5183int AudioFlinger::newAudioSessionId()
5184{
Eric Laurent464d5b32011-06-17 21:29:58 -07005185 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005186}
5187
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005188void AudioFlinger::acquireAudioSessionId(int audioSession)
5189{
5190 Mutex::Autolock _l(mLock);
5191 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005192 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005193 int num = mAudioSessionRefs.size();
5194 for (int i = 0; i< num; i++) {
5195 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5196 if (ref->sessionid == audioSession && ref->pid == caller) {
5197 ref->cnt++;
Steve Block71f2cf12011-10-20 11:56:00 +01005198 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005199 return;
5200 }
5201 }
5202 AudioSessionRef *ref = new AudioSessionRef();
5203 ref->sessionid = audioSession;
5204 ref->pid = caller;
5205 ref->cnt = 1;
5206 mAudioSessionRefs.push(ref);
Steve Block71f2cf12011-10-20 11:56:00 +01005207 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005208}
5209
5210void AudioFlinger::releaseAudioSessionId(int audioSession)
5211{
5212 Mutex::Autolock _l(mLock);
5213 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005214 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005215 int num = mAudioSessionRefs.size();
5216 for (int i = 0; i< num; i++) {
5217 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5218 if (ref->sessionid == audioSession && ref->pid == caller) {
5219 ref->cnt--;
Steve Block71f2cf12011-10-20 11:56:00 +01005220 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005221 if (ref->cnt == 0) {
5222 mAudioSessionRefs.removeAt(i);
5223 delete ref;
5224 purgeStaleEffects_l();
5225 }
5226 return;
5227 }
5228 }
5229 LOGW("session id %d not found for pid %d", audioSession, caller);
5230}
5231
5232void AudioFlinger::purgeStaleEffects_l() {
5233
Steve Block71f2cf12011-10-20 11:56:00 +01005234 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005235
5236 Vector< sp<EffectChain> > chains;
5237
5238 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5239 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5240 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5241 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005242 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5243 chains.push(ec);
5244 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005245 }
5246 }
5247 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5248 sp<RecordThread> t = mRecordThreads.valueAt(i);
5249 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5250 sp<EffectChain> ec = t->mEffectChains[j];
5251 chains.push(ec);
5252 }
5253 }
5254
5255 for (size_t i = 0; i < chains.size(); i++) {
5256 sp<EffectChain> ec = chains[i];
5257 int sessionid = ec->sessionId();
5258 sp<ThreadBase> t = ec->mThread.promote();
5259 if (t == 0) {
5260 continue;
5261 }
5262 size_t numsessionrefs = mAudioSessionRefs.size();
5263 bool found = false;
5264 for (size_t k = 0; k < numsessionrefs; k++) {
5265 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5266 if (ref->sessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005267 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005268 sessionid, ref->pid, ref->cnt);
5269 found = true;
5270 break;
5271 }
5272 }
5273 if (!found) {
5274 // remove all effects from the chain
5275 while (ec->mEffects.size()) {
5276 sp<EffectModule> effect = ec->mEffects[0];
5277 effect->unPin();
5278 Mutex::Autolock _l (t->mLock);
5279 t->removeEffect_l(effect);
5280 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5281 sp<EffectHandle> handle = effect->mHandles[j].promote();
5282 if (handle != 0) {
5283 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005284 if (handle->mHasControl && handle->mEnabled) {
5285 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5286 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005287 }
5288 }
5289 AudioSystem::unregisterEffect(effect->id());
5290 }
5291 }
5292 }
5293 return;
5294}
5295
Eric Laurenta553c252009-07-17 12:17:14 -07005296// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005297AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005298{
5299 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005300 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5301 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005302 }
Eric Laurenta553c252009-07-17 12:17:14 -07005303 return thread;
5304}
5305
5306// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005307AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005308{
5309 PlaybackThread *thread = checkPlaybackThread_l(output);
5310 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005311 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005312 thread = NULL;
5313 }
5314 }
5315 return (MixerThread *)thread;
5316}
5317
5318// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005319AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005320{
5321 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005322 if (mRecordThreads.indexOfKey(input) >= 0) {
5323 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005324 }
Eric Laurenta553c252009-07-17 12:17:14 -07005325 return thread;
5326}
5327
Eric Laurent464d5b32011-06-17 21:29:58 -07005328uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005329{
Eric Laurent464d5b32011-06-17 21:29:58 -07005330 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005331}
5332
Eric Laurent464d5b32011-06-17 21:29:58 -07005333AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5334{
5335 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5336 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005337 AudioStreamOut *output = thread->getOutput();
5338 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005339 return thread;
5340 }
5341 }
5342 return NULL;
5343}
5344
5345uint32_t AudioFlinger::primaryOutputDevice_l()
5346{
5347 PlaybackThread *thread = primaryPlaybackThread_l();
5348
5349 if (thread == NULL) {
5350 return 0;
5351 }
5352
5353 return thread->device();
5354}
5355
5356
Eric Laurent65b65452010-06-01 23:49:17 -07005357// ----------------------------------------------------------------------------
5358// Effect management
5359// ----------------------------------------------------------------------------
5360
5361
Eric Laurent65b65452010-06-01 23:49:17 -07005362status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5363{
5364 Mutex::Autolock _l(mLock);
5365 return EffectQueryNumberEffects(numEffects);
5366}
5367
Eric Laurent53334cd2010-06-23 17:38:20 -07005368status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07005369{
5370 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005371 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005372}
5373
5374status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5375{
5376 Mutex::Autolock _l(mLock);
5377 return EffectGetDescriptor(pUuid, descriptor);
5378}
5379
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005380
Eric Laurent65b65452010-06-01 23:49:17 -07005381sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5382 effect_descriptor_t *pDesc,
5383 const sp<IEffectClient>& effectClient,
5384 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005385 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005386 int sessionId,
5387 status_t *status,
5388 int *id,
5389 int *enabled)
5390{
5391 status_t lStatus = NO_ERROR;
5392 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005393 effect_descriptor_t desc;
5394 sp<Client> client;
5395 wp<Client> wclient;
5396
Steve Block71f2cf12011-10-20 11:56:00 +01005397 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005398 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005399
5400 if (pDesc == NULL) {
5401 lStatus = BAD_VALUE;
5402 goto Exit;
5403 }
5404
Eric Laurent98c92592010-09-23 16:10:16 -07005405 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005406 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005407 lStatus = PERMISSION_DENIED;
5408 goto Exit;
5409 }
5410
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005411 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005412 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005413 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005414 lStatus = PERMISSION_DENIED;
5415 goto Exit;
5416 }
5417
Eric Laurent464d5b32011-06-17 21:29:58 -07005418 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005419 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005420 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005421 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005422 lStatus = BAD_VALUE;
5423 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005424 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005425 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005426 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005427 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005428 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005429 }
5430 }
5431
Eric Laurent65b65452010-06-01 23:49:17 -07005432 {
5433 Mutex::Autolock _l(mLock);
5434
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005435
Eric Laurent65b65452010-06-01 23:49:17 -07005436 if (!EffectIsNullUuid(&pDesc->uuid)) {
5437 // if uuid is specified, request effect descriptor
5438 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5439 if (lStatus < 0) {
5440 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5441 goto Exit;
5442 }
5443 } else {
5444 // if uuid is not specified, look for an available implementation
5445 // of the required type in effect factory
5446 if (EffectIsNullUuid(&pDesc->type)) {
5447 LOGW("createEffect() no effect type");
5448 lStatus = BAD_VALUE;
5449 goto Exit;
5450 }
5451 uint32_t numEffects = 0;
5452 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005453 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005454 bool found = false;
5455
5456 lStatus = EffectQueryNumberEffects(&numEffects);
5457 if (lStatus < 0) {
5458 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5459 goto Exit;
5460 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005461 for (uint32_t i = 0; i < numEffects; i++) {
5462 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005463 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005464 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005465 continue;
5466 }
5467 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5468 // If matching type found save effect descriptor. If the session is
5469 // 0 and the effect is not auxiliary, continue enumeration in case
5470 // an auxiliary version of this effect type is available
5471 found = true;
5472 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005473 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005474 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5475 break;
5476 }
5477 }
5478 }
5479 if (!found) {
5480 lStatus = BAD_VALUE;
5481 LOGW("createEffect() effect not found");
5482 goto Exit;
5483 }
5484 // For same effect type, chose auxiliary version over insert version if
5485 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005486 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005487 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5488 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5489 }
5490 }
5491
5492 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005493 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005494 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5495 lStatus = INVALID_OPERATION;
5496 goto Exit;
5497 }
5498
Eric Laurentf82fccd2011-07-27 19:49:51 -07005499 // check recording permission for visualizer
5500 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5501 !recordingAllowed()) {
5502 lStatus = PERMISSION_DENIED;
5503 goto Exit;
5504 }
5505
Eric Laurent65b65452010-06-01 23:49:17 -07005506 // return effect descriptor
5507 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5508
5509 // If output is not specified try to find a matching audio session ID in one of the
5510 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005511 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5512 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005513 // Note: io is never 0 when creating an effect on an input
5514 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005515 // look for the thread where the specified audio session is present
5516 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5517 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005518 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005519 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005520 }
Eric Laurent65b65452010-06-01 23:49:17 -07005521 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005522 if (io == 0) {
5523 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5524 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5525 io = mRecordThreads.keyAt(i);
5526 break;
5527 }
5528 }
5529 }
Eric Laurent98c92592010-09-23 16:10:16 -07005530 // If no output thread contains the requested session ID, default to
5531 // first output. The effect chain will be moved to the correct output
5532 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005533 if (io == 0 && mPlaybackThreads.size()) {
5534 io = mPlaybackThreads.keyAt(0);
5535 }
Steve Block71f2cf12011-10-20 11:56:00 +01005536 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005537 }
5538 ThreadBase *thread = checkRecordThread_l(io);
5539 if (thread == NULL) {
5540 thread = checkPlaybackThread_l(io);
5541 if (thread == NULL) {
5542 LOGE("createEffect() unknown output thread");
5543 lStatus = BAD_VALUE;
5544 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005545 }
Eric Laurent65b65452010-06-01 23:49:17 -07005546 }
Eric Laurent98c92592010-09-23 16:10:16 -07005547
Eric Laurent65b65452010-06-01 23:49:17 -07005548 wclient = mClients.valueFor(pid);
5549
5550 if (wclient != NULL) {
5551 client = wclient.promote();
5552 } else {
5553 client = new Client(this, pid);
5554 mClients.add(pid, client);
5555 }
5556
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005557 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005558 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5559 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005560 if (handle != 0 && id != NULL) {
5561 *id = handle->id();
5562 }
5563 }
5564
5565Exit:
5566 if(status) {
5567 *status = lStatus;
5568 }
5569 return handle;
5570}
5571
Eric Laurentf82fccd2011-07-27 19:49:51 -07005572status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005573{
Steve Block71f2cf12011-10-20 11:56:00 +01005574 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005575 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005576 Mutex::Autolock _l(mLock);
5577 if (srcOutput == dstOutput) {
5578 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5579 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005580 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005581 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5582 if (srcThread == NULL) {
5583 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5584 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005585 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005586 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5587 if (dstThread == NULL) {
5588 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5589 return BAD_VALUE;
5590 }
5591
5592 Mutex::Autolock _dl(dstThread->mLock);
5593 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005594 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005595
Eric Laurent53334cd2010-06-23 17:38:20 -07005596 return NO_ERROR;
5597}
5598
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005599// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005600status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005601 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005602 AudioFlinger::PlaybackThread *dstThread,
5603 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005604{
Steve Block71f2cf12011-10-20 11:56:00 +01005605 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005606 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005607
Eric Laurentf82fccd2011-07-27 19:49:51 -07005608 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005609 if (chain == 0) {
5610 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005611 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005612 return INVALID_OPERATION;
5613 }
5614
Eric Laurent493941b2010-07-28 01:32:47 -07005615 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005616 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005617 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005618 // removed.
5619 srcThread->removeEffectChain_l(chain);
5620
5621 // transfer all effects one by one so that new effect chain is created on new thread with
5622 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005623 int dstOutput = dstThread->id();
5624 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005625 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005626 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5627 while (effect != 0) {
5628 srcThread->removeEffect_l(effect);
5629 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005630 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5631 if (effect->state() == EffectModule::ACTIVE ||
5632 effect->state() == EffectModule::STOPPING) {
5633 effect->start();
5634 }
Eric Laurent493941b2010-07-28 01:32:47 -07005635 // if the move request is not received from audio policy manager, the effect must be
5636 // re-registered with the new strategy and output
5637 if (dstChain == 0) {
5638 dstChain = effect->chain().promote();
5639 if (dstChain == 0) {
5640 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5641 srcThread->addEffect_l(effect);
5642 return NO_INIT;
5643 }
5644 strategy = dstChain->strategy();
5645 }
5646 if (reRegister) {
5647 AudioSystem::unregisterEffect(effect->id());
5648 AudioSystem::registerEffect(&effect->desc(),
5649 dstOutput,
5650 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005651 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005652 effect->id());
5653 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005654 effect = chain->getEffectFromId_l(0);
5655 }
5656
5657 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005658}
5659
Eric Laurent464d5b32011-06-17 21:29:58 -07005660
Eric Laurent65b65452010-06-01 23:49:17 -07005661// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005662sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005663 const sp<AudioFlinger::Client>& client,
5664 const sp<IEffectClient>& effectClient,
5665 int32_t priority,
5666 int sessionId,
5667 effect_descriptor_t *desc,
5668 int *enabled,
5669 status_t *status
5670 )
5671{
5672 sp<EffectModule> effect;
5673 sp<EffectHandle> handle;
5674 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005675 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005676 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005677 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005678 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005679
Eric Laurent464d5b32011-06-17 21:29:58 -07005680 lStatus = initCheck();
5681 if (lStatus != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07005682 LOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005683 goto Exit;
5684 }
5685
5686 // Do not allow effects with session ID 0 on direct output or duplicating threads
5687 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005688 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005689 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5690 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005691 lStatus = BAD_VALUE;
5692 goto Exit;
5693 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005694 // Only Pre processor effects are allowed on input threads and only on input threads
5695 if ((mType == RECORD &&
5696 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5697 (mType != RECORD &&
5698 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5699 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5700 desc->name, desc->flags, mType);
5701 lStatus = BAD_VALUE;
5702 goto Exit;
5703 }
Eric Laurent65b65452010-06-01 23:49:17 -07005704
Steve Block71f2cf12011-10-20 11:56:00 +01005705 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005706
5707 { // scope for mLock
5708 Mutex::Autolock _l(mLock);
5709
5710 // check for existing effect chain with the requested audio session
5711 chain = getEffectChain_l(sessionId);
5712 if (chain == 0) {
5713 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005714 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005715 chain = new EffectChain(this, sessionId);
5716 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005717 chain->setStrategy(getStrategyForSession_l(sessionId));
5718 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005719 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005720 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005721 }
5722
Steve Block71f2cf12011-10-20 11:56:00 +01005723 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005724
5725 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005726 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005727 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005728 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005729 if (lStatus != NO_ERROR) {
5730 goto Exit;
5731 }
5732 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005733 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005734 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005735 lStatus = effect->status();
5736 if (lStatus != NO_ERROR) {
5737 goto Exit;
5738 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005739 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005740 if (lStatus != NO_ERROR) {
5741 goto Exit;
5742 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005743 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005744
5745 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005746 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005747 }
5748 // create effect handle and connect it to effect module
5749 handle = new EffectHandle(effect, client, effectClient, priority);
5750 lStatus = effect->addHandle(handle);
5751 if (enabled) {
5752 *enabled = (int)effect->isEnabled();
5753 }
5754 }
5755
5756Exit:
5757 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005758 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005759 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005760 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005761 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005762 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005763 AudioSystem::unregisterEffect(effect->id());
5764 }
5765 if (chainCreated) {
5766 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005767 }
Eric Laurent65b65452010-06-01 23:49:17 -07005768 handle.clear();
5769 }
5770
5771 if(status) {
5772 *status = lStatus;
5773 }
5774 return handle;
5775}
5776
Eric Laurent464d5b32011-06-17 21:29:58 -07005777sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5778{
5779 sp<EffectModule> effect;
5780
5781 sp<EffectChain> chain = getEffectChain_l(sessionId);
5782 if (chain != 0) {
5783 effect = chain->getEffectFromId_l(effectId);
5784 }
5785 return effect;
5786}
5787
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005788// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5789// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005790status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005791{
5792 // check for existing effect chain with the requested audio session
5793 int sessionId = effect->sessionId();
5794 sp<EffectChain> chain = getEffectChain_l(sessionId);
5795 bool chainCreated = false;
5796
5797 if (chain == 0) {
5798 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005799 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005800 chain = new EffectChain(this, sessionId);
5801 addEffectChain_l(chain);
5802 chain->setStrategy(getStrategyForSession_l(sessionId));
5803 chainCreated = true;
5804 }
Steve Block71f2cf12011-10-20 11:56:00 +01005805 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005806
5807 if (chain->getEffectFromId_l(effect->id()) != 0) {
5808 LOGW("addEffect_l() %p effect %s already present in chain %p",
5809 this, effect->desc().name, chain.get());
5810 return BAD_VALUE;
5811 }
5812
5813 status_t status = chain->addEffect_l(effect);
5814 if (status != NO_ERROR) {
5815 if (chainCreated) {
5816 removeEffectChain_l(chain);
5817 }
5818 return status;
5819 }
5820
5821 effect->setDevice(mDevice);
5822 effect->setMode(mAudioFlinger->getMode());
5823 return NO_ERROR;
5824}
5825
Eric Laurent464d5b32011-06-17 21:29:58 -07005826void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005827
Steve Block71f2cf12011-10-20 11:56:00 +01005828 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005829 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005830 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5831 detachAuxEffect_l(effect->id());
5832 }
5833
5834 sp<EffectChain> chain = effect->chain().promote();
5835 if (chain != 0) {
5836 // remove effect chain if removing last effect
5837 if (chain->removeEffect_l(effect) == 0) {
5838 removeEffectChain_l(chain);
5839 }
5840 } else {
5841 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5842 }
5843}
5844
Eric Laurent464d5b32011-06-17 21:29:58 -07005845void AudioFlinger::ThreadBase::lockEffectChains_l(
5846 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5847{
5848 effectChains = mEffectChains;
5849 for (size_t i = 0; i < mEffectChains.size(); i++) {
5850 mEffectChains[i]->lock();
5851 }
5852}
5853
5854void AudioFlinger::ThreadBase::unlockEffectChains(
5855 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5856{
5857 for (size_t i = 0; i < effectChains.size(); i++) {
5858 effectChains[i]->unlock();
5859 }
5860}
5861
5862sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5863{
5864 Mutex::Autolock _l(mLock);
5865 return getEffectChain_l(sessionId);
5866}
5867
5868sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5869{
5870 sp<EffectChain> chain;
5871
5872 size_t size = mEffectChains.size();
5873 for (size_t i = 0; i < size; i++) {
5874 if (mEffectChains[i]->sessionId() == sessionId) {
5875 chain = mEffectChains[i];
5876 break;
5877 }
5878 }
5879 return chain;
5880}
5881
5882void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5883{
5884 Mutex::Autolock _l(mLock);
5885 size_t size = mEffectChains.size();
5886 for (size_t i = 0; i < size; i++) {
5887 mEffectChains[i]->setMode_l(mode);
5888 }
5889}
5890
5891void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005892 const wp<EffectHandle>& handle,
5893 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005894
Eric Laurent53334cd2010-06-23 17:38:20 -07005895 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01005896 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005897 // delete the effect module if removing last handle on it
5898 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005899 if (!effect->isPinned() || unpiniflast) {
5900 removeEffect_l(effect);
5901 AudioSystem::unregisterEffect(effect->id());
5902 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005903 }
5904}
5905
Eric Laurent65b65452010-06-01 23:49:17 -07005906status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5907{
5908 int session = chain->sessionId();
5909 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005910 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005911
Steve Block71f2cf12011-10-20 11:56:00 +01005912 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005913 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005914 // Only one effect chain can be present in direct output thread and it uses
5915 // the mix buffer as input
5916 if (mType != DIRECT) {
5917 size_t numSamples = mFrameCount * mChannelCount;
5918 buffer = new int16_t[numSamples];
5919 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01005920 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005921 ownsBuffer = true;
5922 }
Eric Laurent65b65452010-06-01 23:49:17 -07005923
Eric Laurent53334cd2010-06-23 17:38:20 -07005924 // Attach all tracks with same session ID to this chain.
5925 for (size_t i = 0; i < mTracks.size(); ++i) {
5926 sp<Track> track = mTracks[i];
5927 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005928 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07005929 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005930 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005931 }
5932 }
5933
5934 // indicate all active tracks in the chain
5935 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5936 sp<Track> track = mActiveTracks[i].promote();
5937 if (track == 0) continue;
5938 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005939 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005940 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005941 }
Eric Laurent65b65452010-06-01 23:49:17 -07005942 }
5943 }
5944
Eric Laurent53334cd2010-06-23 17:38:20 -07005945 chain->setInBuffer(buffer, ownsBuffer);
5946 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005947 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005948 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005949 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5950 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005951 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005952 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5953 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005954 // Effect chain for other sessions are inserted at beginning of effect
5955 // chains list to be processed before output mix effects. Relative order between other
5956 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005957 size_t size = mEffectChains.size();
5958 size_t i = 0;
5959 for (i = 0; i < size; i++) {
5960 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005961 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005962 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005963 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005964
5965 return NO_ERROR;
5966}
5967
5968size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5969{
5970 int session = chain->sessionId();
5971
Steve Block71f2cf12011-10-20 11:56:00 +01005972 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005973
5974 for (size_t i = 0; i < mEffectChains.size(); i++) {
5975 if (chain == mEffectChains[i]) {
5976 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005977 // detach all active tracks from the chain
5978 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5979 sp<Track> track = mActiveTracks[i].promote();
5980 if (track == 0) continue;
5981 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005982 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07005983 chain.get(), session);
5984 chain->decActiveTrackCnt();
5985 }
5986 }
5987
Eric Laurent65b65452010-06-01 23:49:17 -07005988 // detach all tracks with same session ID from this chain
5989 for (size_t i = 0; i < mTracks.size(); ++i) {
5990 sp<Track> track = mTracks[i];
5991 if (session == track->sessionId()) {
5992 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005993 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005994 }
5995 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005996 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005997 }
5998 }
5999 return mEffectChains.size();
6000}
6001
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006002status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6003 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006004{
6005 Mutex::Autolock _l(mLock);
6006 return attachAuxEffect_l(track, EffectId);
6007}
6008
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006009status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6010 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006011{
6012 status_t status = NO_ERROR;
6013
6014 if (EffectId == 0) {
6015 track->setAuxBuffer(0, NULL);
6016 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006017 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6018 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006019 if (effect != 0) {
6020 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6021 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6022 } else {
6023 status = INVALID_OPERATION;
6024 }
6025 } else {
6026 status = BAD_VALUE;
6027 }
6028 }
6029 return status;
6030}
6031
6032void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6033{
6034 for (size_t i = 0; i < mTracks.size(); ++i) {
6035 sp<Track> track = mTracks[i];
6036 if (track->auxEffectId() == effectId) {
6037 attachAuxEffect_l(track, 0);
6038 }
6039 }
6040}
6041
Eric Laurent464d5b32011-06-17 21:29:58 -07006042status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6043{
6044 // only one chain per input thread
6045 if (mEffectChains.size() != 0) {
6046 return INVALID_OPERATION;
6047 }
Steve Block71f2cf12011-10-20 11:56:00 +01006048 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006049
6050 chain->setInBuffer(NULL);
6051 chain->setOutBuffer(NULL);
6052
Eric Laurentf82fccd2011-07-27 19:49:51 -07006053 checkSuspendOnAddEffectChain_l(chain);
6054
Eric Laurent464d5b32011-06-17 21:29:58 -07006055 mEffectChains.add(chain);
6056
6057 return NO_ERROR;
6058}
6059
6060size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6061{
Steve Block71f2cf12011-10-20 11:56:00 +01006062 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006063 LOGW_IF(mEffectChains.size() != 1,
6064 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6065 chain.get(), mEffectChains.size(), this);
6066 if (mEffectChains.size() == 1) {
6067 mEffectChains.removeAt(0);
6068 }
6069 return 0;
6070}
6071
Eric Laurent65b65452010-06-01 23:49:17 -07006072// ----------------------------------------------------------------------------
6073// EffectModule implementation
6074// ----------------------------------------------------------------------------
6075
6076#undef LOG_TAG
6077#define LOG_TAG "AudioFlinger::EffectModule"
6078
6079AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6080 const wp<AudioFlinger::EffectChain>& chain,
6081 effect_descriptor_t *desc,
6082 int id,
6083 int sessionId)
6084 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006085 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006086{
Steve Block71f2cf12011-10-20 11:56:00 +01006087 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006088 int lStatus;
6089 sp<ThreadBase> thread = mThread.promote();
6090 if (thread == 0) {
6091 return;
6092 }
Eric Laurent65b65452010-06-01 23:49:17 -07006093
6094 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6095
6096 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006097 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006098
Eric Laurent65b65452010-06-01 23:49:17 -07006099 if (mStatus != NO_ERROR) {
6100 return;
6101 }
6102 lStatus = init();
6103 if (lStatus < 0) {
6104 mStatus = lStatus;
6105 goto Error;
6106 }
6107
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006108 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6109 mPinned = true;
6110 }
Steve Block71f2cf12011-10-20 11:56:00 +01006111 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006112 return;
6113Error:
6114 EffectRelease(mEffectInterface);
6115 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006116 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006117}
6118
6119AudioFlinger::EffectModule::~EffectModule()
6120{
Steve Block71f2cf12011-10-20 11:56:00 +01006121 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006122 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006123 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6124 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6125 sp<ThreadBase> thread = mThread.promote();
6126 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006127 audio_stream_t *stream = thread->stream();
6128 if (stream != NULL) {
6129 stream->remove_audio_effect(stream, mEffectInterface);
6130 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006131 }
6132 }
Eric Laurent65b65452010-06-01 23:49:17 -07006133 // release effect engine
6134 EffectRelease(mEffectInterface);
6135 }
6136}
6137
6138status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6139{
6140 status_t status;
6141
6142 Mutex::Autolock _l(mLock);
6143 // First handle in mHandles has highest priority and controls the effect module
6144 int priority = handle->priority();
6145 size_t size = mHandles.size();
6146 sp<EffectHandle> h;
6147 size_t i;
6148 for (i = 0; i < size; i++) {
6149 h = mHandles[i].promote();
6150 if (h == 0) continue;
6151 if (h->priority() <= priority) break;
6152 }
6153 // if inserted in first place, move effect control from previous owner to this handle
6154 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006155 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006156 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006157 enabled = h->enabled();
6158 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006159 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006160 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006161 status = NO_ERROR;
6162 } else {
6163 status = ALREADY_EXISTS;
6164 }
Steve Block71f2cf12011-10-20 11:56:00 +01006165 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006166 mHandles.insertAt(handle, i);
6167 return status;
6168}
6169
6170size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6171{
6172 Mutex::Autolock _l(mLock);
6173 size_t size = mHandles.size();
6174 size_t i;
6175 for (i = 0; i < size; i++) {
6176 if (mHandles[i] == handle) break;
6177 }
6178 if (i == size) {
6179 return size;
6180 }
Steve Block71f2cf12011-10-20 11:56:00 +01006181 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006182
6183 bool enabled = false;
6184 EffectHandle *hdl = handle.unsafe_get();
6185 if (hdl) {
Steve Block71f2cf12011-10-20 11:56:00 +01006186 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006187 enabled = hdl->enabled();
6188 }
Eric Laurent65b65452010-06-01 23:49:17 -07006189 mHandles.removeAt(i);
6190 size = mHandles.size();
6191 // if removed from first place, move effect control from this handle to next in line
6192 if (i == 0 && size != 0) {
6193 sp<EffectHandle> h = mHandles[0].promote();
6194 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006195 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006196 }
6197 }
6198
Eric Laurent21b5c472011-07-26 20:54:46 -07006199 // Prevent calls to process() and other functions on effect interface from now on.
6200 // The effect engine will be released by the destructor when the last strong reference on
6201 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006202 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006203 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006204 }
6205
Eric Laurent65b65452010-06-01 23:49:17 -07006206 return size;
6207}
6208
Eric Laurentf82fccd2011-07-27 19:49:51 -07006209sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6210{
6211 Mutex::Autolock _l(mLock);
6212 sp<EffectHandle> handle;
6213 if (mHandles.size() != 0) {
6214 handle = mHandles[0].promote();
6215 }
6216 return handle;
6217}
6218
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006219void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006220{
Steve Block71f2cf12011-10-20 11:56:00 +01006221 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006222 // keep a strong reference on this EffectModule to avoid calling the
6223 // destructor before we exit
6224 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006225 {
6226 sp<ThreadBase> thread = mThread.promote();
6227 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006228 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006229 }
6230 }
6231}
6232
Eric Laurent7d850f22010-07-09 13:34:17 -07006233void AudioFlinger::EffectModule::updateState() {
6234 Mutex::Autolock _l(mLock);
6235
6236 switch (mState) {
6237 case RESTART:
6238 reset_l();
6239 // FALL THROUGH
6240
6241 case STARTING:
6242 // clear auxiliary effect input buffer for next accumulation
6243 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6244 memset(mConfig.inputCfg.buffer.raw,
6245 0,
6246 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6247 }
6248 start_l();
6249 mState = ACTIVE;
6250 break;
6251 case STOPPING:
6252 stop_l();
6253 mDisableWaitCnt = mMaxDisableWaitCnt;
6254 mState = STOPPED;
6255 break;
6256 case STOPPED:
6257 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6258 // turn off sequence.
6259 if (--mDisableWaitCnt == 0) {
6260 reset_l();
6261 mState = IDLE;
6262 }
6263 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006264 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006265 break;
6266 }
6267}
6268
Eric Laurent65b65452010-06-01 23:49:17 -07006269void AudioFlinger::EffectModule::process()
6270{
6271 Mutex::Autolock _l(mLock);
6272
Eric Laurent21b5c472011-07-26 20:54:46 -07006273 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006274 mConfig.inputCfg.buffer.raw == NULL ||
6275 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006276 return;
6277 }
6278
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006279 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006280 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6281 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten490909d2011-12-15 09:52:39 -08006282 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Eric Laurent65b65452010-06-01 23:49:17 -07006283 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006284 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006285 }
6286
Eric Laurent65b65452010-06-01 23:49:17 -07006287 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006288 int ret = (*mEffectInterface)->process(mEffectInterface,
6289 &mConfig.inputCfg.buffer,
6290 &mConfig.outputCfg.buffer);
6291
6292 // force transition to IDLE state when engine is ready
6293 if (mState == STOPPED && ret == -ENODATA) {
6294 mDisableWaitCnt = 1;
6295 }
Eric Laurent65b65452010-06-01 23:49:17 -07006296
6297 // clear auxiliary effect input buffer for next accumulation
6298 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006299 memset(mConfig.inputCfg.buffer.raw, 0,
6300 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006301 }
6302 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006303 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6304 // If an insert effect is idle and input buffer is different from output buffer,
6305 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006306 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006307 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006308 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6309 int16_t *in = mConfig.inputCfg.buffer.s16;
6310 int16_t *out = mConfig.outputCfg.buffer.s16;
6311 for (size_t i = 0; i < frameCnt; i++) {
6312 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006313 }
Eric Laurent65b65452010-06-01 23:49:17 -07006314 }
6315 }
6316}
6317
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006318void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006319{
6320 if (mEffectInterface == NULL) {
6321 return;
6322 }
6323 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6324}
6325
6326status_t AudioFlinger::EffectModule::configure()
6327{
6328 uint32_t channels;
6329 if (mEffectInterface == NULL) {
6330 return NO_INIT;
6331 }
6332
6333 sp<ThreadBase> thread = mThread.promote();
6334 if (thread == 0) {
6335 return DEAD_OBJECT;
6336 }
6337
6338 // TODO: handle configuration of effects replacing track process
6339 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006340 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006341 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006342 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006343 }
6344
6345 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006346 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006347 } else {
6348 mConfig.inputCfg.channels = channels;
6349 }
6350 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006351 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6352 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006353 mConfig.inputCfg.samplingRate = thread->sampleRate();
6354 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6355 mConfig.inputCfg.bufferProvider.cookie = NULL;
6356 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6357 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6358 mConfig.outputCfg.bufferProvider.cookie = NULL;
6359 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6360 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6361 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6362 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006363 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006364 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006365 // - in other sessions:
6366 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6367 // other effect: overwrites output buffer: input buffer == output buffer
6368 // Auxiliary effect:
6369 // accumulates in output buffer: input buffer != output buffer
6370 // Therefore: accumulate <=> input buffer != output buffer
6371 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6372 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6373 } else {
6374 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6375 }
6376 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6377 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6378 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6379 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6380
Steve Block71f2cf12011-10-20 11:56:00 +01006381 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006382 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6383
Eric Laurent65b65452010-06-01 23:49:17 -07006384 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006385 uint32_t size = sizeof(int);
6386 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent4abf8822011-12-16 15:30:36 -08006387 EFFECT_CMD_SET_CONFIG,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006388 sizeof(effect_config_t),
6389 &mConfig,
6390 &size,
6391 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006392 if (status == 0) {
6393 status = cmdStatus;
6394 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006395
6396 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6397 (1000 * mConfig.outputCfg.buffer.frameCount);
6398
Eric Laurent65b65452010-06-01 23:49:17 -07006399 return status;
6400}
6401
6402status_t AudioFlinger::EffectModule::init()
6403{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006404 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006405 if (mEffectInterface == NULL) {
6406 return NO_INIT;
6407 }
6408 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006409 uint32_t size = sizeof(status_t);
6410 status_t status = (*mEffectInterface)->command(mEffectInterface,
6411 EFFECT_CMD_INIT,
6412 0,
6413 NULL,
6414 &size,
6415 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006416 if (status == 0) {
6417 status = cmdStatus;
6418 }
6419 return status;
6420}
6421
Eric Laurent6fccbd02011-10-05 17:42:25 -07006422status_t AudioFlinger::EffectModule::start()
6423{
6424 Mutex::Autolock _l(mLock);
6425 return start_l();
6426}
6427
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006428status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006429{
6430 if (mEffectInterface == NULL) {
6431 return NO_INIT;
6432 }
6433 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006434 uint32_t size = sizeof(status_t);
6435 status_t status = (*mEffectInterface)->command(mEffectInterface,
6436 EFFECT_CMD_ENABLE,
6437 0,
6438 NULL,
6439 &size,
6440 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006441 if (status == 0) {
6442 status = cmdStatus;
6443 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006444 if (status == 0 &&
6445 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6446 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6447 sp<ThreadBase> thread = mThread.promote();
6448 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006449 audio_stream_t *stream = thread->stream();
6450 if (stream != NULL) {
6451 stream->add_audio_effect(stream, mEffectInterface);
6452 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006453 }
6454 }
Eric Laurent65b65452010-06-01 23:49:17 -07006455 return status;
6456}
6457
Eric Laurent21b5c472011-07-26 20:54:46 -07006458status_t AudioFlinger::EffectModule::stop()
6459{
6460 Mutex::Autolock _l(mLock);
6461 return stop_l();
6462}
6463
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006464status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006465{
6466 if (mEffectInterface == NULL) {
6467 return NO_INIT;
6468 }
6469 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006470 uint32_t size = sizeof(status_t);
6471 status_t status = (*mEffectInterface)->command(mEffectInterface,
6472 EFFECT_CMD_DISABLE,
6473 0,
6474 NULL,
6475 &size,
6476 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006477 if (status == 0) {
6478 status = cmdStatus;
6479 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006480 if (status == 0 &&
6481 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6482 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6483 sp<ThreadBase> thread = mThread.promote();
6484 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006485 audio_stream_t *stream = thread->stream();
6486 if (stream != NULL) {
6487 stream->remove_audio_effect(stream, mEffectInterface);
6488 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006489 }
6490 }
Eric Laurent65b65452010-06-01 23:49:17 -07006491 return status;
6492}
6493
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006494status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6495 uint32_t cmdSize,
6496 void *pCmdData,
6497 uint32_t *replySize,
6498 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006499{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006500 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006501// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006502
Eric Laurent21b5c472011-07-26 20:54:46 -07006503 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006504 return NO_INIT;
6505 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006506 status_t status = (*mEffectInterface)->command(mEffectInterface,
6507 cmdCode,
6508 cmdSize,
6509 pCmdData,
6510 replySize,
6511 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006512 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006513 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006514 for (size_t i = 1; i < mHandles.size(); i++) {
6515 sp<EffectHandle> h = mHandles[i].promote();
6516 if (h != 0) {
6517 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6518 }
6519 }
6520 }
6521 return status;
6522}
6523
6524status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6525{
Eric Laurent6752ec82011-08-10 10:37:50 -07006526
Eric Laurent65b65452010-06-01 23:49:17 -07006527 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006528 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006529
6530 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006531 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6532 if (enabled && status != NO_ERROR) {
6533 return status;
6534 }
6535
Eric Laurent65b65452010-06-01 23:49:17 -07006536 switch (mState) {
6537 // going from disabled to enabled
6538 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006539 mState = STARTING;
6540 break;
6541 case STOPPED:
6542 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006543 break;
6544 case STOPPING:
6545 mState = ACTIVE;
6546 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006547
6548 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006549 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006550 mState = STOPPED;
6551 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006552 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006553 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006554 break;
6555 case ACTIVE:
6556 mState = STOPPING;
6557 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006558 case DESTROYED:
6559 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006560 }
6561 for (size_t i = 1; i < mHandles.size(); i++) {
6562 sp<EffectHandle> h = mHandles[i].promote();
6563 if (h != 0) {
6564 h->setEnabled(enabled);
6565 }
6566 }
6567 }
6568 return NO_ERROR;
6569}
6570
6571bool AudioFlinger::EffectModule::isEnabled()
6572{
6573 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006574 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006575 case STARTING:
6576 case ACTIVE:
6577 return true;
6578 case IDLE:
6579 case STOPPING:
6580 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006581 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006582 default:
6583 return false;
6584 }
6585}
6586
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006587bool AudioFlinger::EffectModule::isProcessEnabled()
6588{
6589 switch (mState) {
6590 case RESTART:
6591 case ACTIVE:
6592 case STOPPING:
6593 case STOPPED:
6594 return true;
6595 case IDLE:
6596 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006597 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006598 default:
6599 return false;
6600 }
6601}
6602
Eric Laurent65b65452010-06-01 23:49:17 -07006603status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6604{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006605 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006606 status_t status = NO_ERROR;
6607
6608 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6609 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006610 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006611 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6612 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006613 status_t cmdStatus;
6614 uint32_t volume[2];
6615 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006616 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006617 volume[0] = *left;
6618 volume[1] = *right;
6619 if (controller) {
6620 pVolume = volume;
6621 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006622 status = (*mEffectInterface)->command(mEffectInterface,
6623 EFFECT_CMD_SET_VOLUME,
6624 size,
6625 volume,
6626 &size,
6627 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006628 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6629 *left = volume[0];
6630 *right = volume[1];
6631 }
6632 }
6633 return status;
6634}
6635
6636status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6637{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006638 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006639 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006640 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6641 // audio pre processing modules on RecordThread can receive both output and
6642 // input device indication in the same call
6643 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6644 if (dev) {
6645 status_t cmdStatus;
6646 uint32_t size = sizeof(status_t);
6647
6648 status = (*mEffectInterface)->command(mEffectInterface,
6649 EFFECT_CMD_SET_DEVICE,
6650 sizeof(uint32_t),
6651 &dev,
6652 &size,
6653 &cmdStatus);
6654 if (status == NO_ERROR) {
6655 status = cmdStatus;
6656 }
6657 }
6658 dev = device & AUDIO_DEVICE_IN_ALL;
6659 if (dev) {
6660 status_t cmdStatus;
6661 uint32_t size = sizeof(status_t);
6662
6663 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6664 EFFECT_CMD_SET_INPUT_DEVICE,
6665 sizeof(uint32_t),
6666 &dev,
6667 &size,
6668 &cmdStatus);
6669 if (status2 == NO_ERROR) {
6670 status2 = cmdStatus;
6671 }
6672 if (status == NO_ERROR) {
6673 status = status2;
6674 }
Eric Laurent65b65452010-06-01 23:49:17 -07006675 }
6676 }
6677 return status;
6678}
6679
Eric Laurent53334cd2010-06-23 17:38:20 -07006680status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6681{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006682 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006683 status_t status = NO_ERROR;
6684 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006685 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006686 uint32_t size = sizeof(status_t);
6687 status = (*mEffectInterface)->command(mEffectInterface,
6688 EFFECT_CMD_SET_AUDIO_MODE,
6689 sizeof(int),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006690 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006691 &size,
6692 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006693 if (status == NO_ERROR) {
6694 status = cmdStatus;
6695 }
6696 }
6697 return status;
6698}
6699
Eric Laurentf82fccd2011-07-27 19:49:51 -07006700void AudioFlinger::EffectModule::setSuspended(bool suspended)
6701{
6702 Mutex::Autolock _l(mLock);
6703 mSuspended = suspended;
6704}
Glenn Kasten1dce8412012-01-04 11:01:11 -08006705
6706bool AudioFlinger::EffectModule::suspended() const
Eric Laurentf82fccd2011-07-27 19:49:51 -07006707{
6708 Mutex::Autolock _l(mLock);
6709 return mSuspended;
6710}
6711
Eric Laurent65b65452010-06-01 23:49:17 -07006712status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6713{
6714 const size_t SIZE = 256;
6715 char buffer[SIZE];
6716 String8 result;
6717
6718 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6719 result.append(buffer);
6720
6721 bool locked = tryLock(mLock);
6722 // failed to lock - AudioFlinger is probably deadlocked
6723 if (!locked) {
6724 result.append("\t\tCould not lock Fx mutex:\n");
6725 }
6726
6727 result.append("\t\tSession Status State Engine:\n");
6728 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6729 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6730 result.append(buffer);
6731
6732 result.append("\t\tDescriptor:\n");
6733 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6734 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6735 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6736 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6737 result.append(buffer);
6738 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6739 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6740 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6741 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6742 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006743 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006744 mDescriptor.apiVersion,
6745 mDescriptor.flags);
6746 result.append(buffer);
6747 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6748 mDescriptor.name);
6749 result.append(buffer);
6750 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6751 mDescriptor.implementor);
6752 result.append(buffer);
6753
6754 result.append("\t\t- Input configuration:\n");
6755 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6756 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6757 (uint32_t)mConfig.inputCfg.buffer.raw,
6758 mConfig.inputCfg.buffer.frameCount,
6759 mConfig.inputCfg.samplingRate,
6760 mConfig.inputCfg.channels,
6761 mConfig.inputCfg.format);
6762 result.append(buffer);
6763
6764 result.append("\t\t- Output configuration:\n");
6765 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6766 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6767 (uint32_t)mConfig.outputCfg.buffer.raw,
6768 mConfig.outputCfg.buffer.frameCount,
6769 mConfig.outputCfg.samplingRate,
6770 mConfig.outputCfg.channels,
6771 mConfig.outputCfg.format);
6772 result.append(buffer);
6773
6774 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6775 result.append(buffer);
6776 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6777 for (size_t i = 0; i < mHandles.size(); ++i) {
6778 sp<EffectHandle> handle = mHandles[i].promote();
6779 if (handle != 0) {
6780 handle->dump(buffer, SIZE);
6781 result.append(buffer);
6782 }
6783 }
6784
6785 result.append("\n");
6786
6787 write(fd, result.string(), result.length());
6788
6789 if (locked) {
6790 mLock.unlock();
6791 }
6792
6793 return NO_ERROR;
6794}
6795
6796// ----------------------------------------------------------------------------
6797// EffectHandle implementation
6798// ----------------------------------------------------------------------------
6799
6800#undef LOG_TAG
6801#define LOG_TAG "AudioFlinger::EffectHandle"
6802
6803AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6804 const sp<AudioFlinger::Client>& client,
6805 const sp<IEffectClient>& effectClient,
6806 int32_t priority)
6807 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006808 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006809 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006810{
Steve Block71f2cf12011-10-20 11:56:00 +01006811 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006812
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006813 if (client == 0) {
6814 return;
6815 }
Eric Laurent65b65452010-06-01 23:49:17 -07006816 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6817 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6818 if (mCblkMemory != 0) {
6819 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6820
6821 if (mCblk) {
6822 new(mCblk) effect_param_cblk_t();
6823 mBuffer = (uint8_t *)mCblk + bufOffset;
6824 }
6825 } else {
6826 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6827 return;
6828 }
6829}
6830
6831AudioFlinger::EffectHandle::~EffectHandle()
6832{
Steve Block71f2cf12011-10-20 11:56:00 +01006833 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006834 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01006835 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006836}
6837
6838status_t AudioFlinger::EffectHandle::enable()
6839{
Steve Block71f2cf12011-10-20 11:56:00 +01006840 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006841 if (!mHasControl) return INVALID_OPERATION;
6842 if (mEffect == 0) return DEAD_OBJECT;
6843
Eric Laurent6752ec82011-08-10 10:37:50 -07006844 if (mEnabled) {
6845 return NO_ERROR;
6846 }
6847
Eric Laurentf82fccd2011-07-27 19:49:51 -07006848 mEnabled = true;
6849
6850 sp<ThreadBase> thread = mEffect->thread().promote();
6851 if (thread != 0) {
6852 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6853 }
6854
6855 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6856 if (mEffect->suspended()) {
6857 return NO_ERROR;
6858 }
6859
Eric Laurent6752ec82011-08-10 10:37:50 -07006860 status_t status = mEffect->setEnabled(true);
6861 if (status != NO_ERROR) {
6862 if (thread != 0) {
6863 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6864 }
6865 mEnabled = false;
6866 }
6867 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006868}
6869
6870status_t AudioFlinger::EffectHandle::disable()
6871{
Steve Block71f2cf12011-10-20 11:56:00 +01006872 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006873 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006874 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006875
Eric Laurent6752ec82011-08-10 10:37:50 -07006876 if (!mEnabled) {
6877 return NO_ERROR;
6878 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006879 mEnabled = false;
6880
6881 if (mEffect->suspended()) {
6882 return NO_ERROR;
6883 }
6884
6885 status_t status = mEffect->setEnabled(false);
6886
6887 sp<ThreadBase> thread = mEffect->thread().promote();
6888 if (thread != 0) {
6889 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6890 }
6891
6892 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006893}
6894
6895void AudioFlinger::EffectHandle::disconnect()
6896{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006897 disconnect(true);
6898}
6899
6900void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6901{
Steve Block71f2cf12011-10-20 11:56:00 +01006902 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006903 if (mEffect == 0) {
6904 return;
6905 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006906 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006907
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006908 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006909 sp<ThreadBase> thread = mEffect->thread().promote();
6910 if (thread != 0) {
6911 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6912 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006913 }
6914
Eric Laurent65b65452010-06-01 23:49:17 -07006915 // release sp on module => module destructor can be called now
6916 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006917 if (mClient != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006918 if (mCblk) {
6919 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6920 }
6921 mCblkMemory.clear(); // and free the shared memory
Eric Laurent65b65452010-06-01 23:49:17 -07006922 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6923 mClient.clear();
6924 }
6925}
6926
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006927status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6928 uint32_t cmdSize,
6929 void *pCmdData,
6930 uint32_t *replySize,
6931 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006932{
Steve Block71f2cf12011-10-20 11:56:00 +01006933// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006934// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006935
6936 // only get parameter command is permitted for applications not controlling the effect
6937 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6938 return INVALID_OPERATION;
6939 }
6940 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006941 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006942
6943 // handle commands that are not forwarded transparently to effect engine
6944 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6945 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6946 // no risk to block the whole media server process or mixer threads is we are stuck here
6947 Mutex::Autolock _l(mCblk->lock);
6948 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6949 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6950 mCblk->serverIndex = 0;
6951 mCblk->clientIndex = 0;
6952 return BAD_VALUE;
6953 }
6954 status_t status = NO_ERROR;
6955 while (mCblk->serverIndex < mCblk->clientIndex) {
6956 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006957 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006958 int *p = (int *)(mBuffer + mCblk->serverIndex);
6959 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006960 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6961 LOGW("command(): invalid parameter block size");
6962 break;
6963 }
Eric Laurent65b65452010-06-01 23:49:17 -07006964 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006965 if (param->psize == 0 || param->vsize == 0) {
6966 LOGW("command(): null parameter or value size");
6967 mCblk->serverIndex += size;
6968 continue;
6969 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006970 uint32_t psize = sizeof(effect_param_t) +
6971 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6972 param->vsize;
6973 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6974 psize,
6975 p,
6976 &rsize,
6977 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006978 // stop at first error encountered
6979 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006980 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006981 *(int *)pReplyData = reply;
6982 break;
6983 } else if (reply != NO_ERROR) {
6984 *(int *)pReplyData = reply;
6985 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006986 }
6987 mCblk->serverIndex += size;
6988 }
6989 mCblk->serverIndex = 0;
6990 mCblk->clientIndex = 0;
6991 return status;
6992 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006993 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006994 return enable();
6995 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006996 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006997 return disable();
6998 }
6999
7000 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7001}
7002
7003sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7004 return mCblkMemory;
7005}
7006
Eric Laurentf82fccd2011-07-27 19:49:51 -07007007void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07007008{
Steve Block71f2cf12011-10-20 11:56:00 +01007009 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07007010
7011 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007012 mEnabled = enabled;
7013
Eric Laurent65b65452010-06-01 23:49:17 -07007014 if (signal && mEffectClient != 0) {
7015 mEffectClient->controlStatusChanged(hasControl);
7016 }
7017}
7018
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007019void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7020 uint32_t cmdSize,
7021 void *pCmdData,
7022 uint32_t replySize,
7023 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007024{
7025 if (mEffectClient != 0) {
7026 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7027 }
7028}
7029
7030
7031
7032void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7033{
7034 if (mEffectClient != 0) {
7035 mEffectClient->enableStatusChanged(enabled);
7036 }
7037}
7038
7039status_t AudioFlinger::EffectHandle::onTransact(
7040 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7041{
7042 return BnEffect::onTransact(code, data, reply, flags);
7043}
7044
7045
7046void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7047{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007048 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Eric Laurent65b65452010-06-01 23:49:17 -07007049
7050 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7051 (mClient == NULL) ? getpid() : mClient->pid(),
7052 mPriority,
7053 mHasControl,
7054 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007055 mCblk ? mCblk->clientIndex : 0,
7056 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007057 );
7058
7059 if (locked) {
7060 mCblk->lock.unlock();
7061 }
7062}
7063
7064#undef LOG_TAG
7065#define LOG_TAG "AudioFlinger::EffectChain"
7066
7067AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7068 int sessionId)
Eric Laurentf9c361d2011-11-11 15:42:52 -08007069 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007070 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7071 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007072{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007073 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007074 sp<ThreadBase> thread = mThread.promote();
7075 if (thread == 0) {
7076 return;
7077 }
7078 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7079 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007080}
7081
7082AudioFlinger::EffectChain::~EffectChain()
7083{
7084 if (mOwnInBuffer) {
7085 delete mInBuffer;
7086 }
7087
7088}
7089
Eric Laurentf82fccd2011-07-27 19:49:51 -07007090// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007091sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007092{
7093 sp<EffectModule> effect;
7094 size_t size = mEffects.size();
7095
7096 for (size_t i = 0; i < size; i++) {
7097 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7098 effect = mEffects[i];
7099 break;
7100 }
7101 }
7102 return effect;
7103}
7104
Eric Laurentf82fccd2011-07-27 19:49:51 -07007105// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007106sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007107{
7108 sp<EffectModule> effect;
7109 size_t size = mEffects.size();
7110
7111 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007112 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7113 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07007114 effect = mEffects[i];
7115 break;
7116 }
7117 }
7118 return effect;
7119}
7120
Eric Laurentf82fccd2011-07-27 19:49:51 -07007121// getEffectFromType_l() must be called with ThreadBase::mLock held
7122sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7123 const effect_uuid_t *type)
7124{
7125 sp<EffectModule> effect;
7126 size_t size = mEffects.size();
7127
7128 for (size_t i = 0; i < size; i++) {
7129 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7130 effect = mEffects[i];
7131 break;
7132 }
7133 }
7134 return effect;
7135}
7136
Eric Laurent65b65452010-06-01 23:49:17 -07007137// Must be called with EffectChain::mLock locked
7138void AudioFlinger::EffectChain::process_l()
7139{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007140 sp<ThreadBase> thread = mThread.promote();
7141 if (thread == 0) {
7142 LOGW("process_l(): cannot promote mixer thread");
7143 return;
7144 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007145 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7146 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007147 // always process effects unless no more tracks are on the session and the effect tail
7148 // has been rendered
7149 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007150 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007151 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007152
Eric Laurentf9c361d2011-11-11 15:42:52 -08007153 if (!tracksOnSession && mTailBufferCount == 0) {
7154 doProcess = false;
7155 }
7156
7157 if (activeTrackCnt() == 0) {
7158 // if no track is active and the effect tail has not been rendered,
7159 // the input buffer must be cleared here as the mixer process will not do it
7160 if (tracksOnSession || mTailBufferCount > 0) {
7161 size_t numSamples = thread->frameCount() * thread->channelCount();
7162 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7163 if (mTailBufferCount > 0) {
7164 mTailBufferCount--;
7165 }
7166 }
7167 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007168 }
7169
Eric Laurent65b65452010-06-01 23:49:17 -07007170 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007171 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007172 for (size_t i = 0; i < size; i++) {
7173 mEffects[i]->process();
7174 }
Eric Laurent65b65452010-06-01 23:49:17 -07007175 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007176 for (size_t i = 0; i < size; i++) {
7177 mEffects[i]->updateState();
7178 }
Eric Laurent65b65452010-06-01 23:49:17 -07007179}
7180
Eric Laurent76c40f72010-07-15 12:50:15 -07007181// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007182status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007183{
7184 effect_descriptor_t desc = effect->desc();
7185 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7186
7187 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007188 effect->setChain(this);
7189 sp<ThreadBase> thread = mThread.promote();
7190 if (thread == 0) {
7191 return NO_INIT;
7192 }
7193 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007194
7195 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7196 // Auxiliary effects are inserted at the beginning of mEffects vector as
7197 // they are processed first and accumulated in chain input buffer
7198 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007199
Eric Laurent65b65452010-06-01 23:49:17 -07007200 // the input buffer for auxiliary effect contains mono samples in
7201 // 32 bit format. This is to avoid saturation in AudoMixer
7202 // accumulation stage. Saturation is done in EffectModule::process() before
7203 // calling the process in effect engine
7204 size_t numSamples = thread->frameCount();
7205 int32_t *buffer = new int32_t[numSamples];
7206 memset(buffer, 0, numSamples * sizeof(int32_t));
7207 effect->setInBuffer((int16_t *)buffer);
7208 // auxiliary effects output samples to chain input buffer for further processing
7209 // by insert effects
7210 effect->setOutBuffer(mInBuffer);
7211 } else {
7212 // Insert effects are inserted at the end of mEffects vector as they are processed
7213 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007214 // Insert effect order as a function of indicated preference:
7215 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7216 // another effect is present
7217 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7218 // last effect claiming first position
7219 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7220 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007221 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007222 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7223 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007224
7225 int size = (int)mEffects.size();
7226 int idx_insert = size;
7227 int idx_insert_first = -1;
7228 int idx_insert_last = -1;
7229
7230 for (int i = 0; i < size; i++) {
7231 effect_descriptor_t d = mEffects[i]->desc();
7232 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7233 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7234 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7235 // check invalid effect chaining combinations
7236 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007237 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007238 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007239 return INVALID_OPERATION;
7240 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007241 // remember position of first insert effect and by default
7242 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007243 if (idx_insert == size) {
7244 idx_insert = i;
7245 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007246 // remember position of last insert effect claiming
7247 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007248 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7249 idx_insert_first = i;
7250 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007251 // remember position of first insert effect claiming
7252 // last position
7253 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7254 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007255 idx_insert_last = i;
7256 }
7257 }
7258 }
7259
Eric Laurent53334cd2010-06-23 17:38:20 -07007260 // modify idx_insert from first position if needed
7261 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7262 if (idx_insert_last != -1) {
7263 idx_insert = idx_insert_last;
7264 } else {
7265 idx_insert = size;
7266 }
7267 } else {
7268 if (idx_insert_first != -1) {
7269 idx_insert = idx_insert_first + 1;
7270 }
Eric Laurent65b65452010-06-01 23:49:17 -07007271 }
7272
7273 // always read samples from chain input buffer
7274 effect->setInBuffer(mInBuffer);
7275
7276 // if last effect in the chain, output samples to chain
7277 // output buffer, otherwise to chain input buffer
7278 if (idx_insert == size) {
7279 if (idx_insert != 0) {
7280 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7281 mEffects[idx_insert-1]->configure();
7282 }
7283 effect->setOutBuffer(mOutBuffer);
7284 } else {
7285 effect->setOutBuffer(mInBuffer);
7286 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007287 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007288
Steve Block71f2cf12011-10-20 11:56:00 +01007289 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007290 }
7291 effect->configure();
7292 return NO_ERROR;
7293}
7294
Eric Laurent76c40f72010-07-15 12:50:15 -07007295// removeEffect_l() must be called with PlaybackThread::mLock held
7296size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007297{
7298 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007299 int size = (int)mEffects.size();
7300 int i;
7301 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7302
7303 for (i = 0; i < size; i++) {
7304 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007305 // calling stop here will remove pre-processing effect from the audio HAL.
7306 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7307 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007308 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7309 mEffects[i]->state() == EffectModule::STOPPING) {
7310 mEffects[i]->stop();
7311 }
Eric Laurent65b65452010-06-01 23:49:17 -07007312 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7313 delete[] effect->inBuffer();
7314 } else {
7315 if (i == size - 1 && i != 0) {
7316 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7317 mEffects[i - 1]->configure();
7318 }
7319 }
7320 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007321 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007322 break;
7323 }
7324 }
Eric Laurent65b65452010-06-01 23:49:17 -07007325
7326 return mEffects.size();
7327}
7328
Eric Laurent76c40f72010-07-15 12:50:15 -07007329// setDevice_l() must be called with PlaybackThread::mLock held
7330void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007331{
7332 size_t size = mEffects.size();
7333 for (size_t i = 0; i < size; i++) {
7334 mEffects[i]->setDevice(device);
7335 }
7336}
7337
Eric Laurent76c40f72010-07-15 12:50:15 -07007338// setMode_l() must be called with PlaybackThread::mLock held
7339void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007340{
7341 size_t size = mEffects.size();
7342 for (size_t i = 0; i < size; i++) {
7343 mEffects[i]->setMode(mode);
7344 }
7345}
7346
Eric Laurent76c40f72010-07-15 12:50:15 -07007347// setVolume_l() must be called with PlaybackThread::mLock held
7348bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007349{
7350 uint32_t newLeft = *left;
7351 uint32_t newRight = *right;
7352 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007353 int ctrlIdx = -1;
7354 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007355
Eric Laurent76c40f72010-07-15 12:50:15 -07007356 // first update volume controller
7357 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007358 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007359 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7360 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007361 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007362 break;
7363 }
7364 }
7365
7366 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007367 if (hasControl) {
7368 *left = mNewLeftVolume;
7369 *right = mNewRightVolume;
7370 }
7371 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007372 }
7373
7374 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007375 mLeftVolume = newLeft;
7376 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007377
7378 // second get volume update from volume controller
7379 if (ctrlIdx >= 0) {
7380 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007381 mNewLeftVolume = newLeft;
7382 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007383 }
7384 // then indicate volume to all other effects in chain.
7385 // Pass altered volume to effects before volume controller
7386 // and requested volume to effects after controller
7387 uint32_t lVol = newLeft;
7388 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007389
Eric Laurent65b65452010-06-01 23:49:17 -07007390 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007391 if ((int)i == ctrlIdx) continue;
7392 // this also works for ctrlIdx == -1 when there is no volume controller
7393 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007394 lVol = *left;
7395 rVol = *right;
7396 }
7397 mEffects[i]->setVolume(&lVol, &rVol, false);
7398 }
7399 *left = newLeft;
7400 *right = newRight;
7401
7402 return hasControl;
7403}
7404
Eric Laurent65b65452010-06-01 23:49:17 -07007405status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7406{
7407 const size_t SIZE = 256;
7408 char buffer[SIZE];
7409 String8 result;
7410
7411 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7412 result.append(buffer);
7413
7414 bool locked = tryLock(mLock);
7415 // failed to lock - AudioFlinger is probably deadlocked
7416 if (!locked) {
7417 result.append("\tCould not lock mutex:\n");
7418 }
7419
Eric Laurent76c40f72010-07-15 12:50:15 -07007420 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7421 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007422 mEffects.size(),
7423 (uint32_t)mInBuffer,
7424 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007425 mActiveTrackCnt);
7426 result.append(buffer);
7427 write(fd, result.string(), result.size());
7428
7429 for (size_t i = 0; i < mEffects.size(); ++i) {
7430 sp<EffectModule> effect = mEffects[i];
7431 if (effect != 0) {
7432 effect->dump(fd, args);
7433 }
7434 }
7435
7436 if (locked) {
7437 mLock.unlock();
7438 }
7439
7440 return NO_ERROR;
7441}
7442
Eric Laurentf82fccd2011-07-27 19:49:51 -07007443// must be called with ThreadBase::mLock held
7444void AudioFlinger::EffectChain::setEffectSuspended_l(
7445 const effect_uuid_t *type, bool suspend)
7446{
7447 sp<SuspendedEffectDesc> desc;
7448 // use effect type UUID timelow as key as there is no real risk of identical
7449 // timeLow fields among effect type UUIDs.
7450 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7451 if (suspend) {
7452 if (index >= 0) {
7453 desc = mSuspendedEffects.valueAt(index);
7454 } else {
7455 desc = new SuspendedEffectDesc();
7456 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7457 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007458 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007459 }
7460 if (desc->mRefCount++ == 0) {
7461 sp<EffectModule> effect = getEffectIfEnabled(type);
7462 if (effect != 0) {
7463 desc->mEffect = effect;
7464 effect->setSuspended(true);
7465 effect->setEnabled(false);
7466 }
7467 }
7468 } else {
7469 if (index < 0) {
7470 return;
7471 }
7472 desc = mSuspendedEffects.valueAt(index);
7473 if (desc->mRefCount <= 0) {
7474 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7475 desc->mRefCount = 1;
7476 }
7477 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007478 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007479 if (desc->mEffect != 0) {
7480 sp<EffectModule> effect = desc->mEffect.promote();
7481 if (effect != 0) {
7482 effect->setSuspended(false);
7483 sp<EffectHandle> handle = effect->controlHandle();
7484 if (handle != 0) {
7485 effect->setEnabled(handle->enabled());
7486 }
7487 }
7488 desc->mEffect.clear();
7489 }
7490 mSuspendedEffects.removeItemsAt(index);
7491 }
7492 }
7493}
7494
7495// must be called with ThreadBase::mLock held
7496void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7497{
7498 sp<SuspendedEffectDesc> desc;
7499
7500 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7501 if (suspend) {
7502 if (index >= 0) {
7503 desc = mSuspendedEffects.valueAt(index);
7504 } else {
7505 desc = new SuspendedEffectDesc();
7506 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007507 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007508 }
7509 if (desc->mRefCount++ == 0) {
7510 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7511 for (size_t i = 0; i < effects.size(); i++) {
7512 setEffectSuspended_l(&effects[i]->desc().type, true);
7513 }
7514 }
7515 } else {
7516 if (index < 0) {
7517 return;
7518 }
7519 desc = mSuspendedEffects.valueAt(index);
7520 if (desc->mRefCount <= 0) {
7521 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7522 desc->mRefCount = 1;
7523 }
7524 if (--desc->mRefCount == 0) {
7525 Vector<const effect_uuid_t *> types;
7526 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7527 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7528 continue;
7529 }
7530 types.add(&mSuspendedEffects.valueAt(i)->mType);
7531 }
7532 for (size_t i = 0; i < types.size(); i++) {
7533 setEffectSuspended_l(types[i], false);
7534 }
Steve Block71f2cf12011-10-20 11:56:00 +01007535 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007536 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7537 }
7538 }
7539}
7540
Eric Laurent5e7acae2011-09-23 08:40:41 -07007541
7542// The volume effect is used for automated tests only
7543#ifndef OPENSL_ES_H_
7544static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7545 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7546const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7547#endif //OPENSL_ES_H_
7548
Eric Laurent6752ec82011-08-10 10:37:50 -07007549bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7550{
7551 // auxiliary effects and visualizer are never suspended on output mix
7552 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7553 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007554 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7555 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007556 return false;
7557 }
7558 return true;
7559}
7560
Eric Laurentf82fccd2011-07-27 19:49:51 -07007561Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7562{
7563 Vector< sp<EffectModule> > effects;
7564 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007565 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07007566 continue;
7567 }
7568 effects.add(mEffects[i]);
7569 }
7570 return effects;
7571}
7572
7573sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7574 const effect_uuid_t *type)
7575{
7576 sp<EffectModule> effect;
7577 effect = getEffectFromType_l(type);
7578 if (effect != 0 && !effect->isEnabled()) {
7579 effect.clear();
7580 }
7581 return effect;
7582}
7583
7584void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7585 bool enabled)
7586{
7587 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7588 if (enabled) {
7589 if (index < 0) {
7590 // if the effect is not suspend check if all effects are suspended
7591 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7592 if (index < 0) {
7593 return;
7594 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007595 if (!isEffectEligibleForSuspend(effect->desc())) {
7596 return;
7597 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007598 setEffectSuspended_l(&effect->desc().type, enabled);
7599 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007600 if (index < 0) {
7601 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7602 return;
7603 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007604 }
Steve Block71f2cf12011-10-20 11:56:00 +01007605 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007606 effect->desc().type.timeLow);
7607 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7608 // if effect is requested to suspended but was not yet enabled, supend it now.
7609 if (desc->mEffect == 0) {
7610 desc->mEffect = effect;
7611 effect->setEnabled(false);
7612 effect->setSuspended(true);
7613 }
7614 } else {
7615 if (index < 0) {
7616 return;
7617 }
Steve Block71f2cf12011-10-20 11:56:00 +01007618 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007619 effect->desc().type.timeLow);
7620 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7621 desc->mEffect.clear();
7622 effect->setSuspended(false);
7623 }
7624}
7625
Eric Laurent65b65452010-06-01 23:49:17 -07007626#undef LOG_TAG
7627#define LOG_TAG "AudioFlinger"
7628
Eric Laurenta553c252009-07-17 12:17:14 -07007629// ----------------------------------------------------------------------------
7630
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007631status_t AudioFlinger::onTransact(
7632 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7633{
7634 return BnAudioFlinger::onTransact(code, data, reply, flags);
7635}
7636
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007637}; // namespace android