blob: a893cf2093b7ec40deb4a0f83ab4677d9e13ffe0 [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>
38
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039#include <media/AudioTrack.h>
40#include <media/AudioRecord.h>
Gloria Wang9b3f1522011-02-24 14:51:45 -080041#include <media/IMediaPlayerService.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070044#include <private/media/AudioEffectShared.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070045
Dima Zavin34bb4192011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin290029d2011-06-13 18:16:26 -070047#include <hardware/audio.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Eric Laurent53334cd2010-06-23 17:38:20 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent5cc05262011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent6639b552011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Eric Laurent65b65452010-06-01 23:49:17 -070056
Glenn Kasten490909d2011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Glenn Kastenda494f92011-07-08 15:26:12 -070059#include <cpustats/ThreadCpuUsage.h>
Eric Laurent6dbdc402011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kastenda494f92011-07-08 15:26:12 -070061// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
62
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063// ----------------------------------------------------------------------------
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064
Eric Laurent8ed6ed02010-07-13 04:45:46 -070065
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066namespace android {
67
Glenn Kasten62de3db2011-12-12 09:04:45 -080068static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
69static const char kHardwareLockedString[] = "Hardware lock is taken\n";
The Android Open Source Project10592532009-03-18 17:39:46 -070070
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080071//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070072static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070073static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070074
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080079// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070083
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070084static const int kDumpLockRetries = 50;
Glenn Kastencbfe2e12011-12-13 11:04:14 -080085static const int kDumpLockSleepUs = 20000;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070086
Glenn Kastencbfe2e12011-12-13 11:04:14 -080087// don't warn about blocked writes or record buffer overflows more often than this
88static const nsecs_t kWarningThrottleNs = seconds(5);
Dave Sparksd0ac8c02009-09-30 03:09:03 -070089
Eric Laurent464d5b32011-06-17 21:29:58 -070090// RecordThread loop sleep time upon application overrun or audio HAL read error
91static const int kRecordThreadSleepUs = 5000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
Glenn Kastencbfe2e12011-12-13 11:04:14 -080093// maximum time to wait for setParameters to complete
94static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent5f37be32011-09-13 11:40:21 -070095
Eric Laurentf1f5fc82011-11-22 18:50:29 -080096// minimum sleep time for the mixer thread loop when tracks are active but in underrun
97static const uint32_t kMinThreadSleepTimeUs = 5000;
98// maximum divider applied to the active sleep time in the mixer thread loop
99static const uint32_t kMaxThreadSleepTimeShift = 2;
100
101
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700102// ----------------------------------------------------------------------------
103
104static bool recordingAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
107 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
108 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700109}
110
111static bool settingsAllowed() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700112 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
113 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
114 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
115 return ok;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700116}
117
Gloria Wang9b3f1522011-02-24 14:51:45 -0800118// To collect the amplifier usage
119static void addBatteryData(uint32_t params) {
120 sp<IBinder> binder =
121 defaultServiceManager()->getService(String16("media.player"));
122 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
123 if (service.get() == NULL) {
124 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
125 return;
126 }
127
128 service->addBatteryData(params);
129}
130
Dima Zavin31f188892011-04-18 16:57:27 -0700131static int load_audio_interface(const char *if_name, const hw_module_t **mod,
132 audio_hw_device_t **dev)
133{
134 int rc;
135
136 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
137 if (rc)
138 goto out;
139
140 rc = audio_hw_device_open(*mod, dev);
141 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
142 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
143 if (rc)
144 goto out;
145
146 return 0;
147
148out:
149 *mod = NULL;
150 *dev = NULL;
151 return rc;
152}
153
Glenn Kasten62de3db2011-12-12 09:04:45 -0800154static const char * const audio_interfaces[] = {
Dima Zavin31f188892011-04-18 16:57:27 -0700155 "primary",
156 "a2dp",
157 "usb",
158};
159#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
160
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700161// ----------------------------------------------------------------------------
162
163AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 : BnAudioFlinger(),
Glenn Kastenc434c902011-12-13 11:53:26 -0800165 mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700166 mBtNrecIsOff(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700167{
Dima Zavin2986f5b2011-04-19 19:04:32 -0700168}
169
170void AudioFlinger::onFirstRef()
171{
Dima Zavin31f188892011-04-18 16:57:27 -0700172 int rc = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700173
Eric Laurent01635942011-01-18 18:39:02 -0800174 Mutex::Autolock _l(mLock);
175
Dima Zavin31f188892011-04-18 16:57:27 -0700176 /* TODO: move all this work into an Init() function */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700177 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700178
Dima Zavin31f188892011-04-18 16:57:27 -0700179 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
180 const hw_module_t *mod;
181 audio_hw_device_t *dev;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700182
Dima Zavin31f188892011-04-18 16:57:27 -0700183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184 if (rc)
185 continue;
186
Steve Block6215d3f2012-01-04 20:05:49 +0000187 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin31f188892011-04-18 16:57:27 -0700188 mod->name, mod->id);
189 mAudioHwDevs.push(dev);
190
191 if (!mPrimaryHardwareDev) {
192 mPrimaryHardwareDev = dev;
Steve Block6215d3f2012-01-04 20:05:49 +0000193 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin2986f5b2011-04-19 19:04:32 -0700194 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin31f188892011-04-18 16:57:27 -0700195 }
196 }
Eric Laurenta553c252009-07-17 12:17:14 -0700197
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700198 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700199
Dima Zavin31f188892011-04-18 16:57:27 -0700200 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
201 LOGE("Primary audio interface not found");
202 return;
203 }
204
205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
206 audio_hw_device_t *dev = mAudioHwDevs[i];
207
208 mHardwareStatus = AUDIO_HW_INIT;
209 rc = dev->init_check(dev);
210 if (rc == 0) {
211 AutoMutex lock(mHardwareLock);
212
213 mMode = AUDIO_MODE_NORMAL;
214 mHardwareStatus = AUDIO_HW_SET_MODE;
215 dev->set_mode(dev, mMode);
216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
217 dev->set_master_volume(dev, 1.0f);
218 mHardwareStatus = AUDIO_HW_IDLE;
219 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700220 }
221}
222
Dima Zavin2986f5b2011-04-19 19:04:32 -0700223status_t AudioFlinger::initCheck() const
224{
225 Mutex::Autolock _l(mLock);
226 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
227 return NO_INIT;
228 return NO_ERROR;
229}
230
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700231AudioFlinger::~AudioFlinger()
232{
Dima Zavin31f188892011-04-18 16:57:27 -0700233 int num_devs = mAudioHwDevs.size();
234
Eric Laurent7954c462009-08-28 10:39:03 -0700235 while (!mRecordThreads.isEmpty()) {
236 // closeInput() will remove first entry from mRecordThreads
237 closeInput(mRecordThreads.keyAt(0));
238 }
239 while (!mPlaybackThreads.isEmpty()) {
240 // closeOutput() will remove first entry from mPlaybackThreads
241 closeOutput(mPlaybackThreads.keyAt(0));
242 }
Dima Zavin31f188892011-04-18 16:57:27 -0700243
244 for (int i = 0; i < num_devs; i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 audio_hw_device_close(dev);
Eric Laurent7954c462009-08-28 10:39:03 -0700247 }
Dima Zavin31f188892011-04-18 16:57:27 -0700248 mAudioHwDevs.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800249}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800250
Dima Zavin31f188892011-04-18 16:57:27 -0700251audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
252{
253 /* first matching HW device is returned */
254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
255 audio_hw_device_t *dev = mAudioHwDevs[i];
256 if ((dev->get_supported_devices(dev) & devices) == devices)
257 return dev;
258 }
259 return NULL;
260}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700261
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700262status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
263{
264 const size_t SIZE = 256;
265 char buffer[SIZE];
266 String8 result;
267
268 result.append("Clients:\n");
269 for (size_t i = 0; i < mClients.size(); ++i) {
270 wp<Client> wClient = mClients.valueAt(i);
271 if (wClient != 0) {
272 sp<Client> client = wClient.promote();
273 if (client != 0) {
274 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
275 result.append(buffer);
276 }
277 }
278 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700279
280 result.append("Global session refs:\n");
281 result.append(" session pid cnt\n");
282 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
283 AudioSessionRef *r = mAudioSessionRefs[i];
284 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
285 result.append(buffer);
286 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700287 write(fd, result.string(), result.size());
288 return NO_ERROR;
289}
290
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700291
292status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
293{
294 const size_t SIZE = 256;
295 char buffer[SIZE];
296 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700297 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700298
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700299 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700300 result.append(buffer);
301 write(fd, result.string(), result.size());
302 return NO_ERROR;
303}
304
305status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
306{
307 const size_t SIZE = 256;
308 char buffer[SIZE];
309 String8 result;
310 snprintf(buffer, SIZE, "Permission Denial: "
311 "can't dump AudioFlinger from pid=%d, uid=%d\n",
312 IPCThreadState::self()->getCallingPid(),
313 IPCThreadState::self()->getCallingUid());
314 result.append(buffer);
315 write(fd, result.string(), result.size());
316 return NO_ERROR;
317}
318
The Android Open Source Project10592532009-03-18 17:39:46 -0700319static bool tryLock(Mutex& mutex)
320{
321 bool locked = false;
322 for (int i = 0; i < kDumpLockRetries; ++i) {
323 if (mutex.tryLock() == NO_ERROR) {
324 locked = true;
325 break;
326 }
Glenn Kastencbfe2e12011-12-13 11:04:14 -0800327 usleep(kDumpLockSleepUs);
The Android Open Source Project10592532009-03-18 17:39:46 -0700328 }
329 return locked;
330}
331
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700332status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
333{
334 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
335 dumpPermissionDenial(fd, args);
336 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700337 // get state of hardware lock
338 bool hardwareLocked = tryLock(mHardwareLock);
339 if (!hardwareLocked) {
340 String8 result(kHardwareLockedString);
341 write(fd, result.string(), result.size());
342 } else {
343 mHardwareLock.unlock();
344 }
345
346 bool locked = tryLock(mLock);
347
348 // failed to lock - AudioFlinger is probably deadlocked
349 if (!locked) {
350 String8 result(kDeadlockedString);
351 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700352 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700353
354 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700355 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356
Eric Laurenta553c252009-07-17 12:17:14 -0700357 // dump playback threads
358 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700359 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700360 }
361
362 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700363 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700364 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366
Dima Zavin31f188892011-04-18 16:57:27 -0700367 // dump all hardware devs
368 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
369 audio_hw_device_t *dev = mAudioHwDevs[i];
370 dev->dump(dev, fd);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700371 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700372 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700373 }
374 return NO_ERROR;
375}
376
Eric Laurenta553c252009-07-17 12:17:14 -0700377
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700378// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379
380
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700381sp<IAudioTrack> AudioFlinger::createTrack(
382 pid_t pid,
383 int streamType,
384 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700385 uint32_t format,
386 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800387 int frameCount,
388 uint32_t flags,
389 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700390 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700391 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800392 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700393{
Eric Laurenta553c252009-07-17 12:17:14 -0700394 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700395 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700396 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800397 wp<Client> wclient;
398 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700399 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700400
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700401 if (streamType >= AUDIO_STREAM_CNT) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -0700402 LOGE("createTrack() invalid stream type %d", streamType);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800403 lStatus = BAD_VALUE;
404 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700405 }
406
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800407 {
408 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700409 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent493941b2010-07-28 01:32:47 -0700410 PlaybackThread *effectThread = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -0700411 if (thread == NULL) {
412 LOGE("unknown output thread");
413 lStatus = BAD_VALUE;
414 goto Exit;
415 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800416
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800417 wclient = mClients.valueFor(pid);
418
419 if (wclient != NULL) {
420 client = wclient.promote();
421 } else {
422 client = new Client(this, pid);
423 mClients.add(pid, client);
424 }
Eric Laurent65b65452010-06-01 23:49:17 -0700425
Steve Block71f2cf12011-10-20 11:56:00 +0100426 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700427 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700428 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent493941b2010-07-28 01:32:47 -0700429 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
430 if (mPlaybackThreads.keyAt(i) != output) {
431 // prevent same audio session on different output threads
432 uint32_t sessions = t->hasAudioSession(*sessionId);
433 if (sessions & PlaybackThread::TRACK_SESSION) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -0700434 LOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent493941b2010-07-28 01:32:47 -0700435 lStatus = BAD_VALUE;
436 goto Exit;
437 }
438 // check if an effect with same session ID is waiting for a track to be created
439 if (sessions & PlaybackThread::EFFECT_SESSION) {
440 effectThread = t.get();
441 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700442 }
443 }
Eric Laurent65b65452010-06-01 23:49:17 -0700444 lSessionId = *sessionId;
445 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700446 // if no audio session id is provided, create one here
Eric Laurent464d5b32011-06-17 21:29:58 -0700447 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -0700448 if (sessionId != NULL) {
449 *sessionId = lSessionId;
450 }
451 }
Steve Block71f2cf12011-10-20 11:56:00 +0100452 ALOGV("createTrack() lSessionId: %d", lSessionId);
Eric Laurent65b65452010-06-01 23:49:17 -0700453
Eric Laurenta553c252009-07-17 12:17:14 -0700454 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700455 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent493941b2010-07-28 01:32:47 -0700456
457 // move effect chain to this output thread if an effect on same session was waiting
458 // for a track to be created
459 if (lStatus == NO_ERROR && effectThread != NULL) {
460 Mutex::Autolock _dl(thread->mLock);
461 Mutex::Autolock _sl(effectThread->mLock);
462 moveEffectChain_l(lSessionId, effectThread, thread, true);
463 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700464 }
465 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800466 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700467 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700468 // remove local strong reference to Client before deleting the Track so that the Client
469 // destructor is called by the TrackBase destructor with mLock held
470 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700471 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800472 }
473
474Exit:
475 if(status) {
476 *status = lStatus;
477 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700478 return trackHandle;
479}
480
Eric Laurentddb78e72009-07-28 08:44:33 -0700481uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700482{
Eric Laurenta553c252009-07-17 12:17:14 -0700483 Mutex::Autolock _l(mLock);
484 PlaybackThread *thread = checkPlaybackThread_l(output);
485 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700486 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700487 return 0;
488 }
489 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700490}
491
Eric Laurentddb78e72009-07-28 08:44:33 -0700492int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700493{
Eric Laurenta553c252009-07-17 12:17:14 -0700494 Mutex::Autolock _l(mLock);
495 PlaybackThread *thread = checkPlaybackThread_l(output);
496 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700497 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700498 return 0;
499 }
500 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700501}
502
Jean-Michel Trivi54392232011-05-24 15:53:33 -0700503uint32_t AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700504{
Eric Laurenta553c252009-07-17 12:17:14 -0700505 Mutex::Autolock _l(mLock);
506 PlaybackThread *thread = checkPlaybackThread_l(output);
507 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700508 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700509 return 0;
510 }
511 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700512}
513
Eric Laurentddb78e72009-07-28 08:44:33 -0700514size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700515{
Eric Laurenta553c252009-07-17 12:17:14 -0700516 Mutex::Autolock _l(mLock);
517 PlaybackThread *thread = checkPlaybackThread_l(output);
518 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700519 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700520 return 0;
521 }
522 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700523}
524
Eric Laurentddb78e72009-07-28 08:44:33 -0700525uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800526{
Eric Laurenta553c252009-07-17 12:17:14 -0700527 Mutex::Autolock _l(mLock);
528 PlaybackThread *thread = checkPlaybackThread_l(output);
529 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700530 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700531 return 0;
532 }
533 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800534}
535
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700536status_t AudioFlinger::setMasterVolume(float value)
537{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700538 status_t ret = initCheck();
539 if (ret != NO_ERROR) {
540 return ret;
541 }
542
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700543 // check calling permissions
544 if (!settingsAllowed()) {
545 return PERMISSION_DENIED;
546 }
547
548 // when hw supports master volume, don't scale in sw mixer
Eric Laurent01635942011-01-18 18:39:02 -0800549 { // scope for the lock
550 AutoMutex lock(mHardwareLock);
551 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin31f188892011-04-18 16:57:27 -0700552 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent01635942011-01-18 18:39:02 -0800553 value = 1.0f;
554 }
555 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700556 }
Eric Laurenta553c252009-07-17 12:17:14 -0700557
Eric Laurent01635942011-01-18 18:39:02 -0800558 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700559 mMasterVolume = value;
560 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700561 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700562
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700563 return NO_ERROR;
564}
565
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700566status_t AudioFlinger::setMode(int mode)
567{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700568 status_t ret = initCheck();
569 if (ret != NO_ERROR) {
570 return ret;
571 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700572
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700573 // check calling permissions
574 if (!settingsAllowed()) {
575 return PERMISSION_DENIED;
576 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700577 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700578 LOGW("Illegal value: setMode(%d)", mode);
579 return BAD_VALUE;
580 }
581
Eric Laurent53334cd2010-06-23 17:38:20 -0700582 { // scope for the lock
583 AutoMutex lock(mHardwareLock);
584 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin31f188892011-04-18 16:57:27 -0700585 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700586 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800587 }
Eric Laurent53334cd2010-06-23 17:38:20 -0700588
589 if (NO_ERROR == ret) {
590 Mutex::Autolock _l(mLock);
591 mMode = mode;
592 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
593 mPlaybackThreads.valueAt(i)->setMode(mode);
Eric Laurent53334cd2010-06-23 17:38:20 -0700594 }
595
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700596 return ret;
597}
598
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700599status_t AudioFlinger::setMicMute(bool state)
600{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700601 status_t ret = initCheck();
602 if (ret != NO_ERROR) {
603 return ret;
604 }
605
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700606 // check calling permissions
607 if (!settingsAllowed()) {
608 return PERMISSION_DENIED;
609 }
610
611 AutoMutex lock(mHardwareLock);
612 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700613 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700614 mHardwareStatus = AUDIO_HW_IDLE;
615 return ret;
616}
617
618bool AudioFlinger::getMicMute() const
619{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700620 status_t ret = initCheck();
621 if (ret != NO_ERROR) {
622 return false;
623 }
624
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700625 bool state = AUDIO_MODE_INVALID;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700626 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin31f188892011-04-18 16:57:27 -0700627 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700628 mHardwareStatus = AUDIO_HW_IDLE;
629 return state;
630}
631
632status_t AudioFlinger::setMasterMute(bool muted)
633{
634 // check calling permissions
635 if (!settingsAllowed()) {
636 return PERMISSION_DENIED;
637 }
Eric Laurenta553c252009-07-17 12:17:14 -0700638
Eric Laurent01635942011-01-18 18:39:02 -0800639 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700640 mMasterMute = muted;
641 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700642 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700643
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700644 return NO_ERROR;
645}
646
647float AudioFlinger::masterVolume() const
648{
Eric Laurenta553c252009-07-17 12:17:14 -0700649 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700650}
651
652bool AudioFlinger::masterMute() const
653{
Eric Laurenta553c252009-07-17 12:17:14 -0700654 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700655}
656
Eric Laurentddb78e72009-07-28 08:44:33 -0700657status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700658{
659 // check calling permissions
660 if (!settingsAllowed()) {
661 return PERMISSION_DENIED;
662 }
663
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700664 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -0700665 LOGE("setStreamVolume() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700666 return BAD_VALUE;
667 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800668
Eric Laurenta553c252009-07-17 12:17:14 -0700669 AutoMutex lock(mLock);
670 PlaybackThread *thread = NULL;
671 if (output) {
672 thread = checkPlaybackThread_l(output);
673 if (thread == NULL) {
674 return BAD_VALUE;
675 }
676 }
677
Eric Laurenta553c252009-07-17 12:17:14 -0700678 mStreamTypes[stream].volume = value;
679
680 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700681 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700682 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700683 }
Eric Laurenta553c252009-07-17 12:17:14 -0700684 } else {
685 thread->setStreamVolume(stream, value);
686 }
Eric Laurentef028272009-04-21 07:56:33 -0700687
Eric Laurent415f3e22009-10-21 08:14:22 -0700688 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700689}
690
691status_t AudioFlinger::setStreamMute(int stream, bool muted)
692{
693 // check calling permissions
694 if (!settingsAllowed()) {
695 return PERMISSION_DENIED;
696 }
697
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700698 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
699 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -0700700 LOGE("setStreamMute() invalid stream %d", stream);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700701 return BAD_VALUE;
702 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700703
Eric Laurent01635942011-01-18 18:39:02 -0800704 AutoMutex lock(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700705 mStreamTypes[stream].mute = muted;
706 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700707 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700709 return NO_ERROR;
710}
711
Eric Laurentddb78e72009-07-28 08:44:33 -0700712float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700713{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700714 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700715 return 0.0f;
716 }
Eric Laurenta553c252009-07-17 12:17:14 -0700717
718 AutoMutex lock(mLock);
719 float volume;
720 if (output) {
721 PlaybackThread *thread = checkPlaybackThread_l(output);
722 if (thread == NULL) {
723 return 0.0f;
724 }
725 volume = thread->streamVolume(stream);
726 } else {
727 volume = mStreamTypes[stream].volume;
728 }
729
Eric Laurentef028272009-04-21 07:56:33 -0700730 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700731}
732
733bool AudioFlinger::streamMute(int stream) const
734{
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700735 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700736 return true;
737 }
Eric Laurenta553c252009-07-17 12:17:14 -0700738
739 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700740}
741
Eric Laurentddb78e72009-07-28 08:44:33 -0700742status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700743{
Eric Laurenta553c252009-07-17 12:17:14 -0700744 status_t result;
745
Steve Block71f2cf12011-10-20 11:56:00 +0100746 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700747 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
748 // check calling permissions
749 if (!settingsAllowed()) {
750 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800751 }
Eric Laurenta553c252009-07-17 12:17:14 -0700752
753 // ioHandle == 0 means the parameters are global to the audio hardware interface
754 if (ioHandle == 0) {
755 AutoMutex lock(mHardwareLock);
756 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin31f188892011-04-18 16:57:27 -0700757 status_t final_result = NO_ERROR;
758 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
759 audio_hw_device_t *dev = mAudioHwDevs[i];
760 result = dev->set_parameters(dev, keyValuePairs.string());
761 final_result = result ?: final_result;
762 }
Eric Laurenta553c252009-07-17 12:17:14 -0700763 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent6639b552011-08-01 09:52:20 -0700764 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
765 AudioParameter param = AudioParameter(keyValuePairs);
766 String8 value;
767 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
768 Mutex::Autolock _l(mLock);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700769 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
770 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent6639b552011-08-01 09:52:20 -0700771 for (size_t i = 0; i < mRecordThreads.size(); i++) {
772 sp<RecordThread> thread = mRecordThreads.valueAt(i);
773 RecordThread::RecordTrack *track = thread->track();
774 if (track != NULL) {
775 audio_devices_t device = (audio_devices_t)(
776 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700777 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700778 thread->setEffectSuspended(FX_IID_AEC,
779 suspend,
780 track->sessionId());
781 thread->setEffectSuspended(FX_IID_NS,
782 suspend,
783 track->sessionId());
784 }
785 }
Eric Laurent2d95dfb2011-08-29 12:42:48 -0700786 mBtNrecIsOff = btNrecIsOff;
Eric Laurent6639b552011-08-01 09:52:20 -0700787 }
788 }
Dima Zavin31f188892011-04-18 16:57:27 -0700789 return final_result;
Eric Laurenta553c252009-07-17 12:17:14 -0700790 }
791
Eric Laurentb7d94602009-09-29 11:12:57 -0700792 // hold a strong ref on thread in case closeOutput() or closeInput() is called
793 // and the thread is exited once the lock is released
794 sp<ThreadBase> thread;
795 {
796 Mutex::Autolock _l(mLock);
797 thread = checkPlaybackThread_l(ioHandle);
798 if (thread == NULL) {
799 thread = checkRecordThread_l(ioHandle);
Eric Laurent464d5b32011-06-17 21:29:58 -0700800 } else if (thread.get() == primaryPlaybackThread_l()) {
801 // indicate output device change to all input threads for pre processing
802 AudioParameter param = AudioParameter(keyValuePairs);
803 int value;
804 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
805 for (size_t i = 0; i < mRecordThreads.size(); i++) {
806 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
807 }
808 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700809 }
Eric Laurenta553c252009-07-17 12:17:14 -0700810 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700811 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800812 result = thread->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800813 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700814 }
Eric Laurenta553c252009-07-17 12:17:14 -0700815 return BAD_VALUE;
816}
817
Eric Laurentddb78e72009-07-28 08:44:33 -0700818String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700819{
Steve Block71f2cf12011-10-20 11:56:00 +0100820// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700821// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
822
823 if (ioHandle == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700824 String8 out_s8;
825
Dima Zavin31f188892011-04-18 16:57:27 -0700826 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
827 audio_hw_device_t *dev = mAudioHwDevs[i];
828 char *s = dev->get_parameters(dev, keys.string());
829 out_s8 += String8(s);
830 free(s);
831 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -0700832 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -0700833 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700834
835 Mutex::Autolock _l(mLock);
836
Eric Laurenta553c252009-07-17 12:17:14 -0700837 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
838 if (playbackThread != NULL) {
839 return playbackThread->getParameters(keys);
840 }
841 RecordThread *recordThread = checkRecordThread_l(ioHandle);
842 if (recordThread != NULL) {
843 return recordThread->getParameters(keys);
844 }
845 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700846}
847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
849{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700850 status_t ret = initCheck();
851 if (ret != NO_ERROR) {
852 return 0;
853 }
854
Dima Zavin31f188892011-04-18 16:57:27 -0700855 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856}
857
Eric Laurent47d0a922010-02-26 02:47:27 -0800858unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
859{
860 if (ioHandle == 0) {
861 return 0;
862 }
863
864 Mutex::Autolock _l(mLock);
865
866 RecordThread *recordThread = checkRecordThread_l(ioHandle);
867 if (recordThread != NULL) {
868 return recordThread->getInputFramesLost();
869 }
870 return 0;
871}
872
Eric Laurent415f3e22009-10-21 08:14:22 -0700873status_t AudioFlinger::setVoiceVolume(float value)
874{
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700875 status_t ret = initCheck();
876 if (ret != NO_ERROR) {
877 return ret;
878 }
879
Eric Laurent415f3e22009-10-21 08:14:22 -0700880 // check calling permissions
881 if (!settingsAllowed()) {
882 return PERMISSION_DENIED;
883 }
884
885 AutoMutex lock(mHardwareLock);
886 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurent8b4dbf72011-08-23 08:25:03 -0700887 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700888 mHardwareStatus = AUDIO_HW_IDLE;
889
890 return ret;
891}
892
Eric Laurent0986e792010-01-19 17:37:09 -0800893status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
894{
895 status_t status;
896
897 Mutex::Autolock _l(mLock);
898
899 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
900 if (playbackThread != NULL) {
901 return playbackThread->getRenderPosition(halFrames, dspFrames);
902 }
903
904 return BAD_VALUE;
905}
906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
908{
Eric Laurenta553c252009-07-17 12:17:14 -0700909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 Mutex::Autolock _l(mLock);
911
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700912 int pid = IPCThreadState::self()->getCallingPid();
913 if (mNotificationClients.indexOfKey(pid) < 0) {
914 sp<NotificationClient> notificationClient = new NotificationClient(this,
915 client,
916 pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100917 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700918
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700919 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700920
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700921 sp<IBinder> binder = client->asBinder();
922 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700924 // the config change is always sent from playback or record threads to avoid deadlock
925 // with AudioSystem::gLock
926 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
927 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
928 }
Eric Laurenta553c252009-07-17 12:17:14 -0700929
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700930 for (size_t i = 0; i < mRecordThreads.size(); i++) {
931 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 }
933 }
934}
935
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700936void AudioFlinger::removeNotificationClient(pid_t pid)
937{
938 Mutex::Autolock _l(mLock);
939
940 int index = mNotificationClients.indexOfKey(pid);
941 if (index >= 0) {
942 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block71f2cf12011-10-20 11:56:00 +0100943 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700944 mNotificationClients.removeItem(pid);
945 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700946
Steve Block71f2cf12011-10-20 11:56:00 +0100947 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700948 int num = mAudioSessionRefs.size();
949 bool removed = false;
950 for (int i = 0; i< num; i++) {
951 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +0100952 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700953 if (ref->pid == pid) {
Steve Block71f2cf12011-10-20 11:56:00 +0100954 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -0700955 mAudioSessionRefs.removeAt(i);
956 delete ref;
957 removed = true;
958 i--;
959 num--;
960 }
961 }
962 if (removed) {
963 purgeStaleEffects_l();
964 }
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700965}
966
Eric Laurent296a0ec2009-09-15 07:10:12 -0700967// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700968void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
969{
Eric Laurent49f02be2009-11-19 09:00:56 -0800970 size_t size = mNotificationClients.size();
971 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700972 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700973 }
974}
975
Eric Laurentb9481d82009-09-17 05:12:56 -0700976// removeClient_l() must be called with AudioFlinger::mLock held
977void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700978{
Steve Block71f2cf12011-10-20 11:56:00 +0100979 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700980 mClients.removeItem(pid);
981}
982
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700983
Eric Laurenta553c252009-07-17 12:17:14 -0700984// ----------------------------------------------------------------------------
985
Eric Laurent464d5b32011-06-17 21:29:58 -0700986AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Eric Laurenta553c252009-07-17 12:17:14 -0700987 : Thread(false),
988 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent6dbdc402011-07-22 09:04:31 -0700989 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
990 mDevice(device)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700991{
Eric Laurent6dbdc402011-07-22 09:04:31 -0700992 mDeathRecipient = new PMDeathRecipient(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993}
994
Eric Laurenta553c252009-07-17 12:17:14 -0700995AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700997 mParamCond.broadcast();
Eric Laurent6dbdc402011-07-22 09:04:31 -0700998 // do not lock the mutex in destructor
999 releaseWakeLock_l();
Eric Laurent4a64a6e2011-09-27 12:07:15 -07001000 if (mPowerManager != 0) {
1001 sp<IBinder> binder = mPowerManager->asBinder();
1002 binder->unlinkToDeath(mDeathRecipient);
1003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004}
1005
Eric Laurenta553c252009-07-17 12:17:14 -07001006void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001007{
Glenn Kastene5fb2632011-12-14 10:28:06 -08001008 // keep a strong ref on ourself so that we won't get
Eric Laurenta553c252009-07-17 12:17:14 -07001009 // destroyed in the middle of requestExitAndWait()
1010 sp <ThreadBase> strongMe = this;
1011
Steve Block71f2cf12011-10-20 11:56:00 +01001012 ALOGV("ThreadBase::exit");
Eric Laurenta553c252009-07-17 12:17:14 -07001013 {
1014 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001015 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -07001016 requestExit();
1017 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001018 }
Eric Laurenta553c252009-07-17 12:17:14 -07001019 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001020}
Eric Laurenta553c252009-07-17 12:17:14 -07001021
1022uint32_t AudioFlinger::ThreadBase::sampleRate() const
1023{
1024 return mSampleRate;
1025}
1026
1027int AudioFlinger::ThreadBase::channelCount() const
1028{
Eric Laurentb0a01472010-05-14 05:45:46 -07001029 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07001030}
1031
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001032uint32_t AudioFlinger::ThreadBase::format() const
Eric Laurenta553c252009-07-17 12:17:14 -07001033{
1034 return mFormat;
1035}
1036
1037size_t AudioFlinger::ThreadBase::frameCount() const
1038{
1039 return mFrameCount;
1040}
1041
1042status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1043{
Eric Laurent8fce46a2009-08-04 09:45:33 -07001044 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -07001045
Steve Block71f2cf12011-10-20 11:56:00 +01001046 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -07001047 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001048
Eric Laurent8fce46a2009-08-04 09:45:33 -07001049 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -07001050 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -07001051 // wait condition with timeout in case the thread loop has exited
1052 // before the request could be processed
Glenn Kastencbfe2e12011-12-13 11:04:14 -08001053 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Eric Laurentb7d94602009-09-29 11:12:57 -07001054 status = mParamStatus;
1055 mWaitWorkCV.signal();
1056 } else {
1057 status = TIMED_OUT;
1058 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001059 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07001060}
1061
1062void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1063{
1064 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -07001065 sendConfigEvent_l(event, param);
1066}
1067
1068// sendConfigEvent_l() must be called with ThreadBase::mLock held
1069void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1070{
Glenn Kasten4b220f02011-12-13 11:50:00 -08001071 ConfigEvent configEvent;
1072 configEvent.mEvent = event;
1073 configEvent.mParam = param;
Eric Laurenta553c252009-07-17 12:17:14 -07001074 mConfigEvents.add(configEvent);
Steve Block71f2cf12011-10-20 11:56:00 +01001075 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001076 mWaitWorkCV.signal();
1077}
1078
1079void AudioFlinger::ThreadBase::processConfigEvents()
1080{
1081 mLock.lock();
1082 while(!mConfigEvents.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001083 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kasten4b220f02011-12-13 11:50:00 -08001084 ConfigEvent configEvent = mConfigEvents[0];
Eric Laurenta553c252009-07-17 12:17:14 -07001085 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001086 // release mLock before locking AudioFlinger mLock: lock order is always
1087 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -07001088 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001089 mAudioFlinger->mLock.lock();
Glenn Kasten4b220f02011-12-13 11:50:00 -08001090 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001091 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001092 mLock.lock();
1093 }
1094 mLock.unlock();
1095}
1096
Eric Laurent3fdb1262009-11-07 00:01:32 -08001097status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1098{
1099 const size_t SIZE = 256;
1100 char buffer[SIZE];
1101 String8 result;
1102
1103 bool locked = tryLock(mLock);
1104 if (!locked) {
1105 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1106 write(fd, buffer, strlen(buffer));
1107 }
1108
1109 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1110 result.append(buffer);
1111 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1112 result.append(buffer);
1113 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1114 result.append(buffer);
1115 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1116 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001117 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1118 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001119 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1120 result.append(buffer);
1121 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1122 result.append(buffer);
1123
1124 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1125 result.append(buffer);
1126 result.append(" Index Command");
1127 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1128 snprintf(buffer, SIZE, "\n %02d ", i);
1129 result.append(buffer);
1130 result.append(mNewParameters[i]);
1131 }
1132
1133 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1134 result.append(buffer);
1135 snprintf(buffer, SIZE, " Index event param\n");
1136 result.append(buffer);
1137 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kasten4b220f02011-12-13 11:50:00 -08001138 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Eric Laurent3fdb1262009-11-07 00:01:32 -08001139 result.append(buffer);
1140 }
1141 result.append("\n");
1142
1143 write(fd, result.string(), result.size());
1144
1145 if (locked) {
1146 mLock.unlock();
1147 }
1148 return NO_ERROR;
1149}
1150
Eric Laurent1345d332011-07-24 17:49:51 -07001151status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1152{
1153 const size_t SIZE = 256;
1154 char buffer[SIZE];
1155 String8 result;
1156
1157 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1158 write(fd, buffer, strlen(buffer));
1159
1160 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1161 sp<EffectChain> chain = mEffectChains[i];
1162 if (chain != 0) {
1163 chain->dump(fd, args);
1164 }
1165 }
1166 return NO_ERROR;
1167}
1168
Eric Laurent6dbdc402011-07-22 09:04:31 -07001169void AudioFlinger::ThreadBase::acquireWakeLock()
1170{
1171 Mutex::Autolock _l(mLock);
1172 acquireWakeLock_l();
1173}
1174
1175void AudioFlinger::ThreadBase::acquireWakeLock_l()
1176{
1177 if (mPowerManager == 0) {
1178 // use checkService() to avoid blocking if power service is not up yet
1179 sp<IBinder> binder =
1180 defaultServiceManager()->checkService(String16("power"));
1181 if (binder == 0) {
1182 LOGW("Thread %s cannot connect to the power manager service", mName);
1183 } else {
1184 mPowerManager = interface_cast<IPowerManager>(binder);
1185 binder->linkToDeath(mDeathRecipient);
1186 }
1187 }
1188 if (mPowerManager != 0) {
1189 sp<IBinder> binder = new BBinder();
1190 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1191 binder,
1192 String16(mName));
1193 if (status == NO_ERROR) {
1194 mWakeLockToken = binder;
1195 }
Steve Block71f2cf12011-10-20 11:56:00 +01001196 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001197 }
1198}
1199
1200void AudioFlinger::ThreadBase::releaseWakeLock()
1201{
1202 Mutex::Autolock _l(mLock);
Eric Laurentd49ead62011-07-28 13:59:02 -07001203 releaseWakeLock_l();
Eric Laurent6dbdc402011-07-22 09:04:31 -07001204}
1205
1206void AudioFlinger::ThreadBase::releaseWakeLock_l()
1207{
1208 if (mWakeLockToken != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001209 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurent6dbdc402011-07-22 09:04:31 -07001210 if (mPowerManager != 0) {
1211 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1212 }
1213 mWakeLockToken.clear();
1214 }
1215}
1216
1217void AudioFlinger::ThreadBase::clearPowerManager()
1218{
1219 Mutex::Autolock _l(mLock);
1220 releaseWakeLock_l();
1221 mPowerManager.clear();
1222}
1223
1224void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1225{
1226 sp<ThreadBase> thread = mThread.promote();
1227 if (thread != 0) {
1228 thread->clearPowerManager();
1229 }
1230 LOGW("power manager service died !!!");
1231}
Eric Laurent1345d332011-07-24 17:49:51 -07001232
Eric Laurentf82fccd2011-07-27 19:49:51 -07001233void AudioFlinger::ThreadBase::setEffectSuspended(
1234 const effect_uuid_t *type, bool suspend, int sessionId)
1235{
1236 Mutex::Autolock _l(mLock);
1237 setEffectSuspended_l(type, suspend, sessionId);
1238}
1239
1240void AudioFlinger::ThreadBase::setEffectSuspended_l(
1241 const effect_uuid_t *type, bool suspend, int sessionId)
1242{
1243 sp<EffectChain> chain;
1244 chain = getEffectChain_l(sessionId);
1245 if (chain != 0) {
1246 if (type != NULL) {
1247 chain->setEffectSuspended_l(type, suspend);
1248 } else {
1249 chain->setEffectSuspendedAll_l(suspend);
1250 }
1251 }
1252
1253 updateSuspendedSessions_l(type, suspend, sessionId);
1254}
1255
1256void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1257{
1258 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1259 if (index < 0) {
1260 return;
1261 }
1262
1263 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1264 mSuspendedSessions.editValueAt(index);
1265
1266 for (size_t i = 0; i < sessionEffects.size(); i++) {
1267 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1268 for (int j = 0; j < desc->mRefCount; j++) {
1269 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1270 chain->setEffectSuspendedAll_l(true);
1271 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001272 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001273 desc->mType.timeLow);
1274 chain->setEffectSuspended_l(&desc->mType, true);
1275 }
1276 }
1277 }
1278}
1279
Eric Laurentf82fccd2011-07-27 19:49:51 -07001280void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1281 bool suspend,
1282 int sessionId)
1283{
1284 int index = mSuspendedSessions.indexOfKey(sessionId);
1285
1286 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1287
1288 if (suspend) {
1289 if (index >= 0) {
1290 sessionEffects = mSuspendedSessions.editValueAt(index);
1291 } else {
1292 mSuspendedSessions.add(sessionId, sessionEffects);
1293 }
1294 } else {
1295 if (index < 0) {
1296 return;
1297 }
1298 sessionEffects = mSuspendedSessions.editValueAt(index);
1299 }
1300
1301
1302 int key = EffectChain::kKeyForSuspendAll;
1303 if (type != NULL) {
1304 key = type->timeLow;
1305 }
1306 index = sessionEffects.indexOfKey(key);
1307
1308 sp <SuspendedSessionDesc> desc;
1309 if (suspend) {
1310 if (index >= 0) {
1311 desc = sessionEffects.valueAt(index);
1312 } else {
1313 desc = new SuspendedSessionDesc();
1314 if (type != NULL) {
1315 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1316 }
1317 sessionEffects.add(key, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01001318 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001319 }
1320 desc->mRefCount++;
1321 } else {
1322 if (index < 0) {
1323 return;
1324 }
1325 desc = sessionEffects.valueAt(index);
1326 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001327 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurentf82fccd2011-07-27 19:49:51 -07001328 sessionEffects.removeItemsAt(index);
1329 if (sessionEffects.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01001330 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07001331 sessionId);
1332 mSuspendedSessions.removeItem(sessionId);
1333 }
1334 }
1335 }
1336 if (!sessionEffects.isEmpty()) {
1337 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1338 }
1339}
1340
1341void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1342 bool enabled,
1343 int sessionId)
1344{
1345 Mutex::Autolock _l(mLock);
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001346 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1347}
Eric Laurentf82fccd2011-07-27 19:49:51 -07001348
Eric Laurent7fa1cee2011-10-19 11:44:54 -07001349void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1350 bool enabled,
1351 int sessionId)
1352{
Eric Laurent6752ec82011-08-10 10:37:50 -07001353 if (mType != RECORD) {
1354 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1355 // another session. This gives the priority to well behaved effect control panels
1356 // and applications not using global effects.
1357 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1358 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1359 }
1360 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07001361
1362 sp<EffectChain> chain = getEffectChain_l(sessionId);
1363 if (chain != 0) {
1364 chain->checkSuspendOnEffectEnabled(effect, enabled);
1365 }
1366}
1367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368// ----------------------------------------------------------------------------
1369
Eric Laurent464d5b32011-06-17 21:29:58 -07001370AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1371 AudioStreamOut* output,
1372 int id,
1373 uint32_t device)
1374 : ThreadBase(audioFlinger, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08001375 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent464d5b32011-06-17 21:29:58 -07001376 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001378 snprintf(mName, kNameLength, "AudioOut_%d", id);
1379
Eric Laurenta553c252009-07-17 12:17:14 -07001380 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381
Eric Laurenta553c252009-07-17 12:17:14 -07001382 mMasterVolume = mAudioFlinger->masterVolume();
1383 mMasterMute = mAudioFlinger->masterMute();
1384
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001385 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurenta553c252009-07-17 12:17:14 -07001386 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1387 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent05ce0942011-08-30 10:18:54 -07001388 mStreamTypes[stream].valid = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390}
1391
Eric Laurenta553c252009-07-17 12:17:14 -07001392AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393{
1394 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395}
1396
Eric Laurenta553c252009-07-17 12:17:14 -07001397status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398{
1399 dumpInternals(fd, args);
1400 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -07001401 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 return NO_ERROR;
1403}
1404
Eric Laurenta553c252009-07-17 12:17:14 -07001405status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406{
1407 const size_t SIZE = 256;
1408 char buffer[SIZE];
1409 String8 result;
1410
Eric Laurenta553c252009-07-17 12:17:14 -07001411 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001413 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 -08001414 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001415 sp<Track> track = mTracks[i];
1416 if (track != 0) {
1417 track->dump(buffer, SIZE);
1418 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
1420 }
1421
Eric Laurenta553c252009-07-17 12:17:14 -07001422 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 result.append(buffer);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001424 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 -08001425 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001426 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 if (wTrack != 0) {
1428 sp<Track> track = wTrack.promote();
1429 if (track != 0) {
1430 track->dump(buffer, SIZE);
1431 result.append(buffer);
1432 }
1433 }
1434 }
1435 write(fd, result.string(), result.size());
1436 return NO_ERROR;
1437}
1438
Eric Laurenta553c252009-07-17 12:17:14 -07001439status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440{
1441 const size_t SIZE = 256;
1442 char buffer[SIZE];
1443 String8 result;
1444
Eric Laurent3fdb1262009-11-07 00:01:32 -08001445 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 result.append(buffer);
1447 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1448 result.append(buffer);
1449 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1450 result.append(buffer);
1451 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1452 result.append(buffer);
1453 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1454 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001455 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1456 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001457 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1458 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001460
1461 dumpBase(fd, args);
1462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 return NO_ERROR;
1464}
1465
1466// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001467status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468{
Eric Laurent828b9772011-08-07 16:32:26 -07001469 status_t status = initCheck();
1470 if (status == NO_ERROR) {
Steve Block6215d3f2012-01-04 20:05:49 +00001471 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurent828b9772011-08-07 16:32:26 -07001472 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 LOGE("No working audio driver found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 }
Eric Laurent828b9772011-08-07 16:32:26 -07001475 return status;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476}
1477
Eric Laurenta553c252009-07-17 12:17:14 -07001478void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479{
Eric Laurent6dbdc402011-07-22 09:04:31 -07001480 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481}
1482
Eric Laurenta553c252009-07-17 12:17:14 -07001483// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1484sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 const sp<AudioFlinger::Client>& client,
1486 int streamType,
1487 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001488 uint32_t format,
1489 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 int frameCount,
1491 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001492 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 status_t *status)
1494{
1495 sp<Track> track;
1496 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001497
1498 if (mType == DIRECT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001499 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1500 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1501 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1502 "for output %p with format %d",
1503 sampleRate, format, channelMask, mOutput, mFormat);
1504 lStatus = BAD_VALUE;
1505 goto Exit;
1506 }
Eric Laurenta553c252009-07-17 12:17:14 -07001507 }
1508 } else {
1509 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1510 if (sampleRate > mSampleRate*2) {
1511 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1512 lStatus = BAD_VALUE;
1513 goto Exit;
1514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516
Eric Laurent464d5b32011-06-17 21:29:58 -07001517 lStatus = initCheck();
1518 if (lStatus != NO_ERROR) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001519 LOGE("Audio driver not initialized.");
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001520 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
1522
Eric Laurenta553c252009-07-17 12:17:14 -07001523 { // scope for mLock
1524 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001525
1526 // all tracks in same audio session must share the same routing strategy otherwise
1527 // conflicts will happen when tracks are moved from one output to another by audio policy
1528 // manager
1529 uint32_t strategy =
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001530 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001531 for (size_t i = 0; i < mTracks.size(); ++i) {
1532 sp<Track> t = mTracks[i];
1533 if (t != 0) {
Glenn Kasten9818a9d2011-10-28 10:31:42 -07001534 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1535 if (sessionId == t->sessionId() && strategy != actual) {
1536 LOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1537 strategy, actual);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001538 lStatus = BAD_VALUE;
1539 goto Exit;
1540 }
1541 }
1542 }
1543
Eric Laurenta553c252009-07-17 12:17:14 -07001544 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001545 channelMask, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001546 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001547 lStatus = NO_MEMORY;
1548 goto Exit;
1549 }
1550 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001551
1552 sp<EffectChain> chain = getEffectChain_l(sessionId);
1553 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001554 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Eric Laurent65b65452010-06-01 23:49:17 -07001555 track->setMainBuffer(chain->inBuffer());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001556 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurent90681d62011-05-09 12:09:06 -07001557 chain->incTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001558 }
Eric Laurent05ce0942011-08-30 10:18:54 -07001559
1560 // invalidate track immediately if the stream type was moved to another thread since
1561 // createTrack() was called by the client process.
1562 if (!mStreamTypes[streamType].valid) {
1563 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1564 this, streamType);
1565 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1566 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001567 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001568 lStatus = NO_ERROR;
1569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570Exit:
1571 if(status) {
1572 *status = lStatus;
1573 }
1574 return track;
1575}
1576
Eric Laurenta553c252009-07-17 12:17:14 -07001577uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578{
Eric Laurent828b9772011-08-07 16:32:26 -07001579 Mutex::Autolock _l(mLock);
1580 if (initCheck() == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07001581 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurent828b9772011-08-07 16:32:26 -07001582 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 return 0;
1584 }
1585}
1586
Eric Laurenta553c252009-07-17 12:17:14 -07001587status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588{
1589 mMasterVolume = value;
1590 return NO_ERROR;
1591}
1592
Eric Laurenta553c252009-07-17 12:17:14 -07001593status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594{
1595 mMasterMute = muted;
1596 return NO_ERROR;
1597}
1598
Eric Laurenta553c252009-07-17 12:17:14 -07001599float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600{
1601 return mMasterVolume;
1602}
1603
Eric Laurenta553c252009-07-17 12:17:14 -07001604bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605{
1606 return mMasterMute;
1607}
1608
Eric Laurenta553c252009-07-17 12:17:14 -07001609status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610{
1611 mStreamTypes[stream].volume = value;
1612 return NO_ERROR;
1613}
1614
Eric Laurenta553c252009-07-17 12:17:14 -07001615status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616{
1617 mStreamTypes[stream].mute = muted;
1618 return NO_ERROR;
1619}
1620
Eric Laurenta553c252009-07-17 12:17:14 -07001621float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622{
1623 return mStreamTypes[stream].volume;
1624}
1625
Eric Laurenta553c252009-07-17 12:17:14 -07001626bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627{
1628 return mStreamTypes[stream].mute;
1629}
1630
Eric Laurenta553c252009-07-17 12:17:14 -07001631// addTrack_l() must be called with ThreadBase::mLock held
1632status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633{
1634 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001635
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001636 // set retry count for buffer fill
1637 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001638 if (mActiveTracks.indexOf(track) < 0) {
1639 // the track is newly added, make sure it fills up all its
1640 // buffers before playing. This is to ensure the client will
1641 // effectively get the latency it requested.
1642 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001643 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001644 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001645 if (track->mainBuffer() != mMixBuffer) {
1646 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1647 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001648 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07001649 chain->incActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07001650 }
1651 }
1652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001654 }
Eric Laurenta553c252009-07-17 12:17:14 -07001655
Steve Block71f2cf12011-10-20 11:56:00 +01001656 ALOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001657 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658
1659 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001660}
1661
Eric Laurenta553c252009-07-17 12:17:14 -07001662// destroyTrack_l() must be called with ThreadBase::mLock held
1663void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001664{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001665 track->mState = TrackBase::TERMINATED;
1666 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent90681d62011-05-09 12:09:06 -07001667 removeTrack_l(track);
1668 }
1669}
1670
1671void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1672{
1673 mTracks.remove(track);
1674 deleteTrackName_l(track->name());
1675 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1676 if (chain != 0) {
1677 chain->decTrackCnt();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001678 }
1679}
1680
Eric Laurenta553c252009-07-17 12:17:14 -07001681String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001682{
Eric Laurent828b9772011-08-07 16:32:26 -07001683 String8 out_s8 = String8("");
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001684 char *s;
1685
Eric Laurent828b9772011-08-07 16:32:26 -07001686 Mutex::Autolock _l(mLock);
1687 if (initCheck() != NO_ERROR) {
1688 return out_s8;
1689 }
1690
Dima Zavin31f188892011-04-18 16:57:27 -07001691 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001692 out_s8 = String8(s);
1693 free(s);
1694 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07001695}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001696
Eric Laurent828b9772011-08-07 16:32:26 -07001697// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001698void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001699 AudioSystem::OutputDescriptor desc;
1700 void *param2 = 0;
1701
Steve Block71f2cf12011-10-20 11:56:00 +01001702 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001703
1704 switch (event) {
1705 case AudioSystem::OUTPUT_OPENED:
1706 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001707 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07001708 desc.samplingRate = mSampleRate;
1709 desc.format = mFormat;
1710 desc.frameCount = mFrameCount;
1711 desc.latency = latency();
1712 param2 = &desc;
1713 break;
1714
1715 case AudioSystem::STREAM_CONFIG_CHANGED:
1716 param2 = &param;
1717 case AudioSystem::OUTPUT_CLOSED:
1718 default:
1719 break;
1720 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001721 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001722}
1723
1724void AudioFlinger::PlaybackThread::readOutputParameters()
1725{
Dima Zavin31f188892011-04-18 16:57:27 -07001726 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001727 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1728 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07001729 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1730 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1731 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Eric Laurenta553c252009-07-17 12:17:14 -07001732
Eric Laurenta553c252009-07-17 12:17:14 -07001733 // FIXME - Current mixer implementation only supports stereo output: Always
1734 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001735 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001736 mMixBuffer = new int16_t[mFrameCount * 2];
1737 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001738
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001739 // force reconfiguration of effect chains and engines to take new buffer size and audio
1740 // parameters into account
1741 // Note that mLock is not held when readOutputParameters() is called from the constructor
1742 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1743 // matter.
1744 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1745 Vector< sp<EffectChain> > effectChains = mEffectChains;
1746 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent493941b2010-07-28 01:32:47 -07001747 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001748 }
Eric Laurenta553c252009-07-17 12:17:14 -07001749}
1750
Eric Laurent0986e792010-01-19 17:37:09 -08001751status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1752{
1753 if (halFrames == 0 || dspFrames == 0) {
1754 return BAD_VALUE;
1755 }
Eric Laurent828b9772011-08-07 16:32:26 -07001756 Mutex::Autolock _l(mLock);
Eric Laurent464d5b32011-06-17 21:29:58 -07001757 if (initCheck() != NO_ERROR) {
Eric Laurent0986e792010-01-19 17:37:09 -08001758 return INVALID_OPERATION;
1759 }
Dima Zavin31f188892011-04-18 16:57:27 -07001760 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Eric Laurent0986e792010-01-19 17:37:09 -08001761
Dima Zavin31f188892011-04-18 16:57:27 -07001762 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Eric Laurent0986e792010-01-19 17:37:09 -08001763}
1764
Eric Laurent493941b2010-07-28 01:32:47 -07001765uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Eric Laurent65b65452010-06-01 23:49:17 -07001766{
1767 Mutex::Autolock _l(mLock);
Eric Laurent493941b2010-07-28 01:32:47 -07001768 uint32_t result = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001769 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent493941b2010-07-28 01:32:47 -07001770 result = EFFECT_SESSION;
Eric Laurent65b65452010-06-01 23:49:17 -07001771 }
1772
1773 for (size_t i = 0; i < mTracks.size(); ++i) {
1774 sp<Track> track = mTracks[i];
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001775 if (sessionId == track->sessionId() &&
1776 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent493941b2010-07-28 01:32:47 -07001777 result |= TRACK_SESSION;
1778 break;
Eric Laurent65b65452010-06-01 23:49:17 -07001779 }
1780 }
1781
Eric Laurent493941b2010-07-28 01:32:47 -07001782 return result;
Eric Laurent65b65452010-06-01 23:49:17 -07001783}
1784
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001785uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1786{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001787 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001788 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001789 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1790 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001791 }
1792 for (size_t i = 0; i < mTracks.size(); i++) {
1793 sp<Track> track = mTracks[i];
1794 if (sessionId == track->sessionId() &&
1795 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001796 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001797 }
1798 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001799 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001800}
1801
Eric Laurent53334cd2010-06-23 17:38:20 -07001802
Eric Laurent828b9772011-08-07 16:32:26 -07001803AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1804{
1805 Mutex::Autolock _l(mLock);
1806 return mOutput;
1807}
1808
1809AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1810{
1811 Mutex::Autolock _l(mLock);
1812 AudioStreamOut *output = mOutput;
1813 mOutput = NULL;
1814 return output;
1815}
1816
1817// this method must always be called either with ThreadBase mLock held or inside the thread loop
1818audio_stream_t* AudioFlinger::PlaybackThread::stream()
1819{
1820 if (mOutput == NULL) {
1821 return NULL;
1822 }
1823 return &mOutput->stream->common;
1824}
1825
Eric Laurent44331692011-12-05 09:47:19 -08001826uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1827{
1828 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1829 // decoding and transfer time. So sleeping for half of the latency would likely cause
1830 // underruns
1831 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1832 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1833 } else {
1834 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1835 }
1836}
1837
Eric Laurenta553c252009-07-17 12:17:14 -07001838// ----------------------------------------------------------------------------
1839
Dima Zavin31f188892011-04-18 16:57:27 -07001840AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07001841 : PlaybackThread(audioFlinger, output, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08001842 mAudioMixer(NULL)
Eric Laurenta553c252009-07-17 12:17:14 -07001843{
Eric Laurent464d5b32011-06-17 21:29:58 -07001844 mType = ThreadBase::MIXER;
Eric Laurenta553c252009-07-17 12:17:14 -07001845 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1846
1847 // FIXME - Current mixer implementation only supports stereo output
1848 if (mChannelCount == 1) {
1849 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001851}
1852
Eric Laurenta553c252009-07-17 12:17:14 -07001853AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001854{
Eric Laurenta553c252009-07-17 12:17:14 -07001855 delete mAudioMixer;
1856}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857
Eric Laurenta553c252009-07-17 12:17:14 -07001858bool AudioFlinger::MixerThread::threadLoop()
1859{
Eric Laurenta553c252009-07-17 12:17:14 -07001860 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001861 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001862 nsecs_t standbyTime = systemTime();
1863 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001864 // FIXME: Relaxed timing because of a certain device that can't meet latency
1865 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001866 // increase threshold again due to low power audio mode. The way this warning threshold is
1867 // calculated and its usefulness should be reconsidered anyway.
1868 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001869 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001870 bool longStandbyExit = false;
1871 uint32_t activeSleepTime = activeSleepTimeUs();
1872 uint32_t idleSleepTime = idleSleepTimeUs();
1873 uint32_t sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001874 uint32_t sleepTimeShift = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07001875 Vector< sp<EffectChain> > effectChains;
Glenn Kastenda494f92011-07-08 15:26:12 -07001876#ifdef DEBUG_CPU_USAGE
1877 ThreadCpuUsage cpu;
1878 const CentralTendencyStatistics& stats = cpu.statistics();
1879#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880
Eric Laurent6dbdc402011-07-22 09:04:31 -07001881 acquireWakeLock();
1882
Eric Laurenta553c252009-07-17 12:17:14 -07001883 while (!exitPending())
1884 {
Glenn Kastenda494f92011-07-08 15:26:12 -07001885#ifdef DEBUG_CPU_USAGE
1886 cpu.sampleAndEnable();
1887 unsigned n = stats.n();
1888 // cpu.elapsed() is expensive, so don't call it every loop
1889 if ((n & 127) == 1) {
1890 long long elapsed = cpu.elapsed();
1891 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1892 double perLoop = elapsed / (double) n;
1893 double perLoop100 = perLoop * 0.01;
1894 double mean = stats.mean();
1895 double stddev = stats.stddev();
1896 double minimum = stats.minimum();
1897 double maximum = stats.maximum();
1898 cpu.resetStatistics();
Steve Block6215d3f2012-01-04 20:05:49 +00001899 ALOGI("CPU usage over past %.1f secs (%u mixer loops at %.1f mean ms per loop):\n us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f",
Glenn Kastenda494f92011-07-08 15:26:12 -07001900 elapsed * .000000001, n, perLoop * .000001,
1901 mean * .001,
1902 stddev * .001,
1903 minimum * .001,
1904 maximum * .001,
1905 mean / perLoop100,
1906 stddev / perLoop100,
1907 minimum / perLoop100,
1908 maximum / perLoop100);
1909 }
1910 }
1911#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001912 processConfigEvents();
1913
Eric Laurent059b4be2009-11-09 23:32:22 -08001914 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001915 { // scope for mLock
1916
1917 Mutex::Autolock _l(mLock);
1918
1919 if (checkForNewParameters_l()) {
1920 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001921 // FIXME: Relaxed timing because of a certain device that can't meet latency
1922 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent276fa432011-10-18 15:42:27 -07001923 // increase threshold again due to low power audio mode. The way this warning
1924 // threshold is calculated and its usefulness should be reconsidered anyway.
1925 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Eric Laurent059b4be2009-11-09 23:32:22 -08001926 activeSleepTime = activeSleepTimeUs();
1927 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001928 }
1929
1930 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1931
1932 // put audio hardware into standby after short delay
1933 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1934 mSuspended) {
1935 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01001936 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin31f188892011-04-18 16:57:27 -07001937 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07001938 mStandby = true;
1939 mBytesWritten = 0;
1940 }
1941
1942 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1943 // we're about to wait, flush the binder command buffer
1944 IPCThreadState::self()->flushCommands();
1945
1946 if (exitPending()) break;
1947
Eric Laurent6dbdc402011-07-22 09:04:31 -07001948 releaseWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001949 // wait until we have something to do...
Steve Block71f2cf12011-10-20 11:56:00 +01001950 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07001951 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01001952 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07001953 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001954
1955 if (mMasterMute == false) {
1956 char value[PROPERTY_VALUE_MAX];
1957 property_get("ro.audio.silent", value, "0");
1958 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00001959 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07001960 setMasterMute(true);
1961 }
1962 }
1963
1964 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001965 sleepTime = idleSleepTime;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001966 sleepTimeShift = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001967 continue;
1968 }
1969 }
1970
Eric Laurent059b4be2009-11-09 23:32:22 -08001971 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001972
1973 // prevent any changes in effect chain list and in each effect chain
1974 // during mixing and effect process as the audio buffers could be deleted
1975 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001976 lockEffectChains_l(effectChains);
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08001977 }
Eric Laurenta553c252009-07-17 12:17:14 -07001978
Eric Laurent059b4be2009-11-09 23:32:22 -08001979 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001980 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001981 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001982 sleepTime = 0;
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001983 // increase sleep time progressively when application underrun condition clears
1984 if (sleepTimeShift > 0) {
1985 sleepTimeShift--;
1986 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07001987 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001988 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001989 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001990 // If no tracks are ready, sleep once for the duration of an output
1991 // buffer size, then write 0s to the output
1992 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001993 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentf1f5fc82011-11-22 18:50:29 -08001994 sleepTime = activeSleepTime >> sleepTimeShift;
1995 if (sleepTime < kMinThreadSleepTimeUs) {
1996 sleepTime = kMinThreadSleepTimeUs;
1997 }
1998 // reduce sleep time in case of consecutive application underruns to avoid
1999 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2000 // duration we would end up writing less data than needed by the audio HAL if
2001 // the condition persists.
2002 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2003 sleepTimeShift++;
2004 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002005 } else {
2006 sleepTime = idleSleepTime;
2007 }
2008 } else if (mBytesWritten != 0 ||
2009 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002010 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002011 sleepTime = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01002012 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07002013 }
Eric Laurent65b65452010-06-01 23:49:17 -07002014 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07002015 }
2016
2017 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002018 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002019 }
2020 // sleepTime == 0 means we must write to audio hardware
2021 if (sleepTime == 0) {
Glenn Kastenfb2ab9e2011-12-12 09:05:55 -08002022 for (size_t i = 0; i < effectChains.size(); i ++) {
2023 effectChains[i]->process_l();
2024 }
2025 // enable changes in effect chain
2026 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002027 mLastWriteTime = systemTime();
2028 mInWrite = true;
2029 mBytesWritten += mixBufferSize;
2030
Dima Zavin31f188892011-04-18 16:57:27 -07002031 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002032 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002033 mNumWrites++;
2034 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002035 nsecs_t now = systemTime();
2036 nsecs_t delta = now - mLastWriteTime;
Eric Laurent276fa432011-10-18 15:42:27 -07002037 if (!mStandby && delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002038 mNumDelayedWrites++;
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002039 if ((now - lastWarning) > kWarningThrottleNs) {
Dave Sparksd0ac8c02009-09-30 03:09:03 -07002040 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2041 ns2ms(delta), mNumDelayedWrites, this);
2042 lastWarning = now;
2043 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002044 if (mStandby) {
2045 longStandbyExit = true;
2046 }
Eric Laurenta553c252009-07-17 12:17:14 -07002047 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002048 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002049 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002050 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002051 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002052 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002053 }
2054
2055 // finally let go of all our tracks, without the lock held
2056 // since we can't guarantee the destructors won't acquire that
2057 // same lock.
2058 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002059
2060 // Effect chains will be actually deleted here if they were removed from
2061 // mEffectChains list during mixing or effects processing
2062 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002063 }
2064
2065 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002066 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002067 }
Eric Laurenta553c252009-07-17 12:17:14 -07002068
Eric Laurent6dbdc402011-07-22 09:04:31 -07002069 releaseWakeLock();
2070
Steve Block71f2cf12011-10-20 11:56:00 +01002071 ALOGV("MixerThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002072 return false;
2073}
2074
2075// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08002076uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07002077{
2078
Eric Laurent059b4be2009-11-09 23:32:22 -08002079 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002080 // find out which tracks need to be processed
2081 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07002082 size_t mixedTracks = 0;
2083 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002084
2085 float masterVolume = mMasterVolume;
2086 bool masterMute = mMasterMute;
2087
Eric Laurent8cc93b92010-08-11 05:20:11 -07002088 if (masterMute) {
2089 masterVolume = 0;
2090 }
Eric Laurent65b65452010-06-01 23:49:17 -07002091 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002092 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent65b65452010-06-01 23:49:17 -07002093 if (chain != 0) {
Eric Laurent8cc93b92010-08-11 05:20:11 -07002094 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurent76c40f72010-07-15 12:50:15 -07002095 chain->setVolume_l(&v, &v);
Eric Laurent65b65452010-06-01 23:49:17 -07002096 masterVolume = (float)((v + (1 << 23)) >> 24);
2097 chain.clear();
2098 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08002099
Eric Laurenta553c252009-07-17 12:17:14 -07002100 for (size_t i=0 ; i<count ; i++) {
2101 sp<Track> t = activeTracks[i].promote();
2102 if (t == 0) continue;
2103
2104 Track* const track = t.get();
2105 audio_track_cblk_t* cblk = track->cblk();
2106
2107 // The first time a track is added we wait
2108 // for all its buffers to be filled before processing it
2109 mAudioMixer->setActiveTrack(track->name());
Eric Laurent8a04fe02011-11-08 18:10:16 -08002110 // make sure that we have enough frames to mix one full buffer.
2111 // enforce this condition only once to enable draining the buffer in case the client
2112 // app does not call stop() and relies on underrun to stop:
2113 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2114 // during last round
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002115 uint32_t minFrames = 1;
Eric Laurent8a04fe02011-11-08 18:10:16 -08002116 if (!track->isStopped() && !track->isPausing() &&
2117 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent19ddf0e2011-11-03 12:16:05 -07002118 if (t->sampleRate() == (int)mSampleRate) {
2119 minFrames = mFrameCount;
2120 } else {
2121 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1;
2122 }
2123 }
2124 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07002125 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002126 {
Steve Block71f2cf12011-10-20 11:56:00 +01002127 //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 -07002128
Eric Laurent65b65452010-06-01 23:49:17 -07002129 mixedTracks++;
2130
2131 // track->mainBuffer() != mMixBuffer means there is an effect chain
2132 // connected to the track
2133 chain.clear();
2134 if (track->mainBuffer() != mMixBuffer) {
2135 chain = getEffectChain_l(track->sessionId());
2136 // Delegate volume control to effect in track effect chain if needed
2137 if (chain != 0) {
2138 tracksWithEffect++;
2139 } else {
2140 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2141 track->name(), track->sessionId());
2142 }
2143 }
2144
2145
2146 int param = AudioMixer::VOLUME;
2147 if (track->mFillingUpStatus == Track::FS_FILLED) {
2148 // no ramp for the first volume setting
2149 track->mFillingUpStatus = Track::FS_ACTIVE;
2150 if (track->mState == TrackBase::RESUMING) {
2151 track->mState = TrackBase::ACTIVE;
2152 param = AudioMixer::RAMP_VOLUME;
2153 }
Eric Laurent4bb21c42011-02-28 16:52:51 -08002154 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent65b65452010-06-01 23:49:17 -07002155 } else if (cblk->server != 0) {
2156 // If the track is stopped before the first frame was mixed,
2157 // do not apply ramp
2158 param = AudioMixer::RAMP_VOLUME;
2159 }
2160
Eric Laurenta553c252009-07-17 12:17:14 -07002161 // compute volume for this track
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002162 uint32_t vl, vr, va;
Eric Laurent2a6b80b2010-07-29 23:43:43 -07002163 if (track->isMuted() || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07002164 mStreamTypes[track->type()].mute) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002165 vl = vr = va = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002166 if (track->isPausing()) {
2167 track->setPaused();
2168 }
2169 } else {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002170
Glenn Kasten871c16c2010-03-05 12:18:01 -08002171 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07002172 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08002173 float v = masterVolume * typeVolume;
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002174 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2175 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07002176
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002177 va = (uint32_t)(v * cblk->sendLevel);
Eric Laurenta553c252009-07-17 12:17:14 -07002178 }
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002179 // Delegate volume control to effect in track effect chain if needed
2180 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2181 // Do not ramp volume if volume is controlled by effect
2182 param = AudioMixer::VOLUME;
2183 track->mHasVolumeController = true;
2184 } else {
2185 // force no volume ramp when volume controller was just disabled or removed
2186 // from effect chain to avoid volume spike
2187 if (track->mHasVolumeController) {
2188 param = AudioMixer::VOLUME;
2189 }
2190 track->mHasVolumeController = false;
2191 }
2192
2193 // Convert volumes from 8.24 to 4.12 format
2194 int16_t left, right, aux;
2195 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2196 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2197 left = int16_t(v_clamped);
2198 v_clamped = (vr + (1 << 11)) >> 12;
2199 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2200 right = int16_t(v_clamped);
2201
2202 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2203 aux = int16_t(va);
Eric Laurent65b65452010-06-01 23:49:17 -07002204
Eric Laurent65b65452010-06-01 23:49:17 -07002205 // XXX: these things DON'T need to be done each time
2206 mAudioMixer->setBufferProvider(track);
Glenn Kastenaf62dbc2011-12-15 14:54:01 -08002207 mAudioMixer->enable();
Eric Laurent65b65452010-06-01 23:49:17 -07002208
2209 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2210 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2211 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07002212 mAudioMixer->setParameter(
2213 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07002214 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07002215 mAudioMixer->setParameter(
2216 AudioMixer::TRACK,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07002217 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Eric Laurenta553c252009-07-17 12:17:14 -07002218 mAudioMixer->setParameter(
2219 AudioMixer::RESAMPLE,
2220 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07002221 (void *)(cblk->sampleRate));
2222 mAudioMixer->setParameter(
2223 AudioMixer::TRACK,
2224 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2225 mAudioMixer->setParameter(
2226 AudioMixer::TRACK,
2227 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07002228
2229 // reset retry count
2230 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08002231 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002232 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002233 //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 -07002234 if (track->isStopped()) {
2235 track->reset();
2236 }
2237 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2238 // We have consumed all the buffers of this track.
2239 // Remove it from the list of active tracks.
2240 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002241 } else {
2242 // No buffers for this track. Give it a few chances to
2243 // fill a buffer, then remove it from active list.
2244 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002245 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07002246 tracksToRemove->add(track);
Eric Laurent4712baa2010-09-30 16:12:31 -07002247 // indicate to client process that the track was disabled because of underrun
Eric Laurentae29b762011-03-28 18:37:07 -07002248 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent059b4be2009-11-09 23:32:22 -08002249 } else if (mixerStatus != MIXER_TRACKS_READY) {
2250 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002251 }
Eric Laurenta553c252009-07-17 12:17:14 -07002252 }
Glenn Kastenaf62dbc2011-12-15 14:54:01 -08002253 mAudioMixer->disable();
Eric Laurenta553c252009-07-17 12:17:14 -07002254 }
2255 }
2256
2257 // remove all the tracks that need to be...
2258 count = tracksToRemove->size();
2259 if (UNLIKELY(count)) {
2260 for (size_t i=0 ; i<count ; i++) {
2261 const sp<Track>& track = tracksToRemove->itemAt(i);
2262 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07002263 if (track->mainBuffer() != mMixBuffer) {
2264 chain = getEffectChain_l(track->sessionId());
2265 if (chain != 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002266 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002267 chain->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002268 }
2269 }
Eric Laurenta553c252009-07-17 12:17:14 -07002270 if (track->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002271 removeTrack_l(track);
Eric Laurenta553c252009-07-17 12:17:14 -07002272 }
2273 }
2274 }
2275
Eric Laurent65b65452010-06-01 23:49:17 -07002276 // mix buffer must be cleared if all tracks are connected to an
2277 // effect chain as in this case the mixer will not write to
2278 // mix buffer and track effects will accumulate into it
2279 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2280 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2281 }
2282
Eric Laurent059b4be2009-11-09 23:32:22 -08002283 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002284}
2285
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002286void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07002287{
Steve Block71f2cf12011-10-20 11:56:00 +01002288 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002289 this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07002290 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002291
Eric Laurenta553c252009-07-17 12:17:14 -07002292 size_t size = mTracks.size();
2293 for (size_t i = 0; i < size; i++) {
2294 sp<Track> t = mTracks[i];
2295 if (t->type() == streamType) {
Eric Laurentae29b762011-03-28 18:37:07 -07002296 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002297 t->mCblk->cv.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07002298 }
Eric Laurent53334cd2010-06-23 17:38:20 -07002299 }
2300}
Eric Laurenta553c252009-07-17 12:17:14 -07002301
Eric Laurent05ce0942011-08-30 10:18:54 -07002302void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2303{
Steve Block71f2cf12011-10-20 11:56:00 +01002304 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent05ce0942011-08-30 10:18:54 -07002305 this, streamType, valid);
2306 Mutex::Autolock _l(mLock);
2307
2308 mStreamTypes[streamType].valid = valid;
2309}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310
Eric Laurenta553c252009-07-17 12:17:14 -07002311// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002312int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313{
2314 return mAudioMixer->getTrackName();
2315}
2316
Eric Laurenta553c252009-07-17 12:17:14 -07002317// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002318void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319{
Steve Block71f2cf12011-10-20 11:56:00 +01002320 ALOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 mAudioMixer->deleteTrackName(name);
2322}
2323
Eric Laurenta553c252009-07-17 12:17:14 -07002324// checkForNewParameters_l() must be called with ThreadBase::mLock held
2325bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326{
Eric Laurenta553c252009-07-17 12:17:14 -07002327 bool reconfig = false;
2328
Eric Laurent8fce46a2009-08-04 09:45:33 -07002329 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002330 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002331 String8 keyValuePair = mNewParameters[0];
2332 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002333 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002334
Eric Laurenta553c252009-07-17 12:17:14 -07002335 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2336 reconfig = true;
2337 }
2338 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002339 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07002340 status = BAD_VALUE;
2341 } else {
2342 reconfig = true;
2343 }
2344 }
2345 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002346 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurenta553c252009-07-17 12:17:14 -07002347 status = BAD_VALUE;
2348 } else {
2349 reconfig = true;
2350 }
2351 }
2352 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2353 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kastene5fb2632011-12-14 10:28:06 -08002354 // size depends on frame count and correct behavior would not be guaranteed
Eric Laurenta553c252009-07-17 12:17:14 -07002355 // if frame count is changed after track creation
2356 if (!mTracks.isEmpty()) {
2357 status = INVALID_OPERATION;
2358 } else {
2359 reconfig = true;
2360 }
2361 }
Eric Laurent65b65452010-06-01 23:49:17 -07002362 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002363 // when changing the audio output device, call addBatteryData to notify
2364 // the change
Eric Laurent90681d62011-05-09 12:09:06 -07002365 if ((int)mDevice != value) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002366 uint32_t params = 0;
2367 // check whether speaker is on
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002368 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9b3f1522011-02-24 14:51:45 -08002369 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2370 }
2371
2372 int deviceWithoutSpeaker
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002373 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9b3f1522011-02-24 14:51:45 -08002374 // check if any other device (except speaker) is on
2375 if (value & deviceWithoutSpeaker ) {
2376 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2377 }
2378
2379 if (params != 0) {
2380 addBatteryData(params);
2381 }
2382 }
2383
Eric Laurent65b65452010-06-01 23:49:17 -07002384 // forward device change to effects that have requested to be
2385 // aware of attached audio device.
2386 mDevice = (uint32_t)value;
2387 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07002388 mEffectChains[i]->setDevice_l(mDevice);
Eric Laurent65b65452010-06-01 23:49:17 -07002389 }
2390 }
2391
Eric Laurenta553c252009-07-17 12:17:14 -07002392 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002393 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002394 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002395 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002396 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002397 mStandby = true;
2398 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002399 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002400 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002401 }
2402 if (status == NO_ERROR && reconfig) {
2403 delete mAudioMixer;
2404 readOutputParameters();
2405 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2406 for (size_t i = 0; i < mTracks.size() ; i++) {
2407 int name = getTrackName_l();
2408 if (name < 0) break;
2409 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07002410 // limit track sample rate to 2 x new output sample rate
2411 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2412 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2413 }
Eric Laurenta553c252009-07-17 12:17:14 -07002414 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07002415 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002416 }
2417 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002418
2419 mNewParameters.removeAt(0);
2420
Eric Laurenta553c252009-07-17 12:17:14 -07002421 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002422 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002423 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2424 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002425 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002426 }
2427 return reconfig;
2428}
2429
2430status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2431{
2432 const size_t SIZE = 256;
2433 char buffer[SIZE];
2434 String8 result;
2435
2436 PlaybackThread::dumpInternals(fd, args);
2437
2438 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2439 result.append(buffer);
2440 write(fd, result.string(), result.size());
2441 return NO_ERROR;
2442}
2443
Eric Laurent059b4be2009-11-09 23:32:22 -08002444uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2445{
Eric Laurenta54d7d32010-07-29 06:50:24 -07002446 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002447}
2448
Eric Laurent8448a792010-08-18 18:13:17 -07002449uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2450{
2451 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2452}
2453
Eric Laurenta553c252009-07-17 12:17:14 -07002454// ----------------------------------------------------------------------------
Dima Zavin31f188892011-04-18 16:57:27 -07002455AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07002456 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07002457{
Eric Laurent464d5b32011-06-17 21:29:58 -07002458 mType = ThreadBase::DIRECT;
Eric Laurenta553c252009-07-17 12:17:14 -07002459}
2460
2461AudioFlinger::DirectOutputThread::~DirectOutputThread()
2462{
2463}
2464
Eric Laurent65b65452010-06-01 23:49:17 -07002465static inline
2466int32_t mul(int16_t in, int16_t v)
2467{
2468#if defined(__arm__) && !defined(__thumb__)
2469 int32_t out;
2470 asm( "smulbb %[out], %[in], %[v] \n"
2471 : [out]"=r"(out)
2472 : [in]"%r"(in), [v]"r"(v)
2473 : );
2474 return out;
2475#else
2476 return in * int32_t(v);
2477#endif
2478}
2479
2480void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2481{
2482 // Do not apply volume on compressed audio
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002483 if (!audio_is_linear_pcm(mFormat)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002484 return;
2485 }
2486
2487 // convert to signed 16 bit before volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002488 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002489 size_t count = mFrameCount * mChannelCount;
2490 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2491 int16_t *dst = mMixBuffer + count-1;
2492 while(count--) {
2493 *dst-- = (int16_t)(*src--^0x80) << 8;
2494 }
2495 }
2496
2497 size_t frameCount = mFrameCount;
2498 int16_t *out = mMixBuffer;
2499 if (ramp) {
2500 if (mChannelCount == 1) {
2501 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2502 int32_t vlInc = d / (int32_t)frameCount;
2503 int32_t vl = ((int32_t)mLeftVolShort << 16);
2504 do {
2505 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2506 out++;
2507 vl += vlInc;
2508 } while (--frameCount);
2509
2510 } else {
2511 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2512 int32_t vlInc = d / (int32_t)frameCount;
2513 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2514 int32_t vrInc = d / (int32_t)frameCount;
2515 int32_t vl = ((int32_t)mLeftVolShort << 16);
2516 int32_t vr = ((int32_t)mRightVolShort << 16);
2517 do {
2518 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2519 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2520 out += 2;
2521 vl += vlInc;
2522 vr += vrInc;
2523 } while (--frameCount);
2524 }
2525 } else {
2526 if (mChannelCount == 1) {
2527 do {
2528 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2529 out++;
2530 } while (--frameCount);
2531 } else {
2532 do {
2533 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2534 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2535 out += 2;
2536 } while (--frameCount);
2537 }
2538 }
2539
2540 // convert back to unsigned 8 bit after volume calculation
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002541 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Eric Laurent65b65452010-06-01 23:49:17 -07002542 size_t count = mFrameCount * mChannelCount;
2543 int16_t *src = mMixBuffer;
2544 uint8_t *dst = (uint8_t *)mMixBuffer;
2545 while(count--) {
2546 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2547 }
2548 }
2549
2550 mLeftVolShort = leftVol;
2551 mRightVolShort = rightVol;
2552}
2553
Eric Laurenta553c252009-07-17 12:17:14 -07002554bool AudioFlinger::DirectOutputThread::threadLoop()
2555{
Eric Laurent059b4be2009-11-09 23:32:22 -08002556 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002557 sp<Track> trackToRemove;
2558 sp<Track> activeTrack;
2559 nsecs_t standbyTime = systemTime();
2560 int8_t *curBuf;
2561 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002562 uint32_t activeSleepTime = activeSleepTimeUs();
2563 uint32_t idleSleepTime = idleSleepTimeUs();
2564 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002565 // use shorter standby delay as on normal output to release
2566 // hardware resources as soon as possible
2567 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002568
Eric Laurent6dbdc402011-07-22 09:04:31 -07002569 acquireWakeLock();
2570
Eric Laurenta553c252009-07-17 12:17:14 -07002571 while (!exitPending())
2572 {
Eric Laurent65b65452010-06-01 23:49:17 -07002573 bool rampVolume;
2574 uint16_t leftVol;
2575 uint16_t rightVol;
2576 Vector< sp<EffectChain> > effectChains;
2577
Eric Laurenta553c252009-07-17 12:17:14 -07002578 processConfigEvents();
2579
Eric Laurent059b4be2009-11-09 23:32:22 -08002580 mixerStatus = MIXER_IDLE;
2581
Eric Laurenta553c252009-07-17 12:17:14 -07002582 { // scope for the mLock
2583
2584 Mutex::Autolock _l(mLock);
2585
2586 if (checkForNewParameters_l()) {
2587 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002588 activeSleepTime = activeSleepTimeUs();
2589 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002590 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002591 }
2592
2593 // put audio hardware into standby after short delay
2594 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2595 mSuspended) {
2596 // wait until we have something to do...
2597 if (!mStandby) {
Steve Block71f2cf12011-10-20 11:56:00 +01002598 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin31f188892011-04-18 16:57:27 -07002599 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002600 mStandby = true;
2601 mBytesWritten = 0;
2602 }
2603
2604 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2605 // we're about to wait, flush the binder command buffer
2606 IPCThreadState::self()->flushCommands();
2607
2608 if (exitPending()) break;
2609
Eric Laurent6dbdc402011-07-22 09:04:31 -07002610 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01002611 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07002612 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01002613 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07002614 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002615
2616 if (mMasterMute == false) {
2617 char value[PROPERTY_VALUE_MAX];
2618 property_get("ro.audio.silent", value, "0");
2619 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00002620 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07002621 setMasterMute(true);
2622 }
2623 }
2624
Eric Laurentef9500f2010-03-11 14:47:00 -08002625 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002626 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002627 continue;
2628 }
2629 }
2630
Eric Laurent65b65452010-06-01 23:49:17 -07002631 effectChains = mEffectChains;
2632
Eric Laurenta553c252009-07-17 12:17:14 -07002633 // find out which tracks need to be processed
2634 if (mActiveTracks.size() != 0) {
2635 sp<Track> t = mActiveTracks[0].promote();
2636 if (t == 0) continue;
2637
2638 Track* const track = t.get();
2639 audio_track_cblk_t* cblk = track->cblk();
2640
2641 // The first time a track is added we wait
2642 // for all its buffers to be filled before processing it
Eric Laurent9a30fc12010-10-05 14:41:42 -07002643 if (cblk->framesReady() && track->isReady() &&
Eric Laurent380558b2010-04-09 06:11:48 -07002644 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002645 {
Steve Block71f2cf12011-10-20 11:56:00 +01002646 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002647
Eric Laurent65b65452010-06-01 23:49:17 -07002648 if (track->mFillingUpStatus == Track::FS_FILLED) {
2649 track->mFillingUpStatus = Track::FS_ACTIVE;
2650 mLeftVolFloat = mRightVolFloat = 0;
2651 mLeftVolShort = mRightVolShort = 0;
2652 if (track->mState == TrackBase::RESUMING) {
2653 track->mState = TrackBase::ACTIVE;
2654 rampVolume = true;
2655 }
2656 } else if (cblk->server != 0) {
2657 // If the track is stopped before the first frame was mixed,
2658 // do not apply ramp
2659 rampVolume = true;
2660 }
Eric Laurenta553c252009-07-17 12:17:14 -07002661 // compute volume for this track
2662 float left, right;
2663 if (track->isMuted() || mMasterMute || track->isPausing() ||
2664 mStreamTypes[track->type()].mute) {
2665 left = right = 0;
2666 if (track->isPausing()) {
2667 track->setPaused();
2668 }
2669 } else {
2670 float typeVolume = mStreamTypes[track->type()].volume;
2671 float v = mMasterVolume * typeVolume;
2672 float v_clamped = v * cblk->volume[0];
2673 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2674 left = v_clamped/MAX_GAIN;
2675 v_clamped = v * cblk->volume[1];
2676 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2677 right = v_clamped/MAX_GAIN;
2678 }
2679
Eric Laurent65b65452010-06-01 23:49:17 -07002680 if (left != mLeftVolFloat || right != mRightVolFloat) {
2681 mLeftVolFloat = left;
2682 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002683
Eric Laurent65b65452010-06-01 23:49:17 -07002684 // If audio HAL implements volume control,
2685 // force software volume to nominal value
Dima Zavin31f188892011-04-18 16:57:27 -07002686 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07002687 left = 1.0f;
2688 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002689 }
Eric Laurent65b65452010-06-01 23:49:17 -07002690
2691 // Convert volumes from float to 8.24
2692 uint32_t vl = (uint32_t)(left * (1 << 24));
2693 uint32_t vr = (uint32_t)(right * (1 << 24));
2694
2695 // Delegate volume control to effect in track effect chain if needed
2696 // only one effect chain can be present on DirectOutputThread, so if
2697 // there is one, the track is connected to it
2698 if (!effectChains.isEmpty()) {
Eric Laurent27a2fdf2010-09-10 17:44:44 -07002699 // Do not ramp volume if volume is controlled by effect
Eric Laurent76c40f72010-07-15 12:50:15 -07002700 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002701 rampVolume = false;
2702 }
2703 }
2704
2705 // Convert volumes from 8.24 to 4.12 format
2706 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2707 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2708 leftVol = (uint16_t)v_clamped;
2709 v_clamped = (vr + (1 << 11)) >> 12;
2710 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2711 rightVol = (uint16_t)v_clamped;
2712 } else {
2713 leftVol = mLeftVolShort;
2714 rightVol = mRightVolShort;
2715 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002716 }
2717
2718 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002719 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002720 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002721 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002722 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01002723 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurenta553c252009-07-17 12:17:14 -07002724 if (track->isStopped()) {
2725 track->reset();
2726 }
2727 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2728 // We have consumed all the buffers of this track.
2729 // Remove it from the list of active tracks.
2730 trackToRemove = track;
2731 } else {
2732 // No buffers for this track. Give it a few chances to
2733 // fill a buffer, then remove it from active list.
2734 if (--(track->mRetryCount) <= 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01002735 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurenta553c252009-07-17 12:17:14 -07002736 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002737 } else {
2738 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002739 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002740 }
Eric Laurenta553c252009-07-17 12:17:14 -07002741 }
2742 }
2743
2744 // remove all the tracks that need to be...
2745 if (UNLIKELY(trackToRemove != 0)) {
2746 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002747 if (!effectChains.isEmpty()) {
Steve Block71f2cf12011-10-20 11:56:00 +01002748 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002749 trackToRemove->sessionId());
Eric Laurent90681d62011-05-09 12:09:06 -07002750 effectChains[0]->decActiveTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07002751 }
Eric Laurenta553c252009-07-17 12:17:14 -07002752 if (trackToRemove->isTerminated()) {
Eric Laurent90681d62011-05-09 12:09:06 -07002753 removeTrack_l(trackToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07002754 }
2755 }
Eric Laurent65b65452010-06-01 23:49:17 -07002756
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002757 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07002758 }
2759
Eric Laurent059b4be2009-11-09 23:32:22 -08002760 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002761 AudioBufferProvider::Buffer buffer;
2762 size_t frameCount = mFrameCount;
2763 curBuf = (int8_t *)mMixBuffer;
2764 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002765 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002766 buffer.frameCount = frameCount;
2767 activeTrack->getNextBuffer(&buffer);
Glenn Kastenc434c902011-12-13 11:53:26 -08002768 if (UNLIKELY(buffer.raw == NULL)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002769 memset(curBuf, 0, frameCount * mFrameSize);
2770 break;
2771 }
2772 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2773 frameCount -= buffer.frameCount;
2774 curBuf += buffer.frameCount * mFrameSize;
2775 activeTrack->releaseBuffer(&buffer);
2776 }
2777 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002778 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002779 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002780 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002781 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2782 sleepTime = activeSleepTime;
2783 } else {
2784 sleepTime = idleSleepTime;
2785 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002786 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002787 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002788 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002789 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002790 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002791
Eric Laurentf69a3f82009-09-22 00:35:48 -07002792 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07002793 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002794 }
2795 // sleepTime == 0 means we must write to audio hardware
2796 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002797 if (mixerStatus == MIXER_TRACKS_READY) {
2798 applyVolume(leftVol, rightVol, rampVolume);
2799 }
2800 for (size_t i = 0; i < effectChains.size(); i ++) {
2801 effectChains[i]->process_l();
2802 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002803 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07002804
Eric Laurentf69a3f82009-09-22 00:35:48 -07002805 mLastWriteTime = systemTime();
2806 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002807 mBytesWritten += mixBufferSize;
Dima Zavin31f188892011-04-18 16:57:27 -07002808 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002809 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002810 mNumWrites++;
2811 mInWrite = false;
2812 mStandby = false;
2813 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002814 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002815 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002816 }
2817
2818 // finally let go of removed track, without the lock held
2819 // since we can't guarantee the destructors won't acquire that
2820 // same lock.
2821 trackToRemove.clear();
2822 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002823
2824 // Effect chains will be actually deleted here if they were removed from
2825 // mEffectChains list during mixing or effects processing
2826 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002827 }
2828
2829 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07002830 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002831 }
Eric Laurenta553c252009-07-17 12:17:14 -07002832
Eric Laurent6dbdc402011-07-22 09:04:31 -07002833 releaseWakeLock();
2834
Steve Block71f2cf12011-10-20 11:56:00 +01002835 ALOGV("DirectOutputThread %p exiting", this);
Eric Laurenta553c252009-07-17 12:17:14 -07002836 return false;
2837}
2838
2839// getTrackName_l() must be called with ThreadBase::mLock held
2840int AudioFlinger::DirectOutputThread::getTrackName_l()
2841{
2842 return 0;
2843}
2844
2845// deleteTrackName_l() must be called with ThreadBase::mLock held
2846void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2847{
2848}
2849
2850// checkForNewParameters_l() must be called with ThreadBase::mLock held
2851bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2852{
2853 bool reconfig = false;
2854
Eric Laurent8fce46a2009-08-04 09:45:33 -07002855 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002856 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002857 String8 keyValuePair = mNewParameters[0];
2858 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002859 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002860
Eric Laurenta553c252009-07-17 12:17:14 -07002861 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2862 // do not accept frame count changes if tracks are open as the track buffer
2863 // size depends on frame count and correct behavior would not be garantied
2864 // if frame count is changed after track creation
2865 if (!mTracks.isEmpty()) {
2866 status = INVALID_OPERATION;
2867 } else {
2868 reconfig = true;
2869 }
2870 }
2871 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07002872 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002873 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002874 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07002875 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07002876 mStandby = true;
2877 mBytesWritten = 0;
Dima Zavin31f188892011-04-18 16:57:27 -07002878 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002879 keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07002880 }
2881 if (status == NO_ERROR && reconfig) {
2882 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002883 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002884 }
2885 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002886
2887 mNewParameters.removeAt(0);
2888
Eric Laurenta553c252009-07-17 12:17:14 -07002889 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002890 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07002891 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2892 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08002893 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07002894 }
2895 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002896}
2897
Eric Laurent059b4be2009-11-09 23:32:22 -08002898uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002899{
2900 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002901 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent44331692011-12-05 09:47:19 -08002902 time = PlaybackThread::activeSleepTimeUs();
Eric Laurent059b4be2009-11-09 23:32:22 -08002903 } else {
2904 time = 10000;
2905 }
2906 return time;
2907}
2908
2909uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2910{
2911 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002912 if (audio_is_linear_pcm(mFormat)) {
Eric Laurenta54d7d32010-07-29 06:50:24 -07002913 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Eric Laurent62443f52009-10-05 20:29:18 -07002914 } else {
2915 time = 10000;
2916 }
2917 return time;
2918}
2919
Eric Laurent8448a792010-08-18 18:13:17 -07002920uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2921{
2922 uint32_t time;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07002923 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent8448a792010-08-18 18:13:17 -07002924 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2925 } else {
2926 time = 10000;
2927 }
2928 return time;
2929}
2930
2931
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002932// ----------------------------------------------------------------------------
2933
Eric Laurent49f02be2009-11-19 09:00:56 -08002934AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002935 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002936{
Eric Laurent464d5b32011-06-17 21:29:58 -07002937 mType = ThreadBase::DUPLICATING;
Eric Laurenta553c252009-07-17 12:17:14 -07002938 addOutputTrack(mainThread);
2939}
2940
2941AudioFlinger::DuplicatingThread::~DuplicatingThread()
2942{
Eric Laurent0a080292009-12-07 10:53:10 -08002943 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2944 mOutputTracks[i]->destroy();
2945 }
Eric Laurenta553c252009-07-17 12:17:14 -07002946 mOutputTracks.clear();
2947}
2948
2949bool AudioFlinger::DuplicatingThread::threadLoop()
2950{
Eric Laurenta553c252009-07-17 12:17:14 -07002951 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002952 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002953 nsecs_t standbyTime = systemTime();
2954 size_t mixBufferSize = mFrameCount*mFrameSize;
2955 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002956 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002957 uint32_t activeSleepTime = activeSleepTimeUs();
2958 uint32_t idleSleepTime = idleSleepTimeUs();
2959 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002960 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002961
Eric Laurent6dbdc402011-07-22 09:04:31 -07002962 acquireWakeLock();
2963
Eric Laurenta553c252009-07-17 12:17:14 -07002964 while (!exitPending())
2965 {
2966 processConfigEvents();
2967
Eric Laurent059b4be2009-11-09 23:32:22 -08002968 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002969 { // scope for the mLock
2970
2971 Mutex::Autolock _l(mLock);
2972
2973 if (checkForNewParameters_l()) {
2974 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002975 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002976 activeSleepTime = activeSleepTimeUs();
2977 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002978 }
2979
2980 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2981
2982 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2983 outputTracks.add(mOutputTracks[i]);
2984 }
2985
2986 // put audio hardware into standby after short delay
2987 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2988 mSuspended) {
2989 if (!mStandby) {
2990 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002991 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002992 }
2993 mStandby = true;
2994 mBytesWritten = 0;
2995 }
2996
2997 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2998 // we're about to wait, flush the binder command buffer
2999 IPCThreadState::self()->flushCommands();
3000 outputTracks.clear();
3001
3002 if (exitPending()) break;
3003
Eric Laurent6dbdc402011-07-22 09:04:31 -07003004 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01003005 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Eric Laurenta553c252009-07-17 12:17:14 -07003006 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01003007 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurent6dbdc402011-07-22 09:04:31 -07003008 acquireWakeLock_l();
3009
Eric Laurenta553c252009-07-17 12:17:14 -07003010 if (mMasterMute == false) {
3011 char value[PROPERTY_VALUE_MAX];
3012 property_get("ro.audio.silent", value, "0");
3013 if (atoi(value)) {
Steve Block5baa3a62011-12-20 16:23:08 +00003014 ALOGD("Silence is golden");
Eric Laurenta553c252009-07-17 12:17:14 -07003015 setMasterMute(true);
3016 }
3017 }
3018
3019 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08003020 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07003021 continue;
3022 }
3023 }
3024
Eric Laurent059b4be2009-11-09 23:32:22 -08003025 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07003026
3027 // prevent any changes in effect chain list and in each effect chain
3028 // during mixing and effect process as the audio buffers could be deleted
3029 // or modified if an effect is created or deleted
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003030 lockEffectChains_l(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003031 }
Eric Laurenta553c252009-07-17 12:17:14 -07003032
Eric Laurent059b4be2009-11-09 23:32:22 -08003033 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07003034 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003035 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07003036 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003037 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003038 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003039 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003040 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07003041 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003042 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07003043 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08003044 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3045 sleepTime = activeSleepTime;
3046 } else {
3047 sleepTime = idleSleepTime;
3048 }
Eric Laurent62443f52009-10-05 20:29:18 -07003049 } else if (mBytesWritten != 0) {
3050 // flush remaining overflow buffers in output tracks
3051 for (size_t i = 0; i < outputTracks.size(); i++) {
3052 if (outputTracks[i]->isActive()) {
3053 sleepTime = 0;
3054 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07003055 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07003056 break;
3057 }
3058 }
Eric Laurenta553c252009-07-17 12:17:14 -07003059 }
3060 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003061
3062 if (mSuspended) {
Eric Laurent8448a792010-08-18 18:13:17 -07003063 sleepTime = suspendSleepTimeUs();
Eric Laurentf69a3f82009-09-22 00:35:48 -07003064 }
3065 // sleepTime == 0 means we must write to audio hardware
3066 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07003067 for (size_t i = 0; i < effectChains.size(); i ++) {
3068 effectChains[i]->process_l();
3069 }
3070 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003071 unlockEffectChains(effectChains);
Eric Laurent65b65452010-06-01 23:49:17 -07003072
Eric Laurent62443f52009-10-05 20:29:18 -07003073 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07003074 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07003075 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07003076 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07003077 mStandby = false;
3078 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07003079 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07003080 // enable changes in effect chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003081 unlockEffectChains(effectChains);
Eric Laurentf69a3f82009-09-22 00:35:48 -07003082 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003083 }
3084
3085 // finally let go of all our tracks, without the lock held
3086 // since we can't guarantee the destructors won't acquire that
3087 // same lock.
3088 tracksToRemove.clear();
3089 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07003090
3091 // Effect chains will be actually deleted here if they were removed from
3092 // mEffectChains list during mixing or effects processing
3093 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07003094 }
3095
Eric Laurent6dbdc402011-07-22 09:04:31 -07003096 releaseWakeLock();
3097
Eric Laurenta553c252009-07-17 12:17:14 -07003098 return false;
3099}
3100
3101void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3102{
3103 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3104 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003105 this,
Eric Laurenta553c252009-07-17 12:17:14 -07003106 mSampleRate,
3107 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003108 mChannelMask,
Eric Laurenta553c252009-07-17 12:17:14 -07003109 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07003110 if (outputTrack->cblk() != NULL) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003111 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Eric Laurent6c30a712009-08-10 23:22:32 -07003112 mOutputTracks.add(outputTrack);
Steve Block71f2cf12011-10-20 11:56:00 +01003113 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003114 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07003115 }
Eric Laurenta553c252009-07-17 12:17:14 -07003116}
3117
3118void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3119{
3120 Mutex::Autolock _l(mLock);
3121 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3122 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07003123 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07003124 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003125 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07003126 return;
3127 }
3128 }
Steve Block71f2cf12011-10-20 11:56:00 +01003129 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003130}
3131
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003132void AudioFlinger::DuplicatingThread::updateWaitTime()
3133{
3134 mWaitTimeMs = UINT_MAX;
3135 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3136 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3137 if (strong != NULL) {
3138 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3139 if (waitTimeMs < mWaitTimeMs) {
3140 mWaitTimeMs = waitTimeMs;
3141 }
3142 }
3143 }
3144}
3145
3146
3147bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3148{
3149 for (size_t i = 0; i < outputTracks.size(); i++) {
3150 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3151 if (thread == 0) {
3152 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3153 return false;
3154 }
3155 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3156 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block71f2cf12011-10-20 11:56:00 +01003157 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003158 return false;
3159 }
3160 }
3161 return true;
3162}
3163
3164uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3165{
3166 return (mWaitTimeMs * 1000) / 2;
3167}
3168
Eric Laurenta553c252009-07-17 12:17:14 -07003169// ----------------------------------------------------------------------------
3170
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003171// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003172AudioFlinger::ThreadBase::TrackBase::TrackBase(
3173 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003174 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003175 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003176 uint32_t format,
3177 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003178 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003180 const sp<IMemory>& sharedBuffer,
3181 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003182 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07003183 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003184 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07003185 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003186 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003187 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003188 mClientTid(-1),
3189 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07003190 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3191 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003192{
Steve Block71f2cf12011-10-20 11:56:00 +01003193 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003194
Steve Block5baa3a62011-12-20 16:23:08 +00003195 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003196 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003197 uint8_t channelCount = popcount(channelMask);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003198 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3199 if (sharedBuffer == 0) {
3200 size += bufferSize;
3201 }
3202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 if (client != NULL) {
3204 mCblkMemory = client->heap()->allocate(size);
3205 if (mCblkMemory != 0) {
3206 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3207 if (mCblk) { // construct the shared structure in-place.
3208 new(mCblk) audio_track_cblk_t();
3209 // clear all buffers
3210 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003211 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003212 mChannelCount = channelCount;
3213 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 if (sharedBuffer == 0) {
3215 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3216 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3217 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003218 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003219 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 } else {
3221 mBuffer = sharedBuffer->pointer();
3222 }
3223 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 } else {
3226 LOGE("not enough memory for AudioTrack size=%u", size);
3227 client->heap()->dump("AudioTrack");
3228 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 } else {
3231 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3232 if (mCblk) { // construct the shared structure in-place.
3233 new(mCblk) audio_track_cblk_t();
3234 // clear all buffers
3235 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07003236 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003237 mChannelCount = channelCount;
3238 mChannelMask = channelMask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3240 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3241 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent4712baa2010-09-30 16:12:31 -07003242 // written to buffer (other flags are cleared)
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003243 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3245 }
3246 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003247}
3248
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003249AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003250{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07003252 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3253 if (mClient == NULL) {
3254 delete mCblk;
3255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003257 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07003258 if (mClient != NULL) {
3259 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3260 mClient.clear();
3261 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003262}
3263
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003264void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003265{
Glenn Kastenc434c902011-12-13 11:53:26 -08003266 buffer->raw = NULL;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003267 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003268 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003269 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003270}
3271
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003272bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003273 bool result;
3274 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003275
3276 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003277 if (!result) {
Steve Block71f2cf12011-10-20 11:56:00 +01003278 ALOGV("stepServer failed acquiring cblk mutex");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003279 mFlags |= STEPSERVER_FAILED;
3280 }
3281 return result;
3282}
3283
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003284void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003285 audio_track_cblk_t* cblk = this->cblk();
3286
3287 cblk->user = 0;
3288 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003289 cblk->userBase = 0;
3290 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block71f2cf12011-10-20 11:56:00 +01003292 ALOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003293}
3294
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003295sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003296{
3297 return mCblkMemory;
3298}
3299
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003300int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07003301 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003302}
3303
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003304int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003305 return (const int)mChannelCount;
3306}
3307
3308uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3309 return mChannelMask;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003310}
3311
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07003312void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003313 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07003314 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3315 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003316
3317 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07003318 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3319 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07003320 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 -07003321 server %d, serverBase %d, user %d, userBase %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003322 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003323 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003324 return 0;
3325 }
3326
3327 return bufferStart;
3328}
3329
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003330// ----------------------------------------------------------------------------
3331
Eric Laurenta553c252009-07-17 12:17:14 -07003332// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3333AudioFlinger::PlaybackThread::Track::Track(
3334 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003335 const sp<Client>& client,
3336 int streamType,
3337 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003338 uint32_t format,
3339 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003340 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003341 const sp<IMemory>& sharedBuffer,
3342 int sessionId)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003343 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurenta92ebfa2010-08-31 13:50:07 -07003344 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3345 mAuxEffectId(0), mHasVolumeController(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003346{
Eric Laurent8a77a992009-09-09 05:16:08 -07003347 if (mCblk != NULL) {
3348 sp<ThreadBase> baseThread = thread.promote();
3349 if (baseThread != 0) {
3350 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3351 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07003352 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07003353 }
Steve Block71f2cf12011-10-20 11:56:00 +01003354 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent8a77a992009-09-09 05:16:08 -07003355 if (mName < 0) {
3356 LOGE("no more track names available");
3357 }
3358 mVolume[0] = 1.0f;
3359 mVolume[1] = 1.0f;
3360 mStreamType = streamType;
3361 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3362 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurent09508612011-07-21 19:35:01 -07003363 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07003364 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003365}
3366
Eric Laurenta553c252009-07-17 12:17:14 -07003367AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003368{
Steve Block71f2cf12011-10-20 11:56:00 +01003369 ALOGV("PlaybackThread::Track destructor");
Eric Laurenta553c252009-07-17 12:17:14 -07003370 sp<ThreadBase> thread = mThread.promote();
3371 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003372 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003373 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003374 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003375}
3376
Eric Laurenta553c252009-07-17 12:17:14 -07003377void AudioFlinger::PlaybackThread::Track::destroy()
3378{
3379 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3380 // by removing it from mTracks vector, so there is a risk that this Tracks's
3381 // desctructor is called. As the destructor needs to lock mLock,
3382 // we must acquire a strong reference on this Track before locking mLock
3383 // here so that the destructor is called only when exiting this function.
3384 // On the other hand, as long as Track::destroy() is only called by
3385 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3386 // this Track with its member mTrack.
3387 sp<Track> keep(this);
3388 { // scope for mLock
3389 sp<ThreadBase> thread = mThread.promote();
3390 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08003391 if (!isOutputTrack()) {
3392 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003393 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003394 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003395 mSessionId);
Gloria Wang9b3f1522011-02-24 14:51:45 -08003396
3397 // to track the speaker usage
3398 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurentac196e12009-12-01 02:17:41 -08003399 }
3400 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08003401 }
Eric Laurenta553c252009-07-17 12:17:14 -07003402 Mutex::Autolock _l(thread->mLock);
3403 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3404 playbackThread->destroyTrack_l(this);
3405 }
3406 }
3407}
3408
3409void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003410{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003411 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 -07003412 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003414 mStreamType,
3415 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003416 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003417 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003418 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003419 mState,
3420 mMute,
3421 mFillingUpStatus,
3422 mCblk->sampleRate,
3423 mCblk->volume[0],
3424 mCblk->volume[1],
3425 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07003426 mCblk->user,
3427 (int)mMainBuffer,
3428 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003429}
3430
Eric Laurenta553c252009-07-17 12:17:14 -07003431status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003432{
3433 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003434 uint32_t framesReady;
3435 uint32_t framesReq = buffer->frameCount;
3436
3437 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003438 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3439 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003440 ALOGV("stepServer recovered");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003441 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3442 }
3443
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003444 framesReady = cblk->framesReady();
3445
3446 if (LIKELY(framesReady)) {
3447 uint32_t s = cblk->server;
3448 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3449
3450 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3451 if (framesReq > framesReady) {
3452 framesReq = framesReady;
3453 }
3454 if (s + framesReq > bufferEnd) {
3455 framesReq = bufferEnd - s;
3456 }
3457
3458 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003459 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003460
3461 buffer->frameCount = framesReq;
3462 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003463 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003464
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003465getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003466 buffer->raw = NULL;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003467 buffer->frameCount = 0;
Steve Block71f2cf12011-10-20 11:56:00 +01003468 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 -07003469 return NOT_ENOUGH_DATA;
3470}
3471
Eric Laurenta553c252009-07-17 12:17:14 -07003472bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurent9a30fc12010-10-05 14:41:42 -07003473 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003474
3475 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003476 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003477 mFillingUpStatus = FS_FILLED;
Eric Laurentae29b762011-03-28 18:37:07 -07003478 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003479 return true;
3480 }
3481 return false;
3482}
3483
Eric Laurenta553c252009-07-17 12:17:14 -07003484status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003485{
Eric Laurent49f02be2009-11-19 09:00:56 -08003486 status_t status = NO_ERROR;
Steve Block71f2cf12011-10-20 11:56:00 +01003487 ALOGV("start(%d), calling thread %d session %d",
Eric Laurent0d7e0482010-07-19 06:24:46 -07003488 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Eric Laurenta553c252009-07-17 12:17:14 -07003489 sp<ThreadBase> thread = mThread.promote();
3490 if (thread != 0) {
3491 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003492 int state = mState;
3493 // here the track could be either new, or restarted
3494 // in both cases "unstop" the track
3495 if (mState == PAUSED) {
3496 mState = TrackBase::RESUMING;
Steve Block71f2cf12011-10-20 11:56:00 +01003497 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003498 } else {
3499 mState = TrackBase::ACTIVE;
Steve Block71f2cf12011-10-20 11:56:00 +01003500 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003501 }
3502
3503 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3504 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003505 status = AudioSystem::startOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003506 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003507 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003508 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003509
3510 // to track the speaker usage
3511 if (status == NO_ERROR) {
3512 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3513 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003514 }
3515 if (status == NO_ERROR) {
3516 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3517 playbackThread->addTrack_l(this);
3518 } else {
3519 mState = state;
3520 }
3521 } else {
3522 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003523 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003524 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003525}
3526
Eric Laurenta553c252009-07-17 12:17:14 -07003527void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003528{
Steve Block71f2cf12011-10-20 11:56:00 +01003529 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003530 sp<ThreadBase> thread = mThread.promote();
3531 if (thread != 0) {
3532 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003533 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07003534 if (mState > STOPPED) {
3535 mState = STOPPED;
3536 // If the track is not active (PAUSED and buffers full), flush buffers
3537 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3538 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3539 reset();
3540 }
Steve Block71f2cf12011-10-20 11:56:00 +01003541 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003542 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003543 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3544 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003545 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003546 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003547 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003548 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003549
3550 // to track the speaker usage
3551 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003552 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003553 }
3554}
3555
Eric Laurenta553c252009-07-17 12:17:14 -07003556void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003557{
Steve Block71f2cf12011-10-20 11:56:00 +01003558 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07003559 sp<ThreadBase> thread = mThread.promote();
3560 if (thread != 0) {
3561 Mutex::Autolock _l(thread->mLock);
3562 if (mState == ACTIVE || mState == RESUMING) {
3563 mState = PAUSING;
Steve Block71f2cf12011-10-20 11:56:00 +01003564 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08003565 if (!isOutputTrack()) {
3566 thread->mLock.unlock();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003567 AudioSystem::stopOutput(thread->id(),
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003568 (audio_stream_type_t)mStreamType,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07003569 mSessionId);
Eric Laurent49f02be2009-11-19 09:00:56 -08003570 thread->mLock.lock();
Gloria Wang9b3f1522011-02-24 14:51:45 -08003571
3572 // to track the speaker usage
3573 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent49f02be2009-11-19 09:00:56 -08003574 }
Eric Laurenta553c252009-07-17 12:17:14 -07003575 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003576 }
3577}
3578
Eric Laurenta553c252009-07-17 12:17:14 -07003579void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003580{
Steve Block71f2cf12011-10-20 11:56:00 +01003581 ALOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003582 sp<ThreadBase> thread = mThread.promote();
3583 if (thread != 0) {
3584 Mutex::Autolock _l(thread->mLock);
3585 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3586 return;
3587 }
3588 // No point remaining in PAUSED state after a flush => go to
3589 // STOPPED state
3590 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003591
Eric Laurentae29b762011-03-28 18:37:07 -07003592 // do not reset the track if it is still in the process of being stopped or paused.
3593 // this will be done by prepareTracks_l() when the track is stopped.
3594 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3595 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3596 reset();
3597 }
Eric Laurenta553c252009-07-17 12:17:14 -07003598 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003599}
3600
Eric Laurenta553c252009-07-17 12:17:14 -07003601void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003602{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003603 // Do not reset twice to avoid discarding data written just after a flush and before
3604 // the audioflinger thread detects the track is stopped.
3605 if (!mResetDone) {
3606 TrackBase::reset();
3607 // Force underrun condition to avoid false underrun callback until first data is
3608 // written to buffer
Eric Laurentae29b762011-03-28 18:37:07 -07003609 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3610 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003611 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003612 mResetDone = true;
3613 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003614}
3615
Eric Laurenta553c252009-07-17 12:17:14 -07003616void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003617{
3618 mMute = muted;
3619}
3620
Eric Laurenta553c252009-07-17 12:17:14 -07003621void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003622{
3623 mVolume[0] = left;
3624 mVolume[1] = right;
3625}
3626
Eric Laurent65b65452010-06-01 23:49:17 -07003627status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3628{
3629 status_t status = DEAD_OBJECT;
3630 sp<ThreadBase> thread = mThread.promote();
3631 if (thread != 0) {
3632 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3633 status = playbackThread->attachAuxEffect(this, EffectId);
3634 }
3635 return status;
3636}
3637
3638void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3639{
3640 mAuxEffectId = EffectId;
3641 mAuxBuffer = buffer;
3642}
3643
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003644// ----------------------------------------------------------------------------
3645
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003646// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003647AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3648 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003651 uint32_t format,
3652 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003654 uint32_t flags,
3655 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003656 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003657 channelMask, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003658 mOverflow(false)
3659{
Eric Laurent8a77a992009-09-09 05:16:08 -07003660 if (mCblk != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +01003661 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003662 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003663 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07003664 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003665 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Eric Laurent8a77a992009-09-09 05:16:08 -07003666 } else {
3667 mCblk->frameSize = sizeof(int8_t);
3668 }
3669 }
Eric Laurenta553c252009-07-17 12:17:14 -07003670}
3671
3672AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673{
Eric Laurent49f02be2009-11-19 09:00:56 -08003674 sp<ThreadBase> thread = mThread.promote();
3675 if (thread != 0) {
3676 AudioSystem::releaseInput(thread->id());
3677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678}
3679
Eric Laurenta553c252009-07-17 12:17:14 -07003680status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681{
3682 audio_track_cblk_t* cblk = this->cblk();
3683 uint32_t framesAvail;
3684 uint32_t framesReq = buffer->frameCount;
3685
3686 // Check if last stepServer failed, try to step now
3687 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3688 if (!step()) goto getNextBuffer_exit;
Steve Block71f2cf12011-10-20 11:56:00 +01003689 ALOGV("stepServer recovered");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003690 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3691 }
3692
3693 framesAvail = cblk->framesAvailable_l();
3694
3695 if (LIKELY(framesAvail)) {
3696 uint32_t s = cblk->server;
3697 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3698
3699 if (framesReq > framesAvail) {
3700 framesReq = framesAvail;
3701 }
3702 if (s + framesReq > bufferEnd) {
3703 framesReq = bufferEnd - s;
3704 }
3705
3706 buffer->raw = getBuffer(s, framesReq);
Glenn Kastenc434c902011-12-13 11:53:26 -08003707 if (buffer->raw == NULL) goto getNextBuffer_exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708
3709 buffer->frameCount = framesReq;
3710 return NO_ERROR;
3711 }
3712
3713getNextBuffer_exit:
Glenn Kastenc434c902011-12-13 11:53:26 -08003714 buffer->raw = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 buffer->frameCount = 0;
3716 return NOT_ENOUGH_DATA;
3717}
3718
Eric Laurenta553c252009-07-17 12:17:14 -07003719status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720{
Eric Laurenta553c252009-07-17 12:17:14 -07003721 sp<ThreadBase> thread = mThread.promote();
3722 if (thread != 0) {
3723 RecordThread *recordThread = (RecordThread *)thread.get();
3724 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003725 } else {
3726 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728}
3729
Eric Laurenta553c252009-07-17 12:17:14 -07003730void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731{
Eric Laurenta553c252009-07-17 12:17:14 -07003732 sp<ThreadBase> thread = mThread.promote();
3733 if (thread != 0) {
3734 RecordThread *recordThread = (RecordThread *)thread.get();
3735 recordThread->stop(this);
Eric Laurentae29b762011-03-28 18:37:07 -07003736 TrackBase::reset();
3737 // Force overerrun condition to avoid false overrun callback until first data is
3738 // read from buffer
3739 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Eric Laurenta553c252009-07-17 12:17:14 -07003740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741}
3742
Eric Laurent3fdb1262009-11-07 00:01:32 -08003743void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3744{
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003745 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003746 (mClient == NULL) ? getpid() : mClient->pid(),
3747 mFormat,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003748 mChannelMask,
Eric Laurent65b65452010-06-01 23:49:17 -07003749 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003750 mFrameCount,
3751 mState,
3752 mCblk->sampleRate,
3753 mCblk->server,
3754 mCblk->user);
3755}
3756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757
3758// ----------------------------------------------------------------------------
3759
Eric Laurenta553c252009-07-17 12:17:14 -07003760AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3761 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003762 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003764 uint32_t format,
3765 uint32_t channelMask,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 int frameCount)
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003767 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003768 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769{
Eric Laurenta553c252009-07-17 12:17:14 -07003770
3771 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003772 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003773 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003774 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3775 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3776 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003777 playbackThread->mTracks.add(this);
Steve Block71f2cf12011-10-20 11:56:00 +01003778 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003779 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3780 mCblk, mBuffer, mCblk->buffers,
3781 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003782 } else {
3783 LOGW("Error creating output track on thread %p", playbackThread);
3784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785}
3786
Eric Laurenta553c252009-07-17 12:17:14 -07003787AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788{
Eric Laurent6c30a712009-08-10 23:22:32 -07003789 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790}
3791
Eric Laurenta553c252009-07-17 12:17:14 -07003792status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793{
3794 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003795 if (status != NO_ERROR) {
3796 return status;
3797 }
3798
3799 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800 mRetryCount = 127;
3801 return status;
3802}
3803
Eric Laurenta553c252009-07-17 12:17:14 -07003804void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805{
3806 Track::stop();
3807 clearBufferQueue();
3808 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003809 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810}
3811
Eric Laurenta553c252009-07-17 12:17:14 -07003812bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813{
3814 Buffer *pInBuffer;
3815 Buffer inBuffer;
Jean-Michel Trivi54392232011-05-24 15:53:33 -07003816 uint32_t channelCount = mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003817 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003818 inBuffer.frameCount = frames;
3819 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003820
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003821 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003822
Eric Laurent62443f52009-10-05 20:29:18 -07003823 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003824 start();
3825 sp<ThreadBase> thread = mThread.promote();
3826 if (thread != 0) {
3827 MixerThread *mixerThread = (MixerThread *)thread.get();
3828 if (mCblk->frameCount > frames){
3829 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3830 uint32_t startFrames = (mCblk->frameCount - frames);
3831 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003832 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003833 pInBuffer->frameCount = startFrames;
3834 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003835 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003836 mBufferQueue.add(pInBuffer);
3837 } else {
3838 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 }
Eric Laurenta553c252009-07-17 12:17:14 -07003841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 }
3843
Eric Laurenta553c252009-07-17 12:17:14 -07003844 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003845 // First write pending buffers, then new data
3846 if (mBufferQueue.size()) {
3847 pInBuffer = mBufferQueue.itemAt(0);
3848 } else {
3849 pInBuffer = &inBuffer;
3850 }
Eric Laurenta553c252009-07-17 12:17:14 -07003851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 if (pInBuffer->frameCount == 0) {
3853 break;
3854 }
Eric Laurenta553c252009-07-17 12:17:14 -07003855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 if (mOutBuffer.frameCount == 0) {
3857 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003858 nsecs_t startTime = systemTime();
3859 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block71f2cf12011-10-20 11:56:00 +01003860 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003861 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 break;
3863 }
Eric Laurenta553c252009-07-17 12:17:14 -07003864 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003865 if (waitTimeLeftMs >= waitTimeMs) {
3866 waitTimeLeftMs -= waitTimeMs;
3867 } else {
3868 waitTimeLeftMs = 0;
3869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 }
Eric Laurenta553c252009-07-17 12:17:14 -07003871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003873 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 mCblk->stepUser(outFrames);
3875 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003876 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003878 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 if (pInBuffer->frameCount == 0) {
3881 if (mBufferQueue.size()) {
3882 mBufferQueue.removeAt(0);
3883 delete [] pInBuffer->mBuffer;
3884 delete pInBuffer;
Steve Block71f2cf12011-10-20 11:56:00 +01003885 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 -08003886 } else {
3887 break;
3888 }
3889 }
3890 }
Eric Laurenta553c252009-07-17 12:17:14 -07003891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 // If we could not write all frames, allocate a buffer and queue it for next time.
3893 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003894 sp<ThreadBase> thread = mThread.promote();
3895 if (thread != 0 && !thread->standby()) {
3896 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3897 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003898 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003899 pInBuffer->frameCount = inBuffer.frameCount;
3900 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003901 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003902 mBufferQueue.add(pInBuffer);
Steve Block71f2cf12011-10-20 11:56:00 +01003903 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003904 } else {
3905 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 }
3908 }
Eric Laurenta553c252009-07-17 12:17:14 -07003909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003911 // 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 -08003912 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003913 if (frames == 0 && mBufferQueue.size() == 0) {
3914 if (mCblk->user < mCblk->frameCount) {
3915 frames = mCblk->frameCount - mCblk->user;
3916 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003917 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003918 pInBuffer->frameCount = frames;
3919 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003920 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003921 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003922 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003923 stop();
3924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 }
3926
Eric Laurenta553c252009-07-17 12:17:14 -07003927 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928}
3929
Eric Laurenta553c252009-07-17 12:17:14 -07003930status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931{
3932 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 status_t result;
3934 audio_track_cblk_t* cblk = mCblk;
3935 uint32_t framesReq = buffer->frameCount;
3936
Steve Block71f2cf12011-10-20 11:56:00 +01003937// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 uint32_t framesAvail = cblk->framesAvailable();
3941
Eric Laurenta553c252009-07-17 12:17:14 -07003942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003944 Mutex::Autolock _l(cblk->lock);
3945 goto start_loop_here;
3946 while (framesAvail == 0) {
3947 active = mActive;
3948 if (UNLIKELY(!active)) {
Steve Block71f2cf12011-10-20 11:56:00 +01003949 ALOGV("Not active and NO_MORE_BUFFERS");
Eric Laurenta553c252009-07-17 12:17:14 -07003950 return AudioTrack::NO_MORE_BUFFERS;
3951 }
3952 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3953 if (result != NO_ERROR) {
3954 return AudioTrack::NO_MORE_BUFFERS;
3955 }
3956 // read the server count again
3957 start_loop_here:
3958 framesAvail = cblk->framesAvailable_l();
3959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 }
3961
Eric Laurenta553c252009-07-17 12:17:14 -07003962// if (framesAvail < framesReq) {
3963// return AudioTrack::NO_MORE_BUFFERS;
3964// }
3965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 if (framesReq > framesAvail) {
3967 framesReq = framesAvail;
3968 }
3969
3970 uint32_t u = cblk->user;
3971 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3972
3973 if (u + framesReq > bufferEnd) {
3974 framesReq = bufferEnd - u;
3975 }
3976
3977 buffer->frameCount = framesReq;
3978 buffer->raw = (void *)cblk->buffer(u);
3979 return NO_ERROR;
3980}
3981
3982
Eric Laurenta553c252009-07-17 12:17:14 -07003983void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984{
3985 size_t size = mBufferQueue.size();
3986 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 for (size_t i = 0; i < size; i++) {
3989 pBuffer = mBufferQueue.itemAt(i);
3990 delete [] pBuffer->mBuffer;
3991 delete pBuffer;
3992 }
3993 mBufferQueue.clear();
3994}
3995
3996// ----------------------------------------------------------------------------
3997
3998AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3999 : RefBase(),
4000 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08004001 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 mPid(pid)
4003{
4004 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4005}
4006
Eric Laurentb9481d82009-09-17 05:12:56 -07004007// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008AudioFlinger::Client::~Client()
4009{
Eric Laurentb9481d82009-09-17 05:12:56 -07004010 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011}
4012
4013const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4014{
4015 return mMemoryDealer;
4016}
4017
4018// ----------------------------------------------------------------------------
4019
Eric Laurent4f0f17d2010-05-12 02:05:53 -07004020AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4021 const sp<IAudioFlingerClient>& client,
4022 pid_t pid)
4023 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4024{
4025}
4026
4027AudioFlinger::NotificationClient::~NotificationClient()
4028{
4029 mClient.clear();
4030}
4031
4032void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4033{
4034 sp<NotificationClient> keep(this);
4035 {
4036 mAudioFlinger->removeNotificationClient(mPid);
4037 }
4038}
4039
4040// ----------------------------------------------------------------------------
4041
Eric Laurenta553c252009-07-17 12:17:14 -07004042AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004043 : BnAudioTrack(),
4044 mTrack(track)
4045{
4046}
4047
4048AudioFlinger::TrackHandle::~TrackHandle() {
4049 // just stop the track on deletion, associated resources
4050 // will be freed from the main thread once all pending buffers have
4051 // been played. Unless it's not in the active track list, in which
4052 // case we free everything now...
4053 mTrack->destroy();
4054}
4055
4056status_t AudioFlinger::TrackHandle::start() {
4057 return mTrack->start();
4058}
4059
4060void AudioFlinger::TrackHandle::stop() {
4061 mTrack->stop();
4062}
4063
4064void AudioFlinger::TrackHandle::flush() {
4065 mTrack->flush();
4066}
4067
4068void AudioFlinger::TrackHandle::mute(bool e) {
4069 mTrack->mute(e);
4070}
4071
4072void AudioFlinger::TrackHandle::pause() {
4073 mTrack->pause();
4074}
4075
4076void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4077 mTrack->setVolume(left, right);
4078}
4079
4080sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4081 return mTrack->getCblk();
4082}
4083
Eric Laurent65b65452010-06-01 23:49:17 -07004084status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4085{
4086 return mTrack->attachAuxEffect(EffectId);
4087}
4088
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004089status_t AudioFlinger::TrackHandle::onTransact(
4090 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4091{
4092 return BnAudioTrack::onTransact(code, data, reply, flags);
4093}
4094
4095// ----------------------------------------------------------------------------
4096
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004097sp<IAudioRecord> AudioFlinger::openRecord(
4098 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07004099 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004100 uint32_t sampleRate,
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004101 uint32_t format,
4102 uint32_t channelMask,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004103 int frameCount,
4104 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07004105 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004106 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004107{
Eric Laurenta553c252009-07-17 12:17:14 -07004108 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004109 sp<RecordHandle> recordHandle;
4110 sp<Client> client;
4111 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004112 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07004113 RecordThread *thread;
4114 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07004115 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004116
4117 // check calling permissions
4118 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004119 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004120 goto Exit;
4121 }
4122
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004123 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004124 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004125 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004126 thread = checkRecordThread_l(input);
4127 if (thread == NULL) {
4128 lStatus = BAD_VALUE;
4129 goto Exit;
4130 }
4131
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004132 wclient = mClients.valueFor(pid);
4133 if (wclient != NULL) {
4134 client = wclient.promote();
4135 } else {
4136 client = new Client(this, pid);
4137 mClients.add(pid, client);
4138 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004139
Eric Laurent65b65452010-06-01 23:49:17 -07004140 // If no audio session id is provided, create one here
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004141 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent65b65452010-06-01 23:49:17 -07004142 lSessionId = *sessionId;
4143 } else {
Eric Laurent464d5b32011-06-17 21:29:58 -07004144 lSessionId = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004145 if (sessionId != NULL) {
4146 *sessionId = lSessionId;
4147 }
4148 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004149 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent464d5b32011-06-17 21:29:58 -07004150 recordTrack = thread->createRecordTrack_l(client,
4151 sampleRate,
4152 format,
4153 channelMask,
4154 frameCount,
4155 flags,
4156 lSessionId,
4157 &lStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004158 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004159 if (lStatus != NO_ERROR) {
Eric Laurentb9481d82009-09-17 05:12:56 -07004160 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4161 // destructor is called by the TrackBase destructor with mLock held
4162 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 recordTrack.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 goto Exit;
4165 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004166
4167 // return to handle to client
4168 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004169 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004170
4171Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004172 if (status) {
4173 *status = lStatus;
4174 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004175 return recordHandle;
4176}
4177
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004178// ----------------------------------------------------------------------------
4179
Eric Laurenta553c252009-07-17 12:17:14 -07004180AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004181 : BnAudioRecord(),
4182 mRecordTrack(recordTrack)
4183{
4184}
4185
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004186AudioFlinger::RecordHandle::~RecordHandle() {
4187 stop();
4188}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004189
4190status_t AudioFlinger::RecordHandle::start() {
Steve Block71f2cf12011-10-20 11:56:00 +01004191 ALOGV("RecordHandle::start()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004192 return mRecordTrack->start();
4193}
4194
4195void AudioFlinger::RecordHandle::stop() {
Steve Block71f2cf12011-10-20 11:56:00 +01004196 ALOGV("RecordHandle::stop()");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004197 mRecordTrack->stop();
4198}
4199
4200sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4201 return mRecordTrack->getCblk();
4202}
4203
4204status_t AudioFlinger::RecordHandle::onTransact(
4205 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4206{
4207 return BnAudioRecord::onTransact(code, data, reply, flags);
4208}
4209
4210// ----------------------------------------------------------------------------
4211
Eric Laurent464d5b32011-06-17 21:29:58 -07004212AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4213 AudioStreamIn *input,
4214 uint32_t sampleRate,
4215 uint32_t channels,
4216 int id,
4217 uint32_t device) :
4218 ThreadBase(audioFlinger, id, device),
Glenn Kastenc434c902011-12-13 11:53:26 -08004219 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004220{
Eric Laurent464d5b32011-06-17 21:29:58 -07004221 mType = ThreadBase::RECORD;
Eric Laurent6dbdc402011-07-22 09:04:31 -07004222
4223 snprintf(mName, kNameLength, "AudioIn_%d", id);
4224
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004225 mReqChannelCount = popcount(channels);
Eric Laurenta553c252009-07-17 12:17:14 -07004226 mReqSampleRate = sampleRate;
4227 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004228}
4229
Eric Laurenta553c252009-07-17 12:17:14 -07004230
4231AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004232{
Eric Laurenta553c252009-07-17 12:17:14 -07004233 delete[] mRsmpInBuffer;
Glenn Kastenc434c902011-12-13 11:53:26 -08004234 if (mResampler != NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004235 delete mResampler;
4236 delete[] mRsmpOutBuffer;
4237 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004238}
4239
Eric Laurenta553c252009-07-17 12:17:14 -07004240void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004241{
Eric Laurent6dbdc402011-07-22 09:04:31 -07004242 run(mName, PRIORITY_URGENT_AUDIO);
Eric Laurenta553c252009-07-17 12:17:14 -07004243}
Eric Laurent49f02be2009-11-19 09:00:56 -08004244
Eric Laurent828b9772011-08-07 16:32:26 -07004245status_t AudioFlinger::RecordThread::readyToRun()
4246{
4247 status_t status = initCheck();
4248 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4249 return status;
4250}
4251
Eric Laurenta553c252009-07-17 12:17:14 -07004252bool AudioFlinger::RecordThread::threadLoop()
4253{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004254 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07004255 sp<RecordTrack> activeTrack;
Eric Laurent464d5b32011-06-17 21:29:58 -07004256 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004257
Eric Laurent4712baa2010-09-30 16:12:31 -07004258 nsecs_t lastWarning = 0;
4259
Eric Laurent6dbdc402011-07-22 09:04:31 -07004260 acquireWakeLock();
4261
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004262 // start recording
4263 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004264
Eric Laurenta553c252009-07-17 12:17:14 -07004265 processConfigEvents();
4266
4267 { // scope for mLock
4268 Mutex::Autolock _l(mLock);
4269 checkForNewParameters_l();
4270 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4271 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004272 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004273 mStandby = true;
4274 }
4275
4276 if (exitPending()) break;
4277
Eric Laurent6dbdc402011-07-22 09:04:31 -07004278 releaseWakeLock_l();
Steve Block71f2cf12011-10-20 11:56:00 +01004279 ALOGV("RecordThread: loop stopping");
Eric Laurenta553c252009-07-17 12:17:14 -07004280 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004281 mWaitWorkCV.wait(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01004282 ALOGV("RecordThread: loop starting");
Eric Laurent6dbdc402011-07-22 09:04:31 -07004283 acquireWakeLock_l();
Eric Laurenta553c252009-07-17 12:17:14 -07004284 continue;
4285 }
4286 if (mActiveTrack != 0) {
4287 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004288 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004289 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004290 mStandby = true;
4291 }
Eric Laurenta553c252009-07-17 12:17:14 -07004292 mActiveTrack.clear();
4293 mStartStopCond.broadcast();
4294 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07004295 if (mReqChannelCount != mActiveTrack->channelCount()) {
4296 mActiveTrack.clear();
Eric Laurent9cc489a2009-12-05 05:20:01 -08004297 mStartStopCond.broadcast();
4298 } else if (mBytesRead != 0) {
4299 // record start succeeds only if first read from audio input
4300 // succeeds
4301 if (mBytesRead > 0) {
4302 mActiveTrack->mState = TrackBase::ACTIVE;
4303 } else {
4304 mActiveTrack.clear();
4305 }
4306 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07004307 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004308 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07004309 }
Eric Laurenta553c252009-07-17 12:17:14 -07004310 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004311 lockEffectChains_l(effectChains);
Eric Laurenta553c252009-07-17 12:17:14 -07004312 }
4313
4314 if (mActiveTrack != 0) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004315 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4316 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004317 unlockEffectChains(effectChains);
4318 usleep(kRecordThreadSleepUs);
Eric Laurent49f02be2009-11-19 09:00:56 -08004319 continue;
4320 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004321 for (size_t i = 0; i < effectChains.size(); i ++) {
4322 effectChains[i]->process_l();
4323 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004324
Eric Laurenta553c252009-07-17 12:17:14 -07004325 buffer.frameCount = mFrameCount;
4326 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4327 size_t framesOut = buffer.frameCount;
Glenn Kastenc434c902011-12-13 11:53:26 -08004328 if (mResampler == NULL) {
Eric Laurenta553c252009-07-17 12:17:14 -07004329 // no resampling
4330 while (framesOut) {
4331 size_t framesIn = mFrameCount - mRsmpInIndex;
4332 if (framesIn) {
4333 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4334 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4335 if (framesIn > framesOut)
4336 framesIn = framesOut;
4337 mRsmpInIndex += framesIn;
4338 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07004339 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004340 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Eric Laurenta553c252009-07-17 12:17:14 -07004341 memcpy(dst, src, framesIn * mFrameSize);
4342 } else {
4343 int16_t *src16 = (int16_t *)src;
4344 int16_t *dst16 = (int16_t *)dst;
4345 if (mChannelCount == 1) {
4346 while (framesIn--) {
4347 *dst16++ = *src16;
4348 *dst16++ = *src16++;
4349 }
4350 } else {
4351 while (framesIn--) {
4352 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4353 src16 += 2;
4354 }
4355 }
4356 }
4357 }
4358 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07004359 if (framesOut == mFrameCount &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004360 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin31f188892011-04-18 16:57:27 -07004361 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004362 framesOut = 0;
4363 } else {
Dima Zavin31f188892011-04-18 16:57:27 -07004364 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07004365 mRsmpInIndex = 0;
4366 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004367 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004368 LOGE("Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08004369 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004370 // Force input into standby so that it tries to
4371 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004372 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004373 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004374 }
Eric Laurenta553c252009-07-17 12:17:14 -07004375 mRsmpInIndex = mFrameCount;
4376 framesOut = 0;
4377 buffer.frameCount = 0;
4378 }
4379 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004380 }
4381 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07004382 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004383
Eric Laurenta553c252009-07-17 12:17:14 -07004384 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4385 // alter output frame count as if we were expecting stereo samples
4386 if (mChannelCount == 1 && mReqChannelCount == 1) {
4387 framesOut >>= 1;
4388 }
4389 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4390 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4391 // are 32 bit aligned which should be always true.
4392 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten490909d2011-12-15 09:52:39 -08004393 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004394 // the resampler always outputs stereo samples: do post stereo to mono conversion
4395 int16_t *src = (int16_t *)mRsmpOutBuffer;
4396 int16_t *dst = buffer.i16;
4397 while (framesOut--) {
4398 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4399 src += 2;
4400 }
4401 } else {
Glenn Kasten490909d2011-12-15 09:52:39 -08004402 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Eric Laurenta553c252009-07-17 12:17:14 -07004403 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004404
Eric Laurenta553c252009-07-17 12:17:14 -07004405 }
4406 mActiveTrack->releaseBuffer(&buffer);
4407 mActiveTrack->overflow();
4408 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004409 // client isn't retrieving buffers fast enough
4410 else {
Eric Laurent4712baa2010-09-30 16:12:31 -07004411 if (!mActiveTrack->setOverflow()) {
4412 nsecs_t now = systemTime();
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004413 if ((now - lastWarning) > kWarningThrottleNs) {
Eric Laurent4712baa2010-09-30 16:12:31 -07004414 LOGW("RecordThread: buffer overflow");
4415 lastWarning = now;
4416 }
4417 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004418 // Release the processor for a while before asking for a new buffer.
4419 // This will give the application more chance to read from the buffer and
4420 // clear the overflow.
Eric Laurent464d5b32011-06-17 21:29:58 -07004421 usleep(kRecordThreadSleepUs);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004422 }
4423 }
Eric Laurent21b5c472011-07-26 20:54:46 -07004424 // enable changes in effect chain
4425 unlockEffectChains(effectChains);
Eric Laurent464d5b32011-06-17 21:29:58 -07004426 effectChains.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004427 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004428
Eric Laurenta553c252009-07-17 12:17:14 -07004429 if (!mStandby) {
Dima Zavin31f188892011-04-18 16:57:27 -07004430 mInput->stream->common.standby(&mInput->stream->common);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08004431 }
Eric Laurenta553c252009-07-17 12:17:14 -07004432 mActiveTrack.clear();
4433
Eric Laurent49f02be2009-11-19 09:00:56 -08004434 mStartStopCond.broadcast();
4435
Eric Laurent6dbdc402011-07-22 09:04:31 -07004436 releaseWakeLock();
4437
Steve Block71f2cf12011-10-20 11:56:00 +01004438 ALOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004439 return false;
4440}
4441
Eric Laurent464d5b32011-06-17 21:29:58 -07004442
4443sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4444 const sp<AudioFlinger::Client>& client,
4445 uint32_t sampleRate,
4446 int format,
4447 int channelMask,
4448 int frameCount,
4449 uint32_t flags,
4450 int sessionId,
4451 status_t *status)
4452{
4453 sp<RecordTrack> track;
4454 status_t lStatus;
4455
4456 lStatus = initCheck();
4457 if (lStatus != NO_ERROR) {
4458 LOGE("Audio driver not initialized.");
4459 goto Exit;
4460 }
4461
4462 { // scope for mLock
4463 Mutex::Autolock _l(mLock);
4464
4465 track = new RecordTrack(this, client, sampleRate,
4466 format, channelMask, frameCount, flags, sessionId);
4467
4468 if (track->getCblk() == NULL) {
4469 lStatus = NO_MEMORY;
4470 goto Exit;
4471 }
4472
4473 mTrack = track.get();
Eric Laurent6639b552011-08-01 09:52:20 -07004474 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4475 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004476 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004477 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4478 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent464d5b32011-06-17 21:29:58 -07004479 }
4480 lStatus = NO_ERROR;
4481
4482Exit:
4483 if (status) {
4484 *status = lStatus;
4485 }
4486 return track;
4487}
4488
Eric Laurenta553c252009-07-17 12:17:14 -07004489status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004490{
Steve Block71f2cf12011-10-20 11:56:00 +01004491 ALOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004492 sp <ThreadBase> strongMe = this;
4493 status_t status = NO_ERROR;
4494 {
4495 AutoMutex lock(&mLock);
4496 if (mActiveTrack != 0) {
4497 if (recordTrack != mActiveTrack.get()) {
4498 status = -EBUSY;
4499 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08004500 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08004501 }
4502 return status;
4503 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004504
Eric Laurent49f02be2009-11-19 09:00:56 -08004505 recordTrack->mState = TrackBase::IDLE;
4506 mActiveTrack = recordTrack;
4507 mLock.unlock();
4508 status_t status = AudioSystem::startInput(mId);
4509 mLock.lock();
4510 if (status != NO_ERROR) {
4511 mActiveTrack.clear();
4512 return status;
4513 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08004514 mRsmpInIndex = mFrameCount;
4515 mBytesRead = 0;
Eric Laurent4bb21c42011-02-28 16:52:51 -08004516 if (mResampler != NULL) {
4517 mResampler->reset();
4518 }
4519 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent49f02be2009-11-19 09:00:56 -08004520 // signal thread to start
Steve Block71f2cf12011-10-20 11:56:00 +01004521 ALOGV("Signal record thread");
Eric Laurent49f02be2009-11-19 09:00:56 -08004522 mWaitWorkCV.signal();
4523 // do not wait for mStartStopCond if exiting
4524 if (mExiting) {
4525 mActiveTrack.clear();
4526 status = INVALID_OPERATION;
4527 goto startError;
4528 }
4529 mStartStopCond.wait(mLock);
4530 if (mActiveTrack == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01004531 ALOGV("Record failed to start");
Eric Laurent49f02be2009-11-19 09:00:56 -08004532 status = BAD_VALUE;
4533 goto startError;
4534 }
Steve Block71f2cf12011-10-20 11:56:00 +01004535 ALOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004536 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07004537 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004538startError:
4539 AudioSystem::stopInput(mId);
4540 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004541}
4542
Eric Laurenta553c252009-07-17 12:17:14 -07004543void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block71f2cf12011-10-20 11:56:00 +01004544 ALOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08004545 sp <ThreadBase> strongMe = this;
4546 {
4547 AutoMutex lock(&mLock);
4548 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4549 mActiveTrack->mState = TrackBase::PAUSING;
4550 // do not wait for mStartStopCond if exiting
4551 if (mExiting) {
4552 return;
4553 }
4554 mStartStopCond.wait(mLock);
4555 // if we have been restarted, recordTrack == mActiveTrack.get() here
4556 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4557 mLock.unlock();
4558 AudioSystem::stopInput(mId);
4559 mLock.lock();
Steve Block71f2cf12011-10-20 11:56:00 +01004560 ALOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08004561 }
4562 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004563 }
4564}
4565
Eric Laurenta553c252009-07-17 12:17:14 -07004566status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004567{
4568 const size_t SIZE = 256;
4569 char buffer[SIZE];
4570 String8 result;
4571 pid_t pid = 0;
4572
Eric Laurent3fdb1262009-11-07 00:01:32 -08004573 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4574 result.append(buffer);
4575
4576 if (mActiveTrack != 0) {
4577 result.append("Active Track:\n");
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004578 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08004579 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004581
4582 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4583 result.append(buffer);
4584 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4585 result.append(buffer);
Glenn Kastenc434c902011-12-13 11:53:26 -08004586 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Eric Laurent3fdb1262009-11-07 00:01:32 -08004587 result.append(buffer);
4588 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4589 result.append(buffer);
4590 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4591 result.append(buffer);
4592
4593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 } else {
4595 result.append("No record client\n");
4596 }
4597 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08004598
4599 dumpBase(fd, args);
Eric Laurent1345d332011-07-24 17:49:51 -07004600 dumpEffectChains(fd, args);
Eric Laurent3fdb1262009-11-07 00:01:32 -08004601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 return NO_ERROR;
4603}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004604
Eric Laurenta553c252009-07-17 12:17:14 -07004605status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4606{
4607 size_t framesReq = buffer->frameCount;
4608 size_t framesReady = mFrameCount - mRsmpInIndex;
4609 int channelCount;
4610
4611 if (framesReady == 0) {
Dima Zavin31f188892011-04-18 16:57:27 -07004612 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004613 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07004614 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08004615 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08004616 // Force input into standby so that it tries to
4617 // recover at next read attempt
Dima Zavin31f188892011-04-18 16:57:27 -07004618 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent464d5b32011-06-17 21:29:58 -07004619 usleep(kRecordThreadSleepUs);
Eric Laurent9cc489a2009-12-05 05:20:01 -08004620 }
Glenn Kastenc434c902011-12-13 11:53:26 -08004621 buffer->raw = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004622 buffer->frameCount = 0;
4623 return NOT_ENOUGH_DATA;
4624 }
4625 mRsmpInIndex = 0;
4626 framesReady = mFrameCount;
4627 }
4628
4629 if (framesReq > framesReady) {
4630 framesReq = framesReady;
4631 }
4632
4633 if (mChannelCount == 1 && mReqChannelCount == 2) {
4634 channelCount = 1;
4635 } else {
4636 channelCount = 2;
4637 }
4638 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4639 buffer->frameCount = framesReq;
4640 return NO_ERROR;
4641}
4642
4643void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4644{
4645 mRsmpInIndex += buffer->frameCount;
4646 buffer->frameCount = 0;
4647}
4648
4649bool AudioFlinger::RecordThread::checkForNewParameters_l()
4650{
4651 bool reconfig = false;
4652
Eric Laurent8fce46a2009-08-04 09:45:33 -07004653 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004654 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004655 String8 keyValuePair = mNewParameters[0];
4656 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004657 int value;
4658 int reqFormat = mFormat;
4659 int reqSamplingRate = mReqSampleRate;
4660 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07004661
Eric Laurenta553c252009-07-17 12:17:14 -07004662 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4663 reqSamplingRate = value;
4664 reconfig = true;
4665 }
4666 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4667 reqFormat = value;
4668 reconfig = true;
4669 }
4670 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004671 reqChannelCount = popcount(value);
Eric Laurenta553c252009-07-17 12:17:14 -07004672 reconfig = true;
4673 }
4674 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4675 // do not accept frame count changes if tracks are open as the track buffer
4676 // size depends on frame count and correct behavior would not be garantied
4677 // if frame count is changed after track creation
4678 if (mActiveTrack != 0) {
4679 status = INVALID_OPERATION;
4680 } else {
4681 reconfig = true;
4682 }
4683 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004684 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4685 // forward device change to effects that have requested to be
4686 // aware of attached audio device.
4687 for (size_t i = 0; i < mEffectChains.size(); i++) {
4688 mEffectChains[i]->setDevice_l(value);
4689 }
4690 // store input device and output device but do not forward output device to audio HAL.
4691 // Note that status is ignored by the caller for output device
4692 // (see AudioFlinger::setParameters()
4693 if (value & AUDIO_DEVICE_OUT_ALL) {
4694 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4695 status = BAD_VALUE;
4696 } else {
4697 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent6639b552011-08-01 09:52:20 -07004698 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4699 if (mTrack != NULL) {
4700 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurent2d95dfb2011-08-29 12:42:48 -07004701 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent6639b552011-08-01 09:52:20 -07004702 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4703 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4704 }
Eric Laurent464d5b32011-06-17 21:29:58 -07004705 }
4706 mDevice |= (uint32_t)value;
4707 }
Eric Laurenta553c252009-07-17 12:17:14 -07004708 if (status == NO_ERROR) {
Dima Zavin31f188892011-04-18 16:57:27 -07004709 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004710 if (status == INVALID_OPERATION) {
Dima Zavin31f188892011-04-18 16:57:27 -07004711 mInput->stream->common.standby(&mInput->stream->common);
4712 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Eric Laurenta553c252009-07-17 12:17:14 -07004713 }
4714 if (reconfig) {
4715 if (status == BAD_VALUE &&
Dima Zavin31f188892011-04-18 16:57:27 -07004716 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004717 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin31f188892011-04-18 16:57:27 -07004718 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4719 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004720 (reqChannelCount < 3)) {
Eric Laurenta553c252009-07-17 12:17:14 -07004721 status = NO_ERROR;
4722 }
4723 if (status == NO_ERROR) {
4724 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004725 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004726 }
4727 }
4728 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004729
4730 mNewParameters.removeAt(0);
4731
Eric Laurenta553c252009-07-17 12:17:14 -07004732 mParamStatus = status;
4733 mParamCond.signal();
Eric Laurent5f37be32011-09-13 11:40:21 -07004734 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4735 // already timed out waiting for the status and will never signal the condition.
Glenn Kastencbfe2e12011-12-13 11:04:14 -08004736 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Eric Laurenta553c252009-07-17 12:17:14 -07004737 }
4738 return reconfig;
4739}
4740
4741String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4742{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004743 char *s;
Eric Laurent828b9772011-08-07 16:32:26 -07004744 String8 out_s8 = String8();
4745
4746 Mutex::Autolock _l(mLock);
4747 if (initCheck() != NO_ERROR) {
4748 return out_s8;
4749 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004750
Dima Zavin31f188892011-04-18 16:57:27 -07004751 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004752 out_s8 = String8(s);
4753 free(s);
4754 return out_s8;
Eric Laurenta553c252009-07-17 12:17:14 -07004755}
4756
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004757void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004758 AudioSystem::OutputDescriptor desc;
4759 void *param2 = 0;
4760
4761 switch (event) {
4762 case AudioSystem::INPUT_OPENED:
4763 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004764 desc.channels = mChannelMask;
Eric Laurenta553c252009-07-17 12:17:14 -07004765 desc.samplingRate = mSampleRate;
4766 desc.format = mFormat;
4767 desc.frameCount = mFrameCount;
4768 desc.latency = 0;
4769 param2 = &desc;
4770 break;
4771
4772 case AudioSystem::INPUT_CLOSED:
4773 default:
4774 break;
4775 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004776 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004777}
4778
4779void AudioFlinger::RecordThread::readInputParameters()
4780{
4781 if (mRsmpInBuffer) delete mRsmpInBuffer;
4782 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4783 if (mResampler) delete mResampler;
Glenn Kastenc434c902011-12-13 11:53:26 -08004784 mResampler = NULL;
Eric Laurenta553c252009-07-17 12:17:14 -07004785
Dima Zavin31f188892011-04-18 16:57:27 -07004786 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi54392232011-05-24 15:53:33 -07004787 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4788 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin31f188892011-04-18 16:57:27 -07004789 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4790 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4791 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Eric Laurenta553c252009-07-17 12:17:14 -07004792 mFrameCount = mInputBytes / mFrameSize;
4793 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4794
4795 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4796 {
4797 int channelCount;
4798 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4799 // stereo to mono post process as the resampler always outputs stereo.
4800 if (mChannelCount == 1 && mReqChannelCount == 2) {
4801 channelCount = 1;
4802 } else {
4803 channelCount = 2;
4804 }
4805 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4806 mResampler->setSampleRate(mSampleRate);
4807 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4808 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4809
4810 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4811 if (mChannelCount == 1 && mReqChannelCount == 1) {
4812 mFrameCount >>= 1;
4813 }
4814
4815 }
4816 mRsmpInIndex = mFrameCount;
4817}
4818
Eric Laurent47d0a922010-02-26 02:47:27 -08004819unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4820{
Eric Laurent828b9772011-08-07 16:32:26 -07004821 Mutex::Autolock _l(mLock);
4822 if (initCheck() != NO_ERROR) {
4823 return 0;
4824 }
4825
Dima Zavin31f188892011-04-18 16:57:27 -07004826 return mInput->stream->get_input_frames_lost(mInput->stream);
Eric Laurent47d0a922010-02-26 02:47:27 -08004827}
4828
Eric Laurent464d5b32011-06-17 21:29:58 -07004829uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4830{
4831 Mutex::Autolock _l(mLock);
4832 uint32_t result = 0;
4833 if (getEffectChain_l(sessionId) != 0) {
4834 result = EFFECT_SESSION;
4835 }
4836
4837 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4838 result |= TRACK_SESSION;
4839 }
4840
4841 return result;
4842}
4843
Eric Laurent6639b552011-08-01 09:52:20 -07004844AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4845{
4846 Mutex::Autolock _l(mLock);
4847 return mTrack;
4848}
4849
Eric Laurent828b9772011-08-07 16:32:26 -07004850AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4851{
4852 Mutex::Autolock _l(mLock);
4853 return mInput;
4854}
4855
4856AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4857{
4858 Mutex::Autolock _l(mLock);
4859 AudioStreamIn *input = mInput;
4860 mInput = NULL;
4861 return input;
4862}
4863
4864// this method must always be called either with ThreadBase mLock held or inside the thread loop
4865audio_stream_t* AudioFlinger::RecordThread::stream()
4866{
4867 if (mInput == NULL) {
4868 return NULL;
4869 }
4870 return &mInput->stream->common;
4871}
4872
4873
Eric Laurenta553c252009-07-17 12:17:14 -07004874// ----------------------------------------------------------------------------
4875
Eric Laurentddb78e72009-07-28 08:44:33 -07004876int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004877 uint32_t *pSamplingRate,
4878 uint32_t *pFormat,
4879 uint32_t *pChannels,
4880 uint32_t *pLatencyMs,
4881 uint32_t flags)
4882{
4883 status_t status;
4884 PlaybackThread *thread = NULL;
4885 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4886 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4887 uint32_t format = pFormat ? *pFormat : 0;
4888 uint32_t channels = pChannels ? *pChannels : 0;
4889 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin31f188892011-04-18 16:57:27 -07004890 audio_stream_out_t *outStream;
4891 audio_hw_device_t *outHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07004892
Steve Block71f2cf12011-10-20 11:56:00 +01004893 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Eric Laurenta553c252009-07-17 12:17:14 -07004894 pDevices ? *pDevices : 0,
4895 samplingRate,
4896 format,
4897 channels,
4898 flags);
4899
4900 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004901 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004902 }
Dima Zavin31f188892011-04-18 16:57:27 -07004903
Eric Laurenta553c252009-07-17 12:17:14 -07004904 Mutex::Autolock _l(mLock);
4905
Dima Zavin31f188892011-04-18 16:57:27 -07004906 outHwDev = findSuitableHwDev_l(*pDevices);
4907 if (outHwDev == NULL)
4908 return 0;
4909
4910 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4911 &channels, &samplingRate, &outStream);
Steve Block71f2cf12011-10-20 11:56:00 +01004912 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07004913 outStream,
Eric Laurenta553c252009-07-17 12:17:14 -07004914 samplingRate,
4915 format,
4916 channels,
4917 status);
4918
4919 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin31f188892011-04-18 16:57:27 -07004920 if (outStream != NULL) {
4921 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent464d5b32011-06-17 21:29:58 -07004922 int id = nextUniqueId();
Dima Zavin31f188892011-04-18 16:57:27 -07004923
Dima Zavin24fc2fb2011-04-19 22:30:36 -07004924 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4925 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4926 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004927 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004928 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004929 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004930 thread = new MixerThread(this, output, id, *pDevices);
Steve Block71f2cf12011-10-20 11:56:00 +01004931 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004932 }
Eric Laurent65b65452010-06-01 23:49:17 -07004933 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004934
4935 if (pSamplingRate) *pSamplingRate = samplingRate;
4936 if (pFormat) *pFormat = format;
4937 if (pChannels) *pChannels = channels;
4938 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a2009-12-05 05:20:01 -08004939
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004940 // notify client processes of the new output creation
4941 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004942 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004943 }
4944
Eric Laurent9cc489a2009-12-05 05:20:01 -08004945 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004946}
4947
Eric Laurentddb78e72009-07-28 08:44:33 -07004948int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004949{
4950 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004951 MixerThread *thread1 = checkMixerThread_l(output1);
4952 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004953
Eric Laurentddb78e72009-07-28 08:44:33 -07004954 if (thread1 == NULL || thread2 == NULL) {
4955 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4956 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004957 }
4958
Eric Laurent464d5b32011-06-17 21:29:58 -07004959 int id = nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07004960 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004961 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004962 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004963 // notify client processes of the new output creation
4964 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004965 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004966}
4967
Eric Laurentddb78e72009-07-28 08:44:33 -07004968status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004969{
Eric Laurent49018a52009-08-04 08:37:05 -07004970 // keep strong reference on the playback thread so that
4971 // it is not destroyed while exit() is executed
4972 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004973 {
4974 Mutex::Autolock _l(mLock);
4975 thread = checkPlaybackThread_l(output);
4976 if (thread == NULL) {
4977 return BAD_VALUE;
4978 }
4979
Steve Block71f2cf12011-10-20 11:56:00 +01004980 ALOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004981
Eric Laurent464d5b32011-06-17 21:29:58 -07004982 if (thread->type() == ThreadBase::MIXER) {
Eric Laurenta553c252009-07-17 12:17:14 -07004983 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent464d5b32011-06-17 21:29:58 -07004984 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004985 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004986 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004987 }
4988 }
4989 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004990 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004991 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004992 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004993 }
4994 thread->exit();
4995
Eric Laurent464d5b32011-06-17 21:29:58 -07004996 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent828b9772011-08-07 16:32:26 -07004997 AudioStreamOut *out = thread->clearOutput();
4998 // from now on thread->mOutput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07004999 out->hwDev->close_output_stream(out->hwDev, out->stream);
5000 delete out;
Eric Laurent49018a52009-08-04 08:37:05 -07005001 }
Eric Laurenta553c252009-07-17 12:17:14 -07005002 return NO_ERROR;
5003}
5004
Eric Laurentddb78e72009-07-28 08:44:33 -07005005status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005006{
5007 Mutex::Autolock _l(mLock);
5008 PlaybackThread *thread = checkPlaybackThread_l(output);
5009
5010 if (thread == NULL) {
5011 return BAD_VALUE;
5012 }
5013
Steve Block71f2cf12011-10-20 11:56:00 +01005014 ALOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005015 thread->suspend();
5016
5017 return NO_ERROR;
5018}
5019
Eric Laurentddb78e72009-07-28 08:44:33 -07005020status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005021{
5022 Mutex::Autolock _l(mLock);
5023 PlaybackThread *thread = checkPlaybackThread_l(output);
5024
5025 if (thread == NULL) {
5026 return BAD_VALUE;
5027 }
5028
Steve Block71f2cf12011-10-20 11:56:00 +01005029 ALOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005030
5031 thread->restore();
5032
5033 return NO_ERROR;
5034}
5035
Eric Laurentddb78e72009-07-28 08:44:33 -07005036int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07005037 uint32_t *pSamplingRate,
5038 uint32_t *pFormat,
5039 uint32_t *pChannels,
5040 uint32_t acoustics)
5041{
5042 status_t status;
5043 RecordThread *thread = NULL;
5044 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5045 uint32_t format = pFormat ? *pFormat : 0;
5046 uint32_t channels = pChannels ? *pChannels : 0;
5047 uint32_t reqSamplingRate = samplingRate;
5048 uint32_t reqFormat = format;
5049 uint32_t reqChannels = channels;
Dima Zavin31f188892011-04-18 16:57:27 -07005050 audio_stream_in_t *inStream;
5051 audio_hw_device_t *inHwDev;
Eric Laurenta553c252009-07-17 12:17:14 -07005052
5053 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005054 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005055 }
Dima Zavin31f188892011-04-18 16:57:27 -07005056
Eric Laurenta553c252009-07-17 12:17:14 -07005057 Mutex::Autolock _l(mLock);
5058
Dima Zavin31f188892011-04-18 16:57:27 -07005059 inHwDev = findSuitableHwDev_l(*pDevices);
5060 if (inHwDev == NULL)
5061 return 0;
5062
5063 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5064 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005065 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005066 &inStream);
Steve Block71f2cf12011-10-20 11:56:00 +01005067 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin31f188892011-04-18 16:57:27 -07005068 inStream,
Eric Laurenta553c252009-07-17 12:17:14 -07005069 samplingRate,
5070 format,
5071 channels,
5072 acoustics,
5073 status);
5074
5075 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5076 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5077 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin31f188892011-04-18 16:57:27 -07005078 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005079 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Eric Laurenta553c252009-07-17 12:17:14 -07005080 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005081 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block71f2cf12011-10-20 11:56:00 +01005082 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin31f188892011-04-18 16:57:27 -07005083 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5084 &channels, &samplingRate,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005085 (audio_in_acoustics_t)acoustics,
Dima Zavin31f188892011-04-18 16:57:27 -07005086 &inStream);
Eric Laurenta553c252009-07-17 12:17:14 -07005087 }
5088
Dima Zavin31f188892011-04-18 16:57:27 -07005089 if (inStream != NULL) {
5090 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5091
Eric Laurent464d5b32011-06-17 21:29:58 -07005092 int id = nextUniqueId();
5093 // Start record thread
5094 // RecorThread require both input and output device indication to forward to audio
5095 // pre processing modules
5096 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5097 thread = new RecordThread(this,
5098 input,
5099 reqSamplingRate,
5100 reqChannels,
5101 id,
5102 device);
Eric Laurent65b65452010-06-01 23:49:17 -07005103 mRecordThreads.add(id, thread);
Steve Block71f2cf12011-10-20 11:56:00 +01005104 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07005105 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5106 if (pFormat) *pFormat = format;
5107 if (pChannels) *pChannels = reqChannels;
5108
Dima Zavin31f188892011-04-18 16:57:27 -07005109 input->stream->common.standby(&input->stream->common);
Eric Laurent9cc489a2009-12-05 05:20:01 -08005110
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005111 // notify client processes of the new input creation
5112 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07005113 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07005114 }
5115
Eric Laurent9cc489a2009-12-05 05:20:01 -08005116 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07005117}
5118
Eric Laurentddb78e72009-07-28 08:44:33 -07005119status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07005120{
Eric Laurent49018a52009-08-04 08:37:05 -07005121 // keep strong reference on the record thread so that
5122 // it is not destroyed while exit() is executed
5123 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07005124 {
5125 Mutex::Autolock _l(mLock);
5126 thread = checkRecordThread_l(input);
5127 if (thread == NULL) {
5128 return BAD_VALUE;
5129 }
5130
Steve Block71f2cf12011-10-20 11:56:00 +01005131 ALOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07005132 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08005133 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07005134 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07005135 }
5136 thread->exit();
5137
Eric Laurent828b9772011-08-07 16:32:26 -07005138 AudioStreamIn *in = thread->clearInput();
5139 // from now on thread->mInput is NULL
Dima Zavin31f188892011-04-18 16:57:27 -07005140 in->hwDev->close_input_stream(in->hwDev, in->stream);
5141 delete in;
Eric Laurent49018a52009-08-04 08:37:05 -07005142
Eric Laurenta553c252009-07-17 12:17:14 -07005143 return NO_ERROR;
5144}
5145
Eric Laurentddb78e72009-07-28 08:44:33 -07005146status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07005147{
5148 Mutex::Autolock _l(mLock);
5149 MixerThread *dstThread = checkMixerThread_l(output);
5150 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005151 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07005152 return BAD_VALUE;
5153 }
5154
Steve Block71f2cf12011-10-20 11:56:00 +01005155 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005156 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005157
Eric Laurent05ce0942011-08-30 10:18:54 -07005158 dstThread->setStreamValid(stream, true);
5159
Eric Laurenta553c252009-07-17 12:17:14 -07005160 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07005161 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005162 if (thread != dstThread &&
Eric Laurent464d5b32011-06-17 21:29:58 -07005163 thread->type() != ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005164 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent05ce0942011-08-30 10:18:54 -07005165 srcThread->setStreamValid(stream, false);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07005166 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07005167 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005168 }
Eric Laurentd069f322009-09-01 05:56:26 -07005169
Eric Laurenta553c252009-07-17 12:17:14 -07005170 return NO_ERROR;
5171}
5172
Eric Laurent65b65452010-06-01 23:49:17 -07005173
5174int AudioFlinger::newAudioSessionId()
5175{
Eric Laurent464d5b32011-06-17 21:29:58 -07005176 return nextUniqueId();
Eric Laurent65b65452010-06-01 23:49:17 -07005177}
5178
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005179void AudioFlinger::acquireAudioSessionId(int audioSession)
5180{
5181 Mutex::Autolock _l(mLock);
5182 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005183 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005184 int num = mAudioSessionRefs.size();
5185 for (int i = 0; i< num; i++) {
5186 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5187 if (ref->sessionid == audioSession && ref->pid == caller) {
5188 ref->cnt++;
Steve Block71f2cf12011-10-20 11:56:00 +01005189 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005190 return;
5191 }
5192 }
5193 AudioSessionRef *ref = new AudioSessionRef();
5194 ref->sessionid = audioSession;
5195 ref->pid = caller;
5196 ref->cnt = 1;
5197 mAudioSessionRefs.push(ref);
Steve Block71f2cf12011-10-20 11:56:00 +01005198 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005199}
5200
5201void AudioFlinger::releaseAudioSessionId(int audioSession)
5202{
5203 Mutex::Autolock _l(mLock);
5204 int caller = IPCThreadState::self()->getCallingPid();
Steve Block71f2cf12011-10-20 11:56:00 +01005205 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005206 int num = mAudioSessionRefs.size();
5207 for (int i = 0; i< num; i++) {
5208 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5209 if (ref->sessionid == audioSession && ref->pid == caller) {
5210 ref->cnt--;
Steve Block71f2cf12011-10-20 11:56:00 +01005211 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005212 if (ref->cnt == 0) {
5213 mAudioSessionRefs.removeAt(i);
5214 delete ref;
5215 purgeStaleEffects_l();
5216 }
5217 return;
5218 }
5219 }
5220 LOGW("session id %d not found for pid %d", audioSession, caller);
5221}
5222
5223void AudioFlinger::purgeStaleEffects_l() {
5224
Steve Block71f2cf12011-10-20 11:56:00 +01005225 ALOGV("purging stale effects");
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005226
5227 Vector< sp<EffectChain> > chains;
5228
5229 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5230 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5231 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5232 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen2255a1e2011-08-12 14:14:39 -07005233 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5234 chains.push(ec);
5235 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005236 }
5237 }
5238 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5239 sp<RecordThread> t = mRecordThreads.valueAt(i);
5240 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5241 sp<EffectChain> ec = t->mEffectChains[j];
5242 chains.push(ec);
5243 }
5244 }
5245
5246 for (size_t i = 0; i < chains.size(); i++) {
5247 sp<EffectChain> ec = chains[i];
5248 int sessionid = ec->sessionId();
5249 sp<ThreadBase> t = ec->mThread.promote();
5250 if (t == 0) {
5251 continue;
5252 }
5253 size_t numsessionrefs = mAudioSessionRefs.size();
5254 bool found = false;
5255 for (size_t k = 0; k < numsessionrefs; k++) {
5256 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5257 if (ref->sessionid == sessionid) {
Steve Block71f2cf12011-10-20 11:56:00 +01005258 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005259 sessionid, ref->pid, ref->cnt);
5260 found = true;
5261 break;
5262 }
5263 }
5264 if (!found) {
5265 // remove all effects from the chain
5266 while (ec->mEffects.size()) {
5267 sp<EffectModule> effect = ec->mEffects[0];
5268 effect->unPin();
5269 Mutex::Autolock _l (t->mLock);
5270 t->removeEffect_l(effect);
5271 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5272 sp<EffectHandle> handle = effect->mHandles[j].promote();
5273 if (handle != 0) {
5274 handle->mEffect.clear();
Eric Laurent7fa1cee2011-10-19 11:44:54 -07005275 if (handle->mHasControl && handle->mEnabled) {
5276 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5277 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005278 }
5279 }
5280 AudioSystem::unregisterEffect(effect->id());
5281 }
5282 }
5283 }
5284 return;
5285}
5286
Eric Laurenta553c252009-07-17 12:17:14 -07005287// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005288AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005289{
5290 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005291 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5292 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005293 }
Eric Laurenta553c252009-07-17 12:17:14 -07005294 return thread;
5295}
5296
5297// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005298AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07005299{
5300 PlaybackThread *thread = checkPlaybackThread_l(output);
5301 if (thread != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005302 if (thread->type() == ThreadBase::DIRECT) {
Eric Laurenta553c252009-07-17 12:17:14 -07005303 thread = NULL;
5304 }
5305 }
5306 return (MixerThread *)thread;
5307}
5308
5309// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07005310AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07005311{
5312 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07005313 if (mRecordThreads.indexOfKey(input) >= 0) {
5314 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07005315 }
Eric Laurenta553c252009-07-17 12:17:14 -07005316 return thread;
5317}
5318
Eric Laurent464d5b32011-06-17 21:29:58 -07005319uint32_t AudioFlinger::nextUniqueId()
Eric Laurent65b65452010-06-01 23:49:17 -07005320{
Eric Laurent464d5b32011-06-17 21:29:58 -07005321 return android_atomic_inc(&mNextUniqueId);
Eric Laurent65b65452010-06-01 23:49:17 -07005322}
5323
Eric Laurent464d5b32011-06-17 21:29:58 -07005324AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5325{
5326 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5327 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent828b9772011-08-07 16:32:26 -07005328 AudioStreamOut *output = thread->getOutput();
5329 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005330 return thread;
5331 }
5332 }
5333 return NULL;
5334}
5335
5336uint32_t AudioFlinger::primaryOutputDevice_l()
5337{
5338 PlaybackThread *thread = primaryPlaybackThread_l();
5339
5340 if (thread == NULL) {
5341 return 0;
5342 }
5343
5344 return thread->device();
5345}
5346
5347
Eric Laurent65b65452010-06-01 23:49:17 -07005348// ----------------------------------------------------------------------------
5349// Effect management
5350// ----------------------------------------------------------------------------
5351
5352
Eric Laurent65b65452010-06-01 23:49:17 -07005353status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5354{
5355 Mutex::Autolock _l(mLock);
5356 return EffectQueryNumberEffects(numEffects);
5357}
5358
Eric Laurent53334cd2010-06-23 17:38:20 -07005359status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07005360{
5361 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005362 return EffectQueryEffect(index, descriptor);
Eric Laurent65b65452010-06-01 23:49:17 -07005363}
5364
5365status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5366{
5367 Mutex::Autolock _l(mLock);
5368 return EffectGetDescriptor(pUuid, descriptor);
5369}
5370
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005371
Eric Laurent65b65452010-06-01 23:49:17 -07005372sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5373 effect_descriptor_t *pDesc,
5374 const sp<IEffectClient>& effectClient,
5375 int32_t priority,
Eric Laurent464d5b32011-06-17 21:29:58 -07005376 int io,
Eric Laurent65b65452010-06-01 23:49:17 -07005377 int sessionId,
5378 status_t *status,
5379 int *id,
5380 int *enabled)
5381{
5382 status_t lStatus = NO_ERROR;
5383 sp<EffectHandle> handle;
Eric Laurent65b65452010-06-01 23:49:17 -07005384 effect_descriptor_t desc;
5385 sp<Client> client;
5386 wp<Client> wclient;
5387
Steve Block71f2cf12011-10-20 11:56:00 +01005388 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent464d5b32011-06-17 21:29:58 -07005389 pid, effectClient.get(), priority, sessionId, io);
Eric Laurent65b65452010-06-01 23:49:17 -07005390
5391 if (pDesc == NULL) {
5392 lStatus = BAD_VALUE;
5393 goto Exit;
5394 }
5395
Eric Laurent98c92592010-09-23 16:10:16 -07005396 // check audio settings permission for global effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005397 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent98c92592010-09-23 16:10:16 -07005398 lStatus = PERMISSION_DENIED;
5399 goto Exit;
5400 }
5401
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005402 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent98c92592010-09-23 16:10:16 -07005403 // that can only be created by audio policy manager (running in same process)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005404 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent98c92592010-09-23 16:10:16 -07005405 lStatus = PERMISSION_DENIED;
5406 goto Exit;
5407 }
5408
Eric Laurent464d5b32011-06-17 21:29:58 -07005409 if (io == 0) {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005410 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent98c92592010-09-23 16:10:16 -07005411 // output must be specified by AudioPolicyManager when using session
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005412 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent98c92592010-09-23 16:10:16 -07005413 lStatus = BAD_VALUE;
5414 goto Exit;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005415 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent98c92592010-09-23 16:10:16 -07005416 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent464d5b32011-06-17 21:29:58 -07005417 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent98c92592010-09-23 16:10:16 -07005418 // and we will exit safely
Eric Laurent464d5b32011-06-17 21:29:58 -07005419 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent98c92592010-09-23 16:10:16 -07005420 }
5421 }
5422
Eric Laurent65b65452010-06-01 23:49:17 -07005423 {
5424 Mutex::Autolock _l(mLock);
5425
Eric Laurentdf9b81c2010-07-02 08:12:41 -07005426
Eric Laurent65b65452010-06-01 23:49:17 -07005427 if (!EffectIsNullUuid(&pDesc->uuid)) {
5428 // if uuid is specified, request effect descriptor
5429 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5430 if (lStatus < 0) {
5431 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5432 goto Exit;
5433 }
5434 } else {
5435 // if uuid is not specified, look for an available implementation
5436 // of the required type in effect factory
5437 if (EffectIsNullUuid(&pDesc->type)) {
5438 LOGW("createEffect() no effect type");
5439 lStatus = BAD_VALUE;
5440 goto Exit;
5441 }
5442 uint32_t numEffects = 0;
5443 effect_descriptor_t d;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005444 d.flags = 0; // prevent compiler warning
Eric Laurent65b65452010-06-01 23:49:17 -07005445 bool found = false;
5446
5447 lStatus = EffectQueryNumberEffects(&numEffects);
5448 if (lStatus < 0) {
5449 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5450 goto Exit;
5451 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005452 for (uint32_t i = 0; i < numEffects; i++) {
5453 lStatus = EffectQueryEffect(i, &desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005454 if (lStatus < 0) {
Eric Laurent53334cd2010-06-23 17:38:20 -07005455 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005456 continue;
5457 }
5458 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5459 // If matching type found save effect descriptor. If the session is
5460 // 0 and the effect is not auxiliary, continue enumeration in case
5461 // an auxiliary version of this effect type is available
5462 found = true;
5463 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005464 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Eric Laurent65b65452010-06-01 23:49:17 -07005465 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5466 break;
5467 }
5468 }
5469 }
5470 if (!found) {
5471 lStatus = BAD_VALUE;
5472 LOGW("createEffect() effect not found");
5473 goto Exit;
5474 }
5475 // For same effect type, chose auxiliary version over insert version if
5476 // connect to output mix (Compliance to OpenSL ES)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005477 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005478 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5479 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5480 }
5481 }
5482
5483 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005484 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Eric Laurent65b65452010-06-01 23:49:17 -07005485 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5486 lStatus = INVALID_OPERATION;
5487 goto Exit;
5488 }
5489
Eric Laurentf82fccd2011-07-27 19:49:51 -07005490 // check recording permission for visualizer
5491 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5492 !recordingAllowed()) {
5493 lStatus = PERMISSION_DENIED;
5494 goto Exit;
5495 }
5496
Eric Laurent65b65452010-06-01 23:49:17 -07005497 // return effect descriptor
5498 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5499
5500 // If output is not specified try to find a matching audio session ID in one of the
5501 // output threads.
Eric Laurent98c92592010-09-23 16:10:16 -07005502 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5503 // because of code checking output when entering the function.
Eric Laurent464d5b32011-06-17 21:29:58 -07005504 // Note: io is never 0 when creating an effect on an input
5505 if (io == 0) {
Eric Laurent98c92592010-09-23 16:10:16 -07005506 // look for the thread where the specified audio session is present
5507 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5508 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005509 io = mPlaybackThreads.keyAt(i);
Eric Laurent98c92592010-09-23 16:10:16 -07005510 break;
Eric Laurent493941b2010-07-28 01:32:47 -07005511 }
Eric Laurent65b65452010-06-01 23:49:17 -07005512 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005513 if (io == 0) {
5514 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5515 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5516 io = mRecordThreads.keyAt(i);
5517 break;
5518 }
5519 }
5520 }
Eric Laurent98c92592010-09-23 16:10:16 -07005521 // If no output thread contains the requested session ID, default to
5522 // first output. The effect chain will be moved to the correct output
5523 // thread when a track with the same session ID is created
Eric Laurent464d5b32011-06-17 21:29:58 -07005524 if (io == 0 && mPlaybackThreads.size()) {
5525 io = mPlaybackThreads.keyAt(0);
5526 }
Steve Block71f2cf12011-10-20 11:56:00 +01005527 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent464d5b32011-06-17 21:29:58 -07005528 }
5529 ThreadBase *thread = checkRecordThread_l(io);
5530 if (thread == NULL) {
5531 thread = checkPlaybackThread_l(io);
5532 if (thread == NULL) {
5533 LOGE("createEffect() unknown output thread");
5534 lStatus = BAD_VALUE;
5535 goto Exit;
Eric Laurent98c92592010-09-23 16:10:16 -07005536 }
Eric Laurent65b65452010-06-01 23:49:17 -07005537 }
Eric Laurent98c92592010-09-23 16:10:16 -07005538
Eric Laurent65b65452010-06-01 23:49:17 -07005539 wclient = mClients.valueFor(pid);
5540
5541 if (wclient != NULL) {
5542 client = wclient.promote();
5543 } else {
5544 client = new Client(this, pid);
5545 mClients.add(pid, client);
5546 }
5547
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005548 // create effect on selected output thread
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005549 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5550 &desc, enabled, &lStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07005551 if (handle != 0 && id != NULL) {
5552 *id = handle->id();
5553 }
5554 }
5555
5556Exit:
5557 if(status) {
5558 *status = lStatus;
5559 }
5560 return handle;
5561}
5562
Eric Laurentf82fccd2011-07-27 19:49:51 -07005563status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005564{
Steve Block71f2cf12011-10-20 11:56:00 +01005565 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005566 sessionId, srcOutput, dstOutput);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005567 Mutex::Autolock _l(mLock);
5568 if (srcOutput == dstOutput) {
5569 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5570 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005571 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005572 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5573 if (srcThread == NULL) {
5574 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5575 return BAD_VALUE;
Eric Laurent53334cd2010-06-23 17:38:20 -07005576 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005577 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5578 if (dstThread == NULL) {
5579 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5580 return BAD_VALUE;
5581 }
5582
5583 Mutex::Autolock _dl(dstThread->mLock);
5584 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005585 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005586
Eric Laurent53334cd2010-06-23 17:38:20 -07005587 return NO_ERROR;
5588}
5589
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005590// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurentf82fccd2011-07-27 19:49:51 -07005591status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005592 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent493941b2010-07-28 01:32:47 -07005593 AudioFlinger::PlaybackThread *dstThread,
5594 bool reRegister)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005595{
Steve Block71f2cf12011-10-20 11:56:00 +01005596 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005597 sessionId, srcThread, dstThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005598
Eric Laurentf82fccd2011-07-27 19:49:51 -07005599 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005600 if (chain == 0) {
5601 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurentf82fccd2011-07-27 19:49:51 -07005602 sessionId, srcThread);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005603 return INVALID_OPERATION;
5604 }
5605
Eric Laurent493941b2010-07-28 01:32:47 -07005606 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005607 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurent6fccbd02011-10-05 17:42:25 -07005608 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005609 // removed.
5610 srcThread->removeEffectChain_l(chain);
5611
5612 // transfer all effects one by one so that new effect chain is created on new thread with
5613 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent493941b2010-07-28 01:32:47 -07005614 int dstOutput = dstThread->id();
5615 sp<EffectChain> dstChain;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005616 uint32_t strategy = 0; // prevent compiler warning
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005617 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5618 while (effect != 0) {
5619 srcThread->removeEffect_l(effect);
5620 dstThread->addEffect_l(effect);
Eric Laurent6fccbd02011-10-05 17:42:25 -07005621 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5622 if (effect->state() == EffectModule::ACTIVE ||
5623 effect->state() == EffectModule::STOPPING) {
5624 effect->start();
5625 }
Eric Laurent493941b2010-07-28 01:32:47 -07005626 // if the move request is not received from audio policy manager, the effect must be
5627 // re-registered with the new strategy and output
5628 if (dstChain == 0) {
5629 dstChain = effect->chain().promote();
5630 if (dstChain == 0) {
5631 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5632 srcThread->addEffect_l(effect);
5633 return NO_INIT;
5634 }
5635 strategy = dstChain->strategy();
5636 }
5637 if (reRegister) {
5638 AudioSystem::unregisterEffect(effect->id());
5639 AudioSystem::registerEffect(&effect->desc(),
5640 dstOutput,
5641 strategy,
Eric Laurentf82fccd2011-07-27 19:49:51 -07005642 sessionId,
Eric Laurent493941b2010-07-28 01:32:47 -07005643 effect->id());
5644 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005645 effect = chain->getEffectFromId_l(0);
5646 }
5647
5648 return NO_ERROR;
Eric Laurent53334cd2010-06-23 17:38:20 -07005649}
5650
Eric Laurent464d5b32011-06-17 21:29:58 -07005651
Eric Laurent65b65452010-06-01 23:49:17 -07005652// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005653sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Eric Laurent65b65452010-06-01 23:49:17 -07005654 const sp<AudioFlinger::Client>& client,
5655 const sp<IEffectClient>& effectClient,
5656 int32_t priority,
5657 int sessionId,
5658 effect_descriptor_t *desc,
5659 int *enabled,
5660 status_t *status
5661 )
5662{
5663 sp<EffectModule> effect;
5664 sp<EffectHandle> handle;
5665 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -07005666 sp<EffectChain> chain;
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005667 bool chainCreated = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005668 bool effectCreated = false;
Eric Laurent53334cd2010-06-23 17:38:20 -07005669 bool effectRegistered = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005670
Eric Laurent464d5b32011-06-17 21:29:58 -07005671 lStatus = initCheck();
5672 if (lStatus != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07005673 LOGW("createEffect_l() Audio driver not initialized.");
Eric Laurent65b65452010-06-01 23:49:17 -07005674 goto Exit;
5675 }
5676
5677 // Do not allow effects with session ID 0 on direct output or duplicating threads
5678 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005679 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005680 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5681 desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005682 lStatus = BAD_VALUE;
5683 goto Exit;
5684 }
Eric Laurent464d5b32011-06-17 21:29:58 -07005685 // Only Pre processor effects are allowed on input threads and only on input threads
5686 if ((mType == RECORD &&
5687 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5688 (mType != RECORD &&
5689 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5690 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5691 desc->name, desc->flags, mType);
5692 lStatus = BAD_VALUE;
5693 goto Exit;
5694 }
Eric Laurent65b65452010-06-01 23:49:17 -07005695
Steve Block71f2cf12011-10-20 11:56:00 +01005696 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005697
5698 { // scope for mLock
5699 Mutex::Autolock _l(mLock);
5700
5701 // check for existing effect chain with the requested audio session
5702 chain = getEffectChain_l(sessionId);
5703 if (chain == 0) {
5704 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005705 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005706 chain = new EffectChain(this, sessionId);
5707 addEffectChain_l(chain);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005708 chain->setStrategy(getStrategyForSession_l(sessionId));
5709 chainCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005710 } else {
Eric Laurent76c40f72010-07-15 12:50:15 -07005711 effect = chain->getEffectFromDesc_l(desc);
Eric Laurent65b65452010-06-01 23:49:17 -07005712 }
5713
Steve Block71f2cf12011-10-20 11:56:00 +01005714 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Eric Laurent65b65452010-06-01 23:49:17 -07005715
5716 if (effect == 0) {
Eric Laurent464d5b32011-06-17 21:29:58 -07005717 int id = mAudioFlinger->nextUniqueId();
Eric Laurent53334cd2010-06-23 17:38:20 -07005718 // Check CPU and memory usage
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005719 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Eric Laurent53334cd2010-06-23 17:38:20 -07005720 if (lStatus != NO_ERROR) {
5721 goto Exit;
5722 }
5723 effectRegistered = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005724 // create a new effect module if none present in the chain
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005725 effect = new EffectModule(this, chain, desc, id, sessionId);
Eric Laurent65b65452010-06-01 23:49:17 -07005726 lStatus = effect->status();
5727 if (lStatus != NO_ERROR) {
5728 goto Exit;
5729 }
Eric Laurent76c40f72010-07-15 12:50:15 -07005730 lStatus = chain->addEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005731 if (lStatus != NO_ERROR) {
5732 goto Exit;
5733 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005734 effectCreated = true;
Eric Laurent65b65452010-06-01 23:49:17 -07005735
5736 effect->setDevice(mDevice);
Eric Laurent53334cd2010-06-23 17:38:20 -07005737 effect->setMode(mAudioFlinger->getMode());
Eric Laurent65b65452010-06-01 23:49:17 -07005738 }
5739 // create effect handle and connect it to effect module
5740 handle = new EffectHandle(effect, client, effectClient, priority);
5741 lStatus = effect->addHandle(handle);
5742 if (enabled) {
5743 *enabled = (int)effect->isEnabled();
5744 }
5745 }
5746
5747Exit:
5748 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005749 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07005750 if (effectCreated) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005751 chain->removeEffect_l(effect);
Eric Laurent65b65452010-06-01 23:49:17 -07005752 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005753 if (effectRegistered) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005754 AudioSystem::unregisterEffect(effect->id());
5755 }
5756 if (chainCreated) {
5757 removeEffectChain_l(chain);
Eric Laurent53334cd2010-06-23 17:38:20 -07005758 }
Eric Laurent65b65452010-06-01 23:49:17 -07005759 handle.clear();
5760 }
5761
5762 if(status) {
5763 *status = lStatus;
5764 }
5765 return handle;
5766}
5767
Eric Laurent464d5b32011-06-17 21:29:58 -07005768sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5769{
5770 sp<EffectModule> effect;
5771
5772 sp<EffectChain> chain = getEffectChain_l(sessionId);
5773 if (chain != 0) {
5774 effect = chain->getEffectFromId_l(effectId);
5775 }
5776 return effect;
5777}
5778
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005779// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5780// PlaybackThread::mLock held
Eric Laurent464d5b32011-06-17 21:29:58 -07005781status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005782{
5783 // check for existing effect chain with the requested audio session
5784 int sessionId = effect->sessionId();
5785 sp<EffectChain> chain = getEffectChain_l(sessionId);
5786 bool chainCreated = false;
5787
5788 if (chain == 0) {
5789 // create a new chain for this session
Steve Block71f2cf12011-10-20 11:56:00 +01005790 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005791 chain = new EffectChain(this, sessionId);
5792 addEffectChain_l(chain);
5793 chain->setStrategy(getStrategyForSession_l(sessionId));
5794 chainCreated = true;
5795 }
Steve Block71f2cf12011-10-20 11:56:00 +01005796 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005797
5798 if (chain->getEffectFromId_l(effect->id()) != 0) {
5799 LOGW("addEffect_l() %p effect %s already present in chain %p",
5800 this, effect->desc().name, chain.get());
5801 return BAD_VALUE;
5802 }
5803
5804 status_t status = chain->addEffect_l(effect);
5805 if (status != NO_ERROR) {
5806 if (chainCreated) {
5807 removeEffectChain_l(chain);
5808 }
5809 return status;
5810 }
5811
5812 effect->setDevice(mDevice);
5813 effect->setMode(mAudioFlinger->getMode());
5814 return NO_ERROR;
5815}
5816
Eric Laurent464d5b32011-06-17 21:29:58 -07005817void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005818
Steve Block71f2cf12011-10-20 11:56:00 +01005819 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005820 effect_descriptor_t desc = effect->desc();
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005821 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5822 detachAuxEffect_l(effect->id());
5823 }
5824
5825 sp<EffectChain> chain = effect->chain().promote();
5826 if (chain != 0) {
5827 // remove effect chain if removing last effect
5828 if (chain->removeEffect_l(effect) == 0) {
5829 removeEffectChain_l(chain);
5830 }
5831 } else {
5832 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5833 }
5834}
5835
Eric Laurent464d5b32011-06-17 21:29:58 -07005836void AudioFlinger::ThreadBase::lockEffectChains_l(
5837 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5838{
5839 effectChains = mEffectChains;
5840 for (size_t i = 0; i < mEffectChains.size(); i++) {
5841 mEffectChains[i]->lock();
5842 }
5843}
5844
5845void AudioFlinger::ThreadBase::unlockEffectChains(
5846 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5847{
5848 for (size_t i = 0; i < effectChains.size(); i++) {
5849 effectChains[i]->unlock();
5850 }
5851}
5852
5853sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5854{
5855 Mutex::Autolock _l(mLock);
5856 return getEffectChain_l(sessionId);
5857}
5858
5859sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5860{
5861 sp<EffectChain> chain;
5862
5863 size_t size = mEffectChains.size();
5864 for (size_t i = 0; i < size; i++) {
5865 if (mEffectChains[i]->sessionId() == sessionId) {
5866 chain = mEffectChains[i];
5867 break;
5868 }
5869 }
5870 return chain;
5871}
5872
5873void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5874{
5875 Mutex::Autolock _l(mLock);
5876 size_t size = mEffectChains.size();
5877 for (size_t i = 0; i < size; i++) {
5878 mEffectChains[i]->setMode_l(mode);
5879 }
5880}
5881
5882void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005883 const wp<EffectHandle>& handle,
5884 bool unpiniflast) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07005885
Eric Laurent53334cd2010-06-23 17:38:20 -07005886 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01005887 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Eric Laurent53334cd2010-06-23 17:38:20 -07005888 // delete the effect module if removing last handle on it
5889 if (effect->removeHandle(handle) == 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07005890 if (!effect->isPinned() || unpiniflast) {
5891 removeEffect_l(effect);
5892 AudioSystem::unregisterEffect(effect->id());
5893 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005894 }
5895}
5896
Eric Laurent65b65452010-06-01 23:49:17 -07005897status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5898{
5899 int session = chain->sessionId();
5900 int16_t *buffer = mMixBuffer;
Eric Laurent53334cd2010-06-23 17:38:20 -07005901 bool ownsBuffer = false;
Eric Laurent65b65452010-06-01 23:49:17 -07005902
Steve Block71f2cf12011-10-20 11:56:00 +01005903 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent53334cd2010-06-23 17:38:20 -07005904 if (session > 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07005905 // Only one effect chain can be present in direct output thread and it uses
5906 // the mix buffer as input
5907 if (mType != DIRECT) {
5908 size_t numSamples = mFrameCount * mChannelCount;
5909 buffer = new int16_t[numSamples];
5910 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block71f2cf12011-10-20 11:56:00 +01005911 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005912 ownsBuffer = true;
5913 }
Eric Laurent65b65452010-06-01 23:49:17 -07005914
Eric Laurent53334cd2010-06-23 17:38:20 -07005915 // Attach all tracks with same session ID to this chain.
5916 for (size_t i = 0; i < mTracks.size(); ++i) {
5917 sp<Track> track = mTracks[i];
5918 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005919 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Eric Laurent53334cd2010-06-23 17:38:20 -07005920 track->setMainBuffer(buffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005921 chain->incTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005922 }
5923 }
5924
5925 // indicate all active tracks in the chain
5926 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5927 sp<Track> track = mActiveTracks[i].promote();
5928 if (track == 0) continue;
5929 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005930 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurent90681d62011-05-09 12:09:06 -07005931 chain->incActiveTrackCnt();
Eric Laurent53334cd2010-06-23 17:38:20 -07005932 }
Eric Laurent65b65452010-06-01 23:49:17 -07005933 }
5934 }
5935
Eric Laurent53334cd2010-06-23 17:38:20 -07005936 chain->setInBuffer(buffer, ownsBuffer);
5937 chain->setOutBuffer(mMixBuffer);
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005938 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005939 // chains list in order to be processed last as it contains output stage effects
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005940 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5941 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Eric Laurent53334cd2010-06-23 17:38:20 -07005942 // after track specific effects and before output stage
Dima Zavin24fc2fb2011-04-19 22:30:36 -07005943 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5944 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005945 // Effect chain for other sessions are inserted at beginning of effect
5946 // chains list to be processed before output mix effects. Relative order between other
5947 // sessions is not important
Eric Laurent53334cd2010-06-23 17:38:20 -07005948 size_t size = mEffectChains.size();
5949 size_t i = 0;
5950 for (i = 0; i < size; i++) {
5951 if (mEffectChains[i]->sessionId() < session) break;
Eric Laurent65b65452010-06-01 23:49:17 -07005952 }
Eric Laurent53334cd2010-06-23 17:38:20 -07005953 mEffectChains.insertAt(chain, i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07005954 checkSuspendOnAddEffectChain_l(chain);
Eric Laurent65b65452010-06-01 23:49:17 -07005955
5956 return NO_ERROR;
5957}
5958
5959size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5960{
5961 int session = chain->sessionId();
5962
Steve Block71f2cf12011-10-20 11:56:00 +01005963 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Eric Laurent65b65452010-06-01 23:49:17 -07005964
5965 for (size_t i = 0; i < mEffectChains.size(); i++) {
5966 if (chain == mEffectChains[i]) {
5967 mEffectChains.removeAt(i);
Eric Laurent90681d62011-05-09 12:09:06 -07005968 // detach all active tracks from the chain
5969 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5970 sp<Track> track = mActiveTracks[i].promote();
5971 if (track == 0) continue;
5972 if (session == track->sessionId()) {
Steve Block71f2cf12011-10-20 11:56:00 +01005973 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurent90681d62011-05-09 12:09:06 -07005974 chain.get(), session);
5975 chain->decActiveTrackCnt();
5976 }
5977 }
5978
Eric Laurent65b65452010-06-01 23:49:17 -07005979 // detach all tracks with same session ID from this chain
5980 for (size_t i = 0; i < mTracks.size(); ++i) {
5981 sp<Track> track = mTracks[i];
5982 if (session == track->sessionId()) {
5983 track->setMainBuffer(mMixBuffer);
Eric Laurent90681d62011-05-09 12:09:06 -07005984 chain->decTrackCnt();
Eric Laurent65b65452010-06-01 23:49:17 -07005985 }
5986 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005987 break;
Eric Laurent65b65452010-06-01 23:49:17 -07005988 }
5989 }
5990 return mEffectChains.size();
5991}
5992
Eric Laurent8ed6ed02010-07-13 04:45:46 -07005993status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5994 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07005995{
5996 Mutex::Autolock _l(mLock);
5997 return attachAuxEffect_l(track, EffectId);
5998}
5999
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006000status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6001 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Eric Laurent65b65452010-06-01 23:49:17 -07006002{
6003 status_t status = NO_ERROR;
6004
6005 if (EffectId == 0) {
6006 track->setAuxBuffer(0, NULL);
6007 } else {
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006008 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6009 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent65b65452010-06-01 23:49:17 -07006010 if (effect != 0) {
6011 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6012 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6013 } else {
6014 status = INVALID_OPERATION;
6015 }
6016 } else {
6017 status = BAD_VALUE;
6018 }
6019 }
6020 return status;
6021}
6022
6023void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6024{
6025 for (size_t i = 0; i < mTracks.size(); ++i) {
6026 sp<Track> track = mTracks[i];
6027 if (track->auxEffectId() == effectId) {
6028 attachAuxEffect_l(track, 0);
6029 }
6030 }
6031}
6032
Eric Laurent464d5b32011-06-17 21:29:58 -07006033status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6034{
6035 // only one chain per input thread
6036 if (mEffectChains.size() != 0) {
6037 return INVALID_OPERATION;
6038 }
Steve Block71f2cf12011-10-20 11:56:00 +01006039 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006040
6041 chain->setInBuffer(NULL);
6042 chain->setOutBuffer(NULL);
6043
Eric Laurentf82fccd2011-07-27 19:49:51 -07006044 checkSuspendOnAddEffectChain_l(chain);
6045
Eric Laurent464d5b32011-06-17 21:29:58 -07006046 mEffectChains.add(chain);
6047
6048 return NO_ERROR;
6049}
6050
6051size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6052{
Steve Block71f2cf12011-10-20 11:56:00 +01006053 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurent464d5b32011-06-17 21:29:58 -07006054 LOGW_IF(mEffectChains.size() != 1,
6055 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6056 chain.get(), mEffectChains.size(), this);
6057 if (mEffectChains.size() == 1) {
6058 mEffectChains.removeAt(0);
6059 }
6060 return 0;
6061}
6062
Eric Laurent65b65452010-06-01 23:49:17 -07006063// ----------------------------------------------------------------------------
6064// EffectModule implementation
6065// ----------------------------------------------------------------------------
6066
6067#undef LOG_TAG
6068#define LOG_TAG "AudioFlinger::EffectModule"
6069
6070AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6071 const wp<AudioFlinger::EffectChain>& chain,
6072 effect_descriptor_t *desc,
6073 int id,
6074 int sessionId)
6075 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006076 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006077{
Steve Block71f2cf12011-10-20 11:56:00 +01006078 ALOGV("Constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006079 int lStatus;
6080 sp<ThreadBase> thread = mThread.promote();
6081 if (thread == 0) {
6082 return;
6083 }
Eric Laurent65b65452010-06-01 23:49:17 -07006084
6085 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6086
6087 // create effect engine from effect factory
Eric Laurent464d5b32011-06-17 21:29:58 -07006088 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Eric Laurent53334cd2010-06-23 17:38:20 -07006089
Eric Laurent65b65452010-06-01 23:49:17 -07006090 if (mStatus != NO_ERROR) {
6091 return;
6092 }
6093 lStatus = init();
6094 if (lStatus < 0) {
6095 mStatus = lStatus;
6096 goto Error;
6097 }
6098
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006099 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6100 mPinned = true;
6101 }
Steve Block71f2cf12011-10-20 11:56:00 +01006102 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006103 return;
6104Error:
6105 EffectRelease(mEffectInterface);
6106 mEffectInterface = NULL;
Steve Block71f2cf12011-10-20 11:56:00 +01006107 ALOGV("Constructor Error %d", mStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006108}
6109
6110AudioFlinger::EffectModule::~EffectModule()
6111{
Steve Block71f2cf12011-10-20 11:56:00 +01006112 ALOGV("Destructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006113 if (mEffectInterface != NULL) {
Eric Laurent464d5b32011-06-17 21:29:58 -07006114 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6115 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6116 sp<ThreadBase> thread = mThread.promote();
6117 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006118 audio_stream_t *stream = thread->stream();
6119 if (stream != NULL) {
6120 stream->remove_audio_effect(stream, mEffectInterface);
6121 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006122 }
6123 }
Eric Laurent65b65452010-06-01 23:49:17 -07006124 // release effect engine
6125 EffectRelease(mEffectInterface);
6126 }
6127}
6128
6129status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6130{
6131 status_t status;
6132
6133 Mutex::Autolock _l(mLock);
6134 // First handle in mHandles has highest priority and controls the effect module
6135 int priority = handle->priority();
6136 size_t size = mHandles.size();
6137 sp<EffectHandle> h;
6138 size_t i;
6139 for (i = 0; i < size; i++) {
6140 h = mHandles[i].promote();
6141 if (h == 0) continue;
6142 if (h->priority() <= priority) break;
6143 }
6144 // if inserted in first place, move effect control from previous owner to this handle
6145 if (i == 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006146 bool enabled = false;
Eric Laurent65b65452010-06-01 23:49:17 -07006147 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006148 enabled = h->enabled();
6149 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006150 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006151 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006152 status = NO_ERROR;
6153 } else {
6154 status = ALREADY_EXISTS;
6155 }
Steve Block71f2cf12011-10-20 11:56:00 +01006156 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Eric Laurent65b65452010-06-01 23:49:17 -07006157 mHandles.insertAt(handle, i);
6158 return status;
6159}
6160
6161size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6162{
6163 Mutex::Autolock _l(mLock);
6164 size_t size = mHandles.size();
6165 size_t i;
6166 for (i = 0; i < size; i++) {
6167 if (mHandles[i] == handle) break;
6168 }
6169 if (i == size) {
6170 return size;
6171 }
Steve Block71f2cf12011-10-20 11:56:00 +01006172 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006173
6174 bool enabled = false;
6175 EffectHandle *hdl = handle.unsafe_get();
6176 if (hdl) {
Steve Block71f2cf12011-10-20 11:56:00 +01006177 ALOGV("removeHandle() unsafe_get OK");
Eric Laurentf82fccd2011-07-27 19:49:51 -07006178 enabled = hdl->enabled();
6179 }
Eric Laurent65b65452010-06-01 23:49:17 -07006180 mHandles.removeAt(i);
6181 size = mHandles.size();
6182 // if removed from first place, move effect control from this handle to next in line
6183 if (i == 0 && size != 0) {
6184 sp<EffectHandle> h = mHandles[0].promote();
6185 if (h != 0) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07006186 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Eric Laurent65b65452010-06-01 23:49:17 -07006187 }
6188 }
6189
Eric Laurent21b5c472011-07-26 20:54:46 -07006190 // Prevent calls to process() and other functions on effect interface from now on.
6191 // The effect engine will be released by the destructor when the last strong reference on
6192 // this object is released which can happen after next process is called.
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006193 if (size == 0 && !mPinned) {
Eric Laurent21b5c472011-07-26 20:54:46 -07006194 mState = DESTROYED;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07006195 }
6196
Eric Laurent65b65452010-06-01 23:49:17 -07006197 return size;
6198}
6199
Eric Laurentf82fccd2011-07-27 19:49:51 -07006200sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6201{
6202 Mutex::Autolock _l(mLock);
6203 sp<EffectHandle> handle;
6204 if (mHandles.size() != 0) {
6205 handle = mHandles[0].promote();
6206 }
6207 return handle;
6208}
6209
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006210void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Eric Laurent65b65452010-06-01 23:49:17 -07006211{
Steve Block71f2cf12011-10-20 11:56:00 +01006212 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Eric Laurent65b65452010-06-01 23:49:17 -07006213 // keep a strong reference on this EffectModule to avoid calling the
6214 // destructor before we exit
6215 sp<EffectModule> keep(this);
Eric Laurent53334cd2010-06-23 17:38:20 -07006216 {
6217 sp<ThreadBase> thread = mThread.promote();
6218 if (thread != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006219 thread->disconnectEffect(keep, handle, unpiniflast);
Eric Laurent65b65452010-06-01 23:49:17 -07006220 }
6221 }
6222}
6223
Eric Laurent7d850f22010-07-09 13:34:17 -07006224void AudioFlinger::EffectModule::updateState() {
6225 Mutex::Autolock _l(mLock);
6226
6227 switch (mState) {
6228 case RESTART:
6229 reset_l();
6230 // FALL THROUGH
6231
6232 case STARTING:
6233 // clear auxiliary effect input buffer for next accumulation
6234 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6235 memset(mConfig.inputCfg.buffer.raw,
6236 0,
6237 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6238 }
6239 start_l();
6240 mState = ACTIVE;
6241 break;
6242 case STOPPING:
6243 stop_l();
6244 mDisableWaitCnt = mMaxDisableWaitCnt;
6245 mState = STOPPED;
6246 break;
6247 case STOPPED:
6248 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6249 // turn off sequence.
6250 if (--mDisableWaitCnt == 0) {
6251 reset_l();
6252 mState = IDLE;
6253 }
6254 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006255 default: //IDLE , ACTIVE, DESTROYED
Eric Laurent7d850f22010-07-09 13:34:17 -07006256 break;
6257 }
6258}
6259
Eric Laurent65b65452010-06-01 23:49:17 -07006260void AudioFlinger::EffectModule::process()
6261{
6262 Mutex::Autolock _l(mLock);
6263
Eric Laurent21b5c472011-07-26 20:54:46 -07006264 if (mState == DESTROYED || mEffectInterface == NULL ||
Eric Laurent7d850f22010-07-09 13:34:17 -07006265 mConfig.inputCfg.buffer.raw == NULL ||
6266 mConfig.outputCfg.buffer.raw == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006267 return;
6268 }
6269
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006270 if (isProcessEnabled()) {
Eric Laurent65b65452010-06-01 23:49:17 -07006271 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6272 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten490909d2011-12-15 09:52:39 -08006273 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Eric Laurent65b65452010-06-01 23:49:17 -07006274 mConfig.inputCfg.buffer.s32,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006275 mConfig.inputCfg.buffer.frameCount/2);
Eric Laurent65b65452010-06-01 23:49:17 -07006276 }
6277
Eric Laurent65b65452010-06-01 23:49:17 -07006278 // do the actual processing in the effect engine
Eric Laurent7d850f22010-07-09 13:34:17 -07006279 int ret = (*mEffectInterface)->process(mEffectInterface,
6280 &mConfig.inputCfg.buffer,
6281 &mConfig.outputCfg.buffer);
6282
6283 // force transition to IDLE state when engine is ready
6284 if (mState == STOPPED && ret == -ENODATA) {
6285 mDisableWaitCnt = 1;
6286 }
Eric Laurent65b65452010-06-01 23:49:17 -07006287
6288 // clear auxiliary effect input buffer for next accumulation
6289 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006290 memset(mConfig.inputCfg.buffer.raw, 0,
6291 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Eric Laurent65b65452010-06-01 23:49:17 -07006292 }
6293 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent67b5ed32011-01-19 18:36:13 -08006294 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6295 // If an insert effect is idle and input buffer is different from output buffer,
6296 // accumulate input onto output
Eric Laurent65b65452010-06-01 23:49:17 -07006297 sp<EffectChain> chain = mChain.promote();
Eric Laurent90681d62011-05-09 12:09:06 -07006298 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent67b5ed32011-01-19 18:36:13 -08006299 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6300 int16_t *in = mConfig.inputCfg.buffer.s16;
6301 int16_t *out = mConfig.outputCfg.buffer.s16;
6302 for (size_t i = 0; i < frameCnt; i++) {
6303 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Eric Laurent65b65452010-06-01 23:49:17 -07006304 }
Eric Laurent65b65452010-06-01 23:49:17 -07006305 }
6306 }
6307}
6308
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006309void AudioFlinger::EffectModule::reset_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006310{
6311 if (mEffectInterface == NULL) {
6312 return;
6313 }
6314 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6315}
6316
6317status_t AudioFlinger::EffectModule::configure()
6318{
6319 uint32_t channels;
6320 if (mEffectInterface == NULL) {
6321 return NO_INIT;
6322 }
6323
6324 sp<ThreadBase> thread = mThread.promote();
6325 if (thread == 0) {
6326 return DEAD_OBJECT;
6327 }
6328
6329 // TODO: handle configuration of effects replacing track process
6330 if (thread->channelCount() == 1) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006331 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006332 } else {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006333 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurent65b65452010-06-01 23:49:17 -07006334 }
6335
6336 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent0fb66c22011-05-17 19:16:02 -07006337 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurent65b65452010-06-01 23:49:17 -07006338 } else {
6339 mConfig.inputCfg.channels = channels;
6340 }
6341 mConfig.outputCfg.channels = channels;
Eric Laurent0fb66c22011-05-17 19:16:02 -07006342 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6343 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurent65b65452010-06-01 23:49:17 -07006344 mConfig.inputCfg.samplingRate = thread->sampleRate();
6345 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6346 mConfig.inputCfg.bufferProvider.cookie = NULL;
6347 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6348 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6349 mConfig.outputCfg.bufferProvider.cookie = NULL;
6350 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6351 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6352 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6353 // Insert effect:
Dima Zavin24fc2fb2011-04-19 22:30:36 -07006354 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006355 // always overwrites output buffer: input buffer == output buffer
Eric Laurent65b65452010-06-01 23:49:17 -07006356 // - in other sessions:
6357 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6358 // other effect: overwrites output buffer: input buffer == output buffer
6359 // Auxiliary effect:
6360 // accumulates in output buffer: input buffer != output buffer
6361 // Therefore: accumulate <=> input buffer != output buffer
6362 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6363 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6364 } else {
6365 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6366 }
6367 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6368 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6369 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6370 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6371
Steve Block71f2cf12011-10-20 11:56:00 +01006372 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurent8ed6ed02010-07-13 04:45:46 -07006373 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6374
Eric Laurent65b65452010-06-01 23:49:17 -07006375 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006376 uint32_t size = sizeof(int);
6377 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent4abf8822011-12-16 15:30:36 -08006378 EFFECT_CMD_SET_CONFIG,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006379 sizeof(effect_config_t),
6380 &mConfig,
6381 &size,
6382 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006383 if (status == 0) {
6384 status = cmdStatus;
6385 }
Eric Laurent7d850f22010-07-09 13:34:17 -07006386
6387 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6388 (1000 * mConfig.outputCfg.buffer.frameCount);
6389
Eric Laurent65b65452010-06-01 23:49:17 -07006390 return status;
6391}
6392
6393status_t AudioFlinger::EffectModule::init()
6394{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006395 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006396 if (mEffectInterface == NULL) {
6397 return NO_INIT;
6398 }
6399 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006400 uint32_t size = sizeof(status_t);
6401 status_t status = (*mEffectInterface)->command(mEffectInterface,
6402 EFFECT_CMD_INIT,
6403 0,
6404 NULL,
6405 &size,
6406 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006407 if (status == 0) {
6408 status = cmdStatus;
6409 }
6410 return status;
6411}
6412
Eric Laurent6fccbd02011-10-05 17:42:25 -07006413status_t AudioFlinger::EffectModule::start()
6414{
6415 Mutex::Autolock _l(mLock);
6416 return start_l();
6417}
6418
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006419status_t AudioFlinger::EffectModule::start_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006420{
6421 if (mEffectInterface == NULL) {
6422 return NO_INIT;
6423 }
6424 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006425 uint32_t size = sizeof(status_t);
6426 status_t status = (*mEffectInterface)->command(mEffectInterface,
6427 EFFECT_CMD_ENABLE,
6428 0,
6429 NULL,
6430 &size,
6431 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006432 if (status == 0) {
6433 status = cmdStatus;
6434 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006435 if (status == 0 &&
6436 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6437 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6438 sp<ThreadBase> thread = mThread.promote();
6439 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006440 audio_stream_t *stream = thread->stream();
6441 if (stream != NULL) {
6442 stream->add_audio_effect(stream, mEffectInterface);
6443 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006444 }
6445 }
Eric Laurent65b65452010-06-01 23:49:17 -07006446 return status;
6447}
6448
Eric Laurent21b5c472011-07-26 20:54:46 -07006449status_t AudioFlinger::EffectModule::stop()
6450{
6451 Mutex::Autolock _l(mLock);
6452 return stop_l();
6453}
6454
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006455status_t AudioFlinger::EffectModule::stop_l()
Eric Laurent65b65452010-06-01 23:49:17 -07006456{
6457 if (mEffectInterface == NULL) {
6458 return NO_INIT;
6459 }
6460 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006461 uint32_t size = sizeof(status_t);
6462 status_t status = (*mEffectInterface)->command(mEffectInterface,
6463 EFFECT_CMD_DISABLE,
6464 0,
6465 NULL,
6466 &size,
6467 &cmdStatus);
Eric Laurent65b65452010-06-01 23:49:17 -07006468 if (status == 0) {
6469 status = cmdStatus;
6470 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006471 if (status == 0 &&
6472 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6473 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6474 sp<ThreadBase> thread = mThread.promote();
6475 if (thread != 0) {
Eric Laurent828b9772011-08-07 16:32:26 -07006476 audio_stream_t *stream = thread->stream();
6477 if (stream != NULL) {
6478 stream->remove_audio_effect(stream, mEffectInterface);
6479 }
Eric Laurent464d5b32011-06-17 21:29:58 -07006480 }
6481 }
Eric Laurent65b65452010-06-01 23:49:17 -07006482 return status;
6483}
6484
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006485status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6486 uint32_t cmdSize,
6487 void *pCmdData,
6488 uint32_t *replySize,
6489 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006490{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006491 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006492// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Eric Laurent65b65452010-06-01 23:49:17 -07006493
Eric Laurent21b5c472011-07-26 20:54:46 -07006494 if (mState == DESTROYED || mEffectInterface == NULL) {
Eric Laurent65b65452010-06-01 23:49:17 -07006495 return NO_INIT;
6496 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006497 status_t status = (*mEffectInterface)->command(mEffectInterface,
6498 cmdCode,
6499 cmdSize,
6500 pCmdData,
6501 replySize,
6502 pReplyData);
Eric Laurent65b65452010-06-01 23:49:17 -07006503 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006504 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Eric Laurent65b65452010-06-01 23:49:17 -07006505 for (size_t i = 1; i < mHandles.size(); i++) {
6506 sp<EffectHandle> h = mHandles[i].promote();
6507 if (h != 0) {
6508 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6509 }
6510 }
6511 }
6512 return status;
6513}
6514
6515status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6516{
Eric Laurent6752ec82011-08-10 10:37:50 -07006517
Eric Laurent65b65452010-06-01 23:49:17 -07006518 Mutex::Autolock _l(mLock);
Steve Block71f2cf12011-10-20 11:56:00 +01006519 ALOGV("setEnabled %p enabled %d", this, enabled);
Eric Laurent65b65452010-06-01 23:49:17 -07006520
6521 if (enabled != isEnabled()) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006522 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6523 if (enabled && status != NO_ERROR) {
6524 return status;
6525 }
6526
Eric Laurent65b65452010-06-01 23:49:17 -07006527 switch (mState) {
6528 // going from disabled to enabled
6529 case IDLE:
Eric Laurent7d850f22010-07-09 13:34:17 -07006530 mState = STARTING;
6531 break;
6532 case STOPPED:
6533 mState = RESTART;
Eric Laurent65b65452010-06-01 23:49:17 -07006534 break;
6535 case STOPPING:
6536 mState = ACTIVE;
6537 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006538
6539 // going from enabled to disabled
Eric Laurent7d850f22010-07-09 13:34:17 -07006540 case RESTART:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006541 mState = STOPPED;
6542 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006543 case STARTING:
Eric Laurent7d850f22010-07-09 13:34:17 -07006544 mState = IDLE;
Eric Laurent65b65452010-06-01 23:49:17 -07006545 break;
6546 case ACTIVE:
6547 mState = STOPPING;
6548 break;
Eric Laurent21b5c472011-07-26 20:54:46 -07006549 case DESTROYED:
6550 return NO_ERROR; // simply ignore as we are being destroyed
Eric Laurent65b65452010-06-01 23:49:17 -07006551 }
6552 for (size_t i = 1; i < mHandles.size(); i++) {
6553 sp<EffectHandle> h = mHandles[i].promote();
6554 if (h != 0) {
6555 h->setEnabled(enabled);
6556 }
6557 }
6558 }
6559 return NO_ERROR;
6560}
6561
6562bool AudioFlinger::EffectModule::isEnabled()
6563{
6564 switch (mState) {
Eric Laurent7d850f22010-07-09 13:34:17 -07006565 case RESTART:
Eric Laurent65b65452010-06-01 23:49:17 -07006566 case STARTING:
6567 case ACTIVE:
6568 return true;
6569 case IDLE:
6570 case STOPPING:
6571 case STOPPED:
Eric Laurent21b5c472011-07-26 20:54:46 -07006572 case DESTROYED:
Eric Laurent65b65452010-06-01 23:49:17 -07006573 default:
6574 return false;
6575 }
6576}
6577
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006578bool AudioFlinger::EffectModule::isProcessEnabled()
6579{
6580 switch (mState) {
6581 case RESTART:
6582 case ACTIVE:
6583 case STOPPING:
6584 case STOPPED:
6585 return true;
6586 case IDLE:
6587 case STARTING:
Eric Laurent21b5c472011-07-26 20:54:46 -07006588 case DESTROYED:
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006589 default:
6590 return false;
6591 }
6592}
6593
Eric Laurent65b65452010-06-01 23:49:17 -07006594status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6595{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006596 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006597 status_t status = NO_ERROR;
6598
6599 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6600 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurenta92ebfa2010-08-31 13:50:07 -07006601 if (isProcessEnabled() &&
Eric Laurent0d7e0482010-07-19 06:24:46 -07006602 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6603 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurent65b65452010-06-01 23:49:17 -07006604 status_t cmdStatus;
6605 uint32_t volume[2];
6606 uint32_t *pVolume = NULL;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006607 uint32_t size = sizeof(volume);
Eric Laurent65b65452010-06-01 23:49:17 -07006608 volume[0] = *left;
6609 volume[1] = *right;
6610 if (controller) {
6611 pVolume = volume;
6612 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006613 status = (*mEffectInterface)->command(mEffectInterface,
6614 EFFECT_CMD_SET_VOLUME,
6615 size,
6616 volume,
6617 &size,
6618 pVolume);
Eric Laurent65b65452010-06-01 23:49:17 -07006619 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6620 *left = volume[0];
6621 *right = volume[1];
6622 }
6623 }
6624 return status;
6625}
6626
6627status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6628{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006629 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07006630 status_t status = NO_ERROR;
Eric Laurent464d5b32011-06-17 21:29:58 -07006631 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6632 // audio pre processing modules on RecordThread can receive both output and
6633 // input device indication in the same call
6634 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6635 if (dev) {
6636 status_t cmdStatus;
6637 uint32_t size = sizeof(status_t);
6638
6639 status = (*mEffectInterface)->command(mEffectInterface,
6640 EFFECT_CMD_SET_DEVICE,
6641 sizeof(uint32_t),
6642 &dev,
6643 &size,
6644 &cmdStatus);
6645 if (status == NO_ERROR) {
6646 status = cmdStatus;
6647 }
6648 }
6649 dev = device & AUDIO_DEVICE_IN_ALL;
6650 if (dev) {
6651 status_t cmdStatus;
6652 uint32_t size = sizeof(status_t);
6653
6654 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6655 EFFECT_CMD_SET_INPUT_DEVICE,
6656 sizeof(uint32_t),
6657 &dev,
6658 &size,
6659 &cmdStatus);
6660 if (status2 == NO_ERROR) {
6661 status2 = cmdStatus;
6662 }
6663 if (status == NO_ERROR) {
6664 status = status2;
6665 }
Eric Laurent65b65452010-06-01 23:49:17 -07006666 }
6667 }
6668 return status;
6669}
6670
Eric Laurent53334cd2010-06-23 17:38:20 -07006671status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6672{
Eric Laurentdf9b81c2010-07-02 08:12:41 -07006673 Mutex::Autolock _l(mLock);
Eric Laurent53334cd2010-06-23 17:38:20 -07006674 status_t status = NO_ERROR;
6675 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Eric Laurent53334cd2010-06-23 17:38:20 -07006676 status_t cmdStatus;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006677 uint32_t size = sizeof(status_t);
6678 status = (*mEffectInterface)->command(mEffectInterface,
6679 EFFECT_CMD_SET_AUDIO_MODE,
6680 sizeof(int),
Eric Laurent0fb66c22011-05-17 19:16:02 -07006681 &mode,
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006682 &size,
6683 &cmdStatus);
Eric Laurent53334cd2010-06-23 17:38:20 -07006684 if (status == NO_ERROR) {
6685 status = cmdStatus;
6686 }
6687 }
6688 return status;
6689}
6690
Eric Laurentf82fccd2011-07-27 19:49:51 -07006691void AudioFlinger::EffectModule::setSuspended(bool suspended)
6692{
6693 Mutex::Autolock _l(mLock);
6694 mSuspended = suspended;
6695}
6696bool AudioFlinger::EffectModule::suspended()
6697{
6698 Mutex::Autolock _l(mLock);
6699 return mSuspended;
6700}
6701
Eric Laurent65b65452010-06-01 23:49:17 -07006702status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6703{
6704 const size_t SIZE = 256;
6705 char buffer[SIZE];
6706 String8 result;
6707
6708 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6709 result.append(buffer);
6710
6711 bool locked = tryLock(mLock);
6712 // failed to lock - AudioFlinger is probably deadlocked
6713 if (!locked) {
6714 result.append("\t\tCould not lock Fx mutex:\n");
6715 }
6716
6717 result.append("\t\tSession Status State Engine:\n");
6718 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6719 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6720 result.append(buffer);
6721
6722 result.append("\t\tDescriptor:\n");
6723 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6724 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6725 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6726 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6727 result.append(buffer);
6728 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6729 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6730 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6731 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6732 result.append(buffer);
Eric Laurent0fb66c22011-05-17 19:16:02 -07006733 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Eric Laurent65b65452010-06-01 23:49:17 -07006734 mDescriptor.apiVersion,
6735 mDescriptor.flags);
6736 result.append(buffer);
6737 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6738 mDescriptor.name);
6739 result.append(buffer);
6740 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6741 mDescriptor.implementor);
6742 result.append(buffer);
6743
6744 result.append("\t\t- Input configuration:\n");
6745 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6746 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6747 (uint32_t)mConfig.inputCfg.buffer.raw,
6748 mConfig.inputCfg.buffer.frameCount,
6749 mConfig.inputCfg.samplingRate,
6750 mConfig.inputCfg.channels,
6751 mConfig.inputCfg.format);
6752 result.append(buffer);
6753
6754 result.append("\t\t- Output 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.outputCfg.buffer.raw,
6758 mConfig.outputCfg.buffer.frameCount,
6759 mConfig.outputCfg.samplingRate,
6760 mConfig.outputCfg.channels,
6761 mConfig.outputCfg.format);
6762 result.append(buffer);
6763
6764 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6765 result.append(buffer);
6766 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6767 for (size_t i = 0; i < mHandles.size(); ++i) {
6768 sp<EffectHandle> handle = mHandles[i].promote();
6769 if (handle != 0) {
6770 handle->dump(buffer, SIZE);
6771 result.append(buffer);
6772 }
6773 }
6774
6775 result.append("\n");
6776
6777 write(fd, result.string(), result.length());
6778
6779 if (locked) {
6780 mLock.unlock();
6781 }
6782
6783 return NO_ERROR;
6784}
6785
6786// ----------------------------------------------------------------------------
6787// EffectHandle implementation
6788// ----------------------------------------------------------------------------
6789
6790#undef LOG_TAG
6791#define LOG_TAG "AudioFlinger::EffectHandle"
6792
6793AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6794 const sp<AudioFlinger::Client>& client,
6795 const sp<IEffectClient>& effectClient,
6796 int32_t priority)
6797 : BnEffect(),
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006798 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentf82fccd2011-07-27 19:49:51 -07006799 mPriority(priority), mHasControl(false), mEnabled(false)
Eric Laurent65b65452010-06-01 23:49:17 -07006800{
Steve Block71f2cf12011-10-20 11:56:00 +01006801 ALOGV("constructor %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006802
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006803 if (client == 0) {
6804 return;
6805 }
Eric Laurent65b65452010-06-01 23:49:17 -07006806 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6807 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6808 if (mCblkMemory != 0) {
6809 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6810
6811 if (mCblk) {
6812 new(mCblk) effect_param_cblk_t();
6813 mBuffer = (uint8_t *)mCblk + bufOffset;
6814 }
6815 } else {
6816 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6817 return;
6818 }
6819}
6820
6821AudioFlinger::EffectHandle::~EffectHandle()
6822{
Steve Block71f2cf12011-10-20 11:56:00 +01006823 ALOGV("Destructor %p", this);
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006824 disconnect(false);
Steve Block71f2cf12011-10-20 11:56:00 +01006825 ALOGV("Destructor DONE %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006826}
6827
6828status_t AudioFlinger::EffectHandle::enable()
6829{
Steve Block71f2cf12011-10-20 11:56:00 +01006830 ALOGV("enable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006831 if (!mHasControl) return INVALID_OPERATION;
6832 if (mEffect == 0) return DEAD_OBJECT;
6833
Eric Laurent6752ec82011-08-10 10:37:50 -07006834 if (mEnabled) {
6835 return NO_ERROR;
6836 }
6837
Eric Laurentf82fccd2011-07-27 19:49:51 -07006838 mEnabled = true;
6839
6840 sp<ThreadBase> thread = mEffect->thread().promote();
6841 if (thread != 0) {
6842 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6843 }
6844
6845 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6846 if (mEffect->suspended()) {
6847 return NO_ERROR;
6848 }
6849
Eric Laurent6752ec82011-08-10 10:37:50 -07006850 status_t status = mEffect->setEnabled(true);
6851 if (status != NO_ERROR) {
6852 if (thread != 0) {
6853 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6854 }
6855 mEnabled = false;
6856 }
6857 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006858}
6859
6860status_t AudioFlinger::EffectHandle::disable()
6861{
Steve Block71f2cf12011-10-20 11:56:00 +01006862 ALOGV("disable %p", this);
Eric Laurent65b65452010-06-01 23:49:17 -07006863 if (!mHasControl) return INVALID_OPERATION;
Eric Laurentf82fccd2011-07-27 19:49:51 -07006864 if (mEffect == 0) return DEAD_OBJECT;
Eric Laurent65b65452010-06-01 23:49:17 -07006865
Eric Laurent6752ec82011-08-10 10:37:50 -07006866 if (!mEnabled) {
6867 return NO_ERROR;
6868 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006869 mEnabled = false;
6870
6871 if (mEffect->suspended()) {
6872 return NO_ERROR;
6873 }
6874
6875 status_t status = mEffect->setEnabled(false);
6876
6877 sp<ThreadBase> thread = mEffect->thread().promote();
6878 if (thread != 0) {
6879 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6880 }
6881
6882 return status;
Eric Laurent65b65452010-06-01 23:49:17 -07006883}
6884
6885void AudioFlinger::EffectHandle::disconnect()
6886{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006887 disconnect(true);
6888}
6889
6890void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6891{
Steve Block71f2cf12011-10-20 11:56:00 +01006892 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Eric Laurent65b65452010-06-01 23:49:17 -07006893 if (mEffect == 0) {
6894 return;
6895 }
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006896 mEffect->disconnect(this, unpiniflast);
Eric Laurentf82fccd2011-07-27 19:49:51 -07006897
Eric Laurent7fa1cee2011-10-19 11:44:54 -07006898 if (mHasControl && mEnabled) {
Eric Laurent6752ec82011-08-10 10:37:50 -07006899 sp<ThreadBase> thread = mEffect->thread().promote();
6900 if (thread != 0) {
6901 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6902 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07006903 }
6904
Eric Laurent65b65452010-06-01 23:49:17 -07006905 // release sp on module => module destructor can be called now
6906 mEffect.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07006907 if (mClient != 0) {
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006908 if (mCblk) {
6909 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6910 }
6911 mCblkMemory.clear(); // and free the shared memory
Eric Laurent65b65452010-06-01 23:49:17 -07006912 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6913 mClient.clear();
6914 }
6915}
6916
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006917status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6918 uint32_t cmdSize,
6919 void *pCmdData,
6920 uint32_t *replySize,
6921 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07006922{
Steve Block71f2cf12011-10-20 11:56:00 +01006923// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006924// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Eric Laurent65b65452010-06-01 23:49:17 -07006925
6926 // only get parameter command is permitted for applications not controlling the effect
6927 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6928 return INVALID_OPERATION;
6929 }
6930 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissenc74b93f2011-08-02 13:33:41 -07006931 if (mClient == 0) return INVALID_OPERATION;
Eric Laurent65b65452010-06-01 23:49:17 -07006932
6933 // handle commands that are not forwarded transparently to effect engine
6934 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6935 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6936 // no risk to block the whole media server process or mixer threads is we are stuck here
6937 Mutex::Autolock _l(mCblk->lock);
6938 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6939 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6940 mCblk->serverIndex = 0;
6941 mCblk->clientIndex = 0;
6942 return BAD_VALUE;
6943 }
6944 status_t status = NO_ERROR;
6945 while (mCblk->serverIndex < mCblk->clientIndex) {
6946 int reply;
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006947 uint32_t rsize = sizeof(int);
Eric Laurent65b65452010-06-01 23:49:17 -07006948 int *p = (int *)(mBuffer + mCblk->serverIndex);
6949 int size = *p++;
Eric Laurent53334cd2010-06-23 17:38:20 -07006950 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6951 LOGW("command(): invalid parameter block size");
6952 break;
6953 }
Eric Laurent65b65452010-06-01 23:49:17 -07006954 effect_param_t *param = (effect_param_t *)p;
Eric Laurent53334cd2010-06-23 17:38:20 -07006955 if (param->psize == 0 || param->vsize == 0) {
6956 LOGW("command(): null parameter or value size");
6957 mCblk->serverIndex += size;
6958 continue;
6959 }
Eric Laurenta4c72ac2010-07-28 05:40:18 -07006960 uint32_t psize = sizeof(effect_param_t) +
6961 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6962 param->vsize;
6963 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6964 psize,
6965 p,
6966 &rsize,
6967 &reply);
Eric Laurente65280c2010-09-02 11:56:55 -07006968 // stop at first error encountered
6969 if (ret != NO_ERROR) {
Eric Laurent65b65452010-06-01 23:49:17 -07006970 status = ret;
Eric Laurente65280c2010-09-02 11:56:55 -07006971 *(int *)pReplyData = reply;
6972 break;
6973 } else if (reply != NO_ERROR) {
6974 *(int *)pReplyData = reply;
6975 break;
Eric Laurent65b65452010-06-01 23:49:17 -07006976 }
6977 mCblk->serverIndex += size;
6978 }
6979 mCblk->serverIndex = 0;
6980 mCblk->clientIndex = 0;
6981 return status;
6982 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006983 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006984 return enable();
6985 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurente65280c2010-09-02 11:56:55 -07006986 *(int *)pReplyData = NO_ERROR;
Eric Laurent65b65452010-06-01 23:49:17 -07006987 return disable();
6988 }
6989
6990 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6991}
6992
6993sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6994 return mCblkMemory;
6995}
6996
Eric Laurentf82fccd2011-07-27 19:49:51 -07006997void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Eric Laurent65b65452010-06-01 23:49:17 -07006998{
Steve Block71f2cf12011-10-20 11:56:00 +01006999 ALOGV("setControl %p control %d", this, hasControl);
Eric Laurent65b65452010-06-01 23:49:17 -07007000
7001 mHasControl = hasControl;
Eric Laurentf82fccd2011-07-27 19:49:51 -07007002 mEnabled = enabled;
7003
Eric Laurent65b65452010-06-01 23:49:17 -07007004 if (signal && mEffectClient != 0) {
7005 mEffectClient->controlStatusChanged(hasControl);
7006 }
7007}
7008
Eric Laurenta4c72ac2010-07-28 05:40:18 -07007009void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7010 uint32_t cmdSize,
7011 void *pCmdData,
7012 uint32_t replySize,
7013 void *pReplyData)
Eric Laurent65b65452010-06-01 23:49:17 -07007014{
7015 if (mEffectClient != 0) {
7016 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7017 }
7018}
7019
7020
7021
7022void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7023{
7024 if (mEffectClient != 0) {
7025 mEffectClient->enableStatusChanged(enabled);
7026 }
7027}
7028
7029status_t AudioFlinger::EffectHandle::onTransact(
7030 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7031{
7032 return BnEffect::onTransact(code, data, reply, flags);
7033}
7034
7035
7036void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7037{
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007038 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Eric Laurent65b65452010-06-01 23:49:17 -07007039
7040 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7041 (mClient == NULL) ? getpid() : mClient->pid(),
7042 mPriority,
7043 mHasControl,
7044 !locked,
Marco Nelissenc74b93f2011-08-02 13:33:41 -07007045 mCblk ? mCblk->clientIndex : 0,
7046 mCblk ? mCblk->serverIndex : 0
Eric Laurent65b65452010-06-01 23:49:17 -07007047 );
7048
7049 if (locked) {
7050 mCblk->lock.unlock();
7051 }
7052}
7053
7054#undef LOG_TAG
7055#define LOG_TAG "AudioFlinger::EffectChain"
7056
7057AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7058 int sessionId)
Eric Laurentf9c361d2011-11-11 15:42:52 -08007059 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurent90681d62011-05-09 12:09:06 -07007060 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7061 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurent65b65452010-06-01 23:49:17 -07007062{
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007063 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007064 sp<ThreadBase> thread = mThread.promote();
7065 if (thread == 0) {
7066 return;
7067 }
7068 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7069 thread->frameCount();
Eric Laurent65b65452010-06-01 23:49:17 -07007070}
7071
7072AudioFlinger::EffectChain::~EffectChain()
7073{
7074 if (mOwnInBuffer) {
7075 delete mInBuffer;
7076 }
7077
7078}
7079
Eric Laurentf82fccd2011-07-27 19:49:51 -07007080// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007081sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Eric Laurent65b65452010-06-01 23:49:17 -07007082{
7083 sp<EffectModule> effect;
7084 size_t size = mEffects.size();
7085
7086 for (size_t i = 0; i < size; i++) {
7087 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7088 effect = mEffects[i];
7089 break;
7090 }
7091 }
7092 return effect;
7093}
7094
Eric Laurentf82fccd2011-07-27 19:49:51 -07007095// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurent76c40f72010-07-15 12:50:15 -07007096sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Eric Laurent65b65452010-06-01 23:49:17 -07007097{
7098 sp<EffectModule> effect;
7099 size_t size = mEffects.size();
7100
7101 for (size_t i = 0; i < size; i++) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007102 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7103 if (id == 0 || mEffects[i]->id() == id) {
Eric Laurent65b65452010-06-01 23:49:17 -07007104 effect = mEffects[i];
7105 break;
7106 }
7107 }
7108 return effect;
7109}
7110
Eric Laurentf82fccd2011-07-27 19:49:51 -07007111// getEffectFromType_l() must be called with ThreadBase::mLock held
7112sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7113 const effect_uuid_t *type)
7114{
7115 sp<EffectModule> effect;
7116 size_t size = mEffects.size();
7117
7118 for (size_t i = 0; i < size; i++) {
7119 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7120 effect = mEffects[i];
7121 break;
7122 }
7123 }
7124 return effect;
7125}
7126
Eric Laurent65b65452010-06-01 23:49:17 -07007127// Must be called with EffectChain::mLock locked
7128void AudioFlinger::EffectChain::process_l()
7129{
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007130 sp<ThreadBase> thread = mThread.promote();
7131 if (thread == 0) {
7132 LOGW("process_l(): cannot promote mixer thread");
7133 return;
7134 }
Dima Zavin24fc2fb2011-04-19 22:30:36 -07007135 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7136 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentf9c361d2011-11-11 15:42:52 -08007137 // always process effects unless no more tracks are on the session and the effect tail
7138 // has been rendered
7139 bool doProcess = true;
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007140 if (!isGlobalSession) {
Eric Laurentf9c361d2011-11-11 15:42:52 -08007141 bool tracksOnSession = (trackCnt() != 0);
Eric Laurent90681d62011-05-09 12:09:06 -07007142
Eric Laurentf9c361d2011-11-11 15:42:52 -08007143 if (!tracksOnSession && mTailBufferCount == 0) {
7144 doProcess = false;
7145 }
7146
7147 if (activeTrackCnt() == 0) {
7148 // if no track is active and the effect tail has not been rendered,
7149 // the input buffer must be cleared here as the mixer process will not do it
7150 if (tracksOnSession || mTailBufferCount > 0) {
7151 size_t numSamples = thread->frameCount() * thread->channelCount();
7152 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7153 if (mTailBufferCount > 0) {
7154 mTailBufferCount--;
7155 }
7156 }
7157 }
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007158 }
7159
Eric Laurent65b65452010-06-01 23:49:17 -07007160 size_t size = mEffects.size();
Eric Laurentf9c361d2011-11-11 15:42:52 -08007161 if (doProcess) {
Eric Laurent4fd3ecc2010-09-28 14:09:57 -07007162 for (size_t i = 0; i < size; i++) {
7163 mEffects[i]->process();
7164 }
Eric Laurent65b65452010-06-01 23:49:17 -07007165 }
Eric Laurent7d850f22010-07-09 13:34:17 -07007166 for (size_t i = 0; i < size; i++) {
7167 mEffects[i]->updateState();
7168 }
Eric Laurent65b65452010-06-01 23:49:17 -07007169}
7170
Eric Laurent76c40f72010-07-15 12:50:15 -07007171// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007172status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007173{
7174 effect_descriptor_t desc = effect->desc();
7175 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7176
7177 Mutex::Autolock _l(mLock);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007178 effect->setChain(this);
7179 sp<ThreadBase> thread = mThread.promote();
7180 if (thread == 0) {
7181 return NO_INIT;
7182 }
7183 effect->setThread(thread);
Eric Laurent65b65452010-06-01 23:49:17 -07007184
7185 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7186 // Auxiliary effects are inserted at the beginning of mEffects vector as
7187 // they are processed first and accumulated in chain input buffer
7188 mEffects.insertAt(effect, 0);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07007189
Eric Laurent65b65452010-06-01 23:49:17 -07007190 // the input buffer for auxiliary effect contains mono samples in
7191 // 32 bit format. This is to avoid saturation in AudoMixer
7192 // accumulation stage. Saturation is done in EffectModule::process() before
7193 // calling the process in effect engine
7194 size_t numSamples = thread->frameCount();
7195 int32_t *buffer = new int32_t[numSamples];
7196 memset(buffer, 0, numSamples * sizeof(int32_t));
7197 effect->setInBuffer((int16_t *)buffer);
7198 // auxiliary effects output samples to chain input buffer for further processing
7199 // by insert effects
7200 effect->setOutBuffer(mInBuffer);
7201 } else {
7202 // Insert effects are inserted at the end of mEffects vector as they are processed
7203 // after track and auxiliary effects.
Eric Laurent53334cd2010-06-23 17:38:20 -07007204 // Insert effect order as a function of indicated preference:
7205 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7206 // another effect is present
7207 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7208 // last effect claiming first position
7209 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7210 // first effect claiming last position
Eric Laurent65b65452010-06-01 23:49:17 -07007211 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
Eric Laurent53334cd2010-06-23 17:38:20 -07007212 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7213 // already present
Eric Laurent65b65452010-06-01 23:49:17 -07007214
7215 int size = (int)mEffects.size();
7216 int idx_insert = size;
7217 int idx_insert_first = -1;
7218 int idx_insert_last = -1;
7219
7220 for (int i = 0; i < size; i++) {
7221 effect_descriptor_t d = mEffects[i]->desc();
7222 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7223 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7224 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7225 // check invalid effect chaining combinations
7226 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
Eric Laurent53334cd2010-06-23 17:38:20 -07007227 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007228 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Eric Laurent65b65452010-06-01 23:49:17 -07007229 return INVALID_OPERATION;
7230 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007231 // remember position of first insert effect and by default
7232 // select this as insert position for new effect
Eric Laurent65b65452010-06-01 23:49:17 -07007233 if (idx_insert == size) {
7234 idx_insert = i;
7235 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007236 // remember position of last insert effect claiming
7237 // first position
Eric Laurent65b65452010-06-01 23:49:17 -07007238 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7239 idx_insert_first = i;
7240 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007241 // remember position of first insert effect claiming
7242 // last position
7243 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7244 idx_insert_last == -1) {
Eric Laurent65b65452010-06-01 23:49:17 -07007245 idx_insert_last = i;
7246 }
7247 }
7248 }
7249
Eric Laurent53334cd2010-06-23 17:38:20 -07007250 // modify idx_insert from first position if needed
7251 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7252 if (idx_insert_last != -1) {
7253 idx_insert = idx_insert_last;
7254 } else {
7255 idx_insert = size;
7256 }
7257 } else {
7258 if (idx_insert_first != -1) {
7259 idx_insert = idx_insert_first + 1;
7260 }
Eric Laurent65b65452010-06-01 23:49:17 -07007261 }
7262
7263 // always read samples from chain input buffer
7264 effect->setInBuffer(mInBuffer);
7265
7266 // if last effect in the chain, output samples to chain
7267 // output buffer, otherwise to chain input buffer
7268 if (idx_insert == size) {
7269 if (idx_insert != 0) {
7270 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7271 mEffects[idx_insert-1]->configure();
7272 }
7273 effect->setOutBuffer(mOutBuffer);
7274 } else {
7275 effect->setOutBuffer(mInBuffer);
7276 }
Eric Laurent53334cd2010-06-23 17:38:20 -07007277 mEffects.insertAt(effect, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007278
Steve Block71f2cf12011-10-20 11:56:00 +01007279 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Eric Laurent65b65452010-06-01 23:49:17 -07007280 }
7281 effect->configure();
7282 return NO_ERROR;
7283}
7284
Eric Laurent76c40f72010-07-15 12:50:15 -07007285// removeEffect_l() must be called with PlaybackThread::mLock held
7286size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Eric Laurent65b65452010-06-01 23:49:17 -07007287{
7288 Mutex::Autolock _l(mLock);
Eric Laurent65b65452010-06-01 23:49:17 -07007289 int size = (int)mEffects.size();
7290 int i;
7291 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7292
7293 for (i = 0; i < size; i++) {
7294 if (effect == mEffects[i]) {
Eric Laurent21b5c472011-07-26 20:54:46 -07007295 // calling stop here will remove pre-processing effect from the audio HAL.
7296 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7297 // the middle of a read from audio HAL
Eric Laurent6fccbd02011-10-05 17:42:25 -07007298 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7299 mEffects[i]->state() == EffectModule::STOPPING) {
7300 mEffects[i]->stop();
7301 }
Eric Laurent65b65452010-06-01 23:49:17 -07007302 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7303 delete[] effect->inBuffer();
7304 } else {
7305 if (i == size - 1 && i != 0) {
7306 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7307 mEffects[i - 1]->configure();
7308 }
7309 }
7310 mEffects.removeAt(i);
Steve Block71f2cf12011-10-20 11:56:00 +01007311 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Eric Laurent65b65452010-06-01 23:49:17 -07007312 break;
7313 }
7314 }
Eric Laurent65b65452010-06-01 23:49:17 -07007315
7316 return mEffects.size();
7317}
7318
Eric Laurent76c40f72010-07-15 12:50:15 -07007319// setDevice_l() must be called with PlaybackThread::mLock held
7320void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Eric Laurent65b65452010-06-01 23:49:17 -07007321{
7322 size_t size = mEffects.size();
7323 for (size_t i = 0; i < size; i++) {
7324 mEffects[i]->setDevice(device);
7325 }
7326}
7327
Eric Laurent76c40f72010-07-15 12:50:15 -07007328// setMode_l() must be called with PlaybackThread::mLock held
7329void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Eric Laurent53334cd2010-06-23 17:38:20 -07007330{
7331 size_t size = mEffects.size();
7332 for (size_t i = 0; i < size; i++) {
7333 mEffects[i]->setMode(mode);
7334 }
7335}
7336
Eric Laurent76c40f72010-07-15 12:50:15 -07007337// setVolume_l() must be called with PlaybackThread::mLock held
7338bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Eric Laurent65b65452010-06-01 23:49:17 -07007339{
7340 uint32_t newLeft = *left;
7341 uint32_t newRight = *right;
7342 bool hasControl = false;
Eric Laurent76c40f72010-07-15 12:50:15 -07007343 int ctrlIdx = -1;
7344 size_t size = mEffects.size();
Eric Laurent65b65452010-06-01 23:49:17 -07007345
Eric Laurent76c40f72010-07-15 12:50:15 -07007346 // first update volume controller
7347 for (size_t i = size; i > 0; i--) {
Eric Laurenta92ebfa2010-08-31 13:50:07 -07007348 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurent76c40f72010-07-15 12:50:15 -07007349 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7350 ctrlIdx = i - 1;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007351 hasControl = true;
Eric Laurent76c40f72010-07-15 12:50:15 -07007352 break;
7353 }
7354 }
7355
7356 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurent0d7e0482010-07-19 06:24:46 -07007357 if (hasControl) {
7358 *left = mNewLeftVolume;
7359 *right = mNewRightVolume;
7360 }
7361 return hasControl;
Eric Laurent76c40f72010-07-15 12:50:15 -07007362 }
7363
7364 mVolumeCtrlIdx = ctrlIdx;
Eric Laurent0d7e0482010-07-19 06:24:46 -07007365 mLeftVolume = newLeft;
7366 mRightVolume = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007367
7368 // second get volume update from volume controller
7369 if (ctrlIdx >= 0) {
7370 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurent0d7e0482010-07-19 06:24:46 -07007371 mNewLeftVolume = newLeft;
7372 mNewRightVolume = newRight;
Eric Laurent65b65452010-06-01 23:49:17 -07007373 }
7374 // then indicate volume to all other effects in chain.
7375 // Pass altered volume to effects before volume controller
7376 // and requested volume to effects after controller
7377 uint32_t lVol = newLeft;
7378 uint32_t rVol = newRight;
Eric Laurent76c40f72010-07-15 12:50:15 -07007379
Eric Laurent65b65452010-06-01 23:49:17 -07007380 for (size_t i = 0; i < size; i++) {
Eric Laurent76c40f72010-07-15 12:50:15 -07007381 if ((int)i == ctrlIdx) continue;
7382 // this also works for ctrlIdx == -1 when there is no volume controller
7383 if ((int)i > ctrlIdx) {
Eric Laurent65b65452010-06-01 23:49:17 -07007384 lVol = *left;
7385 rVol = *right;
7386 }
7387 mEffects[i]->setVolume(&lVol, &rVol, false);
7388 }
7389 *left = newLeft;
7390 *right = newRight;
7391
7392 return hasControl;
7393}
7394
Eric Laurent65b65452010-06-01 23:49:17 -07007395status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7396{
7397 const size_t SIZE = 256;
7398 char buffer[SIZE];
7399 String8 result;
7400
7401 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7402 result.append(buffer);
7403
7404 bool locked = tryLock(mLock);
7405 // failed to lock - AudioFlinger is probably deadlocked
7406 if (!locked) {
7407 result.append("\tCould not lock mutex:\n");
7408 }
7409
Eric Laurent76c40f72010-07-15 12:50:15 -07007410 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7411 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Eric Laurent65b65452010-06-01 23:49:17 -07007412 mEffects.size(),
7413 (uint32_t)mInBuffer,
7414 (uint32_t)mOutBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07007415 mActiveTrackCnt);
7416 result.append(buffer);
7417 write(fd, result.string(), result.size());
7418
7419 for (size_t i = 0; i < mEffects.size(); ++i) {
7420 sp<EffectModule> effect = mEffects[i];
7421 if (effect != 0) {
7422 effect->dump(fd, args);
7423 }
7424 }
7425
7426 if (locked) {
7427 mLock.unlock();
7428 }
7429
7430 return NO_ERROR;
7431}
7432
Eric Laurentf82fccd2011-07-27 19:49:51 -07007433// must be called with ThreadBase::mLock held
7434void AudioFlinger::EffectChain::setEffectSuspended_l(
7435 const effect_uuid_t *type, bool suspend)
7436{
7437 sp<SuspendedEffectDesc> desc;
7438 // use effect type UUID timelow as key as there is no real risk of identical
7439 // timeLow fields among effect type UUIDs.
7440 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7441 if (suspend) {
7442 if (index >= 0) {
7443 desc = mSuspendedEffects.valueAt(index);
7444 } else {
7445 desc = new SuspendedEffectDesc();
7446 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7447 mSuspendedEffects.add(type->timeLow, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007448 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurentf82fccd2011-07-27 19:49:51 -07007449 }
7450 if (desc->mRefCount++ == 0) {
7451 sp<EffectModule> effect = getEffectIfEnabled(type);
7452 if (effect != 0) {
7453 desc->mEffect = effect;
7454 effect->setSuspended(true);
7455 effect->setEnabled(false);
7456 }
7457 }
7458 } else {
7459 if (index < 0) {
7460 return;
7461 }
7462 desc = mSuspendedEffects.valueAt(index);
7463 if (desc->mRefCount <= 0) {
7464 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7465 desc->mRefCount = 1;
7466 }
7467 if (--desc->mRefCount == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01007468 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007469 if (desc->mEffect != 0) {
7470 sp<EffectModule> effect = desc->mEffect.promote();
7471 if (effect != 0) {
7472 effect->setSuspended(false);
7473 sp<EffectHandle> handle = effect->controlHandle();
7474 if (handle != 0) {
7475 effect->setEnabled(handle->enabled());
7476 }
7477 }
7478 desc->mEffect.clear();
7479 }
7480 mSuspendedEffects.removeItemsAt(index);
7481 }
7482 }
7483}
7484
7485// must be called with ThreadBase::mLock held
7486void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7487{
7488 sp<SuspendedEffectDesc> desc;
7489
7490 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7491 if (suspend) {
7492 if (index >= 0) {
7493 desc = mSuspendedEffects.valueAt(index);
7494 } else {
7495 desc = new SuspendedEffectDesc();
7496 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block71f2cf12011-10-20 11:56:00 +01007497 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurentf82fccd2011-07-27 19:49:51 -07007498 }
7499 if (desc->mRefCount++ == 0) {
7500 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7501 for (size_t i = 0; i < effects.size(); i++) {
7502 setEffectSuspended_l(&effects[i]->desc().type, true);
7503 }
7504 }
7505 } else {
7506 if (index < 0) {
7507 return;
7508 }
7509 desc = mSuspendedEffects.valueAt(index);
7510 if (desc->mRefCount <= 0) {
7511 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7512 desc->mRefCount = 1;
7513 }
7514 if (--desc->mRefCount == 0) {
7515 Vector<const effect_uuid_t *> types;
7516 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7517 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7518 continue;
7519 }
7520 types.add(&mSuspendedEffects.valueAt(i)->mType);
7521 }
7522 for (size_t i = 0; i < types.size(); i++) {
7523 setEffectSuspended_l(types[i], false);
7524 }
Steve Block71f2cf12011-10-20 11:56:00 +01007525 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurentf82fccd2011-07-27 19:49:51 -07007526 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7527 }
7528 }
7529}
7530
Eric Laurent5e7acae2011-09-23 08:40:41 -07007531
7532// The volume effect is used for automated tests only
7533#ifndef OPENSL_ES_H_
7534static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7535 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7536const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7537#endif //OPENSL_ES_H_
7538
Eric Laurent6752ec82011-08-10 10:37:50 -07007539bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7540{
7541 // auxiliary effects and visualizer are never suspended on output mix
7542 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7543 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent5e7acae2011-09-23 08:40:41 -07007544 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7545 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007546 return false;
7547 }
7548 return true;
7549}
7550
Eric Laurentf82fccd2011-07-27 19:49:51 -07007551Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7552{
7553 Vector< sp<EffectModule> > effects;
7554 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent6752ec82011-08-10 10:37:50 -07007555 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurentf82fccd2011-07-27 19:49:51 -07007556 continue;
7557 }
7558 effects.add(mEffects[i]);
7559 }
7560 return effects;
7561}
7562
7563sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7564 const effect_uuid_t *type)
7565{
7566 sp<EffectModule> effect;
7567 effect = getEffectFromType_l(type);
7568 if (effect != 0 && !effect->isEnabled()) {
7569 effect.clear();
7570 }
7571 return effect;
7572}
7573
7574void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7575 bool enabled)
7576{
7577 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7578 if (enabled) {
7579 if (index < 0) {
7580 // if the effect is not suspend check if all effects are suspended
7581 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7582 if (index < 0) {
7583 return;
7584 }
Eric Laurent6752ec82011-08-10 10:37:50 -07007585 if (!isEffectEligibleForSuspend(effect->desc())) {
7586 return;
7587 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007588 setEffectSuspended_l(&effect->desc().type, enabled);
7589 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent6752ec82011-08-10 10:37:50 -07007590 if (index < 0) {
7591 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7592 return;
7593 }
Eric Laurentf82fccd2011-07-27 19:49:51 -07007594 }
Steve Block71f2cf12011-10-20 11:56:00 +01007595 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007596 effect->desc().type.timeLow);
7597 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7598 // if effect is requested to suspended but was not yet enabled, supend it now.
7599 if (desc->mEffect == 0) {
7600 desc->mEffect = effect;
7601 effect->setEnabled(false);
7602 effect->setSuspended(true);
7603 }
7604 } else {
7605 if (index < 0) {
7606 return;
7607 }
Steve Block71f2cf12011-10-20 11:56:00 +01007608 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurentf82fccd2011-07-27 19:49:51 -07007609 effect->desc().type.timeLow);
7610 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7611 desc->mEffect.clear();
7612 effect->setSuspended(false);
7613 }
7614}
7615
Eric Laurent65b65452010-06-01 23:49:17 -07007616#undef LOG_TAG
7617#define LOG_TAG "AudioFlinger"
7618
Eric Laurenta553c252009-07-17 12:17:14 -07007619// ----------------------------------------------------------------------------
7620
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007621status_t AudioFlinger::onTransact(
7622 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7623{
7624 return BnAudioFlinger::onTransact(code, data, reply, flags);
7625}
7626
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07007627}; // namespace android