blob: bbc919669cbc729df1cea485be01a9e5f352a97e [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -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"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Gloria Wang9ee159b2011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten3b21c502011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070061// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
62
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Eric Laurentde070132010-07-13 04:45:46 -070065
Mathias Agopian65ab4712010-07-14 17:59:35 -070066namespace android {
67
Glenn Kastenec1d6b52011-12-12 09:04:45 -080068static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
69static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
72static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080073static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -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;
79// 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;
83
84static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080085static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Glenn Kasten7dede872011-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);
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Eric Laurent7c7f10b2011-06-17 21:29:58 -070090// RecordThread loop sleep time upon application overrun or audio HAL read error
91static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
Glenn Kasten7dede872011-12-13 11:04:14 -080093// maximum time to wait for setParameters to complete
94static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070095
Eric Laurent7cafbb32011-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
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102// ----------------------------------------------------------------------------
103
104static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block29357bc2012-01-06 19:20:56 +0000107 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109}
110
111static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
113 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block29357bc2012-01-06 19:20:56 +0000114 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116}
117
Gloria Wang9ee159b2011-02-24 14:51:45 -0800118// To collect the amplifier usage
119static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800120 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
121 if (service == NULL) {
122 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800123 return;
124 }
125
126 service->addBatteryData(params);
127}
128
Dima Zavin799a70e2011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800152static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
162 : BnAudioFlinger(),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800163 mPrimaryHardwareDev(NULL),
164 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
165 mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
166 mMode(AUDIO_MODE_INVALID),
Eric Laurentbee53372011-08-29 12:42:48 -0700167 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700169}
170
171void AudioFlinger::onFirstRef()
172{
Dima Zavin799a70e2011-04-18 16:57:27 -0700173 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700174
Eric Laurent93575202011-01-18 18:39:02 -0800175 Mutex::Autolock _l(mLock);
176
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700178
Dima Zavin799a70e2011-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 Zavinfce7a472011-04-19 22:30:36 -0700182
Dima Zavin799a70e2011-04-18 16:57:27 -0700183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184 if (rc)
185 continue;
186
Steve Blockdf64d152012-01-04 20:05:49 +0000187 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 mod->name, mod->id);
189 mAudioHwDevs.push(dev);
190
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800191 if (mPrimaryHardwareDev == NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700192 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000193 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700194 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 }
196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700197
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800198 if (mPrimaryHardwareDev == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000199 ALOGE("Primary audio interface not found");
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800200 // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
Dima Zavin799a70e2011-04-18 16:57:27 -0700201 }
202
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800203 // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
204 // primary HW dev is selected can change so these conditions might not always be equivalent.
205 // When that happens, re-visit all the code that assumes this.
206
207 AutoMutex lock(mHardwareLock);
208
Dima Zavin799a70e2011-04-18 16:57:27 -0700209 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
210 audio_hw_device_t *dev = mAudioHwDevs[i];
211
212 mHardwareStatus = AUDIO_HW_INIT;
213 rc = dev->init_check(dev);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800214 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700215 if (rc == 0) {
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800216 mMode = AUDIO_MODE_NORMAL; // assigned multiple times with same value
Dima Zavin799a70e2011-04-18 16:57:27 -0700217 mHardwareStatus = AUDIO_HW_SET_MODE;
218 dev->set_mode(dev, mMode);
219 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
220 dev->set_master_volume(dev, 1.0f);
221 mHardwareStatus = AUDIO_HW_IDLE;
222 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700224}
225
226AudioFlinger::~AudioFlinger()
227{
Dima Zavin799a70e2011-04-18 16:57:27 -0700228
Mathias Agopian65ab4712010-07-14 17:59:35 -0700229 while (!mRecordThreads.isEmpty()) {
230 // closeInput() will remove first entry from mRecordThreads
231 closeInput(mRecordThreads.keyAt(0));
232 }
233 while (!mPlaybackThreads.isEmpty()) {
234 // closeOutput() will remove first entry from mPlaybackThreads
235 closeOutput(mPlaybackThreads.keyAt(0));
236 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700237
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800238 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
239 // no mHardwareLock needed, as there are no other references to this
240 audio_hw_device_close(mAudioHwDevs[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241 }
242}
243
Dima Zavin799a70e2011-04-18 16:57:27 -0700244audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
245{
246 /* first matching HW device is returned */
247 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
248 audio_hw_device_t *dev = mAudioHwDevs[i];
249 if ((dev->get_supported_devices(dev) & devices) == devices)
250 return dev;
251 }
252 return NULL;
253}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700254
255status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
256{
257 const size_t SIZE = 256;
258 char buffer[SIZE];
259 String8 result;
260
261 result.append("Clients:\n");
262 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800263 sp<Client> client = mClients.valueAt(i).promote();
264 if (client != 0) {
265 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
266 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700267 }
268 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700269
270 result.append("Global session refs:\n");
271 result.append(" session pid cnt\n");
272 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
273 AudioSessionRef *r = mAudioSessionRefs[i];
274 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
275 result.append(buffer);
276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700277 write(fd, result.string(), result.size());
278 return NO_ERROR;
279}
280
281
282status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
283{
284 const size_t SIZE = 256;
285 char buffer[SIZE];
286 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800287 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700288
289 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
290 result.append(buffer);
291 write(fd, result.string(), result.size());
292 return NO_ERROR;
293}
294
295status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
296{
297 const size_t SIZE = 256;
298 char buffer[SIZE];
299 String8 result;
300 snprintf(buffer, SIZE, "Permission Denial: "
301 "can't dump AudioFlinger from pid=%d, uid=%d\n",
302 IPCThreadState::self()->getCallingPid(),
303 IPCThreadState::self()->getCallingUid());
304 result.append(buffer);
305 write(fd, result.string(), result.size());
306 return NO_ERROR;
307}
308
309static bool tryLock(Mutex& mutex)
310{
311 bool locked = false;
312 for (int i = 0; i < kDumpLockRetries; ++i) {
313 if (mutex.tryLock() == NO_ERROR) {
314 locked = true;
315 break;
316 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800317 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700318 }
319 return locked;
320}
321
322status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
323{
Glenn Kastenf1d45922012-01-13 15:54:24 -0800324 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325 dumpPermissionDenial(fd, args);
326 } else {
327 // get state of hardware lock
328 bool hardwareLocked = tryLock(mHardwareLock);
329 if (!hardwareLocked) {
330 String8 result(kHardwareLockedString);
331 write(fd, result.string(), result.size());
332 } else {
333 mHardwareLock.unlock();
334 }
335
336 bool locked = tryLock(mLock);
337
338 // failed to lock - AudioFlinger is probably deadlocked
339 if (!locked) {
340 String8 result(kDeadlockedString);
341 write(fd, result.string(), result.size());
342 }
343
344 dumpClients(fd, args);
345 dumpInternals(fd, args);
346
347 // dump playback threads
348 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
349 mPlaybackThreads.valueAt(i)->dump(fd, args);
350 }
351
352 // dump record threads
353 for (size_t i = 0; i < mRecordThreads.size(); i++) {
354 mRecordThreads.valueAt(i)->dump(fd, args);
355 }
356
Dima Zavin799a70e2011-04-18 16:57:27 -0700357 // dump all hardware devs
358 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
359 audio_hw_device_t *dev = mAudioHwDevs[i];
360 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700361 }
362 if (locked) mLock.unlock();
363 }
364 return NO_ERROR;
365}
366
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800367sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
368{
369 // If pid is already in the mClients wp<> map, then use that entry
370 // (for which promote() is always != 0), otherwise create a new entry and Client.
371 sp<Client> client = mClients.valueFor(pid).promote();
372 if (client == 0) {
373 client = new Client(this, pid);
374 mClients.add(pid, client);
375 }
376
377 return client;
378}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700379
380// IAudioFlinger interface
381
382
383sp<IAudioTrack> AudioFlinger::createTrack(
384 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800385 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700386 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800387 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700388 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700389 int frameCount,
390 uint32_t flags,
391 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800392 audio_io_handle_t output,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700393 int *sessionId,
394 status_t *status)
395{
396 sp<PlaybackThread::Track> track;
397 sp<TrackHandle> trackHandle;
398 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700399 status_t lStatus;
400 int lSessionId;
401
Glenn Kasten263709e2012-01-06 08:40:01 -0800402 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
403 // but if someone uses binder directly they could bypass that and cause us to crash
404 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000405 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406 lStatus = BAD_VALUE;
407 goto Exit;
408 }
409
410 {
411 Mutex::Autolock _l(mLock);
412 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700413 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700414 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000415 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700416 lStatus = BAD_VALUE;
417 goto Exit;
418 }
419
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800420 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421
Steve Block3856b092011-10-20 11:56:00 +0100422 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700423 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700424 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700425 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
426 if (mPlaybackThreads.keyAt(i) != output) {
427 // prevent same audio session on different output threads
428 uint32_t sessions = t->hasAudioSession(*sessionId);
429 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000430 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700431 lStatus = BAD_VALUE;
432 goto Exit;
433 }
434 // check if an effect with same session ID is waiting for a track to be created
435 if (sessions & PlaybackThread::EFFECT_SESSION) {
436 effectThread = t.get();
437 }
Eric Laurentde070132010-07-13 04:45:46 -0700438 }
439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 lSessionId = *sessionId;
441 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700442 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700443 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 if (sessionId != NULL) {
445 *sessionId = lSessionId;
446 }
447 }
Steve Block3856b092011-10-20 11:56:00 +0100448 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449
450 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700451 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700452
453 // move effect chain to this output thread if an effect on same session was waiting
454 // for a track to be created
455 if (lStatus == NO_ERROR && effectThread != NULL) {
456 Mutex::Autolock _dl(thread->mLock);
457 Mutex::Autolock _sl(effectThread->mLock);
458 moveEffectChain_l(lSessionId, effectThread, thread, true);
459 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460 }
461 if (lStatus == NO_ERROR) {
462 trackHandle = new TrackHandle(track);
463 } else {
464 // remove local strong reference to Client before deleting the Track so that the Client
465 // destructor is called by the TrackBase destructor with mLock held
466 client.clear();
467 track.clear();
468 }
469
470Exit:
471 if(status) {
472 *status = lStatus;
473 }
474 return trackHandle;
475}
476
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800477uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700478{
479 Mutex::Autolock _l(mLock);
480 PlaybackThread *thread = checkPlaybackThread_l(output);
481 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000482 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700483 return 0;
484 }
485 return thread->sampleRate();
486}
487
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800488int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700489{
490 Mutex::Autolock _l(mLock);
491 PlaybackThread *thread = checkPlaybackThread_l(output);
492 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000493 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700494 return 0;
495 }
496 return thread->channelCount();
497}
498
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800499audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500{
501 Mutex::Autolock _l(mLock);
502 PlaybackThread *thread = checkPlaybackThread_l(output);
503 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000504 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800505 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506 }
507 return thread->format();
508}
509
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800510size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700511{
512 Mutex::Autolock _l(mLock);
513 PlaybackThread *thread = checkPlaybackThread_l(output);
514 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000515 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700516 return 0;
517 }
518 return thread->frameCount();
519}
520
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800521uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700522{
523 Mutex::Autolock _l(mLock);
524 PlaybackThread *thread = checkPlaybackThread_l(output);
525 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000526 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700527 return 0;
528 }
529 return thread->latency();
530}
531
532status_t AudioFlinger::setMasterVolume(float value)
533{
Eric Laurenta1884f92011-08-23 08:25:03 -0700534 status_t ret = initCheck();
535 if (ret != NO_ERROR) {
536 return ret;
537 }
538
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539 // check calling permissions
540 if (!settingsAllowed()) {
541 return PERMISSION_DENIED;
542 }
543
544 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800545 { // scope for the lock
546 AutoMutex lock(mHardwareLock);
547 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700548 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800549 value = 1.0f;
550 }
551 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700552 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553
Eric Laurent93575202011-01-18 18:39:02 -0800554 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555 mMasterVolume = value;
556 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
557 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
558
559 return NO_ERROR;
560}
561
Glenn Kastenf78aee72012-01-04 11:00:47 -0800562status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563{
Eric Laurenta1884f92011-08-23 08:25:03 -0700564 status_t ret = initCheck();
565 if (ret != NO_ERROR) {
566 return ret;
567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568
569 // check calling permissions
570 if (!settingsAllowed()) {
571 return PERMISSION_DENIED;
572 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800573 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000574 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 return BAD_VALUE;
576 }
577
578 { // scope for the lock
579 AutoMutex lock(mHardwareLock);
580 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700581 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582 mHardwareStatus = AUDIO_HW_IDLE;
583 }
584
585 if (NO_ERROR == ret) {
586 Mutex::Autolock _l(mLock);
587 mMode = mode;
588 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
589 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700590 }
591
592 return ret;
593}
594
595status_t AudioFlinger::setMicMute(bool state)
596{
Eric Laurenta1884f92011-08-23 08:25:03 -0700597 status_t ret = initCheck();
598 if (ret != NO_ERROR) {
599 return ret;
600 }
601
Mathias Agopian65ab4712010-07-14 17:59:35 -0700602 // check calling permissions
603 if (!settingsAllowed()) {
604 return PERMISSION_DENIED;
605 }
606
607 AutoMutex lock(mHardwareLock);
608 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700609 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700610 mHardwareStatus = AUDIO_HW_IDLE;
611 return ret;
612}
613
614bool AudioFlinger::getMicMute() const
615{
Eric Laurenta1884f92011-08-23 08:25:03 -0700616 status_t ret = initCheck();
617 if (ret != NO_ERROR) {
618 return false;
619 }
620
Dima Zavinfce7a472011-04-19 22:30:36 -0700621 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800622 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700624 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 mHardwareStatus = AUDIO_HW_IDLE;
626 return state;
627}
628
629status_t AudioFlinger::setMasterMute(bool muted)
630{
631 // check calling permissions
632 if (!settingsAllowed()) {
633 return PERMISSION_DENIED;
634 }
635
Eric Laurent93575202011-01-18 18:39:02 -0800636 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637 mMasterMute = muted;
638 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
639 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
640
641 return NO_ERROR;
642}
643
644float AudioFlinger::masterVolume() const
645{
Glenn Kasten98067102011-12-13 11:47:54 -0800646 Mutex::Autolock _l(mLock);
647 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700648}
649
650bool AudioFlinger::masterMute() const
651{
Glenn Kasten98067102011-12-13 11:47:54 -0800652 Mutex::Autolock _l(mLock);
653 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654}
655
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800656status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
657 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658{
659 // check calling permissions
660 if (!settingsAllowed()) {
661 return PERMISSION_DENIED;
662 }
663
Glenn Kasten263709e2012-01-06 08:40:01 -0800664 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000665 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666 return BAD_VALUE;
667 }
668
669 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
678 mStreamTypes[stream].volume = value;
679
680 if (thread == NULL) {
681 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
682 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
683 }
684 } else {
685 thread->setStreamVolume(stream, value);
686 }
687
688 return NO_ERROR;
689}
690
Glenn Kastenfff6d712012-01-12 16:38:12 -0800691status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700692{
693 // check calling permissions
694 if (!settingsAllowed()) {
695 return PERMISSION_DENIED;
696 }
697
Glenn Kasten263709e2012-01-06 08:40:01 -0800698 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700699 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000700 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701 return BAD_VALUE;
702 }
703
Eric Laurent93575202011-01-18 18:39:02 -0800704 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 mStreamTypes[stream].mute = muted;
706 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
707 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
708
709 return NO_ERROR;
710}
711
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800712float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700713{
Glenn Kasten263709e2012-01-06 08:40:01 -0800714 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715 return 0.0f;
716 }
717
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
730 return volume;
731}
732
Glenn Kastenfff6d712012-01-12 16:38:12 -0800733bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734{
Glenn Kasten263709e2012-01-06 08:40:01 -0800735 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736 return true;
737 }
738
739 return mStreamTypes[stream].mute;
740}
741
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800742status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743{
744 status_t result;
745
Glenn Kasten23d82a92012-02-03 11:10:00 -0800746 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
748 // check calling permissions
749 if (!settingsAllowed()) {
750 return PERMISSION_DENIED;
751 }
752
Mathias Agopian65ab4712010-07-14 17:59:35 -0700753 // 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 Zavin799a70e2011-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 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-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 Laurentbee53372011-08-29 12:42:48 -0700769 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
770 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-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 Laurentbee53372011-08-29 12:42:48 -0700777 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-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 Laurentbee53372011-08-29 12:42:48 -0700786 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700787 }
788 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700789 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790 }
791
792 // 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);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800800 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700801 // 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 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 }
810 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800811 if (thread != 0) {
812 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 }
814 return BAD_VALUE;
815}
816
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800817String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800819// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
821
822 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700823 String8 out_s8;
824
Dima Zavin799a70e2011-04-18 16:57:27 -0700825 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
826 audio_hw_device_t *dev = mAudioHwDevs[i];
827 char *s = dev->get_parameters(dev, keys.string());
828 out_s8 += String8(s);
829 free(s);
830 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700831 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 }
833
834 Mutex::Autolock _l(mLock);
835
836 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
837 if (playbackThread != NULL) {
838 return playbackThread->getParameters(keys);
839 }
840 RecordThread *recordThread = checkRecordThread_l(ioHandle);
841 if (recordThread != NULL) {
842 return recordThread->getParameters(keys);
843 }
844 return String8("");
845}
846
Glenn Kastenf587ba52012-01-26 16:25:10 -0800847size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848{
Eric Laurenta1884f92011-08-23 08:25:03 -0700849 status_t ret = initCheck();
850 if (ret != NO_ERROR) {
851 return 0;
852 }
853
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800854 AutoMutex lock(mHardwareLock);
855 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
856 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
857 mHardwareStatus = AUDIO_HW_IDLE;
858 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700859}
860
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800861unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700862{
863 if (ioHandle == 0) {
864 return 0;
865 }
866
867 Mutex::Autolock _l(mLock);
868
869 RecordThread *recordThread = checkRecordThread_l(ioHandle);
870 if (recordThread != NULL) {
871 return recordThread->getInputFramesLost();
872 }
873 return 0;
874}
875
876status_t AudioFlinger::setVoiceVolume(float value)
877{
Eric Laurenta1884f92011-08-23 08:25:03 -0700878 status_t ret = initCheck();
879 if (ret != NO_ERROR) {
880 return ret;
881 }
882
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883 // check calling permissions
884 if (!settingsAllowed()) {
885 return PERMISSION_DENIED;
886 }
887
888 AutoMutex lock(mHardwareLock);
889 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700890 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 mHardwareStatus = AUDIO_HW_IDLE;
892
893 return ret;
894}
895
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800896status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
897 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700898{
899 status_t status;
900
901 Mutex::Autolock _l(mLock);
902
903 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
904 if (playbackThread != NULL) {
905 return playbackThread->getRenderPosition(halFrames, dspFrames);
906 }
907
908 return BAD_VALUE;
909}
910
911void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
912{
913
914 Mutex::Autolock _l(mLock);
915
Glenn Kastenbb001922012-02-03 11:10:26 -0800916 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917 if (mNotificationClients.indexOfKey(pid) < 0) {
918 sp<NotificationClient> notificationClient = new NotificationClient(this,
919 client,
920 pid);
Steve Block3856b092011-10-20 11:56:00 +0100921 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922
923 mNotificationClients.add(pid, notificationClient);
924
925 sp<IBinder> binder = client->asBinder();
926 binder->linkToDeath(notificationClient);
927
928 // the config change is always sent from playback or record threads to avoid deadlock
929 // with AudioSystem::gLock
930 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
931 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
932 }
933
934 for (size_t i = 0; i < mRecordThreads.size(); i++) {
935 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
936 }
937 }
938}
939
940void AudioFlinger::removeNotificationClient(pid_t pid)
941{
942 Mutex::Autolock _l(mLock);
943
944 int index = mNotificationClients.indexOfKey(pid);
945 if (index >= 0) {
946 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100947 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 mNotificationClients.removeItem(pid);
949 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700950
Steve Block3856b092011-10-20 11:56:00 +0100951 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700952 int num = mAudioSessionRefs.size();
953 bool removed = false;
954 for (int i = 0; i< num; i++) {
955 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100956 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700957 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100958 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700959 mAudioSessionRefs.removeAt(i);
960 delete ref;
961 removed = true;
962 i--;
963 num--;
964 }
965 }
966 if (removed) {
967 purgeStaleEffects_l();
968 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700969}
970
971// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800972void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700973{
974 size_t size = mNotificationClients.size();
975 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800976 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
977 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700978 }
979}
980
981// removeClient_l() must be called with AudioFlinger::mLock held
982void AudioFlinger::removeClient_l(pid_t pid)
983{
Steve Block3856b092011-10-20 11:56:00 +0100984 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700985 mClients.removeItem(pid);
986}
987
988
989// ----------------------------------------------------------------------------
990
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800991AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
992 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800994 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800995 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
996 // mChannelMask
997 mChannelCount(0),
998 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
999 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001000 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001001 mDevice(device),
1002 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001003{
1004}
1005
1006AudioFlinger::ThreadBase::~ThreadBase()
1007{
1008 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001009 // do not lock the mutex in destructor
1010 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001011 if (mPowerManager != 0) {
1012 sp<IBinder> binder = mPowerManager->asBinder();
1013 binder->unlinkToDeath(mDeathRecipient);
1014 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015}
1016
1017void AudioFlinger::ThreadBase::exit()
1018{
Steve Block3856b092011-10-20 11:56:00 +01001019 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001021 // This lock prevents the following race in thread (uniprocessor for illustration):
1022 // if (!exitPending()) {
1023 // // context switch from here to exit()
1024 // // exit() calls requestExit(), what exitPending() observes
1025 // // exit() calls signal(), which is dropped since no waiters
1026 // // context switch back from exit() to here
1027 // mWaitWorkCV.wait(...);
1028 // // now thread is hung
1029 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001030 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031 requestExit();
1032 mWaitWorkCV.signal();
1033 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001034 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1035 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001036 requestExitAndWait();
1037}
1038
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1040{
1041 status_t status;
1042
Steve Block3856b092011-10-20 11:56:00 +01001043 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001044 Mutex::Autolock _l(mLock);
1045
1046 mNewParameters.add(keyValuePairs);
1047 mWaitWorkCV.signal();
1048 // wait condition with timeout in case the thread loop has exited
1049 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001050 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051 status = mParamStatus;
1052 mWaitWorkCV.signal();
1053 } else {
1054 status = TIMED_OUT;
1055 }
1056 return status;
1057}
1058
1059void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1060{
1061 Mutex::Autolock _l(mLock);
1062 sendConfigEvent_l(event, param);
1063}
1064
1065// sendConfigEvent_l() must be called with ThreadBase::mLock held
1066void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1067{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001068 ConfigEvent configEvent;
1069 configEvent.mEvent = event;
1070 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001071 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001072 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 mWaitWorkCV.signal();
1074}
1075
1076void AudioFlinger::ThreadBase::processConfigEvents()
1077{
1078 mLock.lock();
1079 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001080 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001081 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082 mConfigEvents.removeAt(0);
1083 // release mLock before locking AudioFlinger mLock: lock order is always
1084 // AudioFlinger then ThreadBase to avoid cross deadlock
1085 mLock.unlock();
1086 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001087 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001089 mLock.lock();
1090 }
1091 mLock.unlock();
1092}
1093
1094status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1095{
1096 const size_t SIZE = 256;
1097 char buffer[SIZE];
1098 String8 result;
1099
1100 bool locked = tryLock(mLock);
1101 if (!locked) {
1102 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1103 write(fd, buffer, strlen(buffer));
1104 }
1105
1106 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1107 result.append(buffer);
1108 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1109 result.append(buffer);
1110 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1111 result.append(buffer);
1112 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1113 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001114 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1115 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1117 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001118 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119 result.append(buffer);
1120
1121 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1122 result.append(buffer);
1123 result.append(" Index Command");
1124 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1125 snprintf(buffer, SIZE, "\n %02d ", i);
1126 result.append(buffer);
1127 result.append(mNewParameters[i]);
1128 }
1129
1130 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1131 result.append(buffer);
1132 snprintf(buffer, SIZE, " Index event param\n");
1133 result.append(buffer);
1134 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001135 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136 result.append(buffer);
1137 }
1138 result.append("\n");
1139
1140 write(fd, result.string(), result.size());
1141
1142 if (locked) {
1143 mLock.unlock();
1144 }
1145 return NO_ERROR;
1146}
1147
Eric Laurent1d2bff02011-07-24 17:49:51 -07001148status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1149{
1150 const size_t SIZE = 256;
1151 char buffer[SIZE];
1152 String8 result;
1153
1154 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1155 write(fd, buffer, strlen(buffer));
1156
1157 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1158 sp<EffectChain> chain = mEffectChains[i];
1159 if (chain != 0) {
1160 chain->dump(fd, args);
1161 }
1162 }
1163 return NO_ERROR;
1164}
1165
Eric Laurentfeb0db62011-07-22 09:04:31 -07001166void AudioFlinger::ThreadBase::acquireWakeLock()
1167{
1168 Mutex::Autolock _l(mLock);
1169 acquireWakeLock_l();
1170}
1171
1172void AudioFlinger::ThreadBase::acquireWakeLock_l()
1173{
1174 if (mPowerManager == 0) {
1175 // use checkService() to avoid blocking if power service is not up yet
1176 sp<IBinder> binder =
1177 defaultServiceManager()->checkService(String16("power"));
1178 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001179 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001180 } else {
1181 mPowerManager = interface_cast<IPowerManager>(binder);
1182 binder->linkToDeath(mDeathRecipient);
1183 }
1184 }
1185 if (mPowerManager != 0) {
1186 sp<IBinder> binder = new BBinder();
1187 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1188 binder,
1189 String16(mName));
1190 if (status == NO_ERROR) {
1191 mWakeLockToken = binder;
1192 }
Steve Block3856b092011-10-20 11:56:00 +01001193 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001194 }
1195}
1196
1197void AudioFlinger::ThreadBase::releaseWakeLock()
1198{
1199 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001200 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001201}
1202
1203void AudioFlinger::ThreadBase::releaseWakeLock_l()
1204{
1205 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001206 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001207 if (mPowerManager != 0) {
1208 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1209 }
1210 mWakeLockToken.clear();
1211 }
1212}
1213
1214void AudioFlinger::ThreadBase::clearPowerManager()
1215{
1216 Mutex::Autolock _l(mLock);
1217 releaseWakeLock_l();
1218 mPowerManager.clear();
1219}
1220
1221void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1222{
1223 sp<ThreadBase> thread = mThread.promote();
1224 if (thread != 0) {
1225 thread->clearPowerManager();
1226 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001227 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001228}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001229
Eric Laurent59255e42011-07-27 19:49:51 -07001230void AudioFlinger::ThreadBase::setEffectSuspended(
1231 const effect_uuid_t *type, bool suspend, int sessionId)
1232{
1233 Mutex::Autolock _l(mLock);
1234 setEffectSuspended_l(type, suspend, sessionId);
1235}
1236
1237void AudioFlinger::ThreadBase::setEffectSuspended_l(
1238 const effect_uuid_t *type, bool suspend, int sessionId)
1239{
Glenn Kasten090f0192012-01-30 13:00:02 -08001240 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001241 if (chain != 0) {
1242 if (type != NULL) {
1243 chain->setEffectSuspended_l(type, suspend);
1244 } else {
1245 chain->setEffectSuspendedAll_l(suspend);
1246 }
1247 }
1248
1249 updateSuspendedSessions_l(type, suspend, sessionId);
1250}
1251
1252void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1253{
1254 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1255 if (index < 0) {
1256 return;
1257 }
1258
1259 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1260 mSuspendedSessions.editValueAt(index);
1261
1262 for (size_t i = 0; i < sessionEffects.size(); i++) {
1263 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1264 for (int j = 0; j < desc->mRefCount; j++) {
1265 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1266 chain->setEffectSuspendedAll_l(true);
1267 } else {
Steve Block3856b092011-10-20 11:56:00 +01001268 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001269 desc->mType.timeLow);
1270 chain->setEffectSuspended_l(&desc->mType, true);
1271 }
1272 }
1273 }
1274}
1275
Eric Laurent59255e42011-07-27 19:49:51 -07001276void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1277 bool suspend,
1278 int sessionId)
1279{
1280 int index = mSuspendedSessions.indexOfKey(sessionId);
1281
1282 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1283
1284 if (suspend) {
1285 if (index >= 0) {
1286 sessionEffects = mSuspendedSessions.editValueAt(index);
1287 } else {
1288 mSuspendedSessions.add(sessionId, sessionEffects);
1289 }
1290 } else {
1291 if (index < 0) {
1292 return;
1293 }
1294 sessionEffects = mSuspendedSessions.editValueAt(index);
1295 }
1296
1297
1298 int key = EffectChain::kKeyForSuspendAll;
1299 if (type != NULL) {
1300 key = type->timeLow;
1301 }
1302 index = sessionEffects.indexOfKey(key);
1303
1304 sp <SuspendedSessionDesc> desc;
1305 if (suspend) {
1306 if (index >= 0) {
1307 desc = sessionEffects.valueAt(index);
1308 } else {
1309 desc = new SuspendedSessionDesc();
1310 if (type != NULL) {
1311 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1312 }
1313 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001314 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001315 }
1316 desc->mRefCount++;
1317 } else {
1318 if (index < 0) {
1319 return;
1320 }
1321 desc = sessionEffects.valueAt(index);
1322 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001323 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001324 sessionEffects.removeItemsAt(index);
1325 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001326 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001327 sessionId);
1328 mSuspendedSessions.removeItem(sessionId);
1329 }
1330 }
1331 }
1332 if (!sessionEffects.isEmpty()) {
1333 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1334 }
1335}
1336
1337void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1338 bool enabled,
1339 int sessionId)
1340{
1341 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001342 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1343}
Eric Laurent59255e42011-07-27 19:49:51 -07001344
Eric Laurenta85a74a2011-10-19 11:44:54 -07001345void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1346 bool enabled,
1347 int sessionId)
1348{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001349 if (mType != RECORD) {
1350 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1351 // another session. This gives the priority to well behaved effect control panels
1352 // and applications not using global effects.
1353 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1354 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1355 }
1356 }
Eric Laurent59255e42011-07-27 19:49:51 -07001357
1358 sp<EffectChain> chain = getEffectChain_l(sessionId);
1359 if (chain != 0) {
1360 chain->checkSuspendOnEffectEnabled(effect, enabled);
1361 }
1362}
1363
Mathias Agopian65ab4712010-07-14 17:59:35 -07001364// ----------------------------------------------------------------------------
1365
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001366AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1367 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001368 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001369 uint32_t device,
1370 type_t type)
1371 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001372 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1373 // Assumes constructor is called by AudioFlinger with it's mLock held,
1374 // but it would be safer to explicitly pass initial masterMute as parameter
1375 mMasterMute(audioFlinger->masterMute_l()),
1376 // mStreamTypes[] initialized in constructor body
1377 mOutput(output),
1378 // Assumes constructor is called by AudioFlinger with it's mLock held,
1379 // but it would be safer to explicitly pass initial masterVolume as parameter
1380 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001381 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001382{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001383 snprintf(mName, kNameLength, "AudioOut_%d", id);
1384
Mathias Agopian65ab4712010-07-14 17:59:35 -07001385 readOutputParameters();
1386
Glenn Kasten263709e2012-01-06 08:40:01 -08001387 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001388 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1389 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1390 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1392 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001393 // initialized by stream_type_t default constructor
1394 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001395 }
1396}
1397
1398AudioFlinger::PlaybackThread::~PlaybackThread()
1399{
1400 delete [] mMixBuffer;
1401}
1402
1403status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1404{
1405 dumpInternals(fd, args);
1406 dumpTracks(fd, args);
1407 dumpEffectChains(fd, args);
1408 return NO_ERROR;
1409}
1410
1411status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1412{
1413 const size_t SIZE = 256;
1414 char buffer[SIZE];
1415 String8 result;
1416
1417 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1418 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001419 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001420 for (size_t i = 0; i < mTracks.size(); ++i) {
1421 sp<Track> track = mTracks[i];
1422 if (track != 0) {
1423 track->dump(buffer, SIZE);
1424 result.append(buffer);
1425 }
1426 }
1427
1428 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1429 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001430 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001432 sp<Track> track = mActiveTracks[i].promote();
1433 if (track != 0) {
1434 track->dump(buffer, SIZE);
1435 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436 }
1437 }
1438 write(fd, result.string(), result.size());
1439 return NO_ERROR;
1440}
1441
Mathias Agopian65ab4712010-07-14 17:59:35 -07001442status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1443{
1444 const size_t SIZE = 256;
1445 char buffer[SIZE];
1446 String8 result;
1447
1448 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1449 result.append(buffer);
1450 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1451 result.append(buffer);
1452 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1453 result.append(buffer);
1454 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1455 result.append(buffer);
1456 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1457 result.append(buffer);
1458 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1459 result.append(buffer);
1460 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1461 result.append(buffer);
1462 write(fd, result.string(), result.size());
1463
1464 dumpBase(fd, args);
1465
1466 return NO_ERROR;
1467}
1468
1469// Thread virtuals
1470status_t AudioFlinger::PlaybackThread::readyToRun()
1471{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001472 status_t status = initCheck();
1473 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001474 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001475 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001476 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001478 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479}
1480
1481void AudioFlinger::PlaybackThread::onFirstRef()
1482{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001483 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484}
1485
1486// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1487sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1488 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001489 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001491 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001492 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493 int frameCount,
1494 const sp<IMemory>& sharedBuffer,
1495 int sessionId,
1496 status_t *status)
1497{
1498 sp<Track> track;
1499 status_t lStatus;
1500
1501 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001502 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1503 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001504 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001505 "for output %p with format %d",
1506 sampleRate, format, channelMask, mOutput, mFormat);
1507 lStatus = BAD_VALUE;
1508 goto Exit;
1509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510 }
1511 } else {
1512 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1513 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001514 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515 lStatus = BAD_VALUE;
1516 goto Exit;
1517 }
1518 }
1519
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001520 lStatus = initCheck();
1521 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001522 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523 goto Exit;
1524 }
1525
1526 { // scope for mLock
1527 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001528
1529 // all tracks in same audio session must share the same routing strategy otherwise
1530 // conflicts will happen when tracks are moved from one output to another by audio policy
1531 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001532 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001533 for (size_t i = 0; i < mTracks.size(); ++i) {
1534 sp<Track> t = mTracks[i];
1535 if (t != 0) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001536 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001537 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001538 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001539 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001540 lStatus = BAD_VALUE;
1541 goto Exit;
1542 }
1543 }
1544 }
1545
Mathias Agopian65ab4712010-07-14 17:59:35 -07001546 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001547 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001548 if (track->getCblk() == NULL || track->name() < 0) {
1549 lStatus = NO_MEMORY;
1550 goto Exit;
1551 }
1552 mTracks.add(track);
1553
1554 sp<EffectChain> chain = getEffectChain_l(sessionId);
1555 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001556 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001558 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001559 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001561
1562 // invalidate track immediately if the stream type was moved to another thread since
1563 // createTrack() was called by the client process.
1564 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001565 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001566 this, streamType);
1567 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1568 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569 }
1570 lStatus = NO_ERROR;
1571
1572Exit:
1573 if(status) {
1574 *status = lStatus;
1575 }
1576 return track;
1577}
1578
1579uint32_t AudioFlinger::PlaybackThread::latency() const
1580{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001581 Mutex::Autolock _l(mLock);
1582 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001583 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001584 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585 return 0;
1586 }
1587}
1588
1589status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1590{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 mMasterVolume = value;
1592 return NO_ERROR;
1593}
1594
1595status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1596{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597 mMasterMute = muted;
1598 return NO_ERROR;
1599}
1600
Glenn Kastenfff6d712012-01-12 16:38:12 -08001601status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 mStreamTypes[stream].volume = value;
1604 return NO_ERROR;
1605}
1606
Glenn Kastenfff6d712012-01-12 16:38:12 -08001607status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 mStreamTypes[stream].mute = muted;
1610 return NO_ERROR;
1611}
1612
Glenn Kastenfff6d712012-01-12 16:38:12 -08001613float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614{
1615 return mStreamTypes[stream].volume;
1616}
1617
Glenn Kastenfff6d712012-01-12 16:38:12 -08001618bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619{
1620 return mStreamTypes[stream].mute;
1621}
1622
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623// addTrack_l() must be called with ThreadBase::mLock held
1624status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1625{
1626 status_t status = ALREADY_EXISTS;
1627
1628 // set retry count for buffer fill
1629 track->mRetryCount = kMaxTrackStartupRetries;
1630 if (mActiveTracks.indexOf(track) < 0) {
1631 // the track is newly added, make sure it fills up all its
1632 // buffers before playing. This is to ensure the client will
1633 // effectively get the latency it requested.
1634 track->mFillingUpStatus = Track::FS_FILLING;
1635 track->mResetDone = false;
1636 mActiveTracks.add(track);
1637 if (track->mainBuffer() != mMixBuffer) {
1638 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1639 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001640 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001641 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642 }
1643 }
1644
1645 status = NO_ERROR;
1646 }
1647
Steve Block3856b092011-10-20 11:56:00 +01001648 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 mWaitWorkCV.broadcast();
1650
1651 return status;
1652}
1653
1654// destroyTrack_l() must be called with ThreadBase::mLock held
1655void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1656{
1657 track->mState = TrackBase::TERMINATED;
1658 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001659 removeTrack_l(track);
1660 }
1661}
1662
1663void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1664{
1665 mTracks.remove(track);
1666 deleteTrackName_l(track->name());
1667 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1668 if (chain != 0) {
1669 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001670 }
1671}
1672
1673String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1674{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001675 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001676 char *s;
1677
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001678 Mutex::Autolock _l(mLock);
1679 if (initCheck() != NO_ERROR) {
1680 return out_s8;
1681 }
1682
Dima Zavin799a70e2011-04-18 16:57:27 -07001683 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001684 out_s8 = String8(s);
1685 free(s);
1686 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687}
1688
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001689// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1691 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001692 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693
Steve Block3856b092011-10-20 11:56:00 +01001694 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695
1696 switch (event) {
1697 case AudioSystem::OUTPUT_OPENED:
1698 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001699 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700 desc.samplingRate = mSampleRate;
1701 desc.format = mFormat;
1702 desc.frameCount = mFrameCount;
1703 desc.latency = latency();
1704 param2 = &desc;
1705 break;
1706
1707 case AudioSystem::STREAM_CONFIG_CHANGED:
1708 param2 = &param;
1709 case AudioSystem::OUTPUT_CLOSED:
1710 default:
1711 break;
1712 }
1713 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1714}
1715
1716void AudioFlinger::PlaybackThread::readOutputParameters()
1717{
Dima Zavin799a70e2011-04-18 16:57:27 -07001718 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001719 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1720 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001721 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001722 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001723 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724
1725 // FIXME - Current mixer implementation only supports stereo output: Always
1726 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001727 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 mMixBuffer = new int16_t[mFrameCount * 2];
1729 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1730
Eric Laurentde070132010-07-13 04:45:46 -07001731 // force reconfiguration of effect chains and engines to take new buffer size and audio
1732 // parameters into account
1733 // Note that mLock is not held when readOutputParameters() is called from the constructor
1734 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1735 // matter.
1736 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1737 Vector< sp<EffectChain> > effectChains = mEffectChains;
1738 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001739 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001740 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741}
1742
1743status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1744{
Glenn Kastena0d68332012-01-27 16:47:15 -08001745 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746 return BAD_VALUE;
1747 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001748 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001749 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750 return INVALID_OPERATION;
1751 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001752 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753
Dima Zavin799a70e2011-04-18 16:57:27 -07001754 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755}
1756
Eric Laurent39e94f82010-07-28 01:32:47 -07001757uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758{
1759 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001760 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001762 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763 }
1764
1765 for (size_t i = 0; i < mTracks.size(); ++i) {
1766 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001767 if (sessionId == track->sessionId() &&
1768 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001769 result |= TRACK_SESSION;
1770 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771 }
1772 }
1773
Eric Laurent39e94f82010-07-28 01:32:47 -07001774 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775}
1776
Eric Laurentde070132010-07-13 04:45:46 -07001777uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1778{
Dima Zavinfce7a472011-04-19 22:30:36 -07001779 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001780 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001781 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1782 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001783 }
1784 for (size_t i = 0; i < mTracks.size(); i++) {
1785 sp<Track> track = mTracks[i];
1786 if (sessionId == track->sessionId() &&
1787 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001788 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001789 }
1790 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001791 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001792}
1793
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794
Glenn Kastenaed850d2012-01-26 09:46:34 -08001795AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001796{
1797 Mutex::Autolock _l(mLock);
1798 return mOutput;
1799}
1800
1801AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1802{
1803 Mutex::Autolock _l(mLock);
1804 AudioStreamOut *output = mOutput;
1805 mOutput = NULL;
1806 return output;
1807}
1808
1809// this method must always be called either with ThreadBase mLock held or inside the thread loop
1810audio_stream_t* AudioFlinger::PlaybackThread::stream()
1811{
1812 if (mOutput == NULL) {
1813 return NULL;
1814 }
1815 return &mOutput->stream->common;
1816}
1817
Eric Laurent162b40b2011-12-05 09:47:19 -08001818uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1819{
1820 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1821 // decoding and transfer time. So sleeping for half of the latency would likely cause
1822 // underruns
1823 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1824 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1825 } else {
1826 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1827 }
1828}
1829
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830// ----------------------------------------------------------------------------
1831
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001832AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001833 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001834 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001835 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1836 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838 // FIXME - Current mixer implementation only supports stereo output
1839 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001840 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841 }
1842}
1843
1844AudioFlinger::MixerThread::~MixerThread()
1845{
1846 delete mAudioMixer;
1847}
1848
1849bool AudioFlinger::MixerThread::threadLoop()
1850{
1851 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001852 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 nsecs_t standbyTime = systemTime();
1854 size_t mixBufferSize = mFrameCount * mFrameSize;
1855 // FIXME: Relaxed timing because of a certain device that can't meet latency
1856 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001857 // increase threshold again due to low power audio mode. The way this warning threshold is
1858 // calculated and its usefulness should be reconsidered anyway.
1859 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860 nsecs_t lastWarning = 0;
1861 bool longStandbyExit = false;
1862 uint32_t activeSleepTime = activeSleepTimeUs();
1863 uint32_t idleSleepTime = idleSleepTimeUs();
1864 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001865 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001867#ifdef DEBUG_CPU_USAGE
1868 ThreadCpuUsage cpu;
1869 const CentralTendencyStatistics& stats = cpu.statistics();
1870#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871
Eric Laurentfeb0db62011-07-22 09:04:31 -07001872 acquireWakeLock();
1873
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874 while (!exitPending())
1875 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001876#ifdef DEBUG_CPU_USAGE
1877 cpu.sampleAndEnable();
1878 unsigned n = stats.n();
1879 // cpu.elapsed() is expensive, so don't call it every loop
1880 if ((n & 127) == 1) {
1881 long long elapsed = cpu.elapsed();
1882 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1883 double perLoop = elapsed / (double) n;
1884 double perLoop100 = perLoop * 0.01;
1885 double mean = stats.mean();
1886 double stddev = stats.stddev();
1887 double minimum = stats.minimum();
1888 double maximum = stats.maximum();
1889 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001890 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 Kasten4d8d0c32011-07-08 15:26:12 -07001891 elapsed * .000000001, n, perLoop * .000001,
1892 mean * .001,
1893 stddev * .001,
1894 minimum * .001,
1895 maximum * .001,
1896 mean / perLoop100,
1897 stddev / perLoop100,
1898 minimum / perLoop100,
1899 maximum / perLoop100);
1900 }
1901 }
1902#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903 processConfigEvents();
1904
1905 mixerStatus = MIXER_IDLE;
1906 { // scope for mLock
1907
1908 Mutex::Autolock _l(mLock);
1909
1910 if (checkForNewParameters_l()) {
1911 mixBufferSize = mFrameCount * mFrameSize;
1912 // FIXME: Relaxed timing because of a certain device that can't meet latency
1913 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001914 // increase threshold again due to low power audio mode. The way this warning
1915 // threshold is calculated and its usefulness should be reconsidered anyway.
1916 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001917 activeSleepTime = activeSleepTimeUs();
1918 idleSleepTime = idleSleepTimeUs();
1919 }
1920
1921 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1922
1923 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001924 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1925 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08001927 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001928 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929 mStandby = true;
1930 mBytesWritten = 0;
1931 }
1932
1933 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1934 // we're about to wait, flush the binder command buffer
1935 IPCThreadState::self()->flushCommands();
1936
1937 if (exitPending()) break;
1938
Eric Laurentfeb0db62011-07-22 09:04:31 -07001939 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940 // wait until we have something to do...
Glenn Kasten90bebef2012-01-27 15:24:38 -08001941 ALOGV("MixerThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08001943 ALOGV("MixerThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001944 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945
Eric Laurent27741442012-01-17 19:20:12 -08001946 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001947 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 char value[PROPERTY_VALUE_MAX];
1949 property_get("ro.audio.silent", value, "0");
1950 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001951 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952 setMasterMute(true);
1953 }
1954 }
1955
1956 standbyTime = systemTime() + kStandbyTimeInNsecs;
1957 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001958 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 continue;
1960 }
1961 }
1962
1963 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1964
1965 // prevent any changes in effect chain list and in each effect chain
1966 // during mixing and effect process as the audio buffers could be deleted
1967 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001968 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001969 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970
Glenn Kastenf6b16782011-12-15 09:51:17 -08001971 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 // mix buffers...
1973 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001974 // increase sleep time progressively when application underrun condition clears.
1975 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1976 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1977 // such that we would underrun the audio HAL.
1978 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001979 sleepTimeShift--;
1980 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001981 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982 standbyTime = systemTime() + kStandbyTimeInNsecs;
1983 //TODO: delay standby when effects have a tail
1984 } else {
1985 // If no tracks are ready, sleep once for the duration of an output
1986 // buffer size, then write 0s to the output
1987 if (sleepTime == 0) {
1988 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001989 sleepTime = activeSleepTime >> sleepTimeShift;
1990 if (sleepTime < kMinThreadSleepTimeUs) {
1991 sleepTime = kMinThreadSleepTimeUs;
1992 }
1993 // reduce sleep time in case of consecutive application underruns to avoid
1994 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1995 // duration we would end up writing less data than needed by the audio HAL if
1996 // the condition persists.
1997 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1998 sleepTimeShift++;
1999 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000 } else {
2001 sleepTime = idleSleepTime;
2002 }
2003 } else if (mBytesWritten != 0 ||
2004 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2005 memset (mMixBuffer, 0, mixBufferSize);
2006 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002007 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002008 }
2009 // TODO add standby time extension fct of effect tail
2010 }
2011
2012 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002013 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014 }
2015 // sleepTime == 0 means we must write to audio hardware
2016 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002017 for (size_t i = 0; i < effectChains.size(); i ++) {
2018 effectChains[i]->process_l();
2019 }
2020 // enable changes in effect chain
2021 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 mLastWriteTime = systemTime();
2023 mInWrite = true;
2024 mBytesWritten += mixBufferSize;
2025
Dima Zavin799a70e2011-04-18 16:57:27 -07002026 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2028 mNumWrites++;
2029 mInWrite = false;
2030 nsecs_t now = systemTime();
2031 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002032 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002034 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002035 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036 ns2ms(delta), mNumDelayedWrites, this);
2037 lastWarning = now;
2038 }
2039 if (mStandby) {
2040 longStandbyExit = true;
2041 }
2042 }
2043 mStandby = false;
2044 } else {
2045 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002046 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 usleep(sleepTime);
2048 }
2049
2050 // finally let go of all our tracks, without the lock held
2051 // since we can't guarantee the destructors won't acquire that
2052 // same lock.
2053 tracksToRemove.clear();
2054
2055 // Effect chains will be actually deleted here if they were removed from
2056 // mEffectChains list during mixing or effects processing
2057 effectChains.clear();
2058 }
2059
2060 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002061 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062 }
2063
Eric Laurentfeb0db62011-07-22 09:04:31 -07002064 releaseWakeLock();
2065
Steve Block3856b092011-10-20 11:56:00 +01002066 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067 return false;
2068}
2069
2070// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002071AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2072 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073{
2074
Glenn Kasten29c23c32012-01-26 13:37:52 -08002075 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002076 // find out which tracks need to be processed
2077 size_t count = activeTracks.size();
2078 size_t mixedTracks = 0;
2079 size_t tracksWithEffect = 0;
2080
2081 float masterVolume = mMasterVolume;
2082 bool masterMute = mMasterMute;
2083
Eric Laurent571d49c2010-08-11 05:20:11 -07002084 if (masterMute) {
2085 masterVolume = 0;
2086 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002088 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002090 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002091 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092 masterVolume = (float)((v + (1 << 23)) >> 24);
2093 chain.clear();
2094 }
2095
2096 for (size_t i=0 ; i<count ; i++) {
2097 sp<Track> t = activeTracks[i].promote();
2098 if (t == 0) continue;
2099
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002100 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101 Track* const track = t.get();
2102 audio_track_cblk_t* cblk = track->cblk();
2103
2104 // The first time a track is added we wait
2105 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002106 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002107 // make sure that we have enough frames to mix one full buffer.
2108 // enforce this condition only once to enable draining the buffer in case the client
2109 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002110 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002111 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002112 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002113 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002114 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002115 if (t->sampleRate() == (int)mSampleRate) {
2116 minFrames = mFrameCount;
2117 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002118 // +1 for rounding and +1 for additional sample needed for interpolation
2119 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2120 // add frames already consumed but not yet released by the resampler
2121 // because cblk->framesReady() will include these frames
2122 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2123 // the minimum track buffer size is normally twice the number of frames necessary
2124 // to fill one buffer and the resampler should not leave more than one buffer worth
2125 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002126 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002127 }
2128 }
2129 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130 !track->isPaused() && !track->isTerminated())
2131 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002132 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002133
2134 mixedTracks++;
2135
2136 // track->mainBuffer() != mMixBuffer means there is an effect chain
2137 // connected to the track
2138 chain.clear();
2139 if (track->mainBuffer() != mMixBuffer) {
2140 chain = getEffectChain_l(track->sessionId());
2141 // Delegate volume control to effect in track effect chain if needed
2142 if (chain != 0) {
2143 tracksWithEffect++;
2144 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002145 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002146 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002147 }
2148 }
2149
2150
2151 int param = AudioMixer::VOLUME;
2152 if (track->mFillingUpStatus == Track::FS_FILLED) {
2153 // no ramp for the first volume setting
2154 track->mFillingUpStatus = Track::FS_ACTIVE;
2155 if (track->mState == TrackBase::RESUMING) {
2156 track->mState = TrackBase::ACTIVE;
2157 param = AudioMixer::RAMP_VOLUME;
2158 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002159 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002160 } else if (cblk->server != 0) {
2161 // If the track is stopped before the first frame was mixed,
2162 // do not apply ramp
2163 param = AudioMixer::RAMP_VOLUME;
2164 }
2165
2166 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002167 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002168 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002169 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002170 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171 if (track->isPausing()) {
2172 track->setPaused();
2173 }
2174 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002175
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002177 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002178 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002179 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002180 vl = vlr & 0xFFFF;
2181 vr = vlr >> 16;
2182 // track volumes come from shared memory, so can't be trusted and must be clamped
2183 if (vl > MAX_GAIN_INT) {
2184 ALOGV("Track left volume out of range: %04X", vl);
2185 vl = MAX_GAIN_INT;
2186 }
2187 if (vr > MAX_GAIN_INT) {
2188 ALOGV("Track right volume out of range: %04X", vr);
2189 vr = MAX_GAIN_INT;
2190 }
2191 // now apply the master volume and stream type volume
2192 vl = (uint32_t)(v * vl) << 12;
2193 vr = (uint32_t)(v * vr) << 12;
2194 // assuming master volume and stream type volume each go up to 1.0,
2195 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196
Glenn Kasten05632a52012-01-03 14:22:33 -08002197 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2198 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002199 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002200 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002201 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002202 }
2203 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002205 // Delegate volume control to effect in track effect chain if needed
2206 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2207 // Do not ramp volume if volume is controlled by effect
2208 param = AudioMixer::VOLUME;
2209 track->mHasVolumeController = true;
2210 } else {
2211 // force no volume ramp when volume controller was just disabled or removed
2212 // from effect chain to avoid volume spike
2213 if (track->mHasVolumeController) {
2214 param = AudioMixer::VOLUME;
2215 }
2216 track->mHasVolumeController = false;
2217 }
2218
2219 // Convert volumes from 8.24 to 4.12 format
2220 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002221 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002222 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2223 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2224 left = int16_t(v_clamped);
2225 v_clamped = (vr + (1 << 11)) >> 12;
2226 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2227 right = int16_t(v_clamped);
2228
2229 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2230 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002231
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002233 mAudioMixer->setBufferProvider(name, track);
2234 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002236 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2237 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2238 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002240 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002241 AudioMixer::TRACK,
2242 AudioMixer::FORMAT, (void *)track->format());
2243 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002244 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002245 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002246 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002247 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002248 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002249 AudioMixer::RESAMPLE,
2250 AudioMixer::SAMPLE_RATE,
2251 (void *)(cblk->sampleRate));
2252 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002253 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254 AudioMixer::TRACK,
2255 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2256 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002257 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258 AudioMixer::TRACK,
2259 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2260
2261 // reset retry count
2262 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002263 // If one track is ready, set the mixer ready if:
2264 // - the mixer was not ready during previous round OR
2265 // - no other track is not ready
2266 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2267 mixerStatus != MIXER_TRACKS_ENABLED) {
2268 mixerStatus = MIXER_TRACKS_READY;
2269 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002271 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272 if (track->isStopped()) {
2273 track->reset();
2274 }
2275 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2276 // We have consumed all the buffers of this track.
2277 // Remove it from the list of active tracks.
2278 tracksToRemove->add(track);
2279 } else {
2280 // No buffers for this track. Give it a few chances to
2281 // fill a buffer, then remove it from active list.
2282 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002283 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002284 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002285 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002286 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002287 // If one track is not ready, mark the mixer also not ready if:
2288 // - the mixer was ready during previous round OR
2289 // - no other track is ready
2290 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2291 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 mixerStatus = MIXER_TRACKS_ENABLED;
2293 }
2294 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002295 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002296 }
2297 }
2298
2299 // remove all the tracks that need to be...
2300 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002301 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302 for (size_t i=0 ; i<count ; i++) {
2303 const sp<Track>& track = tracksToRemove->itemAt(i);
2304 mActiveTracks.remove(track);
2305 if (track->mainBuffer() != mMixBuffer) {
2306 chain = getEffectChain_l(track->sessionId());
2307 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002308 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002309 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002310 }
2311 }
2312 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002313 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002314 }
2315 }
2316 }
2317
2318 // mix buffer must be cleared if all tracks are connected to an
2319 // effect chain as in this case the mixer will not write to
2320 // mix buffer and track effects will accumulate into it
2321 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2322 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2323 }
2324
Eric Laurent27741442012-01-17 19:20:12 -08002325 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326 return mixerStatus;
2327}
2328
Glenn Kastenfff6d712012-01-12 16:38:12 -08002329void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330{
Steve Block3856b092011-10-20 11:56:00 +01002331 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002332 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002333 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002334
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335 size_t size = mTracks.size();
2336 for (size_t i = 0; i < size; i++) {
2337 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002338 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002339 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002341 }
2342 }
2343}
2344
Glenn Kastenfff6d712012-01-12 16:38:12 -08002345void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002346{
Steve Block3856b092011-10-20 11:56:00 +01002347 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002348 this, streamType, valid);
2349 Mutex::Autolock _l(mLock);
2350
2351 mStreamTypes[streamType].valid = valid;
2352}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353
2354// getTrackName_l() must be called with ThreadBase::mLock held
2355int AudioFlinger::MixerThread::getTrackName_l()
2356{
2357 return mAudioMixer->getTrackName();
2358}
2359
2360// deleteTrackName_l() must be called with ThreadBase::mLock held
2361void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2362{
Steve Block3856b092011-10-20 11:56:00 +01002363 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364 mAudioMixer->deleteTrackName(name);
2365}
2366
2367// checkForNewParameters_l() must be called with ThreadBase::mLock held
2368bool AudioFlinger::MixerThread::checkForNewParameters_l()
2369{
2370 bool reconfig = false;
2371
2372 while (!mNewParameters.isEmpty()) {
2373 status_t status = NO_ERROR;
2374 String8 keyValuePair = mNewParameters[0];
2375 AudioParameter param = AudioParameter(keyValuePair);
2376 int value;
2377
2378 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2379 reconfig = true;
2380 }
2381 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002382 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002383 status = BAD_VALUE;
2384 } else {
2385 reconfig = true;
2386 }
2387 }
2388 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002389 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390 status = BAD_VALUE;
2391 } else {
2392 reconfig = true;
2393 }
2394 }
2395 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2396 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002397 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398 // if frame count is changed after track creation
2399 if (!mTracks.isEmpty()) {
2400 status = INVALID_OPERATION;
2401 } else {
2402 reconfig = true;
2403 }
2404 }
2405 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002406 // when changing the audio output device, call addBatteryData to notify
2407 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002408 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002409 uint32_t params = 0;
2410 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002411 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002412 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2413 }
2414
2415 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002416 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002417 // check if any other device (except speaker) is on
2418 if (value & deviceWithoutSpeaker ) {
2419 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2420 }
2421
2422 if (params != 0) {
2423 addBatteryData(params);
2424 }
2425 }
2426
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427 // forward device change to effects that have requested to be
2428 // aware of attached audio device.
2429 mDevice = (uint32_t)value;
2430 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002431 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 }
2433 }
2434
2435 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002436 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002437 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002439 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440 mStandby = true;
2441 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002442 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002443 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444 }
2445 if (status == NO_ERROR && reconfig) {
2446 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002447 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2448 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449 readOutputParameters();
2450 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2451 for (size_t i = 0; i < mTracks.size() ; i++) {
2452 int name = getTrackName_l();
2453 if (name < 0) break;
2454 mTracks[i]->mName = name;
2455 // limit track sample rate to 2 x new output sample rate
2456 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2457 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2458 }
2459 }
2460 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2461 }
2462 }
2463
2464 mNewParameters.removeAt(0);
2465
2466 mParamStatus = status;
2467 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002468 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2469 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002470 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471 }
2472 return reconfig;
2473}
2474
2475status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2476{
2477 const size_t SIZE = 256;
2478 char buffer[SIZE];
2479 String8 result;
2480
2481 PlaybackThread::dumpInternals(fd, args);
2482
2483 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2484 result.append(buffer);
2485 write(fd, result.string(), result.size());
2486 return NO_ERROR;
2487}
2488
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2490{
Eric Laurent60e18242010-07-29 06:50:24 -07002491 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492}
2493
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002494uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2495{
2496 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2497}
2498
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002500AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2501 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002502 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002503 // mLeftVolFloat, mRightVolFloat
2504 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506}
2507
2508AudioFlinger::DirectOutputThread::~DirectOutputThread()
2509{
2510}
2511
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2513{
2514 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002515 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516 return;
2517 }
2518
2519 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002520 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 size_t count = mFrameCount * mChannelCount;
2522 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2523 int16_t *dst = mMixBuffer + count-1;
2524 while(count--) {
2525 *dst-- = (int16_t)(*src--^0x80) << 8;
2526 }
2527 }
2528
2529 size_t frameCount = mFrameCount;
2530 int16_t *out = mMixBuffer;
2531 if (ramp) {
2532 if (mChannelCount == 1) {
2533 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2534 int32_t vlInc = d / (int32_t)frameCount;
2535 int32_t vl = ((int32_t)mLeftVolShort << 16);
2536 do {
2537 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2538 out++;
2539 vl += vlInc;
2540 } while (--frameCount);
2541
2542 } else {
2543 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2544 int32_t vlInc = d / (int32_t)frameCount;
2545 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2546 int32_t vrInc = d / (int32_t)frameCount;
2547 int32_t vl = ((int32_t)mLeftVolShort << 16);
2548 int32_t vr = ((int32_t)mRightVolShort << 16);
2549 do {
2550 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2551 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2552 out += 2;
2553 vl += vlInc;
2554 vr += vrInc;
2555 } while (--frameCount);
2556 }
2557 } else {
2558 if (mChannelCount == 1) {
2559 do {
2560 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2561 out++;
2562 } while (--frameCount);
2563 } else {
2564 do {
2565 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2566 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2567 out += 2;
2568 } while (--frameCount);
2569 }
2570 }
2571
2572 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002573 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574 size_t count = mFrameCount * mChannelCount;
2575 int16_t *src = mMixBuffer;
2576 uint8_t *dst = (uint8_t *)mMixBuffer;
2577 while(count--) {
2578 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2579 }
2580 }
2581
2582 mLeftVolShort = leftVol;
2583 mRightVolShort = rightVol;
2584}
2585
2586bool AudioFlinger::DirectOutputThread::threadLoop()
2587{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002588 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589 sp<Track> trackToRemove;
2590 sp<Track> activeTrack;
2591 nsecs_t standbyTime = systemTime();
2592 int8_t *curBuf;
2593 size_t mixBufferSize = mFrameCount*mFrameSize;
2594 uint32_t activeSleepTime = activeSleepTimeUs();
2595 uint32_t idleSleepTime = idleSleepTimeUs();
2596 uint32_t sleepTime = idleSleepTime;
2597 // use shorter standby delay as on normal output to release
2598 // hardware resources as soon as possible
2599 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2600
Eric Laurentfeb0db62011-07-22 09:04:31 -07002601 acquireWakeLock();
2602
Mathias Agopian65ab4712010-07-14 17:59:35 -07002603 while (!exitPending())
2604 {
2605 bool rampVolume;
2606 uint16_t leftVol;
2607 uint16_t rightVol;
2608 Vector< sp<EffectChain> > effectChains;
2609
2610 processConfigEvents();
2611
2612 mixerStatus = MIXER_IDLE;
2613
2614 { // scope for the mLock
2615
2616 Mutex::Autolock _l(mLock);
2617
2618 if (checkForNewParameters_l()) {
2619 mixBufferSize = mFrameCount*mFrameSize;
2620 activeSleepTime = activeSleepTimeUs();
2621 idleSleepTime = idleSleepTimeUs();
2622 standbyDelay = microseconds(activeSleepTime*2);
2623 }
2624
2625 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002626 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2627 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 // wait until we have something to do...
2629 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002630 ALOGV("Audio hardware entering standby, mixer %p", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002631 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632 mStandby = true;
2633 mBytesWritten = 0;
2634 }
2635
2636 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2637 // we're about to wait, flush the binder command buffer
2638 IPCThreadState::self()->flushCommands();
2639
2640 if (exitPending()) break;
2641
Eric Laurentfeb0db62011-07-22 09:04:31 -07002642 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08002643 ALOGV("DirectOutputThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08002645 ALOGV("DirectOutputThread %p TID %d waking up in active mode", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002646 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002647
Glenn Kastenf1d45922012-01-13 15:54:24 -08002648 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 char value[PROPERTY_VALUE_MAX];
2650 property_get("ro.audio.silent", value, "0");
2651 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002652 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653 setMasterMute(true);
2654 }
2655 }
2656
2657 standbyTime = systemTime() + standbyDelay;
2658 sleepTime = idleSleepTime;
2659 continue;
2660 }
2661 }
2662
2663 effectChains = mEffectChains;
2664
2665 // find out which tracks need to be processed
2666 if (mActiveTracks.size() != 0) {
2667 sp<Track> t = mActiveTracks[0].promote();
2668 if (t == 0) continue;
2669
2670 Track* const track = t.get();
2671 audio_track_cblk_t* cblk = track->cblk();
2672
2673 // The first time a track is added we wait
2674 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002675 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676 !track->isPaused() && !track->isTerminated())
2677 {
Steve Block3856b092011-10-20 11:56:00 +01002678 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679
2680 if (track->mFillingUpStatus == Track::FS_FILLED) {
2681 track->mFillingUpStatus = Track::FS_ACTIVE;
2682 mLeftVolFloat = mRightVolFloat = 0;
2683 mLeftVolShort = mRightVolShort = 0;
2684 if (track->mState == TrackBase::RESUMING) {
2685 track->mState = TrackBase::ACTIVE;
2686 rampVolume = true;
2687 }
2688 } else if (cblk->server != 0) {
2689 // If the track is stopped before the first frame was mixed,
2690 // do not apply ramp
2691 rampVolume = true;
2692 }
2693 // compute volume for this track
2694 float left, right;
2695 if (track->isMuted() || mMasterMute || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002696 mStreamTypes[track->streamType()].mute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002697 left = right = 0;
2698 if (track->isPausing()) {
2699 track->setPaused();
2700 }
2701 } else {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002702 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002703 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002704 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002705 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2707 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002708 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2710 right = v_clamped/MAX_GAIN;
2711 }
2712
2713 if (left != mLeftVolFloat || right != mRightVolFloat) {
2714 mLeftVolFloat = left;
2715 mRightVolFloat = right;
2716
2717 // If audio HAL implements volume control,
2718 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002719 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720 left = 1.0f;
2721 right = 1.0f;
2722 }
2723
2724 // Convert volumes from float to 8.24
2725 uint32_t vl = (uint32_t)(left * (1 << 24));
2726 uint32_t vr = (uint32_t)(right * (1 << 24));
2727
2728 // Delegate volume control to effect in track effect chain if needed
2729 // only one effect chain can be present on DirectOutputThread, so if
2730 // there is one, the track is connected to it
2731 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002732 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002733 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002734 rampVolume = false;
2735 }
2736 }
2737
2738 // Convert volumes from 8.24 to 4.12 format
2739 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2740 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2741 leftVol = (uint16_t)v_clamped;
2742 v_clamped = (vr + (1 << 11)) >> 12;
2743 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2744 rightVol = (uint16_t)v_clamped;
2745 } else {
2746 leftVol = mLeftVolShort;
2747 rightVol = mRightVolShort;
2748 rampVolume = false;
2749 }
2750
2751 // reset retry count
2752 track->mRetryCount = kMaxTrackRetriesDirect;
2753 activeTrack = t;
2754 mixerStatus = MIXER_TRACKS_READY;
2755 } else {
Steve Block3856b092011-10-20 11:56:00 +01002756 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757 if (track->isStopped()) {
2758 track->reset();
2759 }
2760 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2761 // We have consumed all the buffers of this track.
2762 // Remove it from the list of active tracks.
2763 trackToRemove = track;
2764 } else {
2765 // No buffers for this track. Give it a few chances to
2766 // fill a buffer, then remove it from active list.
2767 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002768 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002769 trackToRemove = track;
2770 } else {
2771 mixerStatus = MIXER_TRACKS_ENABLED;
2772 }
2773 }
2774 }
2775 }
2776
2777 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002778 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779 mActiveTracks.remove(trackToRemove);
2780 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002781 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002782 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002783 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002784 }
2785 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002786 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002787 }
2788 }
2789
Eric Laurentde070132010-07-13 04:45:46 -07002790 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791 }
2792
Glenn Kastenf6b16782011-12-15 09:51:17 -08002793 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 AudioBufferProvider::Buffer buffer;
2795 size_t frameCount = mFrameCount;
2796 curBuf = (int8_t *)mMixBuffer;
2797 // output audio to hardware
2798 while (frameCount) {
2799 buffer.frameCount = frameCount;
2800 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002801 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002802 memset(curBuf, 0, frameCount * mFrameSize);
2803 break;
2804 }
2805 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2806 frameCount -= buffer.frameCount;
2807 curBuf += buffer.frameCount * mFrameSize;
2808 activeTrack->releaseBuffer(&buffer);
2809 }
2810 sleepTime = 0;
2811 standbyTime = systemTime() + standbyDelay;
2812 } else {
2813 if (sleepTime == 0) {
2814 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2815 sleepTime = activeSleepTime;
2816 } else {
2817 sleepTime = idleSleepTime;
2818 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002819 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2821 sleepTime = 0;
2822 }
2823 }
2824
2825 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002826 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002827 }
2828 // sleepTime == 0 means we must write to audio hardware
2829 if (sleepTime == 0) {
2830 if (mixerStatus == MIXER_TRACKS_READY) {
2831 applyVolume(leftVol, rightVol, rampVolume);
2832 }
2833 for (size_t i = 0; i < effectChains.size(); i ++) {
2834 effectChains[i]->process_l();
2835 }
Eric Laurentde070132010-07-13 04:45:46 -07002836 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837
2838 mLastWriteTime = systemTime();
2839 mInWrite = true;
2840 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002841 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2843 mNumWrites++;
2844 mInWrite = false;
2845 mStandby = false;
2846 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002847 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848 usleep(sleepTime);
2849 }
2850
2851 // finally let go of removed track, without the lock held
2852 // since we can't guarantee the destructors won't acquire that
2853 // same lock.
2854 trackToRemove.clear();
2855 activeTrack.clear();
2856
2857 // Effect chains will be actually deleted here if they were removed from
2858 // mEffectChains list during mixing or effects processing
2859 effectChains.clear();
2860 }
2861
2862 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002863 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864 }
2865
Eric Laurentfeb0db62011-07-22 09:04:31 -07002866 releaseWakeLock();
2867
Steve Block3856b092011-10-20 11:56:00 +01002868 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869 return false;
2870}
2871
2872// getTrackName_l() must be called with ThreadBase::mLock held
2873int AudioFlinger::DirectOutputThread::getTrackName_l()
2874{
2875 return 0;
2876}
2877
2878// deleteTrackName_l() must be called with ThreadBase::mLock held
2879void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2880{
2881}
2882
2883// checkForNewParameters_l() must be called with ThreadBase::mLock held
2884bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2885{
2886 bool reconfig = false;
2887
2888 while (!mNewParameters.isEmpty()) {
2889 status_t status = NO_ERROR;
2890 String8 keyValuePair = mNewParameters[0];
2891 AudioParameter param = AudioParameter(keyValuePair);
2892 int value;
2893
2894 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2895 // do not accept frame count changes if tracks are open as the track buffer
2896 // size depends on frame count and correct behavior would not be garantied
2897 // if frame count is changed after track creation
2898 if (!mTracks.isEmpty()) {
2899 status = INVALID_OPERATION;
2900 } else {
2901 reconfig = true;
2902 }
2903 }
2904 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002905 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002906 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002907 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002908 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002909 mStandby = true;
2910 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002911 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002912 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002913 }
2914 if (status == NO_ERROR && reconfig) {
2915 readOutputParameters();
2916 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2917 }
2918 }
2919
2920 mNewParameters.removeAt(0);
2921
2922 mParamStatus = status;
2923 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002924 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2925 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002926 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927 }
2928 return reconfig;
2929}
2930
2931uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2932{
2933 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002934 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002935 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002936 } else {
2937 time = 10000;
2938 }
2939 return time;
2940}
2941
2942uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2943{
2944 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002945 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002946 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 } else {
2948 time = 10000;
2949 }
2950 return time;
2951}
2952
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002953uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2954{
2955 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002956 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002957 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2958 } else {
2959 time = 10000;
2960 }
2961 return time;
2962}
2963
2964
Mathias Agopian65ab4712010-07-14 17:59:35 -07002965// ----------------------------------------------------------------------------
2966
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002967AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002968 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002969 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2970 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972 addOutputTrack(mainThread);
2973}
2974
2975AudioFlinger::DuplicatingThread::~DuplicatingThread()
2976{
2977 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2978 mOutputTracks[i]->destroy();
2979 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980}
2981
2982bool AudioFlinger::DuplicatingThread::threadLoop()
2983{
2984 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08002985 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986 nsecs_t standbyTime = systemTime();
2987 size_t mixBufferSize = mFrameCount*mFrameSize;
2988 SortedVector< sp<OutputTrack> > outputTracks;
2989 uint32_t writeFrames = 0;
2990 uint32_t activeSleepTime = activeSleepTimeUs();
2991 uint32_t idleSleepTime = idleSleepTimeUs();
2992 uint32_t sleepTime = idleSleepTime;
2993 Vector< sp<EffectChain> > effectChains;
2994
Eric Laurentfeb0db62011-07-22 09:04:31 -07002995 acquireWakeLock();
2996
Mathias Agopian65ab4712010-07-14 17:59:35 -07002997 while (!exitPending())
2998 {
2999 processConfigEvents();
3000
3001 mixerStatus = MIXER_IDLE;
3002 { // scope for the mLock
3003
3004 Mutex::Autolock _l(mLock);
3005
3006 if (checkForNewParameters_l()) {
3007 mixBufferSize = mFrameCount*mFrameSize;
3008 updateWaitTime();
3009 activeSleepTime = activeSleepTimeUs();
3010 idleSleepTime = idleSleepTimeUs();
3011 }
3012
3013 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3014
3015 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3016 outputTracks.add(mOutputTracks[i]);
3017 }
3018
3019 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003020 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3021 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003022 if (!mStandby) {
3023 for (size_t i = 0; i < outputTracks.size(); i++) {
3024 outputTracks[i]->stop();
3025 }
3026 mStandby = true;
3027 mBytesWritten = 0;
3028 }
3029
3030 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3031 // we're about to wait, flush the binder command buffer
3032 IPCThreadState::self()->flushCommands();
3033 outputTracks.clear();
3034
3035 if (exitPending()) break;
3036
Eric Laurentfeb0db62011-07-22 09:04:31 -07003037 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08003038 ALOGV("DuplicatingThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003039 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08003040 ALOGV("DuplicatingThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003041 acquireWakeLock_l();
3042
Eric Laurent27741442012-01-17 19:20:12 -08003043 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003044 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003045 char value[PROPERTY_VALUE_MAX];
3046 property_get("ro.audio.silent", value, "0");
3047 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003048 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003049 setMasterMute(true);
3050 }
3051 }
3052
3053 standbyTime = systemTime() + kStandbyTimeInNsecs;
3054 sleepTime = idleSleepTime;
3055 continue;
3056 }
3057 }
3058
3059 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3060
3061 // prevent any changes in effect chain list and in each effect chain
3062 // during mixing and effect process as the audio buffers could be deleted
3063 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003064 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003065 }
3066
Glenn Kastenf6b16782011-12-15 09:51:17 -08003067 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003068 // mix buffers...
3069 if (outputsReady(outputTracks)) {
3070 mAudioMixer->process();
3071 } else {
3072 memset(mMixBuffer, 0, mixBufferSize);
3073 }
3074 sleepTime = 0;
3075 writeFrames = mFrameCount;
3076 } else {
3077 if (sleepTime == 0) {
3078 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3079 sleepTime = activeSleepTime;
3080 } else {
3081 sleepTime = idleSleepTime;
3082 }
3083 } else if (mBytesWritten != 0) {
3084 // flush remaining overflow buffers in output tracks
3085 for (size_t i = 0; i < outputTracks.size(); i++) {
3086 if (outputTracks[i]->isActive()) {
3087 sleepTime = 0;
3088 writeFrames = 0;
3089 memset(mMixBuffer, 0, mixBufferSize);
3090 break;
3091 }
3092 }
3093 }
3094 }
3095
3096 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003097 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098 }
3099 // sleepTime == 0 means we must write to audio hardware
3100 if (sleepTime == 0) {
3101 for (size_t i = 0; i < effectChains.size(); i ++) {
3102 effectChains[i]->process_l();
3103 }
3104 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003105 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003106
3107 standbyTime = systemTime() + kStandbyTimeInNsecs;
3108 for (size_t i = 0; i < outputTracks.size(); i++) {
3109 outputTracks[i]->write(mMixBuffer, writeFrames);
3110 }
3111 mStandby = false;
3112 mBytesWritten += mixBufferSize;
3113 } else {
3114 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003115 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003116 usleep(sleepTime);
3117 }
3118
3119 // finally let go of all our tracks, without the lock held
3120 // since we can't guarantee the destructors won't acquire that
3121 // same lock.
3122 tracksToRemove.clear();
3123 outputTracks.clear();
3124
3125 // Effect chains will be actually deleted here if they were removed from
3126 // mEffectChains list during mixing or effects processing
3127 effectChains.clear();
3128 }
3129
Eric Laurentfeb0db62011-07-22 09:04:31 -07003130 releaseWakeLock();
3131
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132 return false;
3133}
3134
3135void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3136{
3137 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3138 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3139 this,
3140 mSampleRate,
3141 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003142 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143 frameCount);
3144 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003145 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003147 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003148 updateWaitTime();
3149 }
3150}
3151
3152void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3153{
3154 Mutex::Autolock _l(mLock);
3155 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3156 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3157 mOutputTracks[i]->destroy();
3158 mOutputTracks.removeAt(i);
3159 updateWaitTime();
3160 return;
3161 }
3162 }
Steve Block3856b092011-10-20 11:56:00 +01003163 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164}
3165
3166void AudioFlinger::DuplicatingThread::updateWaitTime()
3167{
3168 mWaitTimeMs = UINT_MAX;
3169 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3170 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003171 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3173 if (waitTimeMs < mWaitTimeMs) {
3174 mWaitTimeMs = waitTimeMs;
3175 }
3176 }
3177 }
3178}
3179
3180
3181bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3182{
3183 for (size_t i = 0; i < outputTracks.size(); i++) {
3184 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3185 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003186 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 return false;
3188 }
3189 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3190 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003191 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192 return false;
3193 }
3194 }
3195 return true;
3196}
3197
3198uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3199{
3200 return (mWaitTimeMs * 1000) / 2;
3201}
3202
3203// ----------------------------------------------------------------------------
3204
3205// TrackBase constructor must be called with AudioFlinger::mLock held
3206AudioFlinger::ThreadBase::TrackBase::TrackBase(
3207 const wp<ThreadBase>& thread,
3208 const sp<Client>& client,
3209 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003210 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003211 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003212 int frameCount,
3213 uint32_t flags,
3214 const sp<IMemory>& sharedBuffer,
3215 int sessionId)
3216 : RefBase(),
3217 mThread(thread),
3218 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003219 mCblk(NULL),
3220 // mBuffer
3221 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 mFrameCount(0),
3223 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224 mFormat(format),
3225 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3226 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003227 // mChannelCount
3228 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003229{
Steve Block3856b092011-10-20 11:56:00 +01003230 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231
Steve Blockb8a80522011-12-20 16:23:08 +00003232 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003234 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3236 if (sharedBuffer == 0) {
3237 size += bufferSize;
3238 }
3239
3240 if (client != NULL) {
3241 mCblkMemory = client->heap()->allocate(size);
3242 if (mCblkMemory != 0) {
3243 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003244 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 new(mCblk) audio_track_cblk_t();
3246 // clear all buffers
3247 mCblk->frameCount = frameCount;
3248 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003249 mChannelCount = channelCount;
3250 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251 if (sharedBuffer == 0) {
3252 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3253 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3254 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003255 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 mCblk->flags = CBLK_UNDERRUN_ON;
3257 } else {
3258 mBuffer = sharedBuffer->pointer();
3259 }
3260 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3261 }
3262 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003263 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 client->heap()->dump("AudioTrack");
3265 return;
3266 }
3267 } else {
3268 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003269 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270 new(mCblk) audio_track_cblk_t();
3271 // clear all buffers
3272 mCblk->frameCount = frameCount;
3273 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003274 mChannelCount = channelCount;
3275 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3277 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3278 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003279 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 mCblk->flags = CBLK_UNDERRUN_ON;
3281 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003282 }
3283}
3284
3285AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3286{
Glenn Kastena0d68332012-01-27 16:47:15 -08003287 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003288 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003290 } else {
3291 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 }
3293 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003294 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003295 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003296 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003297 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003298 // If the client's reference count drops to zero, the associated destructor
3299 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3300 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 mClient.clear();
3302 }
3303}
3304
3305void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3306{
Glenn Kastene0feee32011-12-13 11:53:26 -08003307 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 mFrameCount = buffer->frameCount;
3309 step();
3310 buffer->frameCount = 0;
3311}
3312
3313bool AudioFlinger::ThreadBase::TrackBase::step() {
3314 bool result;
3315 audio_track_cblk_t* cblk = this->cblk();
3316
3317 result = cblk->stepServer(mFrameCount);
3318 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003319 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003320 mFlags |= STEPSERVER_FAILED;
3321 }
3322 return result;
3323}
3324
3325void AudioFlinger::ThreadBase::TrackBase::reset() {
3326 audio_track_cblk_t* cblk = this->cblk();
3327
3328 cblk->user = 0;
3329 cblk->server = 0;
3330 cblk->userBase = 0;
3331 cblk->serverBase = 0;
3332 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003333 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334}
3335
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3337 return (int)mCblk->sampleRate;
3338}
3339
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3341 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003342 size_t frameSize = cblk->frameSize;
3343 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3344 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345
3346 // Check validity of returned pointer in case the track control block would have been corrupted.
3347 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003348 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003349 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003350 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003352 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003353 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354 }
3355
3356 return bufferStart;
3357}
3358
3359// ----------------------------------------------------------------------------
3360
3361// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3362AudioFlinger::PlaybackThread::Track::Track(
3363 const wp<ThreadBase>& thread,
3364 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003365 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003367 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003368 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369 int frameCount,
3370 const sp<IMemory>& sharedBuffer,
3371 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003372 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003373 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3374 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375{
3376 if (mCblk != NULL) {
3377 sp<ThreadBase> baseThread = thread.promote();
3378 if (baseThread != 0) {
3379 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3380 mName = playbackThread->getTrackName_l();
3381 mMainBuffer = playbackThread->mixBuffer();
3382 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003383 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003385 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387 mStreamType = streamType;
3388 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3389 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003390 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003391 }
3392}
3393
3394AudioFlinger::PlaybackThread::Track::~Track()
3395{
Steve Block3856b092011-10-20 11:56:00 +01003396 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003397 sp<ThreadBase> thread = mThread.promote();
3398 if (thread != 0) {
3399 Mutex::Autolock _l(thread->mLock);
3400 mState = TERMINATED;
3401 }
3402}
3403
3404void AudioFlinger::PlaybackThread::Track::destroy()
3405{
3406 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3407 // by removing it from mTracks vector, so there is a risk that this Tracks's
3408 // desctructor is called. As the destructor needs to lock mLock,
3409 // we must acquire a strong reference on this Track before locking mLock
3410 // here so that the destructor is called only when exiting this function.
3411 // On the other hand, as long as Track::destroy() is only called by
3412 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3413 // this Track with its member mTrack.
3414 sp<Track> keep(this);
3415 { // scope for mLock
3416 sp<ThreadBase> thread = mThread.promote();
3417 if (thread != 0) {
3418 if (!isOutputTrack()) {
3419 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003420 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003421
3422 // to track the speaker usage
3423 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003424 }
3425 AudioSystem::releaseOutput(thread->id());
3426 }
3427 Mutex::Autolock _l(thread->mLock);
3428 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3429 playbackThread->destroyTrack_l(this);
3430 }
3431 }
3432}
3433
3434void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3435{
Glenn Kasten83d86532012-01-17 14:39:34 -08003436 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003437 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",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 mName - AudioMixer::TRACK0,
Glenn Kasten7378ca52012-01-20 13:44:40 -08003439 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003440 mStreamType,
3441 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003442 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443 mSessionId,
3444 mFrameCount,
3445 mState,
3446 mMute,
3447 mFillingUpStatus,
3448 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003449 vlr & 0xFFFF,
3450 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003451 mCblk->server,
3452 mCblk->user,
3453 (int)mMainBuffer,
3454 (int)mAuxBuffer);
3455}
3456
3457status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3458{
3459 audio_track_cblk_t* cblk = this->cblk();
3460 uint32_t framesReady;
3461 uint32_t framesReq = buffer->frameCount;
3462
3463 // Check if last stepServer failed, try to step now
3464 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3465 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003466 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003467 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3468 }
3469
3470 framesReady = cblk->framesReady();
3471
Glenn Kastenf6b16782011-12-15 09:51:17 -08003472 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473 uint32_t s = cblk->server;
3474 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3475
3476 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3477 if (framesReq > framesReady) {
3478 framesReq = framesReady;
3479 }
3480 if (s + framesReq > bufferEnd) {
3481 framesReq = bufferEnd - s;
3482 }
3483
3484 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003485 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486
3487 buffer->frameCount = framesReq;
3488 return NO_ERROR;
3489 }
3490
3491getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003492 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003494 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 return NOT_ENOUGH_DATA;
3496}
3497
3498bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003499 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500
3501 if (mCblk->framesReady() >= mCblk->frameCount ||
3502 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3503 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003504 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505 return true;
3506 }
3507 return false;
3508}
3509
3510status_t AudioFlinger::PlaybackThread::Track::start()
3511{
3512 status_t status = NO_ERROR;
Glenn Kasten23d82a92012-02-03 11:10:00 -08003513 ALOGV("start(%d), calling pid %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003514 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003515 sp<ThreadBase> thread = mThread.promote();
3516 if (thread != 0) {
3517 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003518 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003519 // here the track could be either new, or restarted
3520 // in both cases "unstop" the track
3521 if (mState == PAUSED) {
3522 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003523 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003524 } else {
3525 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003526 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003527 }
3528
3529 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3530 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003531 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003532 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003533
3534 // to track the speaker usage
3535 if (status == NO_ERROR) {
3536 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3537 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003538 }
3539 if (status == NO_ERROR) {
3540 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3541 playbackThread->addTrack_l(this);
3542 } else {
3543 mState = state;
3544 }
3545 } else {
3546 status = BAD_VALUE;
3547 }
3548 return status;
3549}
3550
3551void AudioFlinger::PlaybackThread::Track::stop()
3552{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003553 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554 sp<ThreadBase> thread = mThread.promote();
3555 if (thread != 0) {
3556 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003557 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558 if (mState > STOPPED) {
3559 mState = STOPPED;
3560 // If the track is not active (PAUSED and buffers full), flush buffers
3561 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3562 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3563 reset();
3564 }
Steve Block3856b092011-10-20 11:56:00 +01003565 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003566 }
3567 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3568 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003569 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003571
3572 // to track the speaker usage
3573 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 }
3575 }
3576}
3577
3578void AudioFlinger::PlaybackThread::Track::pause()
3579{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003580 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581 sp<ThreadBase> thread = mThread.promote();
3582 if (thread != 0) {
3583 Mutex::Autolock _l(thread->mLock);
3584 if (mState == ACTIVE || mState == RESUMING) {
3585 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003586 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003587 if (!isOutputTrack()) {
3588 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003589 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003591
3592 // to track the speaker usage
3593 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003594 }
3595 }
3596 }
3597}
3598
3599void AudioFlinger::PlaybackThread::Track::flush()
3600{
Steve Block3856b092011-10-20 11:56:00 +01003601 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003602 sp<ThreadBase> thread = mThread.promote();
3603 if (thread != 0) {
3604 Mutex::Autolock _l(thread->mLock);
3605 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3606 return;
3607 }
3608 // No point remaining in PAUSED state after a flush => go to
3609 // STOPPED state
3610 mState = STOPPED;
3611
Eric Laurent38ccae22011-03-28 18:37:07 -07003612 // do not reset the track if it is still in the process of being stopped or paused.
3613 // this will be done by prepareTracks_l() when the track is stopped.
3614 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3615 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3616 reset();
3617 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 }
3619}
3620
3621void AudioFlinger::PlaybackThread::Track::reset()
3622{
3623 // Do not reset twice to avoid discarding data written just after a flush and before
3624 // the audioflinger thread detects the track is stopped.
3625 if (!mResetDone) {
3626 TrackBase::reset();
3627 // Force underrun condition to avoid false underrun callback until first data is
3628 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003629 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3630 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003631 mFillingUpStatus = FS_FILLING;
3632 mResetDone = true;
3633 }
3634}
3635
3636void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3637{
3638 mMute = muted;
3639}
3640
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3642{
3643 status_t status = DEAD_OBJECT;
3644 sp<ThreadBase> thread = mThread.promote();
3645 if (thread != 0) {
3646 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3647 status = playbackThread->attachAuxEffect(this, EffectId);
3648 }
3649 return status;
3650}
3651
3652void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3653{
3654 mAuxEffectId = EffectId;
3655 mAuxBuffer = buffer;
3656}
3657
3658// ----------------------------------------------------------------------------
3659
3660// RecordTrack constructor must be called with AudioFlinger::mLock held
3661AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3662 const wp<ThreadBase>& thread,
3663 const sp<Client>& client,
3664 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003665 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003666 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667 int frameCount,
3668 uint32_t flags,
3669 int sessionId)
3670 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003671 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672 mOverflow(false)
3673{
3674 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003675 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003676 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003677 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003678 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003679 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680 } else {
3681 mCblk->frameSize = sizeof(int8_t);
3682 }
3683 }
3684}
3685
3686AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3687{
3688 sp<ThreadBase> thread = mThread.promote();
3689 if (thread != 0) {
3690 AudioSystem::releaseInput(thread->id());
3691 }
3692}
3693
3694status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3695{
3696 audio_track_cblk_t* cblk = this->cblk();
3697 uint32_t framesAvail;
3698 uint32_t framesReq = buffer->frameCount;
3699
3700 // Check if last stepServer failed, try to step now
3701 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3702 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003703 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003704 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3705 }
3706
3707 framesAvail = cblk->framesAvailable_l();
3708
Glenn Kastenf6b16782011-12-15 09:51:17 -08003709 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710 uint32_t s = cblk->server;
3711 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3712
3713 if (framesReq > framesAvail) {
3714 framesReq = framesAvail;
3715 }
3716 if (s + framesReq > bufferEnd) {
3717 framesReq = bufferEnd - s;
3718 }
3719
3720 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003721 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003722
3723 buffer->frameCount = framesReq;
3724 return NO_ERROR;
3725 }
3726
3727getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003728 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003729 buffer->frameCount = 0;
3730 return NOT_ENOUGH_DATA;
3731}
3732
3733status_t AudioFlinger::RecordThread::RecordTrack::start()
3734{
3735 sp<ThreadBase> thread = mThread.promote();
3736 if (thread != 0) {
3737 RecordThread *recordThread = (RecordThread *)thread.get();
3738 return recordThread->start(this);
3739 } else {
3740 return BAD_VALUE;
3741 }
3742}
3743
3744void AudioFlinger::RecordThread::RecordTrack::stop()
3745{
3746 sp<ThreadBase> thread = mThread.promote();
3747 if (thread != 0) {
3748 RecordThread *recordThread = (RecordThread *)thread.get();
3749 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003750 TrackBase::reset();
3751 // Force overerrun condition to avoid false overrun callback until first data is
3752 // read from buffer
3753 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003754 }
3755}
3756
3757void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3758{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003759 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08003760 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003762 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003763 mSessionId,
3764 mFrameCount,
3765 mState,
3766 mCblk->sampleRate,
3767 mCblk->server,
3768 mCblk->user);
3769}
3770
3771
3772// ----------------------------------------------------------------------------
3773
3774AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3775 const wp<ThreadBase>& thread,
3776 DuplicatingThread *sourceThread,
3777 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003778 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003779 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003781 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003782 mActive(false), mSourceThread(sourceThread)
3783{
3784
3785 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3786 if (mCblk != NULL) {
3787 mCblk->flags |= CBLK_DIRECTION_OUT;
3788 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003789 mOutBuffer.frameCount = 0;
3790 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003791 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003792 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3793 mCblk, mBuffer, mCblk->buffers,
3794 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003795 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003796 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797 }
3798}
3799
3800AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3801{
3802 clearBufferQueue();
3803}
3804
3805status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3806{
3807 status_t status = Track::start();
3808 if (status != NO_ERROR) {
3809 return status;
3810 }
3811
3812 mActive = true;
3813 mRetryCount = 127;
3814 return status;
3815}
3816
3817void AudioFlinger::PlaybackThread::OutputTrack::stop()
3818{
3819 Track::stop();
3820 clearBufferQueue();
3821 mOutBuffer.frameCount = 0;
3822 mActive = false;
3823}
3824
3825bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3826{
3827 Buffer *pInBuffer;
3828 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003829 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003830 bool outputBufferFull = false;
3831 inBuffer.frameCount = frames;
3832 inBuffer.i16 = data;
3833
3834 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3835
3836 if (!mActive && frames != 0) {
3837 start();
3838 sp<ThreadBase> thread = mThread.promote();
3839 if (thread != 0) {
3840 MixerThread *mixerThread = (MixerThread *)thread.get();
3841 if (mCblk->frameCount > frames){
3842 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3843 uint32_t startFrames = (mCblk->frameCount - frames);
3844 pInBuffer = new Buffer;
3845 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3846 pInBuffer->frameCount = startFrames;
3847 pInBuffer->i16 = pInBuffer->mBuffer;
3848 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3849 mBufferQueue.add(pInBuffer);
3850 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003851 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003852 }
3853 }
3854 }
3855 }
3856
3857 while (waitTimeLeftMs) {
3858 // First write pending buffers, then new data
3859 if (mBufferQueue.size()) {
3860 pInBuffer = mBufferQueue.itemAt(0);
3861 } else {
3862 pInBuffer = &inBuffer;
3863 }
3864
3865 if (pInBuffer->frameCount == 0) {
3866 break;
3867 }
3868
3869 if (mOutBuffer.frameCount == 0) {
3870 mOutBuffer.frameCount = pInBuffer->frameCount;
3871 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003872 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003873 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003874 outputBufferFull = true;
3875 break;
3876 }
3877 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3878 if (waitTimeLeftMs >= waitTimeMs) {
3879 waitTimeLeftMs -= waitTimeMs;
3880 } else {
3881 waitTimeLeftMs = 0;
3882 }
3883 }
3884
3885 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3886 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3887 mCblk->stepUser(outFrames);
3888 pInBuffer->frameCount -= outFrames;
3889 pInBuffer->i16 += outFrames * channelCount;
3890 mOutBuffer.frameCount -= outFrames;
3891 mOutBuffer.i16 += outFrames * channelCount;
3892
3893 if (pInBuffer->frameCount == 0) {
3894 if (mBufferQueue.size()) {
3895 mBufferQueue.removeAt(0);
3896 delete [] pInBuffer->mBuffer;
3897 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003898 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003899 } else {
3900 break;
3901 }
3902 }
3903 }
3904
3905 // If we could not write all frames, allocate a buffer and queue it for next time.
3906 if (inBuffer.frameCount) {
3907 sp<ThreadBase> thread = mThread.promote();
3908 if (thread != 0 && !thread->standby()) {
3909 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3910 pInBuffer = new Buffer;
3911 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3912 pInBuffer->frameCount = inBuffer.frameCount;
3913 pInBuffer->i16 = pInBuffer->mBuffer;
3914 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3915 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003916 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003917 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003918 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003919 }
3920 }
3921 }
3922
3923 // Calling write() with a 0 length buffer, means that no more data will be written:
3924 // If no more buffers are pending, fill output track buffer to make sure it is started
3925 // by output mixer.
3926 if (frames == 0 && mBufferQueue.size() == 0) {
3927 if (mCblk->user < mCblk->frameCount) {
3928 frames = mCblk->frameCount - mCblk->user;
3929 pInBuffer = new Buffer;
3930 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3931 pInBuffer->frameCount = frames;
3932 pInBuffer->i16 = pInBuffer->mBuffer;
3933 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3934 mBufferQueue.add(pInBuffer);
3935 } else if (mActive) {
3936 stop();
3937 }
3938 }
3939
3940 return outputBufferFull;
3941}
3942
3943status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3944{
3945 int active;
3946 status_t result;
3947 audio_track_cblk_t* cblk = mCblk;
3948 uint32_t framesReq = buffer->frameCount;
3949
Steve Block3856b092011-10-20 11:56:00 +01003950// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951 buffer->frameCount = 0;
3952
3953 uint32_t framesAvail = cblk->framesAvailable();
3954
3955
3956 if (framesAvail == 0) {
3957 Mutex::Autolock _l(cblk->lock);
3958 goto start_loop_here;
3959 while (framesAvail == 0) {
3960 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003961 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003962 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08003963 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003964 }
3965 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3966 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003967 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003968 }
3969 // read the server count again
3970 start_loop_here:
3971 framesAvail = cblk->framesAvailable_l();
3972 }
3973 }
3974
3975// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003976// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977// }
3978
3979 if (framesReq > framesAvail) {
3980 framesReq = framesAvail;
3981 }
3982
3983 uint32_t u = cblk->user;
3984 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3985
3986 if (u + framesReq > bufferEnd) {
3987 framesReq = bufferEnd - u;
3988 }
3989
3990 buffer->frameCount = framesReq;
3991 buffer->raw = (void *)cblk->buffer(u);
3992 return NO_ERROR;
3993}
3994
3995
3996void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3997{
3998 size_t size = mBufferQueue.size();
3999 Buffer *pBuffer;
4000
4001 for (size_t i = 0; i < size; i++) {
4002 pBuffer = mBufferQueue.itemAt(i);
4003 delete [] pBuffer->mBuffer;
4004 delete pBuffer;
4005 }
4006 mBufferQueue.clear();
4007}
4008
4009// ----------------------------------------------------------------------------
4010
4011AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4012 : RefBase(),
4013 mAudioFlinger(audioFlinger),
4014 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4015 mPid(pid)
4016{
4017 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4018}
4019
4020// Client destructor must be called with AudioFlinger::mLock held
4021AudioFlinger::Client::~Client()
4022{
4023 mAudioFlinger->removeClient_l(mPid);
4024}
4025
Glenn Kasten435dbe62012-01-30 10:15:48 -08004026sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027{
4028 return mMemoryDealer;
4029}
4030
4031// ----------------------------------------------------------------------------
4032
4033AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4034 const sp<IAudioFlingerClient>& client,
4035 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004036 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004037{
4038}
4039
4040AudioFlinger::NotificationClient::~NotificationClient()
4041{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004042}
4043
4044void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4045{
4046 sp<NotificationClient> keep(this);
4047 {
4048 mAudioFlinger->removeNotificationClient(mPid);
4049 }
4050}
4051
4052// ----------------------------------------------------------------------------
4053
4054AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4055 : BnAudioTrack(),
4056 mTrack(track)
4057{
4058}
4059
4060AudioFlinger::TrackHandle::~TrackHandle() {
4061 // just stop the track on deletion, associated resources
4062 // will be freed from the main thread once all pending buffers have
4063 // been played. Unless it's not in the active track list, in which
4064 // case we free everything now...
4065 mTrack->destroy();
4066}
4067
Glenn Kasten90716c52012-01-26 13:40:12 -08004068sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4069 return mTrack->getCblk();
4070}
4071
Mathias Agopian65ab4712010-07-14 17:59:35 -07004072status_t AudioFlinger::TrackHandle::start() {
4073 return mTrack->start();
4074}
4075
4076void AudioFlinger::TrackHandle::stop() {
4077 mTrack->stop();
4078}
4079
4080void AudioFlinger::TrackHandle::flush() {
4081 mTrack->flush();
4082}
4083
4084void AudioFlinger::TrackHandle::mute(bool e) {
4085 mTrack->mute(e);
4086}
4087
4088void AudioFlinger::TrackHandle::pause() {
4089 mTrack->pause();
4090}
4091
Mathias Agopian65ab4712010-07-14 17:59:35 -07004092status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4093{
4094 return mTrack->attachAuxEffect(EffectId);
4095}
4096
4097status_t AudioFlinger::TrackHandle::onTransact(
4098 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4099{
4100 return BnAudioTrack::onTransact(code, data, reply, flags);
4101}
4102
4103// ----------------------------------------------------------------------------
4104
4105sp<IAudioRecord> AudioFlinger::openRecord(
4106 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004107 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004109 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004110 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004111 int frameCount,
4112 uint32_t flags,
4113 int *sessionId,
4114 status_t *status)
4115{
4116 sp<RecordThread::RecordTrack> recordTrack;
4117 sp<RecordHandle> recordHandle;
4118 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004119 status_t lStatus;
4120 RecordThread *thread;
4121 size_t inFrameCount;
4122 int lSessionId;
4123
4124 // check calling permissions
4125 if (!recordingAllowed()) {
4126 lStatus = PERMISSION_DENIED;
4127 goto Exit;
4128 }
4129
4130 // add client to list
4131 { // scope for mLock
4132 Mutex::Autolock _l(mLock);
4133 thread = checkRecordThread_l(input);
4134 if (thread == NULL) {
4135 lStatus = BAD_VALUE;
4136 goto Exit;
4137 }
4138
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004139 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004140
4141 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004142 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143 lSessionId = *sessionId;
4144 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004145 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146 if (sessionId != NULL) {
4147 *sessionId = lSessionId;
4148 }
4149 }
4150 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004151 recordTrack = thread->createRecordTrack_l(client,
4152 sampleRate,
4153 format,
4154 channelMask,
4155 frameCount,
4156 flags,
4157 lSessionId,
4158 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004160 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004161 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4162 // destructor is called by the TrackBase destructor with mLock held
4163 client.clear();
4164 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004165 goto Exit;
4166 }
4167
4168 // return to handle to client
4169 recordHandle = new RecordHandle(recordTrack);
4170 lStatus = NO_ERROR;
4171
4172Exit:
4173 if (status) {
4174 *status = lStatus;
4175 }
4176 return recordHandle;
4177}
4178
4179// ----------------------------------------------------------------------------
4180
4181AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4182 : BnAudioRecord(),
4183 mRecordTrack(recordTrack)
4184{
4185}
4186
4187AudioFlinger::RecordHandle::~RecordHandle() {
4188 stop();
4189}
4190
Glenn Kasten90716c52012-01-26 13:40:12 -08004191sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4192 return mRecordTrack->getCblk();
4193}
4194
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004196 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197 return mRecordTrack->start();
4198}
4199
4200void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004201 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202 mRecordTrack->stop();
4203}
4204
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205status_t AudioFlinger::RecordHandle::onTransact(
4206 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4207{
4208 return BnAudioRecord::onTransact(code, data, reply, flags);
4209}
4210
4211// ----------------------------------------------------------------------------
4212
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004213AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4214 AudioStreamIn *input,
4215 uint32_t sampleRate,
4216 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004217 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004218 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004219 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004220 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4221 // mRsmpInIndex and mInputBytes set by readInputParameters()
4222 mReqChannelCount(popcount(channels)),
4223 mReqSampleRate(sampleRate)
4224 // mBytesRead is only meaningful while active, and so is cleared in start()
4225 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004227 snprintf(mName, kNameLength, "AudioIn_%d", id);
4228
Mathias Agopian65ab4712010-07-14 17:59:35 -07004229 readInputParameters();
4230}
4231
4232
4233AudioFlinger::RecordThread::~RecordThread()
4234{
4235 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004236 delete mResampler;
4237 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004238}
4239
4240void AudioFlinger::RecordThread::onFirstRef()
4241{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004242 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004243}
4244
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004245status_t AudioFlinger::RecordThread::readyToRun()
4246{
4247 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004248 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004249 return status;
4250}
4251
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252bool AudioFlinger::RecordThread::threadLoop()
4253{
4254 AudioBufferProvider::Buffer buffer;
4255 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004256 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004257
Eric Laurent44d98482010-09-30 16:12:31 -07004258 nsecs_t lastWarning = 0;
4259
Eric Laurentfeb0db62011-07-22 09:04:31 -07004260 acquireWakeLock();
4261
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262 // start recording
4263 while (!exitPending()) {
4264
4265 processConfigEvents();
4266
4267 { // scope for mLock
4268 Mutex::Autolock _l(mLock);
4269 checkForNewParameters_l();
4270 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4271 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004272 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004273 mStandby = true;
4274 }
4275
4276 if (exitPending()) break;
4277
Eric Laurentfeb0db62011-07-22 09:04:31 -07004278 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004279 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280 // go to sleep
4281 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004282 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004283 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284 continue;
4285 }
4286 if (mActiveTrack != 0) {
4287 if (mActiveTrack->mState == TrackBase::PAUSING) {
4288 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004289 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290 mStandby = true;
4291 }
4292 mActiveTrack.clear();
4293 mStartStopCond.broadcast();
4294 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4295 if (mReqChannelCount != mActiveTrack->channelCount()) {
4296 mActiveTrack.clear();
4297 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();
4307 }
4308 mStandby = false;
4309 }
4310 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004311 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312 }
4313
4314 if (mActiveTrack != 0) {
4315 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4316 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004317 unlockEffectChains(effectChains);
4318 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319 continue;
4320 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004321 for (size_t i = 0; i < effectChains.size(); i ++) {
4322 effectChains[i]->process_l();
4323 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004324
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004326 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004327 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004328 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -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;
4339 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004340 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -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) {
4359 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004360 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004361 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004362 framesOut = 0;
4363 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004364 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004365 mRsmpInIndex = 0;
4366 }
4367 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004368 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004369 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4370 // Force input into standby so that it tries to
4371 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004372 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004373 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004374 }
4375 mRsmpInIndex = mFrameCount;
4376 framesOut = 0;
4377 buffer.frameCount = 0;
4378 }
4379 }
4380 }
4381 } else {
4382 // resampling
4383
4384 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 Kasten3b21c502011-12-15 09:52:39 -08004393 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -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 Kasten3b21c502011-12-15 09:52:39 -08004402 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004403 }
4404
4405 }
4406 mActiveTrack->releaseBuffer(&buffer);
4407 mActiveTrack->overflow();
4408 }
4409 // client isn't retrieving buffers fast enough
4410 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004411 if (!mActiveTrack->setOverflow()) {
4412 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004413 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004414 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004415 lastWarning = now;
4416 }
4417 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004418 // 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 Laurent7c7f10b2011-06-17 21:29:58 -07004421 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422 }
4423 }
Eric Laurentec437d82011-07-26 20:54:46 -07004424 // enable changes in effect chain
4425 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004426 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004427 }
4428
4429 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004430 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004431 }
4432 mActiveTrack.clear();
4433
4434 mStartStopCond.broadcast();
4435
Eric Laurentfeb0db62011-07-22 09:04:31 -07004436 releaseWakeLock();
4437
Steve Block3856b092011-10-20 11:56:00 +01004438 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439 return false;
4440}
4441
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004442
4443sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4444 const sp<AudioFlinger::Client>& client,
4445 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004446 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004447 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) {
Steve Block29357bc2012-01-06 19:20:56 +00004458 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004459 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
Glenn Kasten7378ca52012-01-20 13:44:40 -08004468 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004469 lStatus = NO_MEMORY;
4470 goto Exit;
4471 }
4472
4473 mTrack = track.get();
Eric Laurent59bd0da2011-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 Laurentbee53372011-08-29 12:42:48 -07004476 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004477 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4478 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004479 }
4480 lStatus = NO_ERROR;
4481
4482Exit:
4483 if (status) {
4484 *status = lStatus;
4485 }
4486 return track;
4487}
4488
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4490{
Steve Block3856b092011-10-20 11:56:00 +01004491 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004492 sp <ThreadBase> strongMe = this;
4493 status_t status = NO_ERROR;
4494 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004495 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496 if (mActiveTrack != 0) {
4497 if (recordTrack != mActiveTrack.get()) {
4498 status = -EBUSY;
4499 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4500 mActiveTrack->mState = TrackBase::ACTIVE;
4501 }
4502 return status;
4503 }
4504
4505 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 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 mRsmpInIndex = mFrameCount;
4515 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004516 if (mResampler != NULL) {
4517 mResampler->reset();
4518 }
4519 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004520 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004521 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522 mWaitWorkCV.signal();
4523 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08004524 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004525 mActiveTrack.clear();
4526 status = INVALID_OPERATION;
4527 goto startError;
4528 }
4529 mStartStopCond.wait(mLock);
4530 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004531 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 status = BAD_VALUE;
4533 goto startError;
4534 }
Steve Block3856b092011-10-20 11:56:00 +01004535 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004536 return status;
4537 }
4538startError:
4539 AudioSystem::stopInput(mId);
4540 return status;
4541}
4542
4543void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004544 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004545 sp <ThreadBase> strongMe = this;
4546 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004547 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4549 mActiveTrack->mState = TrackBase::PAUSING;
4550 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08004551 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004552 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 Block3856b092011-10-20 11:56:00 +01004560 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561 }
4562 }
4563 }
4564}
4565
4566status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4567{
4568 const size_t SIZE = 256;
4569 char buffer[SIZE];
4570 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004571
4572 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4573 result.append(buffer);
4574
4575 if (mActiveTrack != 0) {
4576 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004577 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578 mActiveTrack->dump(buffer, SIZE);
4579 result.append(buffer);
4580
4581 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4582 result.append(buffer);
4583 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4584 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004585 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586 result.append(buffer);
4587 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4588 result.append(buffer);
4589 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4590 result.append(buffer);
4591
4592
4593 } else {
4594 result.append("No record client\n");
4595 }
4596 write(fd, result.string(), result.size());
4597
4598 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004599 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004600
4601 return NO_ERROR;
4602}
4603
4604status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4605{
4606 size_t framesReq = buffer->frameCount;
4607 size_t framesReady = mFrameCount - mRsmpInIndex;
4608 int channelCount;
4609
4610 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004611 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004612 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004613 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004614 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4615 // Force input into standby so that it tries to
4616 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004617 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004618 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004620 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621 buffer->frameCount = 0;
4622 return NOT_ENOUGH_DATA;
4623 }
4624 mRsmpInIndex = 0;
4625 framesReady = mFrameCount;
4626 }
4627
4628 if (framesReq > framesReady) {
4629 framesReq = framesReady;
4630 }
4631
4632 if (mChannelCount == 1 && mReqChannelCount == 2) {
4633 channelCount = 1;
4634 } else {
4635 channelCount = 2;
4636 }
4637 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4638 buffer->frameCount = framesReq;
4639 return NO_ERROR;
4640}
4641
4642void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4643{
4644 mRsmpInIndex += buffer->frameCount;
4645 buffer->frameCount = 0;
4646}
4647
4648bool AudioFlinger::RecordThread::checkForNewParameters_l()
4649{
4650 bool reconfig = false;
4651
4652 while (!mNewParameters.isEmpty()) {
4653 status_t status = NO_ERROR;
4654 String8 keyValuePair = mNewParameters[0];
4655 AudioParameter param = AudioParameter(keyValuePair);
4656 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004657 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004658 int reqSamplingRate = mReqSampleRate;
4659 int reqChannelCount = mReqChannelCount;
4660
4661 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4662 reqSamplingRate = value;
4663 reconfig = true;
4664 }
4665 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004666 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004667 reconfig = true;
4668 }
4669 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004670 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004671 reconfig = true;
4672 }
4673 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4674 // do not accept frame count changes if tracks are open as the track buffer
4675 // size depends on frame count and correct behavior would not be garantied
4676 // if frame count is changed after track creation
4677 if (mActiveTrack != 0) {
4678 status = INVALID_OPERATION;
4679 } else {
4680 reconfig = true;
4681 }
4682 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004683 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4684 // forward device change to effects that have requested to be
4685 // aware of attached audio device.
4686 for (size_t i = 0; i < mEffectChains.size(); i++) {
4687 mEffectChains[i]->setDevice_l(value);
4688 }
4689 // store input device and output device but do not forward output device to audio HAL.
4690 // Note that status is ignored by the caller for output device
4691 // (see AudioFlinger::setParameters()
4692 if (value & AUDIO_DEVICE_OUT_ALL) {
4693 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4694 status = BAD_VALUE;
4695 } else {
4696 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004697 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4698 if (mTrack != NULL) {
4699 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004700 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004701 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4702 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4703 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004704 }
4705 mDevice |= (uint32_t)value;
4706 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004707 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004708 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004709 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004710 mInput->stream->common.standby(&mInput->stream->common);
4711 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004712 }
4713 if (reconfig) {
4714 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004715 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004716 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004717 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4718 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004719 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004720 status = NO_ERROR;
4721 }
4722 if (status == NO_ERROR) {
4723 readInputParameters();
4724 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4725 }
4726 }
4727 }
4728
4729 mNewParameters.removeAt(0);
4730
4731 mParamStatus = status;
4732 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004733 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4734 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004735 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004736 }
4737 return reconfig;
4738}
4739
4740String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4741{
Dima Zavinfce7a472011-04-19 22:30:36 -07004742 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004743 String8 out_s8 = String8();
4744
4745 Mutex::Autolock _l(mLock);
4746 if (initCheck() != NO_ERROR) {
4747 return out_s8;
4748 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004749
Dima Zavin799a70e2011-04-18 16:57:27 -07004750 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004751 out_s8 = String8(s);
4752 free(s);
4753 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004754}
4755
4756void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4757 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08004758 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004759
4760 switch (event) {
4761 case AudioSystem::INPUT_OPENED:
4762 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004763 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004764 desc.samplingRate = mSampleRate;
4765 desc.format = mFormat;
4766 desc.frameCount = mFrameCount;
4767 desc.latency = 0;
4768 param2 = &desc;
4769 break;
4770
4771 case AudioSystem::INPUT_CLOSED:
4772 default:
4773 break;
4774 }
4775 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4776}
4777
4778void AudioFlinger::RecordThread::readInputParameters()
4779{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004780 delete mRsmpInBuffer;
4781 // mRsmpInBuffer is always assigned a new[] below
4782 delete mRsmpOutBuffer;
4783 mRsmpOutBuffer = NULL;
4784 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004785 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004786
Dima Zavin799a70e2011-04-18 16:57:27 -07004787 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004788 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4789 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004790 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004791 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004792 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004793 mFrameCount = mInputBytes / mFrameSize;
4794 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4795
4796 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4797 {
4798 int channelCount;
4799 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4800 // stereo to mono post process as the resampler always outputs stereo.
4801 if (mChannelCount == 1 && mReqChannelCount == 2) {
4802 channelCount = 1;
4803 } else {
4804 channelCount = 2;
4805 }
4806 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4807 mResampler->setSampleRate(mSampleRate);
4808 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4809 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4810
4811 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4812 if (mChannelCount == 1 && mReqChannelCount == 1) {
4813 mFrameCount >>= 1;
4814 }
4815
4816 }
4817 mRsmpInIndex = mFrameCount;
4818}
4819
4820unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4821{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004822 Mutex::Autolock _l(mLock);
4823 if (initCheck() != NO_ERROR) {
4824 return 0;
4825 }
4826
Dima Zavin799a70e2011-04-18 16:57:27 -07004827 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004828}
4829
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004830uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4831{
4832 Mutex::Autolock _l(mLock);
4833 uint32_t result = 0;
4834 if (getEffectChain_l(sessionId) != 0) {
4835 result = EFFECT_SESSION;
4836 }
4837
4838 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4839 result |= TRACK_SESSION;
4840 }
4841
4842 return result;
4843}
4844
Eric Laurent59bd0da2011-08-01 09:52:20 -07004845AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4846{
4847 Mutex::Autolock _l(mLock);
4848 return mTrack;
4849}
4850
Glenn Kastenaed850d2012-01-26 09:46:34 -08004851AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004852{
4853 Mutex::Autolock _l(mLock);
4854 return mInput;
4855}
4856
4857AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4858{
4859 Mutex::Autolock _l(mLock);
4860 AudioStreamIn *input = mInput;
4861 mInput = NULL;
4862 return input;
4863}
4864
4865// this method must always be called either with ThreadBase mLock held or inside the thread loop
4866audio_stream_t* AudioFlinger::RecordThread::stream()
4867{
4868 if (mInput == NULL) {
4869 return NULL;
4870 }
4871 return &mInput->stream->common;
4872}
4873
4874
Mathias Agopian65ab4712010-07-14 17:59:35 -07004875// ----------------------------------------------------------------------------
4876
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004877audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004878 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004879 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004880 uint32_t *pChannels,
4881 uint32_t *pLatencyMs,
4882 uint32_t flags)
4883{
4884 status_t status;
4885 PlaybackThread *thread = NULL;
4886 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4887 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004888 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004889 uint32_t channels = pChannels ? *pChannels : 0;
4890 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004891 audio_stream_out_t *outStream;
4892 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004893
Steve Block3856b092011-10-20 11:56:00 +01004894 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004895 pDevices ? *pDevices : 0,
4896 samplingRate,
4897 format,
4898 channels,
4899 flags);
4900
4901 if (pDevices == NULL || *pDevices == 0) {
4902 return 0;
4903 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004904
Mathias Agopian65ab4712010-07-14 17:59:35 -07004905 Mutex::Autolock _l(mLock);
4906
Dima Zavin799a70e2011-04-18 16:57:27 -07004907 outHwDev = findSuitableHwDev_l(*pDevices);
4908 if (outHwDev == NULL)
4909 return 0;
4910
Glenn Kasten58f30212012-01-12 12:27:51 -08004911 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004912 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004913 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004914 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004915 samplingRate,
4916 format,
4917 channels,
4918 status);
4919
4920 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004921 if (outStream != NULL) {
4922 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004923 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004924
Dima Zavinfce7a472011-04-19 22:30:36 -07004925 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4926 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4927 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004928 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004929 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004930 } else {
4931 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004932 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004933 }
4934 mPlaybackThreads.add(id, thread);
4935
Glenn Kastena0d68332012-01-27 16:47:15 -08004936 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4937 if (pFormat != NULL) *pFormat = format;
4938 if (pChannels != NULL) *pChannels = channels;
4939 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004940
4941 // notify client processes of the new output creation
4942 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4943 return id;
4944 }
4945
4946 return 0;
4947}
4948
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004949audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
4950 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004951{
4952 Mutex::Autolock _l(mLock);
4953 MixerThread *thread1 = checkMixerThread_l(output1);
4954 MixerThread *thread2 = checkMixerThread_l(output2);
4955
4956 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004957 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004958 return 0;
4959 }
4960
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004961 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004962 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4963 thread->addOutputTrack(thread2);
4964 mPlaybackThreads.add(id, thread);
4965 // notify client processes of the new output creation
4966 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4967 return id;
4968}
4969
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004970status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004971{
4972 // keep strong reference on the playback thread so that
4973 // it is not destroyed while exit() is executed
4974 sp <PlaybackThread> thread;
4975 {
4976 Mutex::Autolock _l(mLock);
4977 thread = checkPlaybackThread_l(output);
4978 if (thread == NULL) {
4979 return BAD_VALUE;
4980 }
4981
Steve Block3856b092011-10-20 11:56:00 +01004982 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004983
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004984 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004985 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004986 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4988 dupThread->removeOutputTrack((MixerThread *)thread.get());
4989 }
4990 }
4991 }
Glenn Kastena0d68332012-01-27 16:47:15 -08004992 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4994 mPlaybackThreads.removeItem(output);
4995 }
4996 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08004997 // The thread entity (active unit of execution) is no longer running here,
4998 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004999
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005000 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005001 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005002 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005003 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005004 out->hwDev->close_output_stream(out->hwDev, out->stream);
5005 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005006 }
5007 return NO_ERROR;
5008}
5009
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005010status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005011{
5012 Mutex::Autolock _l(mLock);
5013 PlaybackThread *thread = checkPlaybackThread_l(output);
5014
5015 if (thread == NULL) {
5016 return BAD_VALUE;
5017 }
5018
Steve Block3856b092011-10-20 11:56:00 +01005019 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005020 thread->suspend();
5021
5022 return NO_ERROR;
5023}
5024
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005025status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005026{
5027 Mutex::Autolock _l(mLock);
5028 PlaybackThread *thread = checkPlaybackThread_l(output);
5029
5030 if (thread == NULL) {
5031 return BAD_VALUE;
5032 }
5033
Steve Block3856b092011-10-20 11:56:00 +01005034 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005035
5036 thread->restore();
5037
5038 return NO_ERROR;
5039}
5040
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005041audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005042 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005043 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005044 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005045 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005046{
5047 status_t status;
5048 RecordThread *thread = NULL;
5049 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005050 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005051 uint32_t channels = pChannels ? *pChannels : 0;
5052 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005053 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005054 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005055 audio_stream_in_t *inStream;
5056 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005057
5058 if (pDevices == NULL || *pDevices == 0) {
5059 return 0;
5060 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005061
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062 Mutex::Autolock _l(mLock);
5063
Dima Zavin799a70e2011-04-18 16:57:27 -07005064 inHwDev = findSuitableHwDev_l(*pDevices);
5065 if (inHwDev == NULL)
5066 return 0;
5067
Glenn Kasten58f30212012-01-12 12:27:51 -08005068 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005069 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005070 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005071 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005072 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005073 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005074 samplingRate,
5075 format,
5076 channels,
5077 acoustics,
5078 status);
5079
5080 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5081 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5082 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005083 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005084 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005085 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005086 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005087 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005088 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005089 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005090 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005091 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005092 }
5093
Dima Zavin799a70e2011-04-18 16:57:27 -07005094 if (inStream != NULL) {
5095 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5096
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005097 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005098 // Start record thread
5099 // RecorThread require both input and output device indication to forward to audio
5100 // pre processing modules
5101 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5102 thread = new RecordThread(this,
5103 input,
5104 reqSamplingRate,
5105 reqChannels,
5106 id,
5107 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005108 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005109 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005110 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5111 if (pFormat != NULL) *pFormat = format;
5112 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005113
Dima Zavin799a70e2011-04-18 16:57:27 -07005114 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005115
5116 // notify client processes of the new input creation
5117 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5118 return id;
5119 }
5120
5121 return 0;
5122}
5123
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005124status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125{
5126 // keep strong reference on the record thread so that
5127 // it is not destroyed while exit() is executed
5128 sp <RecordThread> thread;
5129 {
5130 Mutex::Autolock _l(mLock);
5131 thread = checkRecordThread_l(input);
5132 if (thread == NULL) {
5133 return BAD_VALUE;
5134 }
5135
Steve Block3856b092011-10-20 11:56:00 +01005136 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005137 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5139 mRecordThreads.removeItem(input);
5140 }
5141 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005142 // The thread entity (active unit of execution) is no longer running here,
5143 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005144
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005145 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005146 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005147 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005148 in->hwDev->close_input_stream(in->hwDev, in->stream);
5149 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005150
5151 return NO_ERROR;
5152}
5153
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005154status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005155{
5156 Mutex::Autolock _l(mLock);
5157 MixerThread *dstThread = checkMixerThread_l(output);
5158 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005159 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005160 return BAD_VALUE;
5161 }
5162
Steve Block3856b092011-10-20 11:56:00 +01005163 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5165
Eric Laurent9f6530f2011-08-30 10:18:54 -07005166 dstThread->setStreamValid(stream, true);
5167
Mathias Agopian65ab4712010-07-14 17:59:35 -07005168 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5169 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5170 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005171 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005173 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175 }
Eric Laurentde070132010-07-13 04:45:46 -07005176 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005177
5178 return NO_ERROR;
5179}
5180
5181
5182int AudioFlinger::newAudioSessionId()
5183{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005184 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005185}
5186
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005187void AudioFlinger::acquireAudioSessionId(int audioSession)
5188{
5189 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005190 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005191 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005192 int num = mAudioSessionRefs.size();
5193 for (int i = 0; i< num; i++) {
5194 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5195 if (ref->sessionid == audioSession && ref->pid == caller) {
5196 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005197 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005198 return;
5199 }
5200 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005201 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5202 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005203}
5204
5205void AudioFlinger::releaseAudioSessionId(int audioSession)
5206{
5207 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005208 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005209 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005210 int num = mAudioSessionRefs.size();
5211 for (int i = 0; i< num; i++) {
5212 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5213 if (ref->sessionid == audioSession && ref->pid == caller) {
5214 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005215 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005216 if (ref->cnt == 0) {
5217 mAudioSessionRefs.removeAt(i);
5218 delete ref;
5219 purgeStaleEffects_l();
5220 }
5221 return;
5222 }
5223 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005224 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005225}
5226
5227void AudioFlinger::purgeStaleEffects_l() {
5228
Steve Block3856b092011-10-20 11:56:00 +01005229 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005230
5231 Vector< sp<EffectChain> > chains;
5232
5233 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5234 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5235 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5236 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005237 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5238 chains.push(ec);
5239 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005240 }
5241 }
5242 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5243 sp<RecordThread> t = mRecordThreads.valueAt(i);
5244 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5245 sp<EffectChain> ec = t->mEffectChains[j];
5246 chains.push(ec);
5247 }
5248 }
5249
5250 for (size_t i = 0; i < chains.size(); i++) {
5251 sp<EffectChain> ec = chains[i];
5252 int sessionid = ec->sessionId();
5253 sp<ThreadBase> t = ec->mThread.promote();
5254 if (t == 0) {
5255 continue;
5256 }
5257 size_t numsessionrefs = mAudioSessionRefs.size();
5258 bool found = false;
5259 for (size_t k = 0; k < numsessionrefs; k++) {
5260 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5261 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005262 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005263 sessionid, ref->pid, ref->cnt);
5264 found = true;
5265 break;
5266 }
5267 }
5268 if (!found) {
5269 // remove all effects from the chain
5270 while (ec->mEffects.size()) {
5271 sp<EffectModule> effect = ec->mEffects[0];
5272 effect->unPin();
5273 Mutex::Autolock _l (t->mLock);
5274 t->removeEffect_l(effect);
5275 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5276 sp<EffectHandle> handle = effect->mHandles[j].promote();
5277 if (handle != 0) {
5278 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005279 if (handle->mHasControl && handle->mEnabled) {
5280 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5281 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005282 }
5283 }
5284 AudioSystem::unregisterEffect(effect->id());
5285 }
5286 }
5287 }
5288 return;
5289}
5290
Mathias Agopian65ab4712010-07-14 17:59:35 -07005291// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005292AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005293{
5294 PlaybackThread *thread = NULL;
5295 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5296 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5297 }
5298 return thread;
5299}
5300
5301// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005302AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005303{
5304 PlaybackThread *thread = checkPlaybackThread_l(output);
5305 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005306 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005307 thread = NULL;
5308 }
5309 }
5310 return (MixerThread *)thread;
5311}
5312
5313// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005314AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005315{
5316 RecordThread *thread = NULL;
5317 if (mRecordThreads.indexOfKey(input) >= 0) {
5318 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5319 }
5320 return thread;
5321}
5322
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005323uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005324{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005325 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005326}
5327
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005328AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5329{
5330 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5331 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005332 AudioStreamOut *output = thread->getOutput();
5333 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005334 return thread;
5335 }
5336 }
5337 return NULL;
5338}
5339
5340uint32_t AudioFlinger::primaryOutputDevice_l()
5341{
5342 PlaybackThread *thread = primaryPlaybackThread_l();
5343
5344 if (thread == NULL) {
5345 return 0;
5346 }
5347
5348 return thread->device();
5349}
5350
5351
Mathias Agopian65ab4712010-07-14 17:59:35 -07005352// ----------------------------------------------------------------------------
5353// Effect management
5354// ----------------------------------------------------------------------------
5355
5356
Glenn Kastenf587ba52012-01-26 16:25:10 -08005357status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005358{
5359 Mutex::Autolock _l(mLock);
5360 return EffectQueryNumberEffects(numEffects);
5361}
5362
Glenn Kastenf587ba52012-01-26 16:25:10 -08005363status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364{
5365 Mutex::Autolock _l(mLock);
5366 return EffectQueryEffect(index, descriptor);
5367}
5368
Glenn Kasten5e92a782012-01-30 07:40:52 -08005369status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005370 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005371{
5372 Mutex::Autolock _l(mLock);
5373 return EffectGetDescriptor(pUuid, descriptor);
5374}
5375
5376
Mathias Agopian65ab4712010-07-14 17:59:35 -07005377sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5378 effect_descriptor_t *pDesc,
5379 const sp<IEffectClient>& effectClient,
5380 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005381 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005382 int sessionId,
5383 status_t *status,
5384 int *id,
5385 int *enabled)
5386{
5387 status_t lStatus = NO_ERROR;
5388 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005390
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005391 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005392 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005393
5394 if (pDesc == NULL) {
5395 lStatus = BAD_VALUE;
5396 goto Exit;
5397 }
5398
Eric Laurent84e9a102010-09-23 16:10:16 -07005399 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005400 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005401 lStatus = PERMISSION_DENIED;
5402 goto Exit;
5403 }
5404
Dima Zavinfce7a472011-04-19 22:30:36 -07005405 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005406 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005407 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005408 lStatus = PERMISSION_DENIED;
5409 goto Exit;
5410 }
5411
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005412 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005413 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005414 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005415 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005416 lStatus = BAD_VALUE;
5417 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005418 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005419 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005420 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005421 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005422 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005423 }
5424 }
5425
Mathias Agopian65ab4712010-07-14 17:59:35 -07005426 {
5427 Mutex::Autolock _l(mLock);
5428
Mathias Agopian65ab4712010-07-14 17:59:35 -07005429
5430 if (!EffectIsNullUuid(&pDesc->uuid)) {
5431 // if uuid is specified, request effect descriptor
5432 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5433 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005434 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435 goto Exit;
5436 }
5437 } else {
5438 // if uuid is not specified, look for an available implementation
5439 // of the required type in effect factory
5440 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005441 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442 lStatus = BAD_VALUE;
5443 goto Exit;
5444 }
5445 uint32_t numEffects = 0;
5446 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005447 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448 bool found = false;
5449
5450 lStatus = EffectQueryNumberEffects(&numEffects);
5451 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005452 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453 goto Exit;
5454 }
5455 for (uint32_t i = 0; i < numEffects; i++) {
5456 lStatus = EffectQueryEffect(i, &desc);
5457 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005458 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 continue;
5460 }
5461 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5462 // If matching type found save effect descriptor. If the session is
5463 // 0 and the effect is not auxiliary, continue enumeration in case
5464 // an auxiliary version of this effect type is available
5465 found = true;
5466 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005467 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5469 break;
5470 }
5471 }
5472 }
5473 if (!found) {
5474 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005475 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 goto Exit;
5477 }
5478 // For same effect type, chose auxiliary version over insert version if
5479 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005480 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5482 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5483 }
5484 }
5485
5486 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005487 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005488 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5489 lStatus = INVALID_OPERATION;
5490 goto Exit;
5491 }
5492
Eric Laurent59255e42011-07-27 19:49:51 -07005493 // check recording permission for visualizer
5494 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5495 !recordingAllowed()) {
5496 lStatus = PERMISSION_DENIED;
5497 goto Exit;
5498 }
5499
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500 // return effect descriptor
5501 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5502
5503 // If output is not specified try to find a matching audio session ID in one of the
5504 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005505 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5506 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005507 // Note: io is never 0 when creating an effect on an input
5508 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005509 // look for the thread where the specified audio session is present
5510 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5511 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005512 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005513 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005515 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005516 if (io == 0) {
5517 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5518 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5519 io = mRecordThreads.keyAt(i);
5520 break;
5521 }
5522 }
5523 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005524 // If no output thread contains the requested session ID, default to
5525 // first output. The effect chain will be moved to the correct output
5526 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005527 if (io == 0 && mPlaybackThreads.size()) {
5528 io = mPlaybackThreads.keyAt(0);
5529 }
Steve Block3856b092011-10-20 11:56:00 +01005530 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005531 }
5532 ThreadBase *thread = checkRecordThread_l(io);
5533 if (thread == NULL) {
5534 thread = checkPlaybackThread_l(io);
5535 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005536 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005537 lStatus = BAD_VALUE;
5538 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005539 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005541
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005542 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005543
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005544 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005545 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5546 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 if (handle != 0 && id != NULL) {
5548 *id = handle->id();
5549 }
5550 }
5551
5552Exit:
5553 if(status) {
5554 *status = lStatus;
5555 }
5556 return handle;
5557}
5558
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005559status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
5560 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005561{
Steve Block3856b092011-10-20 11:56:00 +01005562 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005563 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005564 Mutex::Autolock _l(mLock);
5565 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005566 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005567 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005568 }
Eric Laurentde070132010-07-13 04:45:46 -07005569 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5570 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005571 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005572 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005573 }
Eric Laurentde070132010-07-13 04:45:46 -07005574 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5575 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005576 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005577 return BAD_VALUE;
5578 }
5579
5580 Mutex::Autolock _dl(dstThread->mLock);
5581 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005582 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005583
Mathias Agopian65ab4712010-07-14 17:59:35 -07005584 return NO_ERROR;
5585}
5586
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005587// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005588status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005589 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005590 AudioFlinger::PlaybackThread *dstThread,
5591 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005592{
Steve Block3856b092011-10-20 11:56:00 +01005593 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005594 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005595
Eric Laurent59255e42011-07-27 19:49:51 -07005596 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005597 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005598 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005599 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005600 return INVALID_OPERATION;
5601 }
5602
Eric Laurent39e94f82010-07-28 01:32:47 -07005603 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005604 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005605 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005606 // removed.
5607 srcThread->removeEffectChain_l(chain);
5608
5609 // transfer all effects one by one so that new effect chain is created on new thread with
5610 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005611 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07005612 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005613 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005614 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5615 while (effect != 0) {
5616 srcThread->removeEffect_l(effect);
5617 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005618 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5619 if (effect->state() == EffectModule::ACTIVE ||
5620 effect->state() == EffectModule::STOPPING) {
5621 effect->start();
5622 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005623 // if the move request is not received from audio policy manager, the effect must be
5624 // re-registered with the new strategy and output
5625 if (dstChain == 0) {
5626 dstChain = effect->chain().promote();
5627 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005628 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005629 srcThread->addEffect_l(effect);
5630 return NO_INIT;
5631 }
5632 strategy = dstChain->strategy();
5633 }
5634 if (reRegister) {
5635 AudioSystem::unregisterEffect(effect->id());
5636 AudioSystem::registerEffect(&effect->desc(),
5637 dstOutput,
5638 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005639 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005640 effect->id());
5641 }
Eric Laurentde070132010-07-13 04:45:46 -07005642 effect = chain->getEffectFromId_l(0);
5643 }
5644
5645 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005646}
5647
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005648
Mathias Agopian65ab4712010-07-14 17:59:35 -07005649// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005650sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005651 const sp<AudioFlinger::Client>& client,
5652 const sp<IEffectClient>& effectClient,
5653 int32_t priority,
5654 int sessionId,
5655 effect_descriptor_t *desc,
5656 int *enabled,
5657 status_t *status
5658 )
5659{
5660 sp<EffectModule> effect;
5661 sp<EffectHandle> handle;
5662 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005664 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005665 bool effectCreated = false;
5666 bool effectRegistered = false;
5667
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005668 lStatus = initCheck();
5669 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005670 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005671 goto Exit;
5672 }
5673
5674 // Do not allow effects with session ID 0 on direct output or duplicating threads
5675 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005676 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005677 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005678 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005679 lStatus = BAD_VALUE;
5680 goto Exit;
5681 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005682 // Only Pre processor effects are allowed on input threads and only on input threads
5683 if ((mType == RECORD &&
5684 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5685 (mType != RECORD &&
5686 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005687 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005688 desc->name, desc->flags, mType);
5689 lStatus = BAD_VALUE;
5690 goto Exit;
5691 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692
Steve Block3856b092011-10-20 11:56:00 +01005693 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694
5695 { // scope for mLock
5696 Mutex::Autolock _l(mLock);
5697
5698 // check for existing effect chain with the requested audio session
5699 chain = getEffectChain_l(sessionId);
5700 if (chain == 0) {
5701 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005702 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703 chain = new EffectChain(this, sessionId);
5704 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005705 chain->setStrategy(getStrategyForSession_l(sessionId));
5706 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005708 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709 }
5710
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005711 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005712
5713 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005714 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005716 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717 if (lStatus != NO_ERROR) {
5718 goto Exit;
5719 }
5720 effectRegistered = true;
5721 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005722 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723 lStatus = effect->status();
5724 if (lStatus != NO_ERROR) {
5725 goto Exit;
5726 }
Eric Laurentcab11242010-07-15 12:50:15 -07005727 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005728 if (lStatus != NO_ERROR) {
5729 goto Exit;
5730 }
5731 effectCreated = true;
5732
5733 effect->setDevice(mDevice);
5734 effect->setMode(mAudioFlinger->getMode());
5735 }
5736 // create effect handle and connect it to effect module
5737 handle = new EffectHandle(effect, client, effectClient, priority);
5738 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08005739 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005740 *enabled = (int)effect->isEnabled();
5741 }
5742 }
5743
5744Exit:
5745 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005746 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005747 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005748 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005749 }
5750 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005751 AudioSystem::unregisterEffect(effect->id());
5752 }
5753 if (chainCreated) {
5754 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005755 }
5756 handle.clear();
5757 }
5758
5759 if(status) {
5760 *status = lStatus;
5761 }
5762 return handle;
5763}
5764
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005765sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5766{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005767 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08005768 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005769}
5770
Eric Laurentde070132010-07-13 04:45:46 -07005771// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5772// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005773status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005774{
5775 // check for existing effect chain with the requested audio session
5776 int sessionId = effect->sessionId();
5777 sp<EffectChain> chain = getEffectChain_l(sessionId);
5778 bool chainCreated = false;
5779
5780 if (chain == 0) {
5781 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005782 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005783 chain = new EffectChain(this, sessionId);
5784 addEffectChain_l(chain);
5785 chain->setStrategy(getStrategyForSession_l(sessionId));
5786 chainCreated = true;
5787 }
Steve Block3856b092011-10-20 11:56:00 +01005788 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005789
5790 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005791 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005792 this, effect->desc().name, chain.get());
5793 return BAD_VALUE;
5794 }
5795
5796 status_t status = chain->addEffect_l(effect);
5797 if (status != NO_ERROR) {
5798 if (chainCreated) {
5799 removeEffectChain_l(chain);
5800 }
5801 return status;
5802 }
5803
5804 effect->setDevice(mDevice);
5805 effect->setMode(mAudioFlinger->getMode());
5806 return NO_ERROR;
5807}
5808
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005809void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005810
Steve Block3856b092011-10-20 11:56:00 +01005811 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005812 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005813 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5814 detachAuxEffect_l(effect->id());
5815 }
5816
5817 sp<EffectChain> chain = effect->chain().promote();
5818 if (chain != 0) {
5819 // remove effect chain if removing last effect
5820 if (chain->removeEffect_l(effect) == 0) {
5821 removeEffectChain_l(chain);
5822 }
5823 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005824 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005825 }
5826}
5827
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005828void AudioFlinger::ThreadBase::lockEffectChains_l(
5829 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5830{
5831 effectChains = mEffectChains;
5832 for (size_t i = 0; i < mEffectChains.size(); i++) {
5833 mEffectChains[i]->lock();
5834 }
5835}
5836
5837void AudioFlinger::ThreadBase::unlockEffectChains(
5838 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5839{
5840 for (size_t i = 0; i < effectChains.size(); i++) {
5841 effectChains[i]->unlock();
5842 }
5843}
5844
5845sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5846{
5847 Mutex::Autolock _l(mLock);
5848 return getEffectChain_l(sessionId);
5849}
5850
5851sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5852{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005853 size_t size = mEffectChains.size();
5854 for (size_t i = 0; i < size; i++) {
5855 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08005856 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005857 }
5858 }
Glenn Kasten090f0192012-01-30 13:00:02 -08005859 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005860}
5861
Glenn Kastenf78aee72012-01-04 11:00:47 -08005862void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005863{
5864 Mutex::Autolock _l(mLock);
5865 size_t size = mEffectChains.size();
5866 for (size_t i = 0; i < size; i++) {
5867 mEffectChains[i]->setMode_l(mode);
5868 }
5869}
5870
5871void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005872 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08005873 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005874
Mathias Agopian65ab4712010-07-14 17:59:35 -07005875 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005876 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005877 // delete the effect module if removing last handle on it
5878 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08005879 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005880 removeEffect_l(effect);
5881 AudioSystem::unregisterEffect(effect->id());
5882 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005883 }
5884}
5885
5886status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5887{
5888 int session = chain->sessionId();
5889 int16_t *buffer = mMixBuffer;
5890 bool ownsBuffer = false;
5891
Steve Block3856b092011-10-20 11:56:00 +01005892 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005893 if (session > 0) {
5894 // Only one effect chain can be present in direct output thread and it uses
5895 // the mix buffer as input
5896 if (mType != DIRECT) {
5897 size_t numSamples = mFrameCount * mChannelCount;
5898 buffer = new int16_t[numSamples];
5899 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005900 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005901 ownsBuffer = true;
5902 }
5903
5904 // Attach all tracks with same session ID to this chain.
5905 for (size_t i = 0; i < mTracks.size(); ++i) {
5906 sp<Track> track = mTracks[i];
5907 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005908 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005909 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005910 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005911 }
5912 }
5913
5914 // indicate all active tracks in the chain
5915 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5916 sp<Track> track = mActiveTracks[i].promote();
5917 if (track == 0) continue;
5918 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005919 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005920 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005921 }
5922 }
5923 }
5924
5925 chain->setInBuffer(buffer, ownsBuffer);
5926 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005927 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005928 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005929 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5930 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005932 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5933 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005934 // Effect chain for other sessions are inserted at beginning of effect
5935 // chains list to be processed before output mix effects. Relative order between other
5936 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937 size_t size = mEffectChains.size();
5938 size_t i = 0;
5939 for (i = 0; i < size; i++) {
5940 if (mEffectChains[i]->sessionId() < session) break;
5941 }
5942 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005943 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005944
5945 return NO_ERROR;
5946}
5947
5948size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5949{
5950 int session = chain->sessionId();
5951
Steve Block3856b092011-10-20 11:56:00 +01005952 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953
5954 for (size_t i = 0; i < mEffectChains.size(); i++) {
5955 if (chain == mEffectChains[i]) {
5956 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005957 // detach all active tracks from the chain
5958 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5959 sp<Track> track = mActiveTracks[i].promote();
5960 if (track == 0) continue;
5961 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005962 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005963 chain.get(), session);
5964 chain->decActiveTrackCnt();
5965 }
5966 }
5967
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968 // detach all tracks with same session ID from this chain
5969 for (size_t i = 0; i < mTracks.size(); ++i) {
5970 sp<Track> track = mTracks[i];
5971 if (session == track->sessionId()) {
5972 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005973 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 }
5975 }
Eric Laurentde070132010-07-13 04:45:46 -07005976 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977 }
5978 }
5979 return mEffectChains.size();
5980}
5981
Eric Laurentde070132010-07-13 04:45:46 -07005982status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5983 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984{
5985 Mutex::Autolock _l(mLock);
5986 return attachAuxEffect_l(track, EffectId);
5987}
5988
Eric Laurentde070132010-07-13 04:45:46 -07005989status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5990 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991{
5992 status_t status = NO_ERROR;
5993
5994 if (EffectId == 0) {
5995 track->setAuxBuffer(0, NULL);
5996 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005997 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5998 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999 if (effect != 0) {
6000 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6001 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6002 } else {
6003 status = INVALID_OPERATION;
6004 }
6005 } else {
6006 status = BAD_VALUE;
6007 }
6008 }
6009 return status;
6010}
6011
6012void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6013{
6014 for (size_t i = 0; i < mTracks.size(); ++i) {
6015 sp<Track> track = mTracks[i];
6016 if (track->auxEffectId() == effectId) {
6017 attachAuxEffect_l(track, 0);
6018 }
6019 }
6020}
6021
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006022status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6023{
6024 // only one chain per input thread
6025 if (mEffectChains.size() != 0) {
6026 return INVALID_OPERATION;
6027 }
Steve Block3856b092011-10-20 11:56:00 +01006028 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006029
6030 chain->setInBuffer(NULL);
6031 chain->setOutBuffer(NULL);
6032
Eric Laurent59255e42011-07-27 19:49:51 -07006033 checkSuspendOnAddEffectChain_l(chain);
6034
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006035 mEffectChains.add(chain);
6036
6037 return NO_ERROR;
6038}
6039
6040size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6041{
Steve Block3856b092011-10-20 11:56:00 +01006042 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006043 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006044 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6045 chain.get(), mEffectChains.size(), this);
6046 if (mEffectChains.size() == 1) {
6047 mEffectChains.removeAt(0);
6048 }
6049 return 0;
6050}
6051
Mathias Agopian65ab4712010-07-14 17:59:35 -07006052// ----------------------------------------------------------------------------
6053// EffectModule implementation
6054// ----------------------------------------------------------------------------
6055
6056#undef LOG_TAG
6057#define LOG_TAG "AudioFlinger::EffectModule"
6058
6059AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6060 const wp<AudioFlinger::EffectChain>& chain,
6061 effect_descriptor_t *desc,
6062 int id,
6063 int sessionId)
6064 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006065 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006066{
Steve Block3856b092011-10-20 11:56:00 +01006067 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006068 int lStatus;
6069 sp<ThreadBase> thread = mThread.promote();
6070 if (thread == 0) {
6071 return;
6072 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006073
6074 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6075
6076 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006077 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006078
6079 if (mStatus != NO_ERROR) {
6080 return;
6081 }
6082 lStatus = init();
6083 if (lStatus < 0) {
6084 mStatus = lStatus;
6085 goto Error;
6086 }
6087
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006088 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6089 mPinned = true;
6090 }
Steve Block3856b092011-10-20 11:56:00 +01006091 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092 return;
6093Error:
6094 EffectRelease(mEffectInterface);
6095 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006096 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006097}
6098
6099AudioFlinger::EffectModule::~EffectModule()
6100{
Steve Block3856b092011-10-20 11:56:00 +01006101 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006103 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6104 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6105 sp<ThreadBase> thread = mThread.promote();
6106 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006107 audio_stream_t *stream = thread->stream();
6108 if (stream != NULL) {
6109 stream->remove_audio_effect(stream, mEffectInterface);
6110 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006111 }
6112 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113 // release effect engine
6114 EffectRelease(mEffectInterface);
6115 }
6116}
6117
Glenn Kasten435dbe62012-01-30 10:15:48 -08006118status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119{
6120 status_t status;
6121
6122 Mutex::Autolock _l(mLock);
6123 // First handle in mHandles has highest priority and controls the effect module
6124 int priority = handle->priority();
6125 size_t size = mHandles.size();
6126 sp<EffectHandle> h;
6127 size_t i;
6128 for (i = 0; i < size; i++) {
6129 h = mHandles[i].promote();
6130 if (h == 0) continue;
6131 if (h->priority() <= priority) break;
6132 }
6133 // if inserted in first place, move effect control from previous owner to this handle
6134 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006135 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006137 enabled = h->enabled();
6138 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 }
Eric Laurent59255e42011-07-27 19:49:51 -07006140 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006141 status = NO_ERROR;
6142 } else {
6143 status = ALREADY_EXISTS;
6144 }
Steve Block3856b092011-10-20 11:56:00 +01006145 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146 mHandles.insertAt(handle, i);
6147 return status;
6148}
6149
6150size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6151{
6152 Mutex::Autolock _l(mLock);
6153 size_t size = mHandles.size();
6154 size_t i;
6155 for (i = 0; i < size; i++) {
6156 if (mHandles[i] == handle) break;
6157 }
6158 if (i == size) {
6159 return size;
6160 }
Steve Block3856b092011-10-20 11:56:00 +01006161 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006162
6163 bool enabled = false;
6164 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006165 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006166 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006167 enabled = hdl->enabled();
6168 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006169 mHandles.removeAt(i);
6170 size = mHandles.size();
6171 // if removed from first place, move effect control from this handle to next in line
6172 if (i == 0 && size != 0) {
6173 sp<EffectHandle> h = mHandles[0].promote();
6174 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006175 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006176 }
6177 }
6178
Eric Laurentec437d82011-07-26 20:54:46 -07006179 // Prevent calls to process() and other functions on effect interface from now on.
6180 // The effect engine will be released by the destructor when the last strong reference on
6181 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006182 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006183 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006184 }
6185
Mathias Agopian65ab4712010-07-14 17:59:35 -07006186 return size;
6187}
6188
Eric Laurent59255e42011-07-27 19:49:51 -07006189sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6190{
6191 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006192 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006193}
6194
Glenn Kasten58123c32012-02-03 10:32:24 -08006195void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006196{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006197 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006198 // keep a strong reference on this EffectModule to avoid calling the
6199 // destructor before we exit
6200 sp<EffectModule> keep(this);
6201 {
6202 sp<ThreadBase> thread = mThread.promote();
6203 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006204 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006205 }
6206 }
6207}
6208
6209void AudioFlinger::EffectModule::updateState() {
6210 Mutex::Autolock _l(mLock);
6211
6212 switch (mState) {
6213 case RESTART:
6214 reset_l();
6215 // FALL THROUGH
6216
6217 case STARTING:
6218 // clear auxiliary effect input buffer for next accumulation
6219 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6220 memset(mConfig.inputCfg.buffer.raw,
6221 0,
6222 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6223 }
6224 start_l();
6225 mState = ACTIVE;
6226 break;
6227 case STOPPING:
6228 stop_l();
6229 mDisableWaitCnt = mMaxDisableWaitCnt;
6230 mState = STOPPED;
6231 break;
6232 case STOPPED:
6233 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6234 // turn off sequence.
6235 if (--mDisableWaitCnt == 0) {
6236 reset_l();
6237 mState = IDLE;
6238 }
6239 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006240 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006241 break;
6242 }
6243}
6244
6245void AudioFlinger::EffectModule::process()
6246{
6247 Mutex::Autolock _l(mLock);
6248
Eric Laurentec437d82011-07-26 20:54:46 -07006249 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006250 mConfig.inputCfg.buffer.raw == NULL ||
6251 mConfig.outputCfg.buffer.raw == NULL) {
6252 return;
6253 }
6254
Eric Laurent8f45bd72010-08-31 13:50:07 -07006255 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006256 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6257 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006258 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006259 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006260 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261 }
6262
6263 // do the actual processing in the effect engine
6264 int ret = (*mEffectInterface)->process(mEffectInterface,
6265 &mConfig.inputCfg.buffer,
6266 &mConfig.outputCfg.buffer);
6267
6268 // force transition to IDLE state when engine is ready
6269 if (mState == STOPPED && ret == -ENODATA) {
6270 mDisableWaitCnt = 1;
6271 }
6272
6273 // clear auxiliary effect input buffer for next accumulation
6274 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006275 memset(mConfig.inputCfg.buffer.raw, 0,
6276 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 }
6278 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006279 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6280 // If an insert effect is idle and input buffer is different from output buffer,
6281 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006283 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006284 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6285 int16_t *in = mConfig.inputCfg.buffer.s16;
6286 int16_t *out = mConfig.outputCfg.buffer.s16;
6287 for (size_t i = 0; i < frameCnt; i++) {
6288 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006290 }
6291 }
6292}
6293
6294void AudioFlinger::EffectModule::reset_l()
6295{
6296 if (mEffectInterface == NULL) {
6297 return;
6298 }
6299 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6300}
6301
6302status_t AudioFlinger::EffectModule::configure()
6303{
6304 uint32_t channels;
6305 if (mEffectInterface == NULL) {
6306 return NO_INIT;
6307 }
6308
6309 sp<ThreadBase> thread = mThread.promote();
6310 if (thread == 0) {
6311 return DEAD_OBJECT;
6312 }
6313
6314 // TODO: handle configuration of effects replacing track process
6315 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006316 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006317 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006318 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006319 }
6320
6321 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006322 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006323 } else {
6324 mConfig.inputCfg.channels = channels;
6325 }
6326 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006327 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6328 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006329 mConfig.inputCfg.samplingRate = thread->sampleRate();
6330 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6331 mConfig.inputCfg.bufferProvider.cookie = NULL;
6332 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6333 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6334 mConfig.outputCfg.bufferProvider.cookie = NULL;
6335 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6336 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6337 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6338 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006339 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006340 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006341 // - in other sessions:
6342 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6343 // other effect: overwrites output buffer: input buffer == output buffer
6344 // Auxiliary effect:
6345 // accumulates in output buffer: input buffer != output buffer
6346 // Therefore: accumulate <=> input buffer != output buffer
6347 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6348 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6349 } else {
6350 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6351 }
6352 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6353 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6354 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6355 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6356
Steve Block3856b092011-10-20 11:56:00 +01006357 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006358 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6359
Mathias Agopian65ab4712010-07-14 17:59:35 -07006360 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006361 uint32_t size = sizeof(int);
6362 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006363 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006364 sizeof(effect_config_t),
6365 &mConfig,
6366 &size,
6367 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006368 if (status == 0) {
6369 status = cmdStatus;
6370 }
6371
6372 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6373 (1000 * mConfig.outputCfg.buffer.frameCount);
6374
6375 return status;
6376}
6377
6378status_t AudioFlinger::EffectModule::init()
6379{
6380 Mutex::Autolock _l(mLock);
6381 if (mEffectInterface == NULL) {
6382 return NO_INIT;
6383 }
6384 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006385 uint32_t size = sizeof(status_t);
6386 status_t status = (*mEffectInterface)->command(mEffectInterface,
6387 EFFECT_CMD_INIT,
6388 0,
6389 NULL,
6390 &size,
6391 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006392 if (status == 0) {
6393 status = cmdStatus;
6394 }
6395 return status;
6396}
6397
Eric Laurentec35a142011-10-05 17:42:25 -07006398status_t AudioFlinger::EffectModule::start()
6399{
6400 Mutex::Autolock _l(mLock);
6401 return start_l();
6402}
6403
Mathias Agopian65ab4712010-07-14 17:59:35 -07006404status_t AudioFlinger::EffectModule::start_l()
6405{
6406 if (mEffectInterface == NULL) {
6407 return NO_INIT;
6408 }
6409 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006410 uint32_t size = sizeof(status_t);
6411 status_t status = (*mEffectInterface)->command(mEffectInterface,
6412 EFFECT_CMD_ENABLE,
6413 0,
6414 NULL,
6415 &size,
6416 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006417 if (status == 0) {
6418 status = cmdStatus;
6419 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006420 if (status == 0 &&
6421 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6422 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6423 sp<ThreadBase> thread = mThread.promote();
6424 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006425 audio_stream_t *stream = thread->stream();
6426 if (stream != NULL) {
6427 stream->add_audio_effect(stream, mEffectInterface);
6428 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006429 }
6430 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006431 return status;
6432}
6433
Eric Laurentec437d82011-07-26 20:54:46 -07006434status_t AudioFlinger::EffectModule::stop()
6435{
6436 Mutex::Autolock _l(mLock);
6437 return stop_l();
6438}
6439
Mathias Agopian65ab4712010-07-14 17:59:35 -07006440status_t AudioFlinger::EffectModule::stop_l()
6441{
6442 if (mEffectInterface == NULL) {
6443 return NO_INIT;
6444 }
6445 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006446 uint32_t size = sizeof(status_t);
6447 status_t status = (*mEffectInterface)->command(mEffectInterface,
6448 EFFECT_CMD_DISABLE,
6449 0,
6450 NULL,
6451 &size,
6452 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006453 if (status == 0) {
6454 status = cmdStatus;
6455 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006456 if (status == 0 &&
6457 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6458 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6459 sp<ThreadBase> thread = mThread.promote();
6460 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006461 audio_stream_t *stream = thread->stream();
6462 if (stream != NULL) {
6463 stream->remove_audio_effect(stream, mEffectInterface);
6464 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006465 }
6466 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006467 return status;
6468}
6469
Eric Laurent25f43952010-07-28 05:40:18 -07006470status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6471 uint32_t cmdSize,
6472 void *pCmdData,
6473 uint32_t *replySize,
6474 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006475{
6476 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006477// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006478
Eric Laurentec437d82011-07-26 20:54:46 -07006479 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006480 return NO_INIT;
6481 }
Eric Laurent25f43952010-07-28 05:40:18 -07006482 status_t status = (*mEffectInterface)->command(mEffectInterface,
6483 cmdCode,
6484 cmdSize,
6485 pCmdData,
6486 replySize,
6487 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006489 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 for (size_t i = 1; i < mHandles.size(); i++) {
6491 sp<EffectHandle> h = mHandles[i].promote();
6492 if (h != 0) {
6493 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6494 }
6495 }
6496 }
6497 return status;
6498}
6499
6500status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6501{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006502
Mathias Agopian65ab4712010-07-14 17:59:35 -07006503 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006504 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006505
6506 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006507 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6508 if (enabled && status != NO_ERROR) {
6509 return status;
6510 }
6511
Mathias Agopian65ab4712010-07-14 17:59:35 -07006512 switch (mState) {
6513 // going from disabled to enabled
6514 case IDLE:
6515 mState = STARTING;
6516 break;
6517 case STOPPED:
6518 mState = RESTART;
6519 break;
6520 case STOPPING:
6521 mState = ACTIVE;
6522 break;
6523
6524 // going from enabled to disabled
6525 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006526 mState = STOPPED;
6527 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006528 case STARTING:
6529 mState = IDLE;
6530 break;
6531 case ACTIVE:
6532 mState = STOPPING;
6533 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006534 case DESTROYED:
6535 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006536 }
6537 for (size_t i = 1; i < mHandles.size(); i++) {
6538 sp<EffectHandle> h = mHandles[i].promote();
6539 if (h != 0) {
6540 h->setEnabled(enabled);
6541 }
6542 }
6543 }
6544 return NO_ERROR;
6545}
6546
Glenn Kastenc59c0042012-02-02 14:06:11 -08006547bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548{
6549 switch (mState) {
6550 case RESTART:
6551 case STARTING:
6552 case ACTIVE:
6553 return true;
6554 case IDLE:
6555 case STOPPING:
6556 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006557 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558 default:
6559 return false;
6560 }
6561}
6562
Glenn Kastenc59c0042012-02-02 14:06:11 -08006563bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07006564{
6565 switch (mState) {
6566 case RESTART:
6567 case ACTIVE:
6568 case STOPPING:
6569 case STOPPED:
6570 return true;
6571 case IDLE:
6572 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006573 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006574 default:
6575 return false;
6576 }
6577}
6578
Mathias Agopian65ab4712010-07-14 17:59:35 -07006579status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6580{
6581 Mutex::Autolock _l(mLock);
6582 status_t status = NO_ERROR;
6583
6584 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6585 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006586 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006587 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6588 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006589 status_t cmdStatus;
6590 uint32_t volume[2];
6591 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006592 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593 volume[0] = *left;
6594 volume[1] = *right;
6595 if (controller) {
6596 pVolume = volume;
6597 }
Eric Laurent25f43952010-07-28 05:40:18 -07006598 status = (*mEffectInterface)->command(mEffectInterface,
6599 EFFECT_CMD_SET_VOLUME,
6600 size,
6601 volume,
6602 &size,
6603 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006604 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6605 *left = volume[0];
6606 *right = volume[1];
6607 }
6608 }
6609 return status;
6610}
6611
6612status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6613{
6614 Mutex::Autolock _l(mLock);
6615 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006616 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6617 // audio pre processing modules on RecordThread can receive both output and
6618 // input device indication in the same call
6619 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6620 if (dev) {
6621 status_t cmdStatus;
6622 uint32_t size = sizeof(status_t);
6623
6624 status = (*mEffectInterface)->command(mEffectInterface,
6625 EFFECT_CMD_SET_DEVICE,
6626 sizeof(uint32_t),
6627 &dev,
6628 &size,
6629 &cmdStatus);
6630 if (status == NO_ERROR) {
6631 status = cmdStatus;
6632 }
6633 }
6634 dev = device & AUDIO_DEVICE_IN_ALL;
6635 if (dev) {
6636 status_t cmdStatus;
6637 uint32_t size = sizeof(status_t);
6638
6639 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6640 EFFECT_CMD_SET_INPUT_DEVICE,
6641 sizeof(uint32_t),
6642 &dev,
6643 &size,
6644 &cmdStatus);
6645 if (status2 == NO_ERROR) {
6646 status2 = cmdStatus;
6647 }
6648 if (status == NO_ERROR) {
6649 status = status2;
6650 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006651 }
6652 }
6653 return status;
6654}
6655
Glenn Kastenf78aee72012-01-04 11:00:47 -08006656status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006657{
6658 Mutex::Autolock _l(mLock);
6659 status_t status = NO_ERROR;
6660 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006661 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006662 uint32_t size = sizeof(status_t);
6663 status = (*mEffectInterface)->command(mEffectInterface,
6664 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006665 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006666 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006667 &size,
6668 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006669 if (status == NO_ERROR) {
6670 status = cmdStatus;
6671 }
6672 }
6673 return status;
6674}
6675
Eric Laurent59255e42011-07-27 19:49:51 -07006676void AudioFlinger::EffectModule::setSuspended(bool suspended)
6677{
6678 Mutex::Autolock _l(mLock);
6679 mSuspended = suspended;
6680}
Glenn Kastena3a85482012-01-04 11:01:11 -08006681
6682bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006683{
6684 Mutex::Autolock _l(mLock);
6685 return mSuspended;
6686}
6687
Mathias Agopian65ab4712010-07-14 17:59:35 -07006688status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6689{
6690 const size_t SIZE = 256;
6691 char buffer[SIZE];
6692 String8 result;
6693
6694 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6695 result.append(buffer);
6696
6697 bool locked = tryLock(mLock);
6698 // failed to lock - AudioFlinger is probably deadlocked
6699 if (!locked) {
6700 result.append("\t\tCould not lock Fx mutex:\n");
6701 }
6702
6703 result.append("\t\tSession Status State Engine:\n");
6704 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6705 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6706 result.append(buffer);
6707
6708 result.append("\t\tDescriptor:\n");
6709 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6710 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6711 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6712 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6713 result.append(buffer);
6714 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6715 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6716 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6717 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6718 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006719 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720 mDescriptor.apiVersion,
6721 mDescriptor.flags);
6722 result.append(buffer);
6723 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6724 mDescriptor.name);
6725 result.append(buffer);
6726 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6727 mDescriptor.implementor);
6728 result.append(buffer);
6729
6730 result.append("\t\t- Input configuration:\n");
6731 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6732 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6733 (uint32_t)mConfig.inputCfg.buffer.raw,
6734 mConfig.inputCfg.buffer.frameCount,
6735 mConfig.inputCfg.samplingRate,
6736 mConfig.inputCfg.channels,
6737 mConfig.inputCfg.format);
6738 result.append(buffer);
6739
6740 result.append("\t\t- Output configuration:\n");
6741 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6742 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6743 (uint32_t)mConfig.outputCfg.buffer.raw,
6744 mConfig.outputCfg.buffer.frameCount,
6745 mConfig.outputCfg.samplingRate,
6746 mConfig.outputCfg.channels,
6747 mConfig.outputCfg.format);
6748 result.append(buffer);
6749
6750 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6751 result.append(buffer);
6752 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6753 for (size_t i = 0; i < mHandles.size(); ++i) {
6754 sp<EffectHandle> handle = mHandles[i].promote();
6755 if (handle != 0) {
6756 handle->dump(buffer, SIZE);
6757 result.append(buffer);
6758 }
6759 }
6760
6761 result.append("\n");
6762
6763 write(fd, result.string(), result.length());
6764
6765 if (locked) {
6766 mLock.unlock();
6767 }
6768
6769 return NO_ERROR;
6770}
6771
6772// ----------------------------------------------------------------------------
6773// EffectHandle implementation
6774// ----------------------------------------------------------------------------
6775
6776#undef LOG_TAG
6777#define LOG_TAG "AudioFlinger::EffectHandle"
6778
6779AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6780 const sp<AudioFlinger::Client>& client,
6781 const sp<IEffectClient>& effectClient,
6782 int32_t priority)
6783 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006784 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006785 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006786{
Steve Block3856b092011-10-20 11:56:00 +01006787 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006788
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006789 if (client == 0) {
6790 return;
6791 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6793 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6794 if (mCblkMemory != 0) {
6795 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6796
Glenn Kastena0d68332012-01-27 16:47:15 -08006797 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006798 new(mCblk) effect_param_cblk_t();
6799 mBuffer = (uint8_t *)mCblk + bufOffset;
6800 }
6801 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006802 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803 return;
6804 }
6805}
6806
6807AudioFlinger::EffectHandle::~EffectHandle()
6808{
Steve Block3856b092011-10-20 11:56:00 +01006809 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006810 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006811 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006812}
6813
6814status_t AudioFlinger::EffectHandle::enable()
6815{
Steve Block3856b092011-10-20 11:56:00 +01006816 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006817 if (!mHasControl) return INVALID_OPERATION;
6818 if (mEffect == 0) return DEAD_OBJECT;
6819
Eric Laurentdb7c0792011-08-10 10:37:50 -07006820 if (mEnabled) {
6821 return NO_ERROR;
6822 }
6823
Eric Laurent59255e42011-07-27 19:49:51 -07006824 mEnabled = true;
6825
6826 sp<ThreadBase> thread = mEffect->thread().promote();
6827 if (thread != 0) {
6828 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6829 }
6830
6831 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6832 if (mEffect->suspended()) {
6833 return NO_ERROR;
6834 }
6835
Eric Laurentdb7c0792011-08-10 10:37:50 -07006836 status_t status = mEffect->setEnabled(true);
6837 if (status != NO_ERROR) {
6838 if (thread != 0) {
6839 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6840 }
6841 mEnabled = false;
6842 }
6843 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006844}
6845
6846status_t AudioFlinger::EffectHandle::disable()
6847{
Steve Block3856b092011-10-20 11:56:00 +01006848 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006849 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006850 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006851
Eric Laurentdb7c0792011-08-10 10:37:50 -07006852 if (!mEnabled) {
6853 return NO_ERROR;
6854 }
Eric Laurent59255e42011-07-27 19:49:51 -07006855 mEnabled = false;
6856
6857 if (mEffect->suspended()) {
6858 return NO_ERROR;
6859 }
6860
6861 status_t status = mEffect->setEnabled(false);
6862
6863 sp<ThreadBase> thread = mEffect->thread().promote();
6864 if (thread != 0) {
6865 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6866 }
6867
6868 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006869}
6870
6871void AudioFlinger::EffectHandle::disconnect()
6872{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006873 disconnect(true);
6874}
6875
Glenn Kasten58123c32012-02-03 10:32:24 -08006876void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006877{
Glenn Kasten58123c32012-02-03 10:32:24 -08006878 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006879 if (mEffect == 0) {
6880 return;
6881 }
Glenn Kasten58123c32012-02-03 10:32:24 -08006882 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07006883
Eric Laurenta85a74a2011-10-19 11:44:54 -07006884 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006885 sp<ThreadBase> thread = mEffect->thread().promote();
6886 if (thread != 0) {
6887 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6888 }
Eric Laurent59255e42011-07-27 19:49:51 -07006889 }
6890
Mathias Agopian65ab4712010-07-14 17:59:35 -07006891 // release sp on module => module destructor can be called now
6892 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006893 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08006894 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08006895 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006896 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6897 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08006898 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006899 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6901 mClient.clear();
6902 }
6903}
6904
Eric Laurent25f43952010-07-28 05:40:18 -07006905status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6906 uint32_t cmdSize,
6907 void *pCmdData,
6908 uint32_t *replySize,
6909 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006910{
Steve Block3856b092011-10-20 11:56:00 +01006911// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006912// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913
6914 // only get parameter command is permitted for applications not controlling the effect
6915 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6916 return INVALID_OPERATION;
6917 }
6918 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006919 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006920
6921 // handle commands that are not forwarded transparently to effect engine
6922 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6923 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6924 // no risk to block the whole media server process or mixer threads is we are stuck here
6925 Mutex::Autolock _l(mCblk->lock);
6926 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6927 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6928 mCblk->serverIndex = 0;
6929 mCblk->clientIndex = 0;
6930 return BAD_VALUE;
6931 }
6932 status_t status = NO_ERROR;
6933 while (mCblk->serverIndex < mCblk->clientIndex) {
6934 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006935 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006936 int *p = (int *)(mBuffer + mCblk->serverIndex);
6937 int size = *p++;
6938 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006939 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006940 break;
6941 }
6942 effect_param_t *param = (effect_param_t *)p;
6943 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006944 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006945 mCblk->serverIndex += size;
6946 continue;
6947 }
Eric Laurent25f43952010-07-28 05:40:18 -07006948 uint32_t psize = sizeof(effect_param_t) +
6949 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6950 param->vsize;
6951 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6952 psize,
6953 p,
6954 &rsize,
6955 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006956 // stop at first error encountered
6957 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006958 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006959 *(int *)pReplyData = reply;
6960 break;
6961 } else if (reply != NO_ERROR) {
6962 *(int *)pReplyData = reply;
6963 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964 }
6965 mCblk->serverIndex += size;
6966 }
6967 mCblk->serverIndex = 0;
6968 mCblk->clientIndex = 0;
6969 return status;
6970 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006971 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972 return enable();
6973 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006974 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006975 return disable();
6976 }
6977
6978 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6979}
6980
Eric Laurent59255e42011-07-27 19:49:51 -07006981void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982{
Steve Block3856b092011-10-20 11:56:00 +01006983 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984
6985 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07006986 mEnabled = enabled;
6987
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988 if (signal && mEffectClient != 0) {
6989 mEffectClient->controlStatusChanged(hasControl);
6990 }
6991}
6992
Eric Laurent25f43952010-07-28 05:40:18 -07006993void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6994 uint32_t cmdSize,
6995 void *pCmdData,
6996 uint32_t replySize,
6997 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998{
6999 if (mEffectClient != 0) {
7000 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7001 }
7002}
7003
7004
7005
7006void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7007{
7008 if (mEffectClient != 0) {
7009 mEffectClient->enableStatusChanged(enabled);
7010 }
7011}
7012
7013status_t AudioFlinger::EffectHandle::onTransact(
7014 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7015{
7016 return BnEffect::onTransact(code, data, reply, flags);
7017}
7018
7019
7020void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7021{
Glenn Kastena0d68332012-01-27 16:47:15 -08007022 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007023
7024 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08007025 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007026 mPriority,
7027 mHasControl,
7028 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007029 mCblk ? mCblk->clientIndex : 0,
7030 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031 );
7032
7033 if (locked) {
7034 mCblk->lock.unlock();
7035 }
7036}
7037
7038#undef LOG_TAG
7039#define LOG_TAG "AudioFlinger::EffectChain"
7040
7041AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7042 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007043 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007044 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7045 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007046{
Dima Zavinfce7a472011-04-19 22:30:36 -07007047 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007048 sp<ThreadBase> thread = mThread.promote();
7049 if (thread == 0) {
7050 return;
7051 }
7052 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7053 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007054}
7055
7056AudioFlinger::EffectChain::~EffectChain()
7057{
7058 if (mOwnInBuffer) {
7059 delete mInBuffer;
7060 }
7061
7062}
7063
Eric Laurent59255e42011-07-27 19:49:51 -07007064// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007065sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007066{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067 size_t size = mEffects.size();
7068
7069 for (size_t i = 0; i < size; i++) {
7070 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007071 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007072 }
7073 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007074 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007075}
7076
Eric Laurent59255e42011-07-27 19:49:51 -07007077// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007078sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007079{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007080 size_t size = mEffects.size();
7081
7082 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007083 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7084 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007085 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007086 }
7087 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007088 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007089}
7090
Eric Laurent59255e42011-07-27 19:49:51 -07007091// getEffectFromType_l() must be called with ThreadBase::mLock held
7092sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7093 const effect_uuid_t *type)
7094{
Eric Laurent59255e42011-07-27 19:49:51 -07007095 size_t size = mEffects.size();
7096
7097 for (size_t i = 0; i < size; i++) {
7098 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007099 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007100 }
7101 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007102 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007103}
7104
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105// Must be called with EffectChain::mLock locked
7106void AudioFlinger::EffectChain::process_l()
7107{
Eric Laurentdac69112010-09-28 14:09:57 -07007108 sp<ThreadBase> thread = mThread.promote();
7109 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007110 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007111 return;
7112 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007113 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7114 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007115 // always process effects unless no more tracks are on the session and the effect tail
7116 // has been rendered
7117 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007118 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007119 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007120
Eric Laurent544fe9b2011-11-11 15:42:52 -08007121 if (!tracksOnSession && mTailBufferCount == 0) {
7122 doProcess = false;
7123 }
7124
7125 if (activeTrackCnt() == 0) {
7126 // if no track is active and the effect tail has not been rendered,
7127 // the input buffer must be cleared here as the mixer process will not do it
7128 if (tracksOnSession || mTailBufferCount > 0) {
7129 size_t numSamples = thread->frameCount() * thread->channelCount();
7130 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7131 if (mTailBufferCount > 0) {
7132 mTailBufferCount--;
7133 }
7134 }
7135 }
Eric Laurentdac69112010-09-28 14:09:57 -07007136 }
7137
Mathias Agopian65ab4712010-07-14 17:59:35 -07007138 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007139 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007140 for (size_t i = 0; i < size; i++) {
7141 mEffects[i]->process();
7142 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007143 }
7144 for (size_t i = 0; i < size; i++) {
7145 mEffects[i]->updateState();
7146 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007147}
7148
Eric Laurentcab11242010-07-15 12:50:15 -07007149// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007150status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007151{
7152 effect_descriptor_t desc = effect->desc();
7153 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7154
7155 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007156 effect->setChain(this);
7157 sp<ThreadBase> thread = mThread.promote();
7158 if (thread == 0) {
7159 return NO_INIT;
7160 }
7161 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007162
7163 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7164 // Auxiliary effects are inserted at the beginning of mEffects vector as
7165 // they are processed first and accumulated in chain input buffer
7166 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007167
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168 // the input buffer for auxiliary effect contains mono samples in
7169 // 32 bit format. This is to avoid saturation in AudoMixer
7170 // accumulation stage. Saturation is done in EffectModule::process() before
7171 // calling the process in effect engine
7172 size_t numSamples = thread->frameCount();
7173 int32_t *buffer = new int32_t[numSamples];
7174 memset(buffer, 0, numSamples * sizeof(int32_t));
7175 effect->setInBuffer((int16_t *)buffer);
7176 // auxiliary effects output samples to chain input buffer for further processing
7177 // by insert effects
7178 effect->setOutBuffer(mInBuffer);
7179 } else {
7180 // Insert effects are inserted at the end of mEffects vector as they are processed
7181 // after track and auxiliary effects.
7182 // Insert effect order as a function of indicated preference:
7183 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7184 // another effect is present
7185 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7186 // last effect claiming first position
7187 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7188 // first effect claiming last position
7189 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7190 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7191 // already present
7192
7193 int size = (int)mEffects.size();
7194 int idx_insert = size;
7195 int idx_insert_first = -1;
7196 int idx_insert_last = -1;
7197
7198 for (int i = 0; i < size; i++) {
7199 effect_descriptor_t d = mEffects[i]->desc();
7200 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7201 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7202 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7203 // check invalid effect chaining combinations
7204 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7205 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007206 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007207 return INVALID_OPERATION;
7208 }
7209 // remember position of first insert effect and by default
7210 // select this as insert position for new effect
7211 if (idx_insert == size) {
7212 idx_insert = i;
7213 }
7214 // remember position of last insert effect claiming
7215 // first position
7216 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7217 idx_insert_first = i;
7218 }
7219 // remember position of first insert effect claiming
7220 // last position
7221 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7222 idx_insert_last == -1) {
7223 idx_insert_last = i;
7224 }
7225 }
7226 }
7227
7228 // modify idx_insert from first position if needed
7229 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7230 if (idx_insert_last != -1) {
7231 idx_insert = idx_insert_last;
7232 } else {
7233 idx_insert = size;
7234 }
7235 } else {
7236 if (idx_insert_first != -1) {
7237 idx_insert = idx_insert_first + 1;
7238 }
7239 }
7240
7241 // always read samples from chain input buffer
7242 effect->setInBuffer(mInBuffer);
7243
7244 // if last effect in the chain, output samples to chain
7245 // output buffer, otherwise to chain input buffer
7246 if (idx_insert == size) {
7247 if (idx_insert != 0) {
7248 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7249 mEffects[idx_insert-1]->configure();
7250 }
7251 effect->setOutBuffer(mOutBuffer);
7252 } else {
7253 effect->setOutBuffer(mInBuffer);
7254 }
7255 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007256
Steve Block3856b092011-10-20 11:56:00 +01007257 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007258 }
7259 effect->configure();
7260 return NO_ERROR;
7261}
7262
Eric Laurentcab11242010-07-15 12:50:15 -07007263// removeEffect_l() must be called with PlaybackThread::mLock held
7264size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007265{
7266 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007267 int size = (int)mEffects.size();
7268 int i;
7269 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7270
7271 for (i = 0; i < size; i++) {
7272 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007273 // calling stop here will remove pre-processing effect from the audio HAL.
7274 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7275 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007276 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7277 mEffects[i]->state() == EffectModule::STOPPING) {
7278 mEffects[i]->stop();
7279 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007280 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7281 delete[] effect->inBuffer();
7282 } else {
7283 if (i == size - 1 && i != 0) {
7284 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7285 mEffects[i - 1]->configure();
7286 }
7287 }
7288 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007289 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007290 break;
7291 }
7292 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007293
7294 return mEffects.size();
7295}
7296
Eric Laurentcab11242010-07-15 12:50:15 -07007297// setDevice_l() must be called with PlaybackThread::mLock held
7298void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007299{
7300 size_t size = mEffects.size();
7301 for (size_t i = 0; i < size; i++) {
7302 mEffects[i]->setDevice(device);
7303 }
7304}
7305
Eric Laurentcab11242010-07-15 12:50:15 -07007306// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007307void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308{
7309 size_t size = mEffects.size();
7310 for (size_t i = 0; i < size; i++) {
7311 mEffects[i]->setMode(mode);
7312 }
7313}
7314
Eric Laurentcab11242010-07-15 12:50:15 -07007315// setVolume_l() must be called with PlaybackThread::mLock held
7316bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317{
7318 uint32_t newLeft = *left;
7319 uint32_t newRight = *right;
7320 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007321 int ctrlIdx = -1;
7322 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007323
Eric Laurentcab11242010-07-15 12:50:15 -07007324 // first update volume controller
7325 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007326 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007327 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7328 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007329 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007330 break;
7331 }
7332 }
7333
7334 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007335 if (hasControl) {
7336 *left = mNewLeftVolume;
7337 *right = mNewRightVolume;
7338 }
7339 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007340 }
7341
7342 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007343 mLeftVolume = newLeft;
7344 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007345
7346 // second get volume update from volume controller
7347 if (ctrlIdx >= 0) {
7348 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007349 mNewLeftVolume = newLeft;
7350 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007351 }
7352 // then indicate volume to all other effects in chain.
7353 // Pass altered volume to effects before volume controller
7354 // and requested volume to effects after controller
7355 uint32_t lVol = newLeft;
7356 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007357
Mathias Agopian65ab4712010-07-14 17:59:35 -07007358 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007359 if ((int)i == ctrlIdx) continue;
7360 // this also works for ctrlIdx == -1 when there is no volume controller
7361 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362 lVol = *left;
7363 rVol = *right;
7364 }
7365 mEffects[i]->setVolume(&lVol, &rVol, false);
7366 }
7367 *left = newLeft;
7368 *right = newRight;
7369
7370 return hasControl;
7371}
7372
Mathias Agopian65ab4712010-07-14 17:59:35 -07007373status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7374{
7375 const size_t SIZE = 256;
7376 char buffer[SIZE];
7377 String8 result;
7378
7379 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7380 result.append(buffer);
7381
7382 bool locked = tryLock(mLock);
7383 // failed to lock - AudioFlinger is probably deadlocked
7384 if (!locked) {
7385 result.append("\tCould not lock mutex:\n");
7386 }
7387
Eric Laurentcab11242010-07-15 12:50:15 -07007388 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7389 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390 mEffects.size(),
7391 (uint32_t)mInBuffer,
7392 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007393 mActiveTrackCnt);
7394 result.append(buffer);
7395 write(fd, result.string(), result.size());
7396
7397 for (size_t i = 0; i < mEffects.size(); ++i) {
7398 sp<EffectModule> effect = mEffects[i];
7399 if (effect != 0) {
7400 effect->dump(fd, args);
7401 }
7402 }
7403
7404 if (locked) {
7405 mLock.unlock();
7406 }
7407
7408 return NO_ERROR;
7409}
7410
Eric Laurent59255e42011-07-27 19:49:51 -07007411// must be called with ThreadBase::mLock held
7412void AudioFlinger::EffectChain::setEffectSuspended_l(
7413 const effect_uuid_t *type, bool suspend)
7414{
7415 sp<SuspendedEffectDesc> desc;
7416 // use effect type UUID timelow as key as there is no real risk of identical
7417 // timeLow fields among effect type UUIDs.
7418 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7419 if (suspend) {
7420 if (index >= 0) {
7421 desc = mSuspendedEffects.valueAt(index);
7422 } else {
7423 desc = new SuspendedEffectDesc();
7424 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7425 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007426 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007427 }
7428 if (desc->mRefCount++ == 0) {
7429 sp<EffectModule> effect = getEffectIfEnabled(type);
7430 if (effect != 0) {
7431 desc->mEffect = effect;
7432 effect->setSuspended(true);
7433 effect->setEnabled(false);
7434 }
7435 }
7436 } else {
7437 if (index < 0) {
7438 return;
7439 }
7440 desc = mSuspendedEffects.valueAt(index);
7441 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007442 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007443 desc->mRefCount = 1;
7444 }
7445 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007446 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007447 if (desc->mEffect != 0) {
7448 sp<EffectModule> effect = desc->mEffect.promote();
7449 if (effect != 0) {
7450 effect->setSuspended(false);
7451 sp<EffectHandle> handle = effect->controlHandle();
7452 if (handle != 0) {
7453 effect->setEnabled(handle->enabled());
7454 }
7455 }
7456 desc->mEffect.clear();
7457 }
7458 mSuspendedEffects.removeItemsAt(index);
7459 }
7460 }
7461}
7462
7463// must be called with ThreadBase::mLock held
7464void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7465{
7466 sp<SuspendedEffectDesc> desc;
7467
7468 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7469 if (suspend) {
7470 if (index >= 0) {
7471 desc = mSuspendedEffects.valueAt(index);
7472 } else {
7473 desc = new SuspendedEffectDesc();
7474 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007475 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007476 }
7477 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007478 Vector< sp<EffectModule> > effects;
7479 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007480 for (size_t i = 0; i < effects.size(); i++) {
7481 setEffectSuspended_l(&effects[i]->desc().type, true);
7482 }
7483 }
7484 } else {
7485 if (index < 0) {
7486 return;
7487 }
7488 desc = mSuspendedEffects.valueAt(index);
7489 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007490 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007491 desc->mRefCount = 1;
7492 }
7493 if (--desc->mRefCount == 0) {
7494 Vector<const effect_uuid_t *> types;
7495 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7496 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7497 continue;
7498 }
7499 types.add(&mSuspendedEffects.valueAt(i)->mType);
7500 }
7501 for (size_t i = 0; i < types.size(); i++) {
7502 setEffectSuspended_l(types[i], false);
7503 }
Steve Block3856b092011-10-20 11:56:00 +01007504 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007505 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7506 }
7507 }
7508}
7509
Eric Laurent6bffdb82011-09-23 08:40:41 -07007510
7511// The volume effect is used for automated tests only
7512#ifndef OPENSL_ES_H_
7513static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7514 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7515const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7516#endif //OPENSL_ES_H_
7517
Eric Laurentdb7c0792011-08-10 10:37:50 -07007518bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7519{
7520 // auxiliary effects and visualizer are never suspended on output mix
7521 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7522 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007523 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7524 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007525 return false;
7526 }
7527 return true;
7528}
7529
Glenn Kastend0539712012-01-30 12:56:03 -08007530void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007531{
Glenn Kastend0539712012-01-30 12:56:03 -08007532 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07007533 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08007534 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7535 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07007536 }
Eric Laurent59255e42011-07-27 19:49:51 -07007537 }
Eric Laurent59255e42011-07-27 19:49:51 -07007538}
7539
7540sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7541 const effect_uuid_t *type)
7542{
Glenn Kasten090f0192012-01-30 13:00:02 -08007543 sp<EffectModule> effect = getEffectFromType_l(type);
7544 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007545}
7546
7547void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7548 bool enabled)
7549{
7550 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7551 if (enabled) {
7552 if (index < 0) {
7553 // if the effect is not suspend check if all effects are suspended
7554 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7555 if (index < 0) {
7556 return;
7557 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007558 if (!isEffectEligibleForSuspend(effect->desc())) {
7559 return;
7560 }
Eric Laurent59255e42011-07-27 19:49:51 -07007561 setEffectSuspended_l(&effect->desc().type, enabled);
7562 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007563 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007564 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007565 return;
7566 }
Eric Laurent59255e42011-07-27 19:49:51 -07007567 }
Steve Block3856b092011-10-20 11:56:00 +01007568 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007569 effect->desc().type.timeLow);
7570 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7571 // if effect is requested to suspended but was not yet enabled, supend it now.
7572 if (desc->mEffect == 0) {
7573 desc->mEffect = effect;
7574 effect->setEnabled(false);
7575 effect->setSuspended(true);
7576 }
7577 } else {
7578 if (index < 0) {
7579 return;
7580 }
Steve Block3856b092011-10-20 11:56:00 +01007581 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007582 effect->desc().type.timeLow);
7583 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7584 desc->mEffect.clear();
7585 effect->setSuspended(false);
7586 }
7587}
7588
Mathias Agopian65ab4712010-07-14 17:59:35 -07007589#undef LOG_TAG
7590#define LOG_TAG "AudioFlinger"
7591
7592// ----------------------------------------------------------------------------
7593
7594status_t AudioFlinger::onTransact(
7595 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7596{
7597 return BnAudioFlinger::onTransact(code, data, reply, flags);
7598}
7599
Mathias Agopian65ab4712010-07-14 17:59:35 -07007600}; // namespace android