blob: 3545b4142fbab8e95e5359d04efebb3e36ba3414 [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 Kastene0feee32011-12-13 11:53:26 -0800163 mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurentbee53372011-08-29 12:42:48 -0700164 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700166}
167
168void AudioFlinger::onFirstRef()
169{
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700171
Eric Laurent93575202011-01-18 18:39:02 -0800172 Mutex::Autolock _l(mLock);
173
Dima Zavin799a70e2011-04-18 16:57:27 -0700174 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700175 mHardwareStatus = AUDIO_HW_IDLE;
176
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
178 const hw_module_t *mod;
179 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700180
Dima Zavin799a70e2011-04-18 16:57:27 -0700181 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
182 if (rc)
183 continue;
184
Steve Blockdf64d152012-01-04 20:05:49 +0000185 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700186 mod->name, mod->id);
187 mAudioHwDevs.push(dev);
188
189 if (!mPrimaryHardwareDev) {
190 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000191 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700192 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700193 }
194 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700195
196 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700197
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000199 ALOGE("Primary audio interface not found");
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 return;
201 }
202
203 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
204 audio_hw_device_t *dev = mAudioHwDevs[i];
205
206 mHardwareStatus = AUDIO_HW_INIT;
207 rc = dev->init_check(dev);
208 if (rc == 0) {
209 AutoMutex lock(mHardwareLock);
210
211 mMode = AUDIO_MODE_NORMAL;
212 mHardwareStatus = AUDIO_HW_SET_MODE;
213 dev->set_mode(dev, mMode);
214 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
215 dev->set_master_volume(dev, 1.0f);
216 mHardwareStatus = AUDIO_HW_IDLE;
217 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700218 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700219}
220
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700221status_t AudioFlinger::initCheck() const
222{
223 Mutex::Autolock _l(mLock);
224 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
225 return NO_INIT;
226 return NO_ERROR;
227}
228
Mathias Agopian65ab4712010-07-14 17:59:35 -0700229AudioFlinger::~AudioFlinger()
230{
Dima Zavin799a70e2011-04-18 16:57:27 -0700231 int num_devs = mAudioHwDevs.size();
232
Mathias Agopian65ab4712010-07-14 17:59:35 -0700233 while (!mRecordThreads.isEmpty()) {
234 // closeInput() will remove first entry from mRecordThreads
235 closeInput(mRecordThreads.keyAt(0));
236 }
237 while (!mPlaybackThreads.isEmpty()) {
238 // closeOutput() will remove first entry from mPlaybackThreads
239 closeOutput(mPlaybackThreads.keyAt(0));
240 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700241
242 for (int i = 0; i < num_devs; i++) {
243 audio_hw_device_t *dev = mAudioHwDevs[i];
244 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700246 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247}
248
Dima Zavin799a70e2011-04-18 16:57:27 -0700249audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
250{
251 /* first matching HW device is returned */
252 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
253 audio_hw_device_t *dev = mAudioHwDevs[i];
254 if ((dev->get_supported_devices(dev) & devices) == devices)
255 return dev;
256 }
257 return NULL;
258}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259
260status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
261{
262 const size_t SIZE = 256;
263 char buffer[SIZE];
264 String8 result;
265
266 result.append("Clients:\n");
267 for (size_t i = 0; i < mClients.size(); ++i) {
268 wp<Client> wClient = mClients.valueAt(i);
269 if (wClient != 0) {
270 sp<Client> client = wClient.promote();
271 if (client != 0) {
272 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
273 result.append(buffer);
274 }
275 }
276 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700277
278 result.append("Global session refs:\n");
279 result.append(" session pid cnt\n");
280 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
281 AudioSessionRef *r = mAudioSessionRefs[i];
282 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
283 result.append(buffer);
284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700285 write(fd, result.string(), result.size());
286 return NO_ERROR;
287}
288
289
290status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
291{
292 const size_t SIZE = 256;
293 char buffer[SIZE];
294 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800295 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700296
297 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
298 result.append(buffer);
299 write(fd, result.string(), result.size());
300 return NO_ERROR;
301}
302
303status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
304{
305 const size_t SIZE = 256;
306 char buffer[SIZE];
307 String8 result;
308 snprintf(buffer, SIZE, "Permission Denial: "
309 "can't dump AudioFlinger from pid=%d, uid=%d\n",
310 IPCThreadState::self()->getCallingPid(),
311 IPCThreadState::self()->getCallingUid());
312 result.append(buffer);
313 write(fd, result.string(), result.size());
314 return NO_ERROR;
315}
316
317static bool tryLock(Mutex& mutex)
318{
319 bool locked = false;
320 for (int i = 0; i < kDumpLockRetries; ++i) {
321 if (mutex.tryLock() == NO_ERROR) {
322 locked = true;
323 break;
324 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800325 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700326 }
327 return locked;
328}
329
330status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
331{
Glenn Kastenf1d45922012-01-13 15:54:24 -0800332 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700333 dumpPermissionDenial(fd, args);
334 } else {
335 // get state of hardware lock
336 bool hardwareLocked = tryLock(mHardwareLock);
337 if (!hardwareLocked) {
338 String8 result(kHardwareLockedString);
339 write(fd, result.string(), result.size());
340 } else {
341 mHardwareLock.unlock();
342 }
343
344 bool locked = tryLock(mLock);
345
346 // failed to lock - AudioFlinger is probably deadlocked
347 if (!locked) {
348 String8 result(kDeadlockedString);
349 write(fd, result.string(), result.size());
350 }
351
352 dumpClients(fd, args);
353 dumpInternals(fd, args);
354
355 // dump playback threads
356 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
357 mPlaybackThreads.valueAt(i)->dump(fd, args);
358 }
359
360 // dump record threads
361 for (size_t i = 0; i < mRecordThreads.size(); i++) {
362 mRecordThreads.valueAt(i)->dump(fd, args);
363 }
364
Dima Zavin799a70e2011-04-18 16:57:27 -0700365 // dump all hardware devs
366 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
367 audio_hw_device_t *dev = mAudioHwDevs[i];
368 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700369 }
370 if (locked) mLock.unlock();
371 }
372 return NO_ERROR;
373}
374
375
376// IAudioFlinger interface
377
378
379sp<IAudioTrack> AudioFlinger::createTrack(
380 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800381 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700382 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800383 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700384 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700385 int frameCount,
386 uint32_t flags,
387 const sp<IMemory>& sharedBuffer,
388 int output,
389 int *sessionId,
390 status_t *status)
391{
392 sp<PlaybackThread::Track> track;
393 sp<TrackHandle> trackHandle;
394 sp<Client> client;
395 wp<Client> wclient;
396 status_t lStatus;
397 int lSessionId;
398
Glenn Kasten263709e2012-01-06 08:40:01 -0800399 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
400 // but if someone uses binder directly they could bypass that and cause us to crash
401 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000402 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403 lStatus = BAD_VALUE;
404 goto Exit;
405 }
406
407 {
408 Mutex::Autolock _l(mLock);
409 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700410 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000412 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700413 lStatus = BAD_VALUE;
414 goto Exit;
415 }
416
417 wclient = mClients.valueFor(pid);
418
419 if (wclient != NULL) {
420 client = wclient.promote();
421 } else {
422 client = new Client(this, pid);
423 mClients.add(pid, client);
424 }
425
Steve Block3856b092011-10-20 11:56:00 +0100426 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700427 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700428 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700429 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
430 if (mPlaybackThreads.keyAt(i) != output) {
431 // prevent same audio session on different output threads
432 uint32_t sessions = t->hasAudioSession(*sessionId);
433 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000434 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700435 lStatus = BAD_VALUE;
436 goto Exit;
437 }
438 // check if an effect with same session ID is waiting for a track to be created
439 if (sessions & PlaybackThread::EFFECT_SESSION) {
440 effectThread = t.get();
441 }
Eric Laurentde070132010-07-13 04:45:46 -0700442 }
443 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 lSessionId = *sessionId;
445 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700446 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700447 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448 if (sessionId != NULL) {
449 *sessionId = lSessionId;
450 }
451 }
Steve Block3856b092011-10-20 11:56:00 +0100452 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453
454 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700455 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700456
457 // move effect chain to this output thread if an effect on same session was waiting
458 // for a track to be created
459 if (lStatus == NO_ERROR && effectThread != NULL) {
460 Mutex::Autolock _dl(thread->mLock);
461 Mutex::Autolock _sl(effectThread->mLock);
462 moveEffectChain_l(lSessionId, effectThread, thread, true);
463 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 }
465 if (lStatus == NO_ERROR) {
466 trackHandle = new TrackHandle(track);
467 } else {
468 // remove local strong reference to Client before deleting the Track so that the Client
469 // destructor is called by the TrackBase destructor with mLock held
470 client.clear();
471 track.clear();
472 }
473
474Exit:
475 if(status) {
476 *status = lStatus;
477 }
478 return trackHandle;
479}
480
481uint32_t AudioFlinger::sampleRate(int output) const
482{
483 Mutex::Autolock _l(mLock);
484 PlaybackThread *thread = checkPlaybackThread_l(output);
485 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000486 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 return 0;
488 }
489 return thread->sampleRate();
490}
491
492int AudioFlinger::channelCount(int output) const
493{
494 Mutex::Autolock _l(mLock);
495 PlaybackThread *thread = checkPlaybackThread_l(output);
496 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000497 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498 return 0;
499 }
500 return thread->channelCount();
501}
502
Glenn Kasten58f30212012-01-12 12:27:51 -0800503audio_format_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700504{
505 Mutex::Autolock _l(mLock);
506 PlaybackThread *thread = checkPlaybackThread_l(output);
507 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000508 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800509 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700510 }
511 return thread->format();
512}
513
514size_t AudioFlinger::frameCount(int output) const
515{
516 Mutex::Autolock _l(mLock);
517 PlaybackThread *thread = checkPlaybackThread_l(output);
518 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000519 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520 return 0;
521 }
522 return thread->frameCount();
523}
524
525uint32_t AudioFlinger::latency(int output) const
526{
527 Mutex::Autolock _l(mLock);
528 PlaybackThread *thread = checkPlaybackThread_l(output);
529 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000530 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531 return 0;
532 }
533 return thread->latency();
534}
535
536status_t AudioFlinger::setMasterVolume(float value)
537{
Eric Laurenta1884f92011-08-23 08:25:03 -0700538 status_t ret = initCheck();
539 if (ret != NO_ERROR) {
540 return ret;
541 }
542
Mathias Agopian65ab4712010-07-14 17:59:35 -0700543 // check calling permissions
544 if (!settingsAllowed()) {
545 return PERMISSION_DENIED;
546 }
547
548 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800549 { // scope for the lock
550 AutoMutex lock(mHardwareLock);
551 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700552 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800553 value = 1.0f;
554 }
555 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557
Eric Laurent93575202011-01-18 18:39:02 -0800558 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559 mMasterVolume = value;
560 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
561 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
562
563 return NO_ERROR;
564}
565
Glenn Kastenf78aee72012-01-04 11:00:47 -0800566status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567{
Eric Laurenta1884f92011-08-23 08:25:03 -0700568 status_t ret = initCheck();
569 if (ret != NO_ERROR) {
570 return ret;
571 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700572
573 // check calling permissions
574 if (!settingsAllowed()) {
575 return PERMISSION_DENIED;
576 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800577 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000578 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579 return BAD_VALUE;
580 }
581
582 { // scope for the lock
583 AutoMutex lock(mHardwareLock);
584 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700585 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 mHardwareStatus = AUDIO_HW_IDLE;
587 }
588
589 if (NO_ERROR == ret) {
590 Mutex::Autolock _l(mLock);
591 mMode = mode;
592 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
593 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594 }
595
596 return ret;
597}
598
599status_t AudioFlinger::setMicMute(bool state)
600{
Eric Laurenta1884f92011-08-23 08:25:03 -0700601 status_t ret = initCheck();
602 if (ret != NO_ERROR) {
603 return ret;
604 }
605
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 // check calling permissions
607 if (!settingsAllowed()) {
608 return PERMISSION_DENIED;
609 }
610
611 AutoMutex lock(mHardwareLock);
612 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700613 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700614 mHardwareStatus = AUDIO_HW_IDLE;
615 return ret;
616}
617
618bool AudioFlinger::getMicMute() const
619{
Eric Laurenta1884f92011-08-23 08:25:03 -0700620 status_t ret = initCheck();
621 if (ret != NO_ERROR) {
622 return false;
623 }
624
Dima Zavinfce7a472011-04-19 22:30:36 -0700625 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700627 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 mHardwareStatus = AUDIO_HW_IDLE;
629 return state;
630}
631
632status_t AudioFlinger::setMasterMute(bool muted)
633{
634 // check calling permissions
635 if (!settingsAllowed()) {
636 return PERMISSION_DENIED;
637 }
638
Eric Laurent93575202011-01-18 18:39:02 -0800639 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700640 mMasterMute = muted;
641 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
642 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
643
644 return NO_ERROR;
645}
646
647float AudioFlinger::masterVolume() const
648{
Glenn Kasten98067102011-12-13 11:47:54 -0800649 Mutex::Autolock _l(mLock);
650 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700651}
652
653bool AudioFlinger::masterMute() const
654{
Glenn Kasten98067102011-12-13 11:47:54 -0800655 Mutex::Autolock _l(mLock);
656 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700657}
658
Glenn Kastenfff6d712012-01-12 16:38:12 -0800659status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660{
661 // check calling permissions
662 if (!settingsAllowed()) {
663 return PERMISSION_DENIED;
664 }
665
Glenn Kasten263709e2012-01-06 08:40:01 -0800666 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000667 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700668 return BAD_VALUE;
669 }
670
671 AutoMutex lock(mLock);
672 PlaybackThread *thread = NULL;
673 if (output) {
674 thread = checkPlaybackThread_l(output);
675 if (thread == NULL) {
676 return BAD_VALUE;
677 }
678 }
679
680 mStreamTypes[stream].volume = value;
681
682 if (thread == NULL) {
683 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
684 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
685 }
686 } else {
687 thread->setStreamVolume(stream, value);
688 }
689
690 return NO_ERROR;
691}
692
Glenn Kastenfff6d712012-01-12 16:38:12 -0800693status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694{
695 // check calling permissions
696 if (!settingsAllowed()) {
697 return PERMISSION_DENIED;
698 }
699
Glenn Kasten263709e2012-01-06 08:40:01 -0800700 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700701 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000702 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 return BAD_VALUE;
704 }
705
Eric Laurent93575202011-01-18 18:39:02 -0800706 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 mStreamTypes[stream].mute = muted;
708 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
709 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
710
711 return NO_ERROR;
712}
713
Glenn Kastenfff6d712012-01-12 16:38:12 -0800714float AudioFlinger::streamVolume(audio_stream_type_t stream, int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715{
Glenn Kasten263709e2012-01-06 08:40:01 -0800716 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717 return 0.0f;
718 }
719
720 AutoMutex lock(mLock);
721 float volume;
722 if (output) {
723 PlaybackThread *thread = checkPlaybackThread_l(output);
724 if (thread == NULL) {
725 return 0.0f;
726 }
727 volume = thread->streamVolume(stream);
728 } else {
729 volume = mStreamTypes[stream].volume;
730 }
731
732 return volume;
733}
734
Glenn Kastenfff6d712012-01-12 16:38:12 -0800735bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736{
Glenn Kasten263709e2012-01-06 08:40:01 -0800737 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738 return true;
739 }
740
741 return mStreamTypes[stream].mute;
742}
743
Mathias Agopian65ab4712010-07-14 17:59:35 -0700744status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
745{
746 status_t result;
747
Steve Block3856b092011-10-20 11:56:00 +0100748 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
750 // check calling permissions
751 if (!settingsAllowed()) {
752 return PERMISSION_DENIED;
753 }
754
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755 // ioHandle == 0 means the parameters are global to the audio hardware interface
756 if (ioHandle == 0) {
757 AutoMutex lock(mHardwareLock);
758 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700759 status_t final_result = NO_ERROR;
760 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
761 audio_hw_device_t *dev = mAudioHwDevs[i];
762 result = dev->set_parameters(dev, keyValuePairs.string());
763 final_result = result ?: final_result;
764 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700765 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700766 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
767 AudioParameter param = AudioParameter(keyValuePairs);
768 String8 value;
769 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
770 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700771 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
772 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700773 for (size_t i = 0; i < mRecordThreads.size(); i++) {
774 sp<RecordThread> thread = mRecordThreads.valueAt(i);
775 RecordThread::RecordTrack *track = thread->track();
776 if (track != NULL) {
777 audio_devices_t device = (audio_devices_t)(
778 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700779 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700780 thread->setEffectSuspended(FX_IID_AEC,
781 suspend,
782 track->sessionId());
783 thread->setEffectSuspended(FX_IID_NS,
784 suspend,
785 track->sessionId());
786 }
787 }
Eric Laurentbee53372011-08-29 12:42:48 -0700788 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700789 }
790 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700791 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792 }
793
794 // hold a strong ref on thread in case closeOutput() or closeInput() is called
795 // and the thread is exited once the lock is released
796 sp<ThreadBase> thread;
797 {
798 Mutex::Autolock _l(mLock);
799 thread = checkPlaybackThread_l(ioHandle);
800 if (thread == NULL) {
801 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800802 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700803 // indicate output device change to all input threads for pre processing
804 AudioParameter param = AudioParameter(keyValuePairs);
805 int value;
806 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
807 for (size_t i = 0; i < mRecordThreads.size(); i++) {
808 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
809 }
810 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 }
812 }
813 if (thread != NULL) {
814 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815 return result;
816 }
817 return BAD_VALUE;
818}
819
820String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
821{
Steve Block3856b092011-10-20 11:56:00 +0100822// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
824
825 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700826 String8 out_s8;
827
Dima Zavin799a70e2011-04-18 16:57:27 -0700828 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
829 audio_hw_device_t *dev = mAudioHwDevs[i];
830 char *s = dev->get_parameters(dev, keys.string());
831 out_s8 += String8(s);
832 free(s);
833 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700834 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835 }
836
837 Mutex::Autolock _l(mLock);
838
839 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
840 if (playbackThread != NULL) {
841 return playbackThread->getParameters(keys);
842 }
843 RecordThread *recordThread = checkRecordThread_l(ioHandle);
844 if (recordThread != NULL) {
845 return recordThread->getParameters(keys);
846 }
847 return String8("");
848}
849
Glenn Kasten58f30212012-01-12 12:27:51 -0800850size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851{
Eric Laurenta1884f92011-08-23 08:25:03 -0700852 status_t ret = initCheck();
853 if (ret != NO_ERROR) {
854 return 0;
855 }
856
Dima Zavin799a70e2011-04-18 16:57:27 -0700857 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858}
859
860unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
861{
862 if (ioHandle == 0) {
863 return 0;
864 }
865
866 Mutex::Autolock _l(mLock);
867
868 RecordThread *recordThread = checkRecordThread_l(ioHandle);
869 if (recordThread != NULL) {
870 return recordThread->getInputFramesLost();
871 }
872 return 0;
873}
874
875status_t AudioFlinger::setVoiceVolume(float value)
876{
Eric Laurenta1884f92011-08-23 08:25:03 -0700877 status_t ret = initCheck();
878 if (ret != NO_ERROR) {
879 return ret;
880 }
881
Mathias Agopian65ab4712010-07-14 17:59:35 -0700882 // check calling permissions
883 if (!settingsAllowed()) {
884 return PERMISSION_DENIED;
885 }
886
887 AutoMutex lock(mHardwareLock);
888 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700889 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700890 mHardwareStatus = AUDIO_HW_IDLE;
891
892 return ret;
893}
894
895status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
896{
897 status_t status;
898
899 Mutex::Autolock _l(mLock);
900
901 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
902 if (playbackThread != NULL) {
903 return playbackThread->getRenderPosition(halFrames, dspFrames);
904 }
905
906 return BAD_VALUE;
907}
908
909void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
910{
911
912 Mutex::Autolock _l(mLock);
913
914 int pid = IPCThreadState::self()->getCallingPid();
915 if (mNotificationClients.indexOfKey(pid) < 0) {
916 sp<NotificationClient> notificationClient = new NotificationClient(this,
917 client,
918 pid);
Steve Block3856b092011-10-20 11:56:00 +0100919 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920
921 mNotificationClients.add(pid, notificationClient);
922
923 sp<IBinder> binder = client->asBinder();
924 binder->linkToDeath(notificationClient);
925
926 // the config change is always sent from playback or record threads to avoid deadlock
927 // with AudioSystem::gLock
928 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
929 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
930 }
931
932 for (size_t i = 0; i < mRecordThreads.size(); i++) {
933 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
934 }
935 }
936}
937
938void AudioFlinger::removeNotificationClient(pid_t pid)
939{
940 Mutex::Autolock _l(mLock);
941
942 int index = mNotificationClients.indexOfKey(pid);
943 if (index >= 0) {
944 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100945 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 mNotificationClients.removeItem(pid);
947 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700948
Steve Block3856b092011-10-20 11:56:00 +0100949 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700950 int num = mAudioSessionRefs.size();
951 bool removed = false;
952 for (int i = 0; i< num; i++) {
953 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100954 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700955 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100956 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700957 mAudioSessionRefs.removeAt(i);
958 delete ref;
959 removed = true;
960 i--;
961 num--;
962 }
963 }
964 if (removed) {
965 purgeStaleEffects_l();
966 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967}
968
969// audioConfigChanged_l() must be called with AudioFlinger::mLock held
970void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
971{
972 size_t size = mNotificationClients.size();
973 for (size_t i = 0; i < size; i++) {
974 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
975 }
976}
977
978// removeClient_l() must be called with AudioFlinger::mLock held
979void AudioFlinger::removeClient_l(pid_t pid)
980{
Steve Block3856b092011-10-20 11:56:00 +0100981 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982 mClients.removeItem(pid);
983}
984
985
986// ----------------------------------------------------------------------------
987
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700988AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989 : Thread(false),
990 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Glenn Kasten58f30212012-01-12 12:27:51 -0800991 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID), mStandby(false), mId(id), mExiting(false),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700992 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700994 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700995}
996
997AudioFlinger::ThreadBase::~ThreadBase()
998{
999 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001000 // do not lock the mutex in destructor
1001 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001002 if (mPowerManager != 0) {
1003 sp<IBinder> binder = mPowerManager->asBinder();
1004 binder->unlinkToDeath(mDeathRecipient);
1005 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006}
1007
1008void AudioFlinger::ThreadBase::exit()
1009{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001010 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011 // destroyed in the middle of requestExitAndWait()
1012 sp <ThreadBase> strongMe = this;
1013
Steve Block3856b092011-10-20 11:56:00 +01001014 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001016 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017 mExiting = true;
1018 requestExit();
1019 mWaitWorkCV.signal();
1020 }
1021 requestExitAndWait();
1022}
1023
1024uint32_t AudioFlinger::ThreadBase::sampleRate() const
1025{
1026 return mSampleRate;
1027}
1028
1029int AudioFlinger::ThreadBase::channelCount() const
1030{
1031 return (int)mChannelCount;
1032}
1033
Glenn Kasten58f30212012-01-12 12:27:51 -08001034audio_format_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035{
1036 return mFormat;
1037}
1038
1039size_t AudioFlinger::ThreadBase::frameCount() const
1040{
1041 return mFrameCount;
1042}
1043
1044status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1045{
1046 status_t status;
1047
Steve Block3856b092011-10-20 11:56:00 +01001048 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049 Mutex::Autolock _l(mLock);
1050
1051 mNewParameters.add(keyValuePairs);
1052 mWaitWorkCV.signal();
1053 // wait condition with timeout in case the thread loop has exited
1054 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001055 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056 status = mParamStatus;
1057 mWaitWorkCV.signal();
1058 } else {
1059 status = TIMED_OUT;
1060 }
1061 return status;
1062}
1063
1064void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1065{
1066 Mutex::Autolock _l(mLock);
1067 sendConfigEvent_l(event, param);
1068}
1069
1070// sendConfigEvent_l() must be called with ThreadBase::mLock held
1071void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1072{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001073 ConfigEvent configEvent;
1074 configEvent.mEvent = event;
1075 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001077 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 mWaitWorkCV.signal();
1079}
1080
1081void AudioFlinger::ThreadBase::processConfigEvents()
1082{
1083 mLock.lock();
1084 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001085 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001086 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087 mConfigEvents.removeAt(0);
1088 // release mLock before locking AudioFlinger mLock: lock order is always
1089 // AudioFlinger then ThreadBase to avoid cross deadlock
1090 mLock.unlock();
1091 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001092 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094 mLock.lock();
1095 }
1096 mLock.unlock();
1097}
1098
1099status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1100{
1101 const size_t SIZE = 256;
1102 char buffer[SIZE];
1103 String8 result;
1104
1105 bool locked = tryLock(mLock);
1106 if (!locked) {
1107 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1108 write(fd, buffer, strlen(buffer));
1109 }
1110
1111 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1112 result.append(buffer);
1113 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1114 result.append(buffer);
1115 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1116 result.append(buffer);
1117 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1118 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001119 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1120 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1122 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001123 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124 result.append(buffer);
1125
1126 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1127 result.append(buffer);
1128 result.append(" Index Command");
1129 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1130 snprintf(buffer, SIZE, "\n %02d ", i);
1131 result.append(buffer);
1132 result.append(mNewParameters[i]);
1133 }
1134
1135 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1136 result.append(buffer);
1137 snprintf(buffer, SIZE, " Index event param\n");
1138 result.append(buffer);
1139 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001140 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141 result.append(buffer);
1142 }
1143 result.append("\n");
1144
1145 write(fd, result.string(), result.size());
1146
1147 if (locked) {
1148 mLock.unlock();
1149 }
1150 return NO_ERROR;
1151}
1152
Eric Laurent1d2bff02011-07-24 17:49:51 -07001153status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1154{
1155 const size_t SIZE = 256;
1156 char buffer[SIZE];
1157 String8 result;
1158
1159 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1160 write(fd, buffer, strlen(buffer));
1161
1162 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1163 sp<EffectChain> chain = mEffectChains[i];
1164 if (chain != 0) {
1165 chain->dump(fd, args);
1166 }
1167 }
1168 return NO_ERROR;
1169}
1170
Eric Laurentfeb0db62011-07-22 09:04:31 -07001171void AudioFlinger::ThreadBase::acquireWakeLock()
1172{
1173 Mutex::Autolock _l(mLock);
1174 acquireWakeLock_l();
1175}
1176
1177void AudioFlinger::ThreadBase::acquireWakeLock_l()
1178{
1179 if (mPowerManager == 0) {
1180 // use checkService() to avoid blocking if power service is not up yet
1181 sp<IBinder> binder =
1182 defaultServiceManager()->checkService(String16("power"));
1183 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001184 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001185 } else {
1186 mPowerManager = interface_cast<IPowerManager>(binder);
1187 binder->linkToDeath(mDeathRecipient);
1188 }
1189 }
1190 if (mPowerManager != 0) {
1191 sp<IBinder> binder = new BBinder();
1192 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1193 binder,
1194 String16(mName));
1195 if (status == NO_ERROR) {
1196 mWakeLockToken = binder;
1197 }
Steve Block3856b092011-10-20 11:56:00 +01001198 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001199 }
1200}
1201
1202void AudioFlinger::ThreadBase::releaseWakeLock()
1203{
1204 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001205 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001206}
1207
1208void AudioFlinger::ThreadBase::releaseWakeLock_l()
1209{
1210 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001211 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001212 if (mPowerManager != 0) {
1213 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1214 }
1215 mWakeLockToken.clear();
1216 }
1217}
1218
1219void AudioFlinger::ThreadBase::clearPowerManager()
1220{
1221 Mutex::Autolock _l(mLock);
1222 releaseWakeLock_l();
1223 mPowerManager.clear();
1224}
1225
1226void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1227{
1228 sp<ThreadBase> thread = mThread.promote();
1229 if (thread != 0) {
1230 thread->clearPowerManager();
1231 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001232 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001233}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001234
Eric Laurent59255e42011-07-27 19:49:51 -07001235void AudioFlinger::ThreadBase::setEffectSuspended(
1236 const effect_uuid_t *type, bool suspend, int sessionId)
1237{
1238 Mutex::Autolock _l(mLock);
1239 setEffectSuspended_l(type, suspend, sessionId);
1240}
1241
1242void AudioFlinger::ThreadBase::setEffectSuspended_l(
1243 const effect_uuid_t *type, bool suspend, int sessionId)
1244{
Glenn Kasten090f0192012-01-30 13:00:02 -08001245 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001246 if (chain != 0) {
1247 if (type != NULL) {
1248 chain->setEffectSuspended_l(type, suspend);
1249 } else {
1250 chain->setEffectSuspendedAll_l(suspend);
1251 }
1252 }
1253
1254 updateSuspendedSessions_l(type, suspend, sessionId);
1255}
1256
1257void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1258{
1259 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1260 if (index < 0) {
1261 return;
1262 }
1263
1264 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1265 mSuspendedSessions.editValueAt(index);
1266
1267 for (size_t i = 0; i < sessionEffects.size(); i++) {
1268 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1269 for (int j = 0; j < desc->mRefCount; j++) {
1270 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1271 chain->setEffectSuspendedAll_l(true);
1272 } else {
Steve Block3856b092011-10-20 11:56:00 +01001273 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001274 desc->mType.timeLow);
1275 chain->setEffectSuspended_l(&desc->mType, true);
1276 }
1277 }
1278 }
1279}
1280
Eric Laurent59255e42011-07-27 19:49:51 -07001281void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1282 bool suspend,
1283 int sessionId)
1284{
1285 int index = mSuspendedSessions.indexOfKey(sessionId);
1286
1287 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1288
1289 if (suspend) {
1290 if (index >= 0) {
1291 sessionEffects = mSuspendedSessions.editValueAt(index);
1292 } else {
1293 mSuspendedSessions.add(sessionId, sessionEffects);
1294 }
1295 } else {
1296 if (index < 0) {
1297 return;
1298 }
1299 sessionEffects = mSuspendedSessions.editValueAt(index);
1300 }
1301
1302
1303 int key = EffectChain::kKeyForSuspendAll;
1304 if (type != NULL) {
1305 key = type->timeLow;
1306 }
1307 index = sessionEffects.indexOfKey(key);
1308
1309 sp <SuspendedSessionDesc> desc;
1310 if (suspend) {
1311 if (index >= 0) {
1312 desc = sessionEffects.valueAt(index);
1313 } else {
1314 desc = new SuspendedSessionDesc();
1315 if (type != NULL) {
1316 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1317 }
1318 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001319 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001320 }
1321 desc->mRefCount++;
1322 } else {
1323 if (index < 0) {
1324 return;
1325 }
1326 desc = sessionEffects.valueAt(index);
1327 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001328 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001329 sessionEffects.removeItemsAt(index);
1330 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001331 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001332 sessionId);
1333 mSuspendedSessions.removeItem(sessionId);
1334 }
1335 }
1336 }
1337 if (!sessionEffects.isEmpty()) {
1338 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1339 }
1340}
1341
1342void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1343 bool enabled,
1344 int sessionId)
1345{
1346 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001347 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1348}
Eric Laurent59255e42011-07-27 19:49:51 -07001349
Eric Laurenta85a74a2011-10-19 11:44:54 -07001350void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1351 bool enabled,
1352 int sessionId)
1353{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001354 if (mType != RECORD) {
1355 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1356 // another session. This gives the priority to well behaved effect control panels
1357 // and applications not using global effects.
1358 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1359 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1360 }
1361 }
Eric Laurent59255e42011-07-27 19:49:51 -07001362
1363 sp<EffectChain> chain = getEffectChain_l(sessionId);
1364 if (chain != 0) {
1365 chain->checkSuspendOnEffectEnabled(effect, enabled);
1366 }
1367}
1368
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369// ----------------------------------------------------------------------------
1370
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001371AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1372 AudioStreamOut* output,
1373 int id,
1374 uint32_t device)
1375 : ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08001376 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001377 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001378{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001379 snprintf(mName, kNameLength, "AudioOut_%d", id);
1380
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381 readOutputParameters();
1382
Glenn Kasten98067102011-12-13 11:47:54 -08001383 // Assumes constructor is called by AudioFlinger with it's mLock held,
1384 // but it would be safer to explicitly pass these as parameters
1385 mMasterVolume = mAudioFlinger->masterVolume_l();
1386 mMasterMute = mAudioFlinger->masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387
Glenn Kasten263709e2012-01-06 08:40:01 -08001388 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001389 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1390 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1391 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1393 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001394 // initialized by stream_type_t default constructor
1395 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001396 }
1397}
1398
1399AudioFlinger::PlaybackThread::~PlaybackThread()
1400{
1401 delete [] mMixBuffer;
1402}
1403
1404status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1405{
1406 dumpInternals(fd, args);
1407 dumpTracks(fd, args);
1408 dumpEffectChains(fd, args);
1409 return NO_ERROR;
1410}
1411
1412status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1413{
1414 const size_t SIZE = 256;
1415 char buffer[SIZE];
1416 String8 result;
1417
1418 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1419 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001420 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001421 for (size_t i = 0; i < mTracks.size(); ++i) {
1422 sp<Track> track = mTracks[i];
1423 if (track != 0) {
1424 track->dump(buffer, SIZE);
1425 result.append(buffer);
1426 }
1427 }
1428
1429 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1430 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001431 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001432 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1433 wp<Track> wTrack = mActiveTracks[i];
1434 if (wTrack != 0) {
1435 sp<Track> track = wTrack.promote();
1436 if (track != 0) {
1437 track->dump(buffer, SIZE);
1438 result.append(buffer);
1439 }
1440 }
1441 }
1442 write(fd, result.string(), result.size());
1443 return NO_ERROR;
1444}
1445
Mathias Agopian65ab4712010-07-14 17:59:35 -07001446status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1447{
1448 const size_t SIZE = 256;
1449 char buffer[SIZE];
1450 String8 result;
1451
1452 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1453 result.append(buffer);
1454 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1455 result.append(buffer);
1456 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1457 result.append(buffer);
1458 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1459 result.append(buffer);
1460 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1461 result.append(buffer);
1462 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1463 result.append(buffer);
1464 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1465 result.append(buffer);
1466 write(fd, result.string(), result.size());
1467
1468 dumpBase(fd, args);
1469
1470 return NO_ERROR;
1471}
1472
1473// Thread virtuals
1474status_t AudioFlinger::PlaybackThread::readyToRun()
1475{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001476 status_t status = initCheck();
1477 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001478 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001479 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001480 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001482 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483}
1484
1485void AudioFlinger::PlaybackThread::onFirstRef()
1486{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001487 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488}
1489
1490// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1491sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1492 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001493 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001494 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001495 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001496 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497 int frameCount,
1498 const sp<IMemory>& sharedBuffer,
1499 int sessionId,
1500 status_t *status)
1501{
1502 sp<Track> track;
1503 status_t lStatus;
1504
1505 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001506 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1507 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001508 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001509 "for output %p with format %d",
1510 sampleRate, format, channelMask, mOutput, mFormat);
1511 lStatus = BAD_VALUE;
1512 goto Exit;
1513 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514 }
1515 } else {
1516 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1517 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001518 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001519 lStatus = BAD_VALUE;
1520 goto Exit;
1521 }
1522 }
1523
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001524 lStatus = initCheck();
1525 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001526 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527 goto Exit;
1528 }
1529
1530 { // scope for mLock
1531 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001532
1533 // all tracks in same audio session must share the same routing strategy otherwise
1534 // conflicts will happen when tracks are moved from one output to another by audio policy
1535 // manager
1536 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001537 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001538 for (size_t i = 0; i < mTracks.size(); ++i) {
1539 sp<Track> t = mTracks[i];
1540 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001541 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1542 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001543 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001544 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001545 lStatus = BAD_VALUE;
1546 goto Exit;
1547 }
1548 }
1549 }
1550
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001552 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 if (track->getCblk() == NULL || track->name() < 0) {
1554 lStatus = NO_MEMORY;
1555 goto Exit;
1556 }
1557 mTracks.add(track);
1558
1559 sp<EffectChain> chain = getEffectChain_l(sessionId);
1560 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001561 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001563 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001564 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001566
1567 // invalidate track immediately if the stream type was moved to another thread since
1568 // createTrack() was called by the client process.
1569 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001570 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001571 this, streamType);
1572 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1573 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574 }
1575 lStatus = NO_ERROR;
1576
1577Exit:
1578 if(status) {
1579 *status = lStatus;
1580 }
1581 return track;
1582}
1583
1584uint32_t AudioFlinger::PlaybackThread::latency() const
1585{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001586 Mutex::Autolock _l(mLock);
1587 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001588 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001589 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 return 0;
1591 }
1592}
1593
1594status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1595{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596 mMasterVolume = value;
1597 return NO_ERROR;
1598}
1599
1600status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1601{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602 mMasterMute = muted;
1603 return NO_ERROR;
1604}
1605
1606float AudioFlinger::PlaybackThread::masterVolume() const
1607{
1608 return mMasterVolume;
1609}
1610
1611bool AudioFlinger::PlaybackThread::masterMute() const
1612{
1613 return mMasterMute;
1614}
1615
Glenn Kastenfff6d712012-01-12 16:38:12 -08001616status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 mStreamTypes[stream].volume = value;
1619 return NO_ERROR;
1620}
1621
Glenn Kastenfff6d712012-01-12 16:38:12 -08001622status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624 mStreamTypes[stream].mute = muted;
1625 return NO_ERROR;
1626}
1627
Glenn Kastenfff6d712012-01-12 16:38:12 -08001628float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629{
1630 return mStreamTypes[stream].volume;
1631}
1632
Glenn Kastenfff6d712012-01-12 16:38:12 -08001633bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001634{
1635 return mStreamTypes[stream].mute;
1636}
1637
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638// addTrack_l() must be called with ThreadBase::mLock held
1639status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1640{
1641 status_t status = ALREADY_EXISTS;
1642
1643 // set retry count for buffer fill
1644 track->mRetryCount = kMaxTrackStartupRetries;
1645 if (mActiveTracks.indexOf(track) < 0) {
1646 // the track is newly added, make sure it fills up all its
1647 // buffers before playing. This is to ensure the client will
1648 // effectively get the latency it requested.
1649 track->mFillingUpStatus = Track::FS_FILLING;
1650 track->mResetDone = false;
1651 mActiveTracks.add(track);
1652 if (track->mainBuffer() != mMixBuffer) {
1653 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1654 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001655 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001656 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 }
1658 }
1659
1660 status = NO_ERROR;
1661 }
1662
Steve Block3856b092011-10-20 11:56:00 +01001663 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 mWaitWorkCV.broadcast();
1665
1666 return status;
1667}
1668
1669// destroyTrack_l() must be called with ThreadBase::mLock held
1670void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1671{
1672 track->mState = TrackBase::TERMINATED;
1673 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001674 removeTrack_l(track);
1675 }
1676}
1677
1678void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1679{
1680 mTracks.remove(track);
1681 deleteTrackName_l(track->name());
1682 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1683 if (chain != 0) {
1684 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 }
1686}
1687
1688String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1689{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001690 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001691 char *s;
1692
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001693 Mutex::Autolock _l(mLock);
1694 if (initCheck() != NO_ERROR) {
1695 return out_s8;
1696 }
1697
Dima Zavin799a70e2011-04-18 16:57:27 -07001698 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001699 out_s8 = String8(s);
1700 free(s);
1701 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702}
1703
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001704// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1706 AudioSystem::OutputDescriptor desc;
1707 void *param2 = 0;
1708
Steve Block3856b092011-10-20 11:56:00 +01001709 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710
1711 switch (event) {
1712 case AudioSystem::OUTPUT_OPENED:
1713 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001714 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 desc.samplingRate = mSampleRate;
1716 desc.format = mFormat;
1717 desc.frameCount = mFrameCount;
1718 desc.latency = latency();
1719 param2 = &desc;
1720 break;
1721
1722 case AudioSystem::STREAM_CONFIG_CHANGED:
1723 param2 = &param;
1724 case AudioSystem::OUTPUT_CLOSED:
1725 default:
1726 break;
1727 }
1728 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1729}
1730
1731void AudioFlinger::PlaybackThread::readOutputParameters()
1732{
Dima Zavin799a70e2011-04-18 16:57:27 -07001733 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001734 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1735 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001736 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001737 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001738 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001739
1740 // FIXME - Current mixer implementation only supports stereo output: Always
1741 // Allocate a stereo buffer even if HW output is mono.
1742 if (mMixBuffer != NULL) delete[] mMixBuffer;
1743 mMixBuffer = new int16_t[mFrameCount * 2];
1744 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1745
Eric Laurentde070132010-07-13 04:45:46 -07001746 // force reconfiguration of effect chains and engines to take new buffer size and audio
1747 // parameters into account
1748 // Note that mLock is not held when readOutputParameters() is called from the constructor
1749 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1750 // matter.
1751 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1752 Vector< sp<EffectChain> > effectChains = mEffectChains;
1753 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001754 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001755 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756}
1757
1758status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1759{
1760 if (halFrames == 0 || dspFrames == 0) {
1761 return BAD_VALUE;
1762 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001763 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001764 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001765 return INVALID_OPERATION;
1766 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001767 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768
Dima Zavin799a70e2011-04-18 16:57:27 -07001769 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770}
1771
Eric Laurent39e94f82010-07-28 01:32:47 -07001772uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773{
1774 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001775 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001777 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778 }
1779
1780 for (size_t i = 0; i < mTracks.size(); ++i) {
1781 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001782 if (sessionId == track->sessionId() &&
1783 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001784 result |= TRACK_SESSION;
1785 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786 }
1787 }
1788
Eric Laurent39e94f82010-07-28 01:32:47 -07001789 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001790}
1791
Eric Laurentde070132010-07-13 04:45:46 -07001792uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1793{
Dima Zavinfce7a472011-04-19 22:30:36 -07001794 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001795 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001796 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1797 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001798 }
1799 for (size_t i = 0; i < mTracks.size(); i++) {
1800 sp<Track> track = mTracks[i];
1801 if (sessionId == track->sessionId() &&
1802 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001803 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001804 }
1805 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001806 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001807}
1808
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809
Glenn Kastenaed850d2012-01-26 09:46:34 -08001810AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001811{
1812 Mutex::Autolock _l(mLock);
1813 return mOutput;
1814}
1815
1816AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1817{
1818 Mutex::Autolock _l(mLock);
1819 AudioStreamOut *output = mOutput;
1820 mOutput = NULL;
1821 return output;
1822}
1823
1824// this method must always be called either with ThreadBase mLock held or inside the thread loop
1825audio_stream_t* AudioFlinger::PlaybackThread::stream()
1826{
1827 if (mOutput == NULL) {
1828 return NULL;
1829 }
1830 return &mOutput->stream->common;
1831}
1832
Eric Laurent162b40b2011-12-05 09:47:19 -08001833uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1834{
1835 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1836 // decoding and transfer time. So sleeping for half of the latency would likely cause
1837 // underruns
1838 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1839 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1840 } else {
1841 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1842 }
1843}
1844
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845// ----------------------------------------------------------------------------
1846
Dima Zavin799a70e2011-04-18 16:57:27 -07001847AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurentaeeb7e22012-01-19 10:00:02 -08001849 mAudioMixer(NULL), mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001851 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1853
1854 // FIXME - Current mixer implementation only supports stereo output
1855 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001856 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857 }
1858}
1859
1860AudioFlinger::MixerThread::~MixerThread()
1861{
1862 delete mAudioMixer;
1863}
1864
1865bool AudioFlinger::MixerThread::threadLoop()
1866{
1867 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001868 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869 nsecs_t standbyTime = systemTime();
1870 size_t mixBufferSize = mFrameCount * mFrameSize;
1871 // FIXME: Relaxed timing because of a certain device that can't meet latency
1872 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001873 // increase threshold again due to low power audio mode. The way this warning threshold is
1874 // calculated and its usefulness should be reconsidered anyway.
1875 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876 nsecs_t lastWarning = 0;
1877 bool longStandbyExit = false;
1878 uint32_t activeSleepTime = activeSleepTimeUs();
1879 uint32_t idleSleepTime = idleSleepTimeUs();
1880 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001881 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001883#ifdef DEBUG_CPU_USAGE
1884 ThreadCpuUsage cpu;
1885 const CentralTendencyStatistics& stats = cpu.statistics();
1886#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887
Eric Laurentfeb0db62011-07-22 09:04:31 -07001888 acquireWakeLock();
1889
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890 while (!exitPending())
1891 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001892#ifdef DEBUG_CPU_USAGE
1893 cpu.sampleAndEnable();
1894 unsigned n = stats.n();
1895 // cpu.elapsed() is expensive, so don't call it every loop
1896 if ((n & 127) == 1) {
1897 long long elapsed = cpu.elapsed();
1898 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1899 double perLoop = elapsed / (double) n;
1900 double perLoop100 = perLoop * 0.01;
1901 double mean = stats.mean();
1902 double stddev = stats.stddev();
1903 double minimum = stats.minimum();
1904 double maximum = stats.maximum();
1905 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001906 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 -07001907 elapsed * .000000001, n, perLoop * .000001,
1908 mean * .001,
1909 stddev * .001,
1910 minimum * .001,
1911 maximum * .001,
1912 mean / perLoop100,
1913 stddev / perLoop100,
1914 minimum / perLoop100,
1915 maximum / perLoop100);
1916 }
1917 }
1918#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919 processConfigEvents();
1920
1921 mixerStatus = MIXER_IDLE;
1922 { // scope for mLock
1923
1924 Mutex::Autolock _l(mLock);
1925
1926 if (checkForNewParameters_l()) {
1927 mixBufferSize = mFrameCount * mFrameSize;
1928 // FIXME: Relaxed timing because of a certain device that can't meet latency
1929 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001930 // increase threshold again due to low power audio mode. The way this warning
1931 // threshold is calculated and its usefulness should be reconsidered anyway.
1932 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933 activeSleepTime = activeSleepTimeUs();
1934 idleSleepTime = idleSleepTimeUs();
1935 }
1936
1937 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1938
1939 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001940 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1941 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001943 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001944 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945 mStandby = true;
1946 mBytesWritten = 0;
1947 }
1948
1949 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1950 // we're about to wait, flush the binder command buffer
1951 IPCThreadState::self()->flushCommands();
1952
1953 if (exitPending()) break;
1954
Eric Laurentfeb0db62011-07-22 09:04:31 -07001955 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001957 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001959 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001960 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961
Eric Laurent27741442012-01-17 19:20:12 -08001962 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001963 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964 char value[PROPERTY_VALUE_MAX];
1965 property_get("ro.audio.silent", value, "0");
1966 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001967 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 setMasterMute(true);
1969 }
1970 }
1971
1972 standbyTime = systemTime() + kStandbyTimeInNsecs;
1973 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001974 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 continue;
1976 }
1977 }
1978
1979 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1980
1981 // prevent any changes in effect chain list and in each effect chain
1982 // during mixing and effect process as the audio buffers could be deleted
1983 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001984 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001985 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001986
Glenn Kastenf6b16782011-12-15 09:51:17 -08001987 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 // mix buffers...
1989 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001990 // increase sleep time progressively when application underrun condition clears.
1991 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1992 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1993 // such that we would underrun the audio HAL.
1994 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001995 sleepTimeShift--;
1996 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001997 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998 standbyTime = systemTime() + kStandbyTimeInNsecs;
1999 //TODO: delay standby when effects have a tail
2000 } else {
2001 // If no tracks are ready, sleep once for the duration of an output
2002 // buffer size, then write 0s to the output
2003 if (sleepTime == 0) {
2004 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002005 sleepTime = activeSleepTime >> sleepTimeShift;
2006 if (sleepTime < kMinThreadSleepTimeUs) {
2007 sleepTime = kMinThreadSleepTimeUs;
2008 }
2009 // reduce sleep time in case of consecutive application underruns to avoid
2010 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2011 // duration we would end up writing less data than needed by the audio HAL if
2012 // the condition persists.
2013 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2014 sleepTimeShift++;
2015 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016 } else {
2017 sleepTime = idleSleepTime;
2018 }
2019 } else if (mBytesWritten != 0 ||
2020 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2021 memset (mMixBuffer, 0, mixBufferSize);
2022 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002023 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024 }
2025 // TODO add standby time extension fct of effect tail
2026 }
2027
2028 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002029 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 }
2031 // sleepTime == 0 means we must write to audio hardware
2032 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002033 for (size_t i = 0; i < effectChains.size(); i ++) {
2034 effectChains[i]->process_l();
2035 }
2036 // enable changes in effect chain
2037 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002038 mLastWriteTime = systemTime();
2039 mInWrite = true;
2040 mBytesWritten += mixBufferSize;
2041
Dima Zavin799a70e2011-04-18 16:57:27 -07002042 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002043 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2044 mNumWrites++;
2045 mInWrite = false;
2046 nsecs_t now = systemTime();
2047 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002048 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002050 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002051 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052 ns2ms(delta), mNumDelayedWrites, this);
2053 lastWarning = now;
2054 }
2055 if (mStandby) {
2056 longStandbyExit = true;
2057 }
2058 }
2059 mStandby = false;
2060 } else {
2061 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002062 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063 usleep(sleepTime);
2064 }
2065
2066 // finally let go of all our tracks, without the lock held
2067 // since we can't guarantee the destructors won't acquire that
2068 // same lock.
2069 tracksToRemove.clear();
2070
2071 // Effect chains will be actually deleted here if they were removed from
2072 // mEffectChains list during mixing or effects processing
2073 effectChains.clear();
2074 }
2075
2076 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002077 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002078 }
2079
Eric Laurentfeb0db62011-07-22 09:04:31 -07002080 releaseWakeLock();
2081
Steve Block3856b092011-10-20 11:56:00 +01002082 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002083 return false;
2084}
2085
2086// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002087AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2088 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089{
2090
Glenn Kasten29c23c32012-01-26 13:37:52 -08002091 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092 // find out which tracks need to be processed
2093 size_t count = activeTracks.size();
2094 size_t mixedTracks = 0;
2095 size_t tracksWithEffect = 0;
2096
2097 float masterVolume = mMasterVolume;
2098 bool masterMute = mMasterMute;
2099
Eric Laurent571d49c2010-08-11 05:20:11 -07002100 if (masterMute) {
2101 masterVolume = 0;
2102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002103 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002104 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002106 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002107 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002108 masterVolume = (float)((v + (1 << 23)) >> 24);
2109 chain.clear();
2110 }
2111
2112 for (size_t i=0 ; i<count ; i++) {
2113 sp<Track> t = activeTracks[i].promote();
2114 if (t == 0) continue;
2115
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002116 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117 Track* const track = t.get();
2118 audio_track_cblk_t* cblk = track->cblk();
2119
2120 // The first time a track is added we wait
2121 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002122 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002123 // make sure that we have enough frames to mix one full buffer.
2124 // enforce this condition only once to enable draining the buffer in case the client
2125 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002126 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002127 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002128 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002129 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002130 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002131 if (t->sampleRate() == (int)mSampleRate) {
2132 minFrames = mFrameCount;
2133 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002134 // +1 for rounding and +1 for additional sample needed for interpolation
2135 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2136 // add frames already consumed but not yet released by the resampler
2137 // because cblk->framesReady() will include these frames
2138 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2139 // the minimum track buffer size is normally twice the number of frames necessary
2140 // to fill one buffer and the resampler should not leave more than one buffer worth
2141 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002142 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002143 }
2144 }
2145 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146 !track->isPaused() && !track->isTerminated())
2147 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002148 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149
2150 mixedTracks++;
2151
2152 // track->mainBuffer() != mMixBuffer means there is an effect chain
2153 // connected to the track
2154 chain.clear();
2155 if (track->mainBuffer() != mMixBuffer) {
2156 chain = getEffectChain_l(track->sessionId());
2157 // Delegate volume control to effect in track effect chain if needed
2158 if (chain != 0) {
2159 tracksWithEffect++;
2160 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002161 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002162 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002163 }
2164 }
2165
2166
2167 int param = AudioMixer::VOLUME;
2168 if (track->mFillingUpStatus == Track::FS_FILLED) {
2169 // no ramp for the first volume setting
2170 track->mFillingUpStatus = Track::FS_ACTIVE;
2171 if (track->mState == TrackBase::RESUMING) {
2172 track->mState = TrackBase::ACTIVE;
2173 param = AudioMixer::RAMP_VOLUME;
2174 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002175 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 } else if (cblk->server != 0) {
2177 // If the track is stopped before the first frame was mixed,
2178 // do not apply ramp
2179 param = AudioMixer::RAMP_VOLUME;
2180 }
2181
2182 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002183 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002184 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002186 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 if (track->isPausing()) {
2188 track->setPaused();
2189 }
2190 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002191
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 // read original volumes with volume control
2193 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 float v = masterVolume * typeVolume;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002195 uint32_t vlr = cblk->volumeLR;
2196 vl = vlr & 0xFFFF;
2197 vr = vlr >> 16;
2198 // track volumes come from shared memory, so can't be trusted and must be clamped
2199 if (vl > MAX_GAIN_INT) {
2200 ALOGV("Track left volume out of range: %04X", vl);
2201 vl = MAX_GAIN_INT;
2202 }
2203 if (vr > MAX_GAIN_INT) {
2204 ALOGV("Track right volume out of range: %04X", vr);
2205 vr = MAX_GAIN_INT;
2206 }
2207 // now apply the master volume and stream type volume
2208 vl = (uint32_t)(v * vl) << 12;
2209 vr = (uint32_t)(v * vr) << 12;
2210 // assuming master volume and stream type volume each go up to 1.0,
2211 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002212
Glenn Kasten05632a52012-01-03 14:22:33 -08002213 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2214 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002215 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002216 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002217 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002218 }
2219 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002220 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002221 // Delegate volume control to effect in track effect chain if needed
2222 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2223 // Do not ramp volume if volume is controlled by effect
2224 param = AudioMixer::VOLUME;
2225 track->mHasVolumeController = true;
2226 } else {
2227 // force no volume ramp when volume controller was just disabled or removed
2228 // from effect chain to avoid volume spike
2229 if (track->mHasVolumeController) {
2230 param = AudioMixer::VOLUME;
2231 }
2232 track->mHasVolumeController = false;
2233 }
2234
2235 // Convert volumes from 8.24 to 4.12 format
2236 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002237 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002238 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2239 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2240 left = int16_t(v_clamped);
2241 v_clamped = (vr + (1 << 11)) >> 12;
2242 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2243 right = int16_t(v_clamped);
2244
2245 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2246 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002247
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002249 mAudioMixer->setBufferProvider(name, track);
2250 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002252 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2253 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2254 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002256 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002257 AudioMixer::TRACK,
2258 AudioMixer::FORMAT, (void *)track->format());
2259 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002260 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002262 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002264 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265 AudioMixer::RESAMPLE,
2266 AudioMixer::SAMPLE_RATE,
2267 (void *)(cblk->sampleRate));
2268 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002269 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 AudioMixer::TRACK,
2271 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2272 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002273 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274 AudioMixer::TRACK,
2275 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2276
2277 // reset retry count
2278 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002279 // If one track is ready, set the mixer ready if:
2280 // - the mixer was not ready during previous round OR
2281 // - no other track is not ready
2282 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2283 mixerStatus != MIXER_TRACKS_ENABLED) {
2284 mixerStatus = MIXER_TRACKS_READY;
2285 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002287 //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 -07002288 if (track->isStopped()) {
2289 track->reset();
2290 }
2291 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2292 // We have consumed all the buffers of this track.
2293 // Remove it from the list of active tracks.
2294 tracksToRemove->add(track);
2295 } else {
2296 // No buffers for this track. Give it a few chances to
2297 // fill a buffer, then remove it from active list.
2298 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002299 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002300 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002301 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002302 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002303 // If one track is not ready, mark the mixer also not ready if:
2304 // - the mixer was ready during previous round OR
2305 // - no other track is ready
2306 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2307 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308 mixerStatus = MIXER_TRACKS_ENABLED;
2309 }
2310 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002311 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312 }
2313 }
2314
2315 // remove all the tracks that need to be...
2316 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002317 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318 for (size_t i=0 ; i<count ; i++) {
2319 const sp<Track>& track = tracksToRemove->itemAt(i);
2320 mActiveTracks.remove(track);
2321 if (track->mainBuffer() != mMixBuffer) {
2322 chain = getEffectChain_l(track->sessionId());
2323 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002324 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002325 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326 }
2327 }
2328 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002329 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330 }
2331 }
2332 }
2333
2334 // mix buffer must be cleared if all tracks are connected to an
2335 // effect chain as in this case the mixer will not write to
2336 // mix buffer and track effects will accumulate into it
2337 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2338 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2339 }
2340
Eric Laurent27741442012-01-17 19:20:12 -08002341 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002342 return mixerStatus;
2343}
2344
Glenn Kastenfff6d712012-01-12 16:38:12 -08002345void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346{
Steve Block3856b092011-10-20 11:56:00 +01002347 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002348 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002350
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351 size_t size = mTracks.size();
2352 for (size_t i = 0; i < size; i++) {
2353 sp<Track> t = mTracks[i];
2354 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002355 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002356 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 }
2358 }
2359}
2360
Glenn Kastenfff6d712012-01-12 16:38:12 -08002361void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002362{
Steve Block3856b092011-10-20 11:56:00 +01002363 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002364 this, streamType, valid);
2365 Mutex::Autolock _l(mLock);
2366
2367 mStreamTypes[streamType].valid = valid;
2368}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002369
2370// getTrackName_l() must be called with ThreadBase::mLock held
2371int AudioFlinger::MixerThread::getTrackName_l()
2372{
2373 return mAudioMixer->getTrackName();
2374}
2375
2376// deleteTrackName_l() must be called with ThreadBase::mLock held
2377void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2378{
Steve Block3856b092011-10-20 11:56:00 +01002379 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380 mAudioMixer->deleteTrackName(name);
2381}
2382
2383// checkForNewParameters_l() must be called with ThreadBase::mLock held
2384bool AudioFlinger::MixerThread::checkForNewParameters_l()
2385{
2386 bool reconfig = false;
2387
2388 while (!mNewParameters.isEmpty()) {
2389 status_t status = NO_ERROR;
2390 String8 keyValuePair = mNewParameters[0];
2391 AudioParameter param = AudioParameter(keyValuePair);
2392 int value;
2393
2394 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2395 reconfig = true;
2396 }
2397 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002398 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002399 status = BAD_VALUE;
2400 } else {
2401 reconfig = true;
2402 }
2403 }
2404 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002405 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406 status = BAD_VALUE;
2407 } else {
2408 reconfig = true;
2409 }
2410 }
2411 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2412 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002413 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 // if frame count is changed after track creation
2415 if (!mTracks.isEmpty()) {
2416 status = INVALID_OPERATION;
2417 } else {
2418 reconfig = true;
2419 }
2420 }
2421 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002422 // when changing the audio output device, call addBatteryData to notify
2423 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002424 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002425 uint32_t params = 0;
2426 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002427 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002428 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2429 }
2430
2431 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002432 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002433 // check if any other device (except speaker) is on
2434 if (value & deviceWithoutSpeaker ) {
2435 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2436 }
2437
2438 if (params != 0) {
2439 addBatteryData(params);
2440 }
2441 }
2442
Mathias Agopian65ab4712010-07-14 17:59:35 -07002443 // forward device change to effects that have requested to be
2444 // aware of attached audio device.
2445 mDevice = (uint32_t)value;
2446 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002447 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002448 }
2449 }
2450
2451 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002452 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002453 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002455 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 mStandby = true;
2457 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002458 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002459 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 }
2461 if (status == NO_ERROR && reconfig) {
2462 delete mAudioMixer;
2463 readOutputParameters();
2464 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2465 for (size_t i = 0; i < mTracks.size() ; i++) {
2466 int name = getTrackName_l();
2467 if (name < 0) break;
2468 mTracks[i]->mName = name;
2469 // limit track sample rate to 2 x new output sample rate
2470 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2471 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2472 }
2473 }
2474 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2475 }
2476 }
2477
2478 mNewParameters.removeAt(0);
2479
2480 mParamStatus = status;
2481 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002482 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2483 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002484 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485 }
2486 return reconfig;
2487}
2488
2489status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2490{
2491 const size_t SIZE = 256;
2492 char buffer[SIZE];
2493 String8 result;
2494
2495 PlaybackThread::dumpInternals(fd, args);
2496
2497 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2498 result.append(buffer);
2499 write(fd, result.string(), result.size());
2500 return NO_ERROR;
2501}
2502
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2504{
Eric Laurent60e18242010-07-29 06:50:24 -07002505 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506}
2507
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002508uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2509{
2510 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2511}
2512
Mathias Agopian65ab4712010-07-14 17:59:35 -07002513// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002514AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515 : PlaybackThread(audioFlinger, output, id, device)
2516{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002517 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518}
2519
2520AudioFlinger::DirectOutputThread::~DirectOutputThread()
2521{
2522}
2523
Mathias Agopian65ab4712010-07-14 17:59:35 -07002524static inline
2525int32_t mul(int16_t in, int16_t v)
2526{
2527#if defined(__arm__) && !defined(__thumb__)
2528 int32_t out;
2529 asm( "smulbb %[out], %[in], %[v] \n"
2530 : [out]"=r"(out)
2531 : [in]"%r"(in), [v]"r"(v)
2532 : );
2533 return out;
2534#else
2535 return in * int32_t(v);
2536#endif
2537}
2538
2539void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2540{
2541 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002542 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 return;
2544 }
2545
2546 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002547 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 size_t count = mFrameCount * mChannelCount;
2549 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2550 int16_t *dst = mMixBuffer + count-1;
2551 while(count--) {
2552 *dst-- = (int16_t)(*src--^0x80) << 8;
2553 }
2554 }
2555
2556 size_t frameCount = mFrameCount;
2557 int16_t *out = mMixBuffer;
2558 if (ramp) {
2559 if (mChannelCount == 1) {
2560 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2561 int32_t vlInc = d / (int32_t)frameCount;
2562 int32_t vl = ((int32_t)mLeftVolShort << 16);
2563 do {
2564 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2565 out++;
2566 vl += vlInc;
2567 } while (--frameCount);
2568
2569 } else {
2570 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2571 int32_t vlInc = d / (int32_t)frameCount;
2572 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2573 int32_t vrInc = d / (int32_t)frameCount;
2574 int32_t vl = ((int32_t)mLeftVolShort << 16);
2575 int32_t vr = ((int32_t)mRightVolShort << 16);
2576 do {
2577 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2578 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2579 out += 2;
2580 vl += vlInc;
2581 vr += vrInc;
2582 } while (--frameCount);
2583 }
2584 } else {
2585 if (mChannelCount == 1) {
2586 do {
2587 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2588 out++;
2589 } while (--frameCount);
2590 } else {
2591 do {
2592 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2593 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2594 out += 2;
2595 } while (--frameCount);
2596 }
2597 }
2598
2599 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002600 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002601 size_t count = mFrameCount * mChannelCount;
2602 int16_t *src = mMixBuffer;
2603 uint8_t *dst = (uint8_t *)mMixBuffer;
2604 while(count--) {
2605 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2606 }
2607 }
2608
2609 mLeftVolShort = leftVol;
2610 mRightVolShort = rightVol;
2611}
2612
2613bool AudioFlinger::DirectOutputThread::threadLoop()
2614{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002615 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 sp<Track> trackToRemove;
2617 sp<Track> activeTrack;
2618 nsecs_t standbyTime = systemTime();
2619 int8_t *curBuf;
2620 size_t mixBufferSize = mFrameCount*mFrameSize;
2621 uint32_t activeSleepTime = activeSleepTimeUs();
2622 uint32_t idleSleepTime = idleSleepTimeUs();
2623 uint32_t sleepTime = idleSleepTime;
2624 // use shorter standby delay as on normal output to release
2625 // hardware resources as soon as possible
2626 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2627
Eric Laurentfeb0db62011-07-22 09:04:31 -07002628 acquireWakeLock();
2629
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630 while (!exitPending())
2631 {
2632 bool rampVolume;
2633 uint16_t leftVol;
2634 uint16_t rightVol;
2635 Vector< sp<EffectChain> > effectChains;
2636
2637 processConfigEvents();
2638
2639 mixerStatus = MIXER_IDLE;
2640
2641 { // scope for the mLock
2642
2643 Mutex::Autolock _l(mLock);
2644
2645 if (checkForNewParameters_l()) {
2646 mixBufferSize = mFrameCount*mFrameSize;
2647 activeSleepTime = activeSleepTimeUs();
2648 idleSleepTime = idleSleepTimeUs();
2649 standbyDelay = microseconds(activeSleepTime*2);
2650 }
2651
2652 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002653 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2654 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002655 // wait until we have something to do...
2656 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002657 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002658 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002659 mStandby = true;
2660 mBytesWritten = 0;
2661 }
2662
2663 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2664 // we're about to wait, flush the binder command buffer
2665 IPCThreadState::self()->flushCommands();
2666
2667 if (exitPending()) break;
2668
Eric Laurentfeb0db62011-07-22 09:04:31 -07002669 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002670 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002671 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002672 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002673 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002674
Glenn Kastenf1d45922012-01-13 15:54:24 -08002675 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676 char value[PROPERTY_VALUE_MAX];
2677 property_get("ro.audio.silent", value, "0");
2678 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002679 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002680 setMasterMute(true);
2681 }
2682 }
2683
2684 standbyTime = systemTime() + standbyDelay;
2685 sleepTime = idleSleepTime;
2686 continue;
2687 }
2688 }
2689
2690 effectChains = mEffectChains;
2691
2692 // find out which tracks need to be processed
2693 if (mActiveTracks.size() != 0) {
2694 sp<Track> t = mActiveTracks[0].promote();
2695 if (t == 0) continue;
2696
2697 Track* const track = t.get();
2698 audio_track_cblk_t* cblk = track->cblk();
2699
2700 // The first time a track is added we wait
2701 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002702 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002703 !track->isPaused() && !track->isTerminated())
2704 {
Steve Block3856b092011-10-20 11:56:00 +01002705 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706
2707 if (track->mFillingUpStatus == Track::FS_FILLED) {
2708 track->mFillingUpStatus = Track::FS_ACTIVE;
2709 mLeftVolFloat = mRightVolFloat = 0;
2710 mLeftVolShort = mRightVolShort = 0;
2711 if (track->mState == TrackBase::RESUMING) {
2712 track->mState = TrackBase::ACTIVE;
2713 rampVolume = true;
2714 }
2715 } else if (cblk->server != 0) {
2716 // If the track is stopped before the first frame was mixed,
2717 // do not apply ramp
2718 rampVolume = true;
2719 }
2720 // compute volume for this track
2721 float left, right;
2722 if (track->isMuted() || mMasterMute || track->isPausing() ||
2723 mStreamTypes[track->type()].mute) {
2724 left = right = 0;
2725 if (track->isPausing()) {
2726 track->setPaused();
2727 }
2728 } else {
2729 float typeVolume = mStreamTypes[track->type()].volume;
2730 float v = mMasterVolume * typeVolume;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002731 uint32_t vlr = cblk->volumeLR;
2732 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002733 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2734 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002735 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002736 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2737 right = v_clamped/MAX_GAIN;
2738 }
2739
2740 if (left != mLeftVolFloat || right != mRightVolFloat) {
2741 mLeftVolFloat = left;
2742 mRightVolFloat = right;
2743
2744 // If audio HAL implements volume control,
2745 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002746 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747 left = 1.0f;
2748 right = 1.0f;
2749 }
2750
2751 // Convert volumes from float to 8.24
2752 uint32_t vl = (uint32_t)(left * (1 << 24));
2753 uint32_t vr = (uint32_t)(right * (1 << 24));
2754
2755 // Delegate volume control to effect in track effect chain if needed
2756 // only one effect chain can be present on DirectOutputThread, so if
2757 // there is one, the track is connected to it
2758 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002759 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002760 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761 rampVolume = false;
2762 }
2763 }
2764
2765 // Convert volumes from 8.24 to 4.12 format
2766 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2767 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2768 leftVol = (uint16_t)v_clamped;
2769 v_clamped = (vr + (1 << 11)) >> 12;
2770 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2771 rightVol = (uint16_t)v_clamped;
2772 } else {
2773 leftVol = mLeftVolShort;
2774 rightVol = mRightVolShort;
2775 rampVolume = false;
2776 }
2777
2778 // reset retry count
2779 track->mRetryCount = kMaxTrackRetriesDirect;
2780 activeTrack = t;
2781 mixerStatus = MIXER_TRACKS_READY;
2782 } else {
Steve Block3856b092011-10-20 11:56:00 +01002783 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002784 if (track->isStopped()) {
2785 track->reset();
2786 }
2787 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2788 // We have consumed all the buffers of this track.
2789 // Remove it from the list of active tracks.
2790 trackToRemove = track;
2791 } else {
2792 // No buffers for this track. Give it a few chances to
2793 // fill a buffer, then remove it from active list.
2794 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002795 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796 trackToRemove = track;
2797 } else {
2798 mixerStatus = MIXER_TRACKS_ENABLED;
2799 }
2800 }
2801 }
2802 }
2803
2804 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002805 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806 mActiveTracks.remove(trackToRemove);
2807 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002808 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002809 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002810 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002811 }
2812 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002813 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814 }
2815 }
2816
Eric Laurentde070132010-07-13 04:45:46 -07002817 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818 }
2819
Glenn Kastenf6b16782011-12-15 09:51:17 -08002820 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 AudioBufferProvider::Buffer buffer;
2822 size_t frameCount = mFrameCount;
2823 curBuf = (int8_t *)mMixBuffer;
2824 // output audio to hardware
2825 while (frameCount) {
2826 buffer.frameCount = frameCount;
2827 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002828 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829 memset(curBuf, 0, frameCount * mFrameSize);
2830 break;
2831 }
2832 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2833 frameCount -= buffer.frameCount;
2834 curBuf += buffer.frameCount * mFrameSize;
2835 activeTrack->releaseBuffer(&buffer);
2836 }
2837 sleepTime = 0;
2838 standbyTime = systemTime() + standbyDelay;
2839 } else {
2840 if (sleepTime == 0) {
2841 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2842 sleepTime = activeSleepTime;
2843 } else {
2844 sleepTime = idleSleepTime;
2845 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002846 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2848 sleepTime = 0;
2849 }
2850 }
2851
2852 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002853 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002854 }
2855 // sleepTime == 0 means we must write to audio hardware
2856 if (sleepTime == 0) {
2857 if (mixerStatus == MIXER_TRACKS_READY) {
2858 applyVolume(leftVol, rightVol, rampVolume);
2859 }
2860 for (size_t i = 0; i < effectChains.size(); i ++) {
2861 effectChains[i]->process_l();
2862 }
Eric Laurentde070132010-07-13 04:45:46 -07002863 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864
2865 mLastWriteTime = systemTime();
2866 mInWrite = true;
2867 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002868 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2870 mNumWrites++;
2871 mInWrite = false;
2872 mStandby = false;
2873 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002874 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002875 usleep(sleepTime);
2876 }
2877
2878 // finally let go of removed track, without the lock held
2879 // since we can't guarantee the destructors won't acquire that
2880 // same lock.
2881 trackToRemove.clear();
2882 activeTrack.clear();
2883
2884 // Effect chains will be actually deleted here if they were removed from
2885 // mEffectChains list during mixing or effects processing
2886 effectChains.clear();
2887 }
2888
2889 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002890 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002891 }
2892
Eric Laurentfeb0db62011-07-22 09:04:31 -07002893 releaseWakeLock();
2894
Steve Block3856b092011-10-20 11:56:00 +01002895 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896 return false;
2897}
2898
2899// getTrackName_l() must be called with ThreadBase::mLock held
2900int AudioFlinger::DirectOutputThread::getTrackName_l()
2901{
2902 return 0;
2903}
2904
2905// deleteTrackName_l() must be called with ThreadBase::mLock held
2906void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2907{
2908}
2909
2910// checkForNewParameters_l() must be called with ThreadBase::mLock held
2911bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2912{
2913 bool reconfig = false;
2914
2915 while (!mNewParameters.isEmpty()) {
2916 status_t status = NO_ERROR;
2917 String8 keyValuePair = mNewParameters[0];
2918 AudioParameter param = AudioParameter(keyValuePair);
2919 int value;
2920
2921 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2922 // do not accept frame count changes if tracks are open as the track buffer
2923 // size depends on frame count and correct behavior would not be garantied
2924 // if frame count is changed after track creation
2925 if (!mTracks.isEmpty()) {
2926 status = INVALID_OPERATION;
2927 } else {
2928 reconfig = true;
2929 }
2930 }
2931 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002932 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002933 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002935 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002936 mStandby = true;
2937 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002938 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002939 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002940 }
2941 if (status == NO_ERROR && reconfig) {
2942 readOutputParameters();
2943 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2944 }
2945 }
2946
2947 mNewParameters.removeAt(0);
2948
2949 mParamStatus = status;
2950 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002951 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2952 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002953 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954 }
2955 return reconfig;
2956}
2957
2958uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2959{
2960 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002961 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002962 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002963 } else {
2964 time = 10000;
2965 }
2966 return time;
2967}
2968
2969uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2970{
2971 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002972 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002973 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974 } else {
2975 time = 10000;
2976 }
2977 return time;
2978}
2979
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002980uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2981{
2982 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002983 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002984 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2985 } else {
2986 time = 10000;
2987 }
2988 return time;
2989}
2990
2991
Mathias Agopian65ab4712010-07-14 17:59:35 -07002992// ----------------------------------------------------------------------------
2993
2994AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2995 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2996{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002997 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002998 addOutputTrack(mainThread);
2999}
3000
3001AudioFlinger::DuplicatingThread::~DuplicatingThread()
3002{
3003 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3004 mOutputTracks[i]->destroy();
3005 }
3006 mOutputTracks.clear();
3007}
3008
3009bool AudioFlinger::DuplicatingThread::threadLoop()
3010{
3011 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08003012 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003013 nsecs_t standbyTime = systemTime();
3014 size_t mixBufferSize = mFrameCount*mFrameSize;
3015 SortedVector< sp<OutputTrack> > outputTracks;
3016 uint32_t writeFrames = 0;
3017 uint32_t activeSleepTime = activeSleepTimeUs();
3018 uint32_t idleSleepTime = idleSleepTimeUs();
3019 uint32_t sleepTime = idleSleepTime;
3020 Vector< sp<EffectChain> > effectChains;
3021
Eric Laurentfeb0db62011-07-22 09:04:31 -07003022 acquireWakeLock();
3023
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 while (!exitPending())
3025 {
3026 processConfigEvents();
3027
3028 mixerStatus = MIXER_IDLE;
3029 { // scope for the mLock
3030
3031 Mutex::Autolock _l(mLock);
3032
3033 if (checkForNewParameters_l()) {
3034 mixBufferSize = mFrameCount*mFrameSize;
3035 updateWaitTime();
3036 activeSleepTime = activeSleepTimeUs();
3037 idleSleepTime = idleSleepTimeUs();
3038 }
3039
3040 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3041
3042 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3043 outputTracks.add(mOutputTracks[i]);
3044 }
3045
3046 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003047 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3048 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003049 if (!mStandby) {
3050 for (size_t i = 0; i < outputTracks.size(); i++) {
3051 outputTracks[i]->stop();
3052 }
3053 mStandby = true;
3054 mBytesWritten = 0;
3055 }
3056
3057 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3058 // we're about to wait, flush the binder command buffer
3059 IPCThreadState::self()->flushCommands();
3060 outputTracks.clear();
3061
3062 if (exitPending()) break;
3063
Eric Laurentfeb0db62011-07-22 09:04:31 -07003064 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003065 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003066 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003067 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003068 acquireWakeLock_l();
3069
Eric Laurent27741442012-01-17 19:20:12 -08003070 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003071 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 char value[PROPERTY_VALUE_MAX];
3073 property_get("ro.audio.silent", value, "0");
3074 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003075 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076 setMasterMute(true);
3077 }
3078 }
3079
3080 standbyTime = systemTime() + kStandbyTimeInNsecs;
3081 sleepTime = idleSleepTime;
3082 continue;
3083 }
3084 }
3085
3086 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3087
3088 // prevent any changes in effect chain list and in each effect chain
3089 // during mixing and effect process as the audio buffers could be deleted
3090 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003091 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003092 }
3093
Glenn Kastenf6b16782011-12-15 09:51:17 -08003094 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095 // mix buffers...
3096 if (outputsReady(outputTracks)) {
3097 mAudioMixer->process();
3098 } else {
3099 memset(mMixBuffer, 0, mixBufferSize);
3100 }
3101 sleepTime = 0;
3102 writeFrames = mFrameCount;
3103 } else {
3104 if (sleepTime == 0) {
3105 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3106 sleepTime = activeSleepTime;
3107 } else {
3108 sleepTime = idleSleepTime;
3109 }
3110 } else if (mBytesWritten != 0) {
3111 // flush remaining overflow buffers in output tracks
3112 for (size_t i = 0; i < outputTracks.size(); i++) {
3113 if (outputTracks[i]->isActive()) {
3114 sleepTime = 0;
3115 writeFrames = 0;
3116 memset(mMixBuffer, 0, mixBufferSize);
3117 break;
3118 }
3119 }
3120 }
3121 }
3122
3123 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003124 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 }
3126 // sleepTime == 0 means we must write to audio hardware
3127 if (sleepTime == 0) {
3128 for (size_t i = 0; i < effectChains.size(); i ++) {
3129 effectChains[i]->process_l();
3130 }
3131 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003132 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133
3134 standbyTime = systemTime() + kStandbyTimeInNsecs;
3135 for (size_t i = 0; i < outputTracks.size(); i++) {
3136 outputTracks[i]->write(mMixBuffer, writeFrames);
3137 }
3138 mStandby = false;
3139 mBytesWritten += mixBufferSize;
3140 } else {
3141 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003142 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143 usleep(sleepTime);
3144 }
3145
3146 // finally let go of all our tracks, without the lock held
3147 // since we can't guarantee the destructors won't acquire that
3148 // same lock.
3149 tracksToRemove.clear();
3150 outputTracks.clear();
3151
3152 // Effect chains will be actually deleted here if they were removed from
3153 // mEffectChains list during mixing or effects processing
3154 effectChains.clear();
3155 }
3156
Eric Laurentfeb0db62011-07-22 09:04:31 -07003157 releaseWakeLock();
3158
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 return false;
3160}
3161
3162void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3163{
3164 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3165 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3166 this,
3167 mSampleRate,
3168 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003169 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 frameCount);
3171 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003172 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003174 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175 updateWaitTime();
3176 }
3177}
3178
3179void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3180{
3181 Mutex::Autolock _l(mLock);
3182 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3183 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3184 mOutputTracks[i]->destroy();
3185 mOutputTracks.removeAt(i);
3186 updateWaitTime();
3187 return;
3188 }
3189 }
Steve Block3856b092011-10-20 11:56:00 +01003190 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191}
3192
3193void AudioFlinger::DuplicatingThread::updateWaitTime()
3194{
3195 mWaitTimeMs = UINT_MAX;
3196 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3197 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3198 if (strong != NULL) {
3199 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3200 if (waitTimeMs < mWaitTimeMs) {
3201 mWaitTimeMs = waitTimeMs;
3202 }
3203 }
3204 }
3205}
3206
3207
3208bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3209{
3210 for (size_t i = 0; i < outputTracks.size(); i++) {
3211 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3212 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003213 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214 return false;
3215 }
3216 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3217 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003218 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003219 return false;
3220 }
3221 }
3222 return true;
3223}
3224
3225uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3226{
3227 return (mWaitTimeMs * 1000) / 2;
3228}
3229
3230// ----------------------------------------------------------------------------
3231
3232// TrackBase constructor must be called with AudioFlinger::mLock held
3233AudioFlinger::ThreadBase::TrackBase::TrackBase(
3234 const wp<ThreadBase>& thread,
3235 const sp<Client>& client,
3236 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003237 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003238 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239 int frameCount,
3240 uint32_t flags,
3241 const sp<IMemory>& sharedBuffer,
3242 int sessionId)
3243 : RefBase(),
3244 mThread(thread),
3245 mClient(client),
3246 mCblk(0),
3247 mFrameCount(0),
3248 mState(IDLE),
3249 mClientTid(-1),
3250 mFormat(format),
3251 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3252 mSessionId(sessionId)
3253{
Steve Block3856b092011-10-20 11:56:00 +01003254 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255
Steve Blockb8a80522011-12-20 16:23:08 +00003256 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003258 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3260 if (sharedBuffer == 0) {
3261 size += bufferSize;
3262 }
3263
3264 if (client != NULL) {
3265 mCblkMemory = client->heap()->allocate(size);
3266 if (mCblkMemory != 0) {
3267 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3268 if (mCblk) { // construct the shared structure in-place.
3269 new(mCblk) audio_track_cblk_t();
3270 // clear all buffers
3271 mCblk->frameCount = frameCount;
3272 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003273 mChannelCount = channelCount;
3274 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 if (sharedBuffer == 0) {
3276 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 } else {
3282 mBuffer = sharedBuffer->pointer();
3283 }
3284 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3285 }
3286 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003287 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003288 client->heap()->dump("AudioTrack");
3289 return;
3290 }
3291 } else {
3292 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003293 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294 new(mCblk) audio_track_cblk_t();
3295 // clear all buffers
3296 mCblk->frameCount = frameCount;
3297 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003298 mChannelCount = channelCount;
3299 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3301 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3302 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003303 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304 mCblk->flags = CBLK_UNDERRUN_ON;
3305 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 }
3307}
3308
3309AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3310{
3311 if (mCblk) {
3312 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3313 if (mClient == NULL) {
3314 delete mCblk;
3315 }
3316 }
3317 mCblkMemory.clear(); // and free the shared memory
3318 if (mClient != NULL) {
3319 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3320 mClient.clear();
3321 }
3322}
3323
3324void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3325{
Glenn Kastene0feee32011-12-13 11:53:26 -08003326 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 mFrameCount = buffer->frameCount;
3328 step();
3329 buffer->frameCount = 0;
3330}
3331
3332bool AudioFlinger::ThreadBase::TrackBase::step() {
3333 bool result;
3334 audio_track_cblk_t* cblk = this->cblk();
3335
3336 result = cblk->stepServer(mFrameCount);
3337 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003338 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 mFlags |= STEPSERVER_FAILED;
3340 }
3341 return result;
3342}
3343
3344void AudioFlinger::ThreadBase::TrackBase::reset() {
3345 audio_track_cblk_t* cblk = this->cblk();
3346
3347 cblk->user = 0;
3348 cblk->server = 0;
3349 cblk->userBase = 0;
3350 cblk->serverBase = 0;
3351 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003352 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353}
3354
3355sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3356{
3357 return mCblkMemory;
3358}
3359
3360int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3361 return (int)mCblk->sampleRate;
3362}
3363
3364int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003365 return (const int)mChannelCount;
3366}
3367
3368uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3369 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370}
3371
3372void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3373 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003374 size_t frameSize = cblk->frameSize;
3375 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3376 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377
3378 // Check validity of returned pointer in case the track control block would have been corrupted.
3379 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003380 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003381 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 -07003382 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003384 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385 return 0;
3386 }
3387
3388 return bufferStart;
3389}
3390
3391// ----------------------------------------------------------------------------
3392
3393// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3394AudioFlinger::PlaybackThread::Track::Track(
3395 const wp<ThreadBase>& thread,
3396 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003397 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003399 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003400 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401 int frameCount,
3402 const sp<IMemory>& sharedBuffer,
3403 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003404 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003405 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3406 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407{
3408 if (mCblk != NULL) {
3409 sp<ThreadBase> baseThread = thread.promote();
3410 if (baseThread != 0) {
3411 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3412 mName = playbackThread->getTrackName_l();
3413 mMainBuffer = playbackThread->mixBuffer();
3414 }
Steve Block3856b092011-10-20 11:56:00 +01003415 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003416 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003417 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419 mStreamType = streamType;
3420 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3421 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003422 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 }
3424}
3425
3426AudioFlinger::PlaybackThread::Track::~Track()
3427{
Steve Block3856b092011-10-20 11:56:00 +01003428 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429 sp<ThreadBase> thread = mThread.promote();
3430 if (thread != 0) {
3431 Mutex::Autolock _l(thread->mLock);
3432 mState = TERMINATED;
3433 }
3434}
3435
3436void AudioFlinger::PlaybackThread::Track::destroy()
3437{
3438 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3439 // by removing it from mTracks vector, so there is a risk that this Tracks's
3440 // desctructor is called. As the destructor needs to lock mLock,
3441 // we must acquire a strong reference on this Track before locking mLock
3442 // here so that the destructor is called only when exiting this function.
3443 // On the other hand, as long as Track::destroy() is only called by
3444 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3445 // this Track with its member mTrack.
3446 sp<Track> keep(this);
3447 { // scope for mLock
3448 sp<ThreadBase> thread = mThread.promote();
3449 if (thread != 0) {
3450 if (!isOutputTrack()) {
3451 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003452 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003453 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003454 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003455
3456 // to track the speaker usage
3457 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458 }
3459 AudioSystem::releaseOutput(thread->id());
3460 }
3461 Mutex::Autolock _l(thread->mLock);
3462 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3463 playbackThread->destroyTrack_l(this);
3464 }
3465 }
3466}
3467
3468void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3469{
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003470 uint32_t vlr = mCblk->volumeLR;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003471 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 -07003472 mName - AudioMixer::TRACK0,
3473 (mClient == NULL) ? getpid() : mClient->pid(),
3474 mStreamType,
3475 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003476 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477 mSessionId,
3478 mFrameCount,
3479 mState,
3480 mMute,
3481 mFillingUpStatus,
3482 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003483 vlr & 0xFFFF,
3484 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 mCblk->server,
3486 mCblk->user,
3487 (int)mMainBuffer,
3488 (int)mAuxBuffer);
3489}
3490
3491status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3492{
3493 audio_track_cblk_t* cblk = this->cblk();
3494 uint32_t framesReady;
3495 uint32_t framesReq = buffer->frameCount;
3496
3497 // Check if last stepServer failed, try to step now
3498 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3499 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003500 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3502 }
3503
3504 framesReady = cblk->framesReady();
3505
Glenn Kastenf6b16782011-12-15 09:51:17 -08003506 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003507 uint32_t s = cblk->server;
3508 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3509
3510 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3511 if (framesReq > framesReady) {
3512 framesReq = framesReady;
3513 }
3514 if (s + framesReq > bufferEnd) {
3515 framesReq = bufferEnd - s;
3516 }
3517
3518 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003519 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003520
3521 buffer->frameCount = framesReq;
3522 return NO_ERROR;
3523 }
3524
3525getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003526 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003527 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003528 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529 return NOT_ENOUGH_DATA;
3530}
3531
3532bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003533 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003534
3535 if (mCblk->framesReady() >= mCblk->frameCount ||
3536 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3537 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003538 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003539 return true;
3540 }
3541 return false;
3542}
3543
3544status_t AudioFlinger::PlaybackThread::Track::start()
3545{
3546 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003547 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003548 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003549 sp<ThreadBase> thread = mThread.promote();
3550 if (thread != 0) {
3551 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003552 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003553 // here the track could be either new, or restarted
3554 // in both cases "unstop" the track
3555 if (mState == PAUSED) {
3556 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003557 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558 } else {
3559 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003560 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003561 }
3562
3563 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3564 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003565 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003566 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003567 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003569
3570 // to track the speaker usage
3571 if (status == NO_ERROR) {
3572 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3573 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 }
3575 if (status == NO_ERROR) {
3576 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3577 playbackThread->addTrack_l(this);
3578 } else {
3579 mState = state;
3580 }
3581 } else {
3582 status = BAD_VALUE;
3583 }
3584 return status;
3585}
3586
3587void AudioFlinger::PlaybackThread::Track::stop()
3588{
Steve Block3856b092011-10-20 11:56:00 +01003589 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590 sp<ThreadBase> thread = mThread.promote();
3591 if (thread != 0) {
3592 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003593 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003594 if (mState > STOPPED) {
3595 mState = STOPPED;
3596 // If the track is not active (PAUSED and buffers full), flush buffers
3597 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3598 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3599 reset();
3600 }
Steve Block3856b092011-10-20 11:56:00 +01003601 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003602 }
3603 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3604 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003605 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003606 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003607 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003609
3610 // to track the speaker usage
3611 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612 }
3613 }
3614}
3615
3616void AudioFlinger::PlaybackThread::Track::pause()
3617{
Steve Block3856b092011-10-20 11:56:00 +01003618 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 sp<ThreadBase> thread = mThread.promote();
3620 if (thread != 0) {
3621 Mutex::Autolock _l(thread->mLock);
3622 if (mState == ACTIVE || mState == RESUMING) {
3623 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003624 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625 if (!isOutputTrack()) {
3626 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003627 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003628 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003629 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003631
3632 // to track the speaker usage
3633 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634 }
3635 }
3636 }
3637}
3638
3639void AudioFlinger::PlaybackThread::Track::flush()
3640{
Steve Block3856b092011-10-20 11:56:00 +01003641 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003642 sp<ThreadBase> thread = mThread.promote();
3643 if (thread != 0) {
3644 Mutex::Autolock _l(thread->mLock);
3645 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3646 return;
3647 }
3648 // No point remaining in PAUSED state after a flush => go to
3649 // STOPPED state
3650 mState = STOPPED;
3651
Eric Laurent38ccae22011-03-28 18:37:07 -07003652 // do not reset the track if it is still in the process of being stopped or paused.
3653 // this will be done by prepareTracks_l() when the track is stopped.
3654 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3655 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3656 reset();
3657 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003658 }
3659}
3660
3661void AudioFlinger::PlaybackThread::Track::reset()
3662{
3663 // Do not reset twice to avoid discarding data written just after a flush and before
3664 // the audioflinger thread detects the track is stopped.
3665 if (!mResetDone) {
3666 TrackBase::reset();
3667 // Force underrun condition to avoid false underrun callback until first data is
3668 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003669 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3670 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003671 mFillingUpStatus = FS_FILLING;
3672 mResetDone = true;
3673 }
3674}
3675
3676void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3677{
3678 mMute = muted;
3679}
3680
Mathias Agopian65ab4712010-07-14 17:59:35 -07003681status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3682{
3683 status_t status = DEAD_OBJECT;
3684 sp<ThreadBase> thread = mThread.promote();
3685 if (thread != 0) {
3686 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3687 status = playbackThread->attachAuxEffect(this, EffectId);
3688 }
3689 return status;
3690}
3691
3692void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3693{
3694 mAuxEffectId = EffectId;
3695 mAuxBuffer = buffer;
3696}
3697
3698// ----------------------------------------------------------------------------
3699
3700// RecordTrack constructor must be called with AudioFlinger::mLock held
3701AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3702 const wp<ThreadBase>& thread,
3703 const sp<Client>& client,
3704 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003705 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003706 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003707 int frameCount,
3708 uint32_t flags,
3709 int sessionId)
3710 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003711 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003712 mOverflow(false)
3713{
3714 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003715 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003716 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003717 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003718 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003719 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003720 } else {
3721 mCblk->frameSize = sizeof(int8_t);
3722 }
3723 }
3724}
3725
3726AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3727{
3728 sp<ThreadBase> thread = mThread.promote();
3729 if (thread != 0) {
3730 AudioSystem::releaseInput(thread->id());
3731 }
3732}
3733
3734status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3735{
3736 audio_track_cblk_t* cblk = this->cblk();
3737 uint32_t framesAvail;
3738 uint32_t framesReq = buffer->frameCount;
3739
3740 // Check if last stepServer failed, try to step now
3741 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3742 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003743 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003744 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3745 }
3746
3747 framesAvail = cblk->framesAvailable_l();
3748
Glenn Kastenf6b16782011-12-15 09:51:17 -08003749 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003750 uint32_t s = cblk->server;
3751 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3752
3753 if (framesReq > framesAvail) {
3754 framesReq = framesAvail;
3755 }
3756 if (s + framesReq > bufferEnd) {
3757 framesReq = bufferEnd - s;
3758 }
3759
3760 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003761 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003762
3763 buffer->frameCount = framesReq;
3764 return NO_ERROR;
3765 }
3766
3767getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003768 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769 buffer->frameCount = 0;
3770 return NOT_ENOUGH_DATA;
3771}
3772
3773status_t AudioFlinger::RecordThread::RecordTrack::start()
3774{
3775 sp<ThreadBase> thread = mThread.promote();
3776 if (thread != 0) {
3777 RecordThread *recordThread = (RecordThread *)thread.get();
3778 return recordThread->start(this);
3779 } else {
3780 return BAD_VALUE;
3781 }
3782}
3783
3784void AudioFlinger::RecordThread::RecordTrack::stop()
3785{
3786 sp<ThreadBase> thread = mThread.promote();
3787 if (thread != 0) {
3788 RecordThread *recordThread = (RecordThread *)thread.get();
3789 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003790 TrackBase::reset();
3791 // Force overerrun condition to avoid false overrun callback until first data is
3792 // read from buffer
3793 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003794 }
3795}
3796
3797void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3798{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003799 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003800 (mClient == NULL) ? getpid() : mClient->pid(),
3801 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003802 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003803 mSessionId,
3804 mFrameCount,
3805 mState,
3806 mCblk->sampleRate,
3807 mCblk->server,
3808 mCblk->user);
3809}
3810
3811
3812// ----------------------------------------------------------------------------
3813
3814AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3815 const wp<ThreadBase>& thread,
3816 DuplicatingThread *sourceThread,
3817 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003818 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003819 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003820 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003821 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822 mActive(false), mSourceThread(sourceThread)
3823{
3824
3825 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3826 if (mCblk != NULL) {
3827 mCblk->flags |= CBLK_DIRECTION_OUT;
3828 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003829 mCblk->volumeLR = (MAX_GAIN_INT << 16) | MAX_GAIN_INT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003830 mOutBuffer.frameCount = 0;
3831 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003832 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003833 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3834 mCblk, mBuffer, mCblk->buffers,
3835 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003836 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003837 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003838 }
3839}
3840
3841AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3842{
3843 clearBufferQueue();
3844}
3845
3846status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3847{
3848 status_t status = Track::start();
3849 if (status != NO_ERROR) {
3850 return status;
3851 }
3852
3853 mActive = true;
3854 mRetryCount = 127;
3855 return status;
3856}
3857
3858void AudioFlinger::PlaybackThread::OutputTrack::stop()
3859{
3860 Track::stop();
3861 clearBufferQueue();
3862 mOutBuffer.frameCount = 0;
3863 mActive = false;
3864}
3865
3866bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3867{
3868 Buffer *pInBuffer;
3869 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003870 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003871 bool outputBufferFull = false;
3872 inBuffer.frameCount = frames;
3873 inBuffer.i16 = data;
3874
3875 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3876
3877 if (!mActive && frames != 0) {
3878 start();
3879 sp<ThreadBase> thread = mThread.promote();
3880 if (thread != 0) {
3881 MixerThread *mixerThread = (MixerThread *)thread.get();
3882 if (mCblk->frameCount > frames){
3883 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3884 uint32_t startFrames = (mCblk->frameCount - frames);
3885 pInBuffer = new Buffer;
3886 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3887 pInBuffer->frameCount = startFrames;
3888 pInBuffer->i16 = pInBuffer->mBuffer;
3889 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3890 mBufferQueue.add(pInBuffer);
3891 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003892 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003893 }
3894 }
3895 }
3896 }
3897
3898 while (waitTimeLeftMs) {
3899 // First write pending buffers, then new data
3900 if (mBufferQueue.size()) {
3901 pInBuffer = mBufferQueue.itemAt(0);
3902 } else {
3903 pInBuffer = &inBuffer;
3904 }
3905
3906 if (pInBuffer->frameCount == 0) {
3907 break;
3908 }
3909
3910 if (mOutBuffer.frameCount == 0) {
3911 mOutBuffer.frameCount = pInBuffer->frameCount;
3912 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003913 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003914 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003915 outputBufferFull = true;
3916 break;
3917 }
3918 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3919 if (waitTimeLeftMs >= waitTimeMs) {
3920 waitTimeLeftMs -= waitTimeMs;
3921 } else {
3922 waitTimeLeftMs = 0;
3923 }
3924 }
3925
3926 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3927 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3928 mCblk->stepUser(outFrames);
3929 pInBuffer->frameCount -= outFrames;
3930 pInBuffer->i16 += outFrames * channelCount;
3931 mOutBuffer.frameCount -= outFrames;
3932 mOutBuffer.i16 += outFrames * channelCount;
3933
3934 if (pInBuffer->frameCount == 0) {
3935 if (mBufferQueue.size()) {
3936 mBufferQueue.removeAt(0);
3937 delete [] pInBuffer->mBuffer;
3938 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003939 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003940 } else {
3941 break;
3942 }
3943 }
3944 }
3945
3946 // If we could not write all frames, allocate a buffer and queue it for next time.
3947 if (inBuffer.frameCount) {
3948 sp<ThreadBase> thread = mThread.promote();
3949 if (thread != 0 && !thread->standby()) {
3950 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3951 pInBuffer = new Buffer;
3952 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3953 pInBuffer->frameCount = inBuffer.frameCount;
3954 pInBuffer->i16 = pInBuffer->mBuffer;
3955 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3956 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003957 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003958 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003959 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003960 }
3961 }
3962 }
3963
3964 // Calling write() with a 0 length buffer, means that no more data will be written:
3965 // If no more buffers are pending, fill output track buffer to make sure it is started
3966 // by output mixer.
3967 if (frames == 0 && mBufferQueue.size() == 0) {
3968 if (mCblk->user < mCblk->frameCount) {
3969 frames = mCblk->frameCount - mCblk->user;
3970 pInBuffer = new Buffer;
3971 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3972 pInBuffer->frameCount = frames;
3973 pInBuffer->i16 = pInBuffer->mBuffer;
3974 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3975 mBufferQueue.add(pInBuffer);
3976 } else if (mActive) {
3977 stop();
3978 }
3979 }
3980
3981 return outputBufferFull;
3982}
3983
3984status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3985{
3986 int active;
3987 status_t result;
3988 audio_track_cblk_t* cblk = mCblk;
3989 uint32_t framesReq = buffer->frameCount;
3990
Steve Block3856b092011-10-20 11:56:00 +01003991// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003992 buffer->frameCount = 0;
3993
3994 uint32_t framesAvail = cblk->framesAvailable();
3995
3996
3997 if (framesAvail == 0) {
3998 Mutex::Autolock _l(cblk->lock);
3999 goto start_loop_here;
4000 while (framesAvail == 0) {
4001 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004002 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004003 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004004 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005 }
4006 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4007 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004008 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004009 }
4010 // read the server count again
4011 start_loop_here:
4012 framesAvail = cblk->framesAvailable_l();
4013 }
4014 }
4015
4016// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004017// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004018// }
4019
4020 if (framesReq > framesAvail) {
4021 framesReq = framesAvail;
4022 }
4023
4024 uint32_t u = cblk->user;
4025 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4026
4027 if (u + framesReq > bufferEnd) {
4028 framesReq = bufferEnd - u;
4029 }
4030
4031 buffer->frameCount = framesReq;
4032 buffer->raw = (void *)cblk->buffer(u);
4033 return NO_ERROR;
4034}
4035
4036
4037void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4038{
4039 size_t size = mBufferQueue.size();
4040 Buffer *pBuffer;
4041
4042 for (size_t i = 0; i < size; i++) {
4043 pBuffer = mBufferQueue.itemAt(i);
4044 delete [] pBuffer->mBuffer;
4045 delete pBuffer;
4046 }
4047 mBufferQueue.clear();
4048}
4049
4050// ----------------------------------------------------------------------------
4051
4052AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4053 : RefBase(),
4054 mAudioFlinger(audioFlinger),
4055 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4056 mPid(pid)
4057{
4058 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4059}
4060
4061// Client destructor must be called with AudioFlinger::mLock held
4062AudioFlinger::Client::~Client()
4063{
4064 mAudioFlinger->removeClient_l(mPid);
4065}
4066
4067const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4068{
4069 return mMemoryDealer;
4070}
4071
4072// ----------------------------------------------------------------------------
4073
4074AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4075 const sp<IAudioFlingerClient>& client,
4076 pid_t pid)
4077 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4078{
4079}
4080
4081AudioFlinger::NotificationClient::~NotificationClient()
4082{
4083 mClient.clear();
4084}
4085
4086void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4087{
4088 sp<NotificationClient> keep(this);
4089 {
4090 mAudioFlinger->removeNotificationClient(mPid);
4091 }
4092}
4093
4094// ----------------------------------------------------------------------------
4095
4096AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4097 : BnAudioTrack(),
4098 mTrack(track)
4099{
4100}
4101
4102AudioFlinger::TrackHandle::~TrackHandle() {
4103 // just stop the track on deletion, associated resources
4104 // will be freed from the main thread once all pending buffers have
4105 // been played. Unless it's not in the active track list, in which
4106 // case we free everything now...
4107 mTrack->destroy();
4108}
4109
Glenn Kasten90716c52012-01-26 13:40:12 -08004110sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4111 return mTrack->getCblk();
4112}
4113
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114status_t AudioFlinger::TrackHandle::start() {
4115 return mTrack->start();
4116}
4117
4118void AudioFlinger::TrackHandle::stop() {
4119 mTrack->stop();
4120}
4121
4122void AudioFlinger::TrackHandle::flush() {
4123 mTrack->flush();
4124}
4125
4126void AudioFlinger::TrackHandle::mute(bool e) {
4127 mTrack->mute(e);
4128}
4129
4130void AudioFlinger::TrackHandle::pause() {
4131 mTrack->pause();
4132}
4133
Mathias Agopian65ab4712010-07-14 17:59:35 -07004134status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4135{
4136 return mTrack->attachAuxEffect(EffectId);
4137}
4138
4139status_t AudioFlinger::TrackHandle::onTransact(
4140 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4141{
4142 return BnAudioTrack::onTransact(code, data, reply, flags);
4143}
4144
4145// ----------------------------------------------------------------------------
4146
4147sp<IAudioRecord> AudioFlinger::openRecord(
4148 pid_t pid,
4149 int input,
4150 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004151 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004152 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004153 int frameCount,
4154 uint32_t flags,
4155 int *sessionId,
4156 status_t *status)
4157{
4158 sp<RecordThread::RecordTrack> recordTrack;
4159 sp<RecordHandle> recordHandle;
4160 sp<Client> client;
4161 wp<Client> wclient;
4162 status_t lStatus;
4163 RecordThread *thread;
4164 size_t inFrameCount;
4165 int lSessionId;
4166
4167 // check calling permissions
4168 if (!recordingAllowed()) {
4169 lStatus = PERMISSION_DENIED;
4170 goto Exit;
4171 }
4172
4173 // add client to list
4174 { // scope for mLock
4175 Mutex::Autolock _l(mLock);
4176 thread = checkRecordThread_l(input);
4177 if (thread == NULL) {
4178 lStatus = BAD_VALUE;
4179 goto Exit;
4180 }
4181
4182 wclient = mClients.valueFor(pid);
4183 if (wclient != NULL) {
4184 client = wclient.promote();
4185 } else {
4186 client = new Client(this, pid);
4187 mClients.add(pid, client);
4188 }
4189
4190 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004191 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192 lSessionId = *sessionId;
4193 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004194 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 if (sessionId != NULL) {
4196 *sessionId = lSessionId;
4197 }
4198 }
4199 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004200 recordTrack = thread->createRecordTrack_l(client,
4201 sampleRate,
4202 format,
4203 channelMask,
4204 frameCount,
4205 flags,
4206 lSessionId,
4207 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004208 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004209 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4211 // destructor is called by the TrackBase destructor with mLock held
4212 client.clear();
4213 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214 goto Exit;
4215 }
4216
4217 // return to handle to client
4218 recordHandle = new RecordHandle(recordTrack);
4219 lStatus = NO_ERROR;
4220
4221Exit:
4222 if (status) {
4223 *status = lStatus;
4224 }
4225 return recordHandle;
4226}
4227
4228// ----------------------------------------------------------------------------
4229
4230AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4231 : BnAudioRecord(),
4232 mRecordTrack(recordTrack)
4233{
4234}
4235
4236AudioFlinger::RecordHandle::~RecordHandle() {
4237 stop();
4238}
4239
Glenn Kasten90716c52012-01-26 13:40:12 -08004240sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4241 return mRecordTrack->getCblk();
4242}
4243
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004245 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004246 return mRecordTrack->start();
4247}
4248
4249void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004250 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251 mRecordTrack->stop();
4252}
4253
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254status_t AudioFlinger::RecordHandle::onTransact(
4255 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4256{
4257 return BnAudioRecord::onTransact(code, data, reply, flags);
4258}
4259
4260// ----------------------------------------------------------------------------
4261
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004262AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4263 AudioStreamIn *input,
4264 uint32_t sampleRate,
4265 uint32_t channels,
4266 int id,
4267 uint32_t device) :
4268 ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08004269 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004270{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004271 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004272
4273 snprintf(mName, kNameLength, "AudioIn_%d", id);
4274
Dima Zavinfce7a472011-04-19 22:30:36 -07004275 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004276 mReqSampleRate = sampleRate;
4277 readInputParameters();
4278}
4279
4280
4281AudioFlinger::RecordThread::~RecordThread()
4282{
4283 delete[] mRsmpInBuffer;
Glenn Kastene0feee32011-12-13 11:53:26 -08004284 if (mResampler != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285 delete mResampler;
4286 delete[] mRsmpOutBuffer;
4287 }
4288}
4289
4290void AudioFlinger::RecordThread::onFirstRef()
4291{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004292 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293}
4294
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004295status_t AudioFlinger::RecordThread::readyToRun()
4296{
4297 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004298 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004299 return status;
4300}
4301
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302bool AudioFlinger::RecordThread::threadLoop()
4303{
4304 AudioBufferProvider::Buffer buffer;
4305 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004306 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004307
Eric Laurent44d98482010-09-30 16:12:31 -07004308 nsecs_t lastWarning = 0;
4309
Eric Laurentfeb0db62011-07-22 09:04:31 -07004310 acquireWakeLock();
4311
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312 // start recording
4313 while (!exitPending()) {
4314
4315 processConfigEvents();
4316
4317 { // scope for mLock
4318 Mutex::Autolock _l(mLock);
4319 checkForNewParameters_l();
4320 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4321 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004322 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323 mStandby = true;
4324 }
4325
4326 if (exitPending()) break;
4327
Eric Laurentfeb0db62011-07-22 09:04:31 -07004328 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004329 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004330 // go to sleep
4331 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004332 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004333 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334 continue;
4335 }
4336 if (mActiveTrack != 0) {
4337 if (mActiveTrack->mState == TrackBase::PAUSING) {
4338 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004339 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004340 mStandby = true;
4341 }
4342 mActiveTrack.clear();
4343 mStartStopCond.broadcast();
4344 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4345 if (mReqChannelCount != mActiveTrack->channelCount()) {
4346 mActiveTrack.clear();
4347 mStartStopCond.broadcast();
4348 } else if (mBytesRead != 0) {
4349 // record start succeeds only if first read from audio input
4350 // succeeds
4351 if (mBytesRead > 0) {
4352 mActiveTrack->mState = TrackBase::ACTIVE;
4353 } else {
4354 mActiveTrack.clear();
4355 }
4356 mStartStopCond.broadcast();
4357 }
4358 mStandby = false;
4359 }
4360 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004361 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004362 }
4363
4364 if (mActiveTrack != 0) {
4365 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4366 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004367 unlockEffectChains(effectChains);
4368 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004369 continue;
4370 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004371 for (size_t i = 0; i < effectChains.size(); i ++) {
4372 effectChains[i]->process_l();
4373 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004374
Mathias Agopian65ab4712010-07-14 17:59:35 -07004375 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004376 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004377 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004378 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004379 // no resampling
4380 while (framesOut) {
4381 size_t framesIn = mFrameCount - mRsmpInIndex;
4382 if (framesIn) {
4383 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4384 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4385 if (framesIn > framesOut)
4386 framesIn = framesOut;
4387 mRsmpInIndex += framesIn;
4388 framesOut -= framesIn;
4389 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004390 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004391 memcpy(dst, src, framesIn * mFrameSize);
4392 } else {
4393 int16_t *src16 = (int16_t *)src;
4394 int16_t *dst16 = (int16_t *)dst;
4395 if (mChannelCount == 1) {
4396 while (framesIn--) {
4397 *dst16++ = *src16;
4398 *dst16++ = *src16++;
4399 }
4400 } else {
4401 while (framesIn--) {
4402 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4403 src16 += 2;
4404 }
4405 }
4406 }
4407 }
4408 if (framesOut && mFrameCount == mRsmpInIndex) {
4409 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004410 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004411 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412 framesOut = 0;
4413 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004414 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004415 mRsmpInIndex = 0;
4416 }
4417 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004418 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004419 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4420 // Force input into standby so that it tries to
4421 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004422 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004423 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004424 }
4425 mRsmpInIndex = mFrameCount;
4426 framesOut = 0;
4427 buffer.frameCount = 0;
4428 }
4429 }
4430 }
4431 } else {
4432 // resampling
4433
4434 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4435 // alter output frame count as if we were expecting stereo samples
4436 if (mChannelCount == 1 && mReqChannelCount == 1) {
4437 framesOut >>= 1;
4438 }
4439 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4440 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4441 // are 32 bit aligned which should be always true.
4442 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004443 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444 // the resampler always outputs stereo samples: do post stereo to mono conversion
4445 int16_t *src = (int16_t *)mRsmpOutBuffer;
4446 int16_t *dst = buffer.i16;
4447 while (framesOut--) {
4448 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4449 src += 2;
4450 }
4451 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004452 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453 }
4454
4455 }
4456 mActiveTrack->releaseBuffer(&buffer);
4457 mActiveTrack->overflow();
4458 }
4459 // client isn't retrieving buffers fast enough
4460 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004461 if (!mActiveTrack->setOverflow()) {
4462 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004463 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004464 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004465 lastWarning = now;
4466 }
4467 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004468 // Release the processor for a while before asking for a new buffer.
4469 // This will give the application more chance to read from the buffer and
4470 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004471 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004472 }
4473 }
Eric Laurentec437d82011-07-26 20:54:46 -07004474 // enable changes in effect chain
4475 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004476 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004477 }
4478
4479 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004480 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004481 }
4482 mActiveTrack.clear();
4483
4484 mStartStopCond.broadcast();
4485
Eric Laurentfeb0db62011-07-22 09:04:31 -07004486 releaseWakeLock();
4487
Steve Block3856b092011-10-20 11:56:00 +01004488 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489 return false;
4490}
4491
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004492
4493sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4494 const sp<AudioFlinger::Client>& client,
4495 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004496 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004497 int channelMask,
4498 int frameCount,
4499 uint32_t flags,
4500 int sessionId,
4501 status_t *status)
4502{
4503 sp<RecordTrack> track;
4504 status_t lStatus;
4505
4506 lStatus = initCheck();
4507 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004508 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004509 goto Exit;
4510 }
4511
4512 { // scope for mLock
4513 Mutex::Autolock _l(mLock);
4514
4515 track = new RecordTrack(this, client, sampleRate,
4516 format, channelMask, frameCount, flags, sessionId);
4517
4518 if (track->getCblk() == NULL) {
4519 lStatus = NO_MEMORY;
4520 goto Exit;
4521 }
4522
4523 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004524 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4525 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004526 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004527 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4528 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004529 }
4530 lStatus = NO_ERROR;
4531
4532Exit:
4533 if (status) {
4534 *status = lStatus;
4535 }
4536 return track;
4537}
4538
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4540{
Steve Block3856b092011-10-20 11:56:00 +01004541 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 sp <ThreadBase> strongMe = this;
4543 status_t status = NO_ERROR;
4544 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004545 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004546 if (mActiveTrack != 0) {
4547 if (recordTrack != mActiveTrack.get()) {
4548 status = -EBUSY;
4549 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4550 mActiveTrack->mState = TrackBase::ACTIVE;
4551 }
4552 return status;
4553 }
4554
4555 recordTrack->mState = TrackBase::IDLE;
4556 mActiveTrack = recordTrack;
4557 mLock.unlock();
4558 status_t status = AudioSystem::startInput(mId);
4559 mLock.lock();
4560 if (status != NO_ERROR) {
4561 mActiveTrack.clear();
4562 return status;
4563 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 mRsmpInIndex = mFrameCount;
4565 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004566 if (mResampler != NULL) {
4567 mResampler->reset();
4568 }
4569 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004571 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004572 mWaitWorkCV.signal();
4573 // do not wait for mStartStopCond if exiting
4574 if (mExiting) {
4575 mActiveTrack.clear();
4576 status = INVALID_OPERATION;
4577 goto startError;
4578 }
4579 mStartStopCond.wait(mLock);
4580 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004581 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004582 status = BAD_VALUE;
4583 goto startError;
4584 }
Steve Block3856b092011-10-20 11:56:00 +01004585 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586 return status;
4587 }
4588startError:
4589 AudioSystem::stopInput(mId);
4590 return status;
4591}
4592
4593void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004594 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004595 sp <ThreadBase> strongMe = this;
4596 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004597 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004598 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4599 mActiveTrack->mState = TrackBase::PAUSING;
4600 // do not wait for mStartStopCond if exiting
4601 if (mExiting) {
4602 return;
4603 }
4604 mStartStopCond.wait(mLock);
4605 // if we have been restarted, recordTrack == mActiveTrack.get() here
4606 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4607 mLock.unlock();
4608 AudioSystem::stopInput(mId);
4609 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004610 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004611 }
4612 }
4613 }
4614}
4615
4616status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4617{
4618 const size_t SIZE = 256;
4619 char buffer[SIZE];
4620 String8 result;
4621 pid_t pid = 0;
4622
4623 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4624 result.append(buffer);
4625
4626 if (mActiveTrack != 0) {
4627 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004628 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004629 mActiveTrack->dump(buffer, SIZE);
4630 result.append(buffer);
4631
4632 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4633 result.append(buffer);
4634 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4635 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004636 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004637 result.append(buffer);
4638 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4639 result.append(buffer);
4640 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4641 result.append(buffer);
4642
4643
4644 } else {
4645 result.append("No record client\n");
4646 }
4647 write(fd, result.string(), result.size());
4648
4649 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004650 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004651
4652 return NO_ERROR;
4653}
4654
4655status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4656{
4657 size_t framesReq = buffer->frameCount;
4658 size_t framesReady = mFrameCount - mRsmpInIndex;
4659 int channelCount;
4660
4661 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004662 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004663 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004664 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004665 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4666 // Force input into standby so that it tries to
4667 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004668 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004669 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004670 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004671 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004672 buffer->frameCount = 0;
4673 return NOT_ENOUGH_DATA;
4674 }
4675 mRsmpInIndex = 0;
4676 framesReady = mFrameCount;
4677 }
4678
4679 if (framesReq > framesReady) {
4680 framesReq = framesReady;
4681 }
4682
4683 if (mChannelCount == 1 && mReqChannelCount == 2) {
4684 channelCount = 1;
4685 } else {
4686 channelCount = 2;
4687 }
4688 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4689 buffer->frameCount = framesReq;
4690 return NO_ERROR;
4691}
4692
4693void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4694{
4695 mRsmpInIndex += buffer->frameCount;
4696 buffer->frameCount = 0;
4697}
4698
4699bool AudioFlinger::RecordThread::checkForNewParameters_l()
4700{
4701 bool reconfig = false;
4702
4703 while (!mNewParameters.isEmpty()) {
4704 status_t status = NO_ERROR;
4705 String8 keyValuePair = mNewParameters[0];
4706 AudioParameter param = AudioParameter(keyValuePair);
4707 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004708 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004709 int reqSamplingRate = mReqSampleRate;
4710 int reqChannelCount = mReqChannelCount;
4711
4712 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4713 reqSamplingRate = value;
4714 reconfig = true;
4715 }
4716 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004717 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004718 reconfig = true;
4719 }
4720 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004721 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004722 reconfig = true;
4723 }
4724 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4725 // do not accept frame count changes if tracks are open as the track buffer
4726 // size depends on frame count and correct behavior would not be garantied
4727 // if frame count is changed after track creation
4728 if (mActiveTrack != 0) {
4729 status = INVALID_OPERATION;
4730 } else {
4731 reconfig = true;
4732 }
4733 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004734 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4735 // forward device change to effects that have requested to be
4736 // aware of attached audio device.
4737 for (size_t i = 0; i < mEffectChains.size(); i++) {
4738 mEffectChains[i]->setDevice_l(value);
4739 }
4740 // store input device and output device but do not forward output device to audio HAL.
4741 // Note that status is ignored by the caller for output device
4742 // (see AudioFlinger::setParameters()
4743 if (value & AUDIO_DEVICE_OUT_ALL) {
4744 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4745 status = BAD_VALUE;
4746 } else {
4747 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004748 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4749 if (mTrack != NULL) {
4750 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004751 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004752 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4753 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4754 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004755 }
4756 mDevice |= (uint32_t)value;
4757 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004758 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004759 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004760 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004761 mInput->stream->common.standby(&mInput->stream->common);
4762 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004763 }
4764 if (reconfig) {
4765 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004766 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004767 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004768 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4769 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004770 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004771 status = NO_ERROR;
4772 }
4773 if (status == NO_ERROR) {
4774 readInputParameters();
4775 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4776 }
4777 }
4778 }
4779
4780 mNewParameters.removeAt(0);
4781
4782 mParamStatus = status;
4783 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004784 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4785 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004786 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004787 }
4788 return reconfig;
4789}
4790
4791String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4792{
Dima Zavinfce7a472011-04-19 22:30:36 -07004793 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004794 String8 out_s8 = String8();
4795
4796 Mutex::Autolock _l(mLock);
4797 if (initCheck() != NO_ERROR) {
4798 return out_s8;
4799 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004800
Dima Zavin799a70e2011-04-18 16:57:27 -07004801 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004802 out_s8 = String8(s);
4803 free(s);
4804 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004805}
4806
4807void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4808 AudioSystem::OutputDescriptor desc;
4809 void *param2 = 0;
4810
4811 switch (event) {
4812 case AudioSystem::INPUT_OPENED:
4813 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004814 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004815 desc.samplingRate = mSampleRate;
4816 desc.format = mFormat;
4817 desc.frameCount = mFrameCount;
4818 desc.latency = 0;
4819 param2 = &desc;
4820 break;
4821
4822 case AudioSystem::INPUT_CLOSED:
4823 default:
4824 break;
4825 }
4826 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4827}
4828
4829void AudioFlinger::RecordThread::readInputParameters()
4830{
4831 if (mRsmpInBuffer) delete mRsmpInBuffer;
4832 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4833 if (mResampler) delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004834 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004835
Dima Zavin799a70e2011-04-18 16:57:27 -07004836 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004837 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4838 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004839 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004840 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004841 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004842 mFrameCount = mInputBytes / mFrameSize;
4843 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4844
4845 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4846 {
4847 int channelCount;
4848 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4849 // stereo to mono post process as the resampler always outputs stereo.
4850 if (mChannelCount == 1 && mReqChannelCount == 2) {
4851 channelCount = 1;
4852 } else {
4853 channelCount = 2;
4854 }
4855 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4856 mResampler->setSampleRate(mSampleRate);
4857 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4858 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4859
4860 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4861 if (mChannelCount == 1 && mReqChannelCount == 1) {
4862 mFrameCount >>= 1;
4863 }
4864
4865 }
4866 mRsmpInIndex = mFrameCount;
4867}
4868
4869unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4870{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004871 Mutex::Autolock _l(mLock);
4872 if (initCheck() != NO_ERROR) {
4873 return 0;
4874 }
4875
Dima Zavin799a70e2011-04-18 16:57:27 -07004876 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004877}
4878
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004879uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4880{
4881 Mutex::Autolock _l(mLock);
4882 uint32_t result = 0;
4883 if (getEffectChain_l(sessionId) != 0) {
4884 result = EFFECT_SESSION;
4885 }
4886
4887 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4888 result |= TRACK_SESSION;
4889 }
4890
4891 return result;
4892}
4893
Eric Laurent59bd0da2011-08-01 09:52:20 -07004894AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4895{
4896 Mutex::Autolock _l(mLock);
4897 return mTrack;
4898}
4899
Glenn Kastenaed850d2012-01-26 09:46:34 -08004900AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004901{
4902 Mutex::Autolock _l(mLock);
4903 return mInput;
4904}
4905
4906AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4907{
4908 Mutex::Autolock _l(mLock);
4909 AudioStreamIn *input = mInput;
4910 mInput = NULL;
4911 return input;
4912}
4913
4914// this method must always be called either with ThreadBase mLock held or inside the thread loop
4915audio_stream_t* AudioFlinger::RecordThread::stream()
4916{
4917 if (mInput == NULL) {
4918 return NULL;
4919 }
4920 return &mInput->stream->common;
4921}
4922
4923
Mathias Agopian65ab4712010-07-14 17:59:35 -07004924// ----------------------------------------------------------------------------
4925
4926int AudioFlinger::openOutput(uint32_t *pDevices,
4927 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004928 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004929 uint32_t *pChannels,
4930 uint32_t *pLatencyMs,
4931 uint32_t flags)
4932{
4933 status_t status;
4934 PlaybackThread *thread = NULL;
4935 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4936 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004937 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004938 uint32_t channels = pChannels ? *pChannels : 0;
4939 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004940 audio_stream_out_t *outStream;
4941 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004942
Steve Block3856b092011-10-20 11:56:00 +01004943 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004944 pDevices ? *pDevices : 0,
4945 samplingRate,
4946 format,
4947 channels,
4948 flags);
4949
4950 if (pDevices == NULL || *pDevices == 0) {
4951 return 0;
4952 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004953
Mathias Agopian65ab4712010-07-14 17:59:35 -07004954 Mutex::Autolock _l(mLock);
4955
Dima Zavin799a70e2011-04-18 16:57:27 -07004956 outHwDev = findSuitableHwDev_l(*pDevices);
4957 if (outHwDev == NULL)
4958 return 0;
4959
Glenn Kasten58f30212012-01-12 12:27:51 -08004960 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004961 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004962 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004963 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004964 samplingRate,
4965 format,
4966 channels,
4967 status);
4968
4969 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004970 if (outStream != NULL) {
4971 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004972 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004973
Dima Zavinfce7a472011-04-19 22:30:36 -07004974 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4975 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4976 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004977 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004978 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979 } else {
4980 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004981 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004982 }
4983 mPlaybackThreads.add(id, thread);
4984
4985 if (pSamplingRate) *pSamplingRate = samplingRate;
4986 if (pFormat) *pFormat = format;
4987 if (pChannels) *pChannels = channels;
4988 if (pLatencyMs) *pLatencyMs = thread->latency();
4989
4990 // notify client processes of the new output creation
4991 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4992 return id;
4993 }
4994
4995 return 0;
4996}
4997
4998int AudioFlinger::openDuplicateOutput(int output1, int output2)
4999{
5000 Mutex::Autolock _l(mLock);
5001 MixerThread *thread1 = checkMixerThread_l(output1);
5002 MixerThread *thread2 = checkMixerThread_l(output2);
5003
5004 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005005 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005006 return 0;
5007 }
5008
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005009 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005010 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5011 thread->addOutputTrack(thread2);
5012 mPlaybackThreads.add(id, thread);
5013 // notify client processes of the new output creation
5014 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5015 return id;
5016}
5017
5018status_t AudioFlinger::closeOutput(int output)
5019{
5020 // keep strong reference on the playback thread so that
5021 // it is not destroyed while exit() is executed
5022 sp <PlaybackThread> thread;
5023 {
5024 Mutex::Autolock _l(mLock);
5025 thread = checkPlaybackThread_l(output);
5026 if (thread == NULL) {
5027 return BAD_VALUE;
5028 }
5029
Steve Block3856b092011-10-20 11:56:00 +01005030 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005031
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005032 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005033 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005034 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005035 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5036 dupThread->removeOutputTrack((MixerThread *)thread.get());
5037 }
5038 }
5039 }
5040 void *param2 = 0;
5041 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5042 mPlaybackThreads.removeItem(output);
5043 }
5044 thread->exit();
5045
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005046 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005047 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005048 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005049 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005050 out->hwDev->close_output_stream(out->hwDev, out->stream);
5051 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052 }
5053 return NO_ERROR;
5054}
5055
5056status_t AudioFlinger::suspendOutput(int output)
5057{
5058 Mutex::Autolock _l(mLock);
5059 PlaybackThread *thread = checkPlaybackThread_l(output);
5060
5061 if (thread == NULL) {
5062 return BAD_VALUE;
5063 }
5064
Steve Block3856b092011-10-20 11:56:00 +01005065 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005066 thread->suspend();
5067
5068 return NO_ERROR;
5069}
5070
5071status_t AudioFlinger::restoreOutput(int output)
5072{
5073 Mutex::Autolock _l(mLock);
5074 PlaybackThread *thread = checkPlaybackThread_l(output);
5075
5076 if (thread == NULL) {
5077 return BAD_VALUE;
5078 }
5079
Steve Block3856b092011-10-20 11:56:00 +01005080 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005081
5082 thread->restore();
5083
5084 return NO_ERROR;
5085}
5086
5087int AudioFlinger::openInput(uint32_t *pDevices,
5088 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005089 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090 uint32_t *pChannels,
5091 uint32_t acoustics)
5092{
5093 status_t status;
5094 RecordThread *thread = NULL;
5095 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005096 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005097 uint32_t channels = pChannels ? *pChannels : 0;
5098 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005099 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005100 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005101 audio_stream_in_t *inStream;
5102 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103
5104 if (pDevices == NULL || *pDevices == 0) {
5105 return 0;
5106 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005107
Mathias Agopian65ab4712010-07-14 17:59:35 -07005108 Mutex::Autolock _l(mLock);
5109
Dima Zavin799a70e2011-04-18 16:57:27 -07005110 inHwDev = findSuitableHwDev_l(*pDevices);
5111 if (inHwDev == NULL)
5112 return 0;
5113
Glenn Kasten58f30212012-01-12 12:27:51 -08005114 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005115 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005116 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005117 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005118 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005119 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005120 samplingRate,
5121 format,
5122 channels,
5123 acoustics,
5124 status);
5125
5126 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5127 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5128 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005129 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005130 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005131 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005132 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005133 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005134 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005135 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005136 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005137 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 }
5139
Dima Zavin799a70e2011-04-18 16:57:27 -07005140 if (inStream != NULL) {
5141 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5142
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005143 int id = nextUniqueId();
5144 // Start record thread
5145 // RecorThread require both input and output device indication to forward to audio
5146 // pre processing modules
5147 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5148 thread = new RecordThread(this,
5149 input,
5150 reqSamplingRate,
5151 reqChannels,
5152 id,
5153 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005154 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005155 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005156 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5157 if (pFormat) *pFormat = format;
5158 if (pChannels) *pChannels = reqChannels;
5159
Dima Zavin799a70e2011-04-18 16:57:27 -07005160 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005161
5162 // notify client processes of the new input creation
5163 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5164 return id;
5165 }
5166
5167 return 0;
5168}
5169
5170status_t AudioFlinger::closeInput(int input)
5171{
5172 // keep strong reference on the record thread so that
5173 // it is not destroyed while exit() is executed
5174 sp <RecordThread> thread;
5175 {
5176 Mutex::Autolock _l(mLock);
5177 thread = checkRecordThread_l(input);
5178 if (thread == NULL) {
5179 return BAD_VALUE;
5180 }
5181
Steve Block3856b092011-10-20 11:56:00 +01005182 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005183 void *param2 = 0;
5184 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5185 mRecordThreads.removeItem(input);
5186 }
5187 thread->exit();
5188
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005189 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005190 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005191 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005192 in->hwDev->close_input_stream(in->hwDev, in->stream);
5193 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005194
5195 return NO_ERROR;
5196}
5197
Glenn Kastenfff6d712012-01-12 16:38:12 -08005198status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005199{
5200 Mutex::Autolock _l(mLock);
5201 MixerThread *dstThread = checkMixerThread_l(output);
5202 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005203 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005204 return BAD_VALUE;
5205 }
5206
Steve Block3856b092011-10-20 11:56:00 +01005207 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005208 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5209
Eric Laurent9f6530f2011-08-30 10:18:54 -07005210 dstThread->setStreamValid(stream, true);
5211
Mathias Agopian65ab4712010-07-14 17:59:35 -07005212 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5213 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5214 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005215 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005216 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005217 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005218 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005219 }
Eric Laurentde070132010-07-13 04:45:46 -07005220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005221
5222 return NO_ERROR;
5223}
5224
5225
5226int AudioFlinger::newAudioSessionId()
5227{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005228 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005229}
5230
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005231void AudioFlinger::acquireAudioSessionId(int audioSession)
5232{
5233 Mutex::Autolock _l(mLock);
5234 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005235 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005236 int num = mAudioSessionRefs.size();
5237 for (int i = 0; i< num; i++) {
5238 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5239 if (ref->sessionid == audioSession && ref->pid == caller) {
5240 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005241 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005242 return;
5243 }
5244 }
5245 AudioSessionRef *ref = new AudioSessionRef();
5246 ref->sessionid = audioSession;
5247 ref->pid = caller;
5248 ref->cnt = 1;
5249 mAudioSessionRefs.push(ref);
Steve Block3856b092011-10-20 11:56:00 +01005250 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005251}
5252
5253void AudioFlinger::releaseAudioSessionId(int audioSession)
5254{
5255 Mutex::Autolock _l(mLock);
5256 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005257 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005258 int num = mAudioSessionRefs.size();
5259 for (int i = 0; i< num; i++) {
5260 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5261 if (ref->sessionid == audioSession && ref->pid == caller) {
5262 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005263 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005264 if (ref->cnt == 0) {
5265 mAudioSessionRefs.removeAt(i);
5266 delete ref;
5267 purgeStaleEffects_l();
5268 }
5269 return;
5270 }
5271 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005272 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005273}
5274
5275void AudioFlinger::purgeStaleEffects_l() {
5276
Steve Block3856b092011-10-20 11:56:00 +01005277 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005278
5279 Vector< sp<EffectChain> > chains;
5280
5281 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5282 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5283 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5284 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005285 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5286 chains.push(ec);
5287 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005288 }
5289 }
5290 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5291 sp<RecordThread> t = mRecordThreads.valueAt(i);
5292 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5293 sp<EffectChain> ec = t->mEffectChains[j];
5294 chains.push(ec);
5295 }
5296 }
5297
5298 for (size_t i = 0; i < chains.size(); i++) {
5299 sp<EffectChain> ec = chains[i];
5300 int sessionid = ec->sessionId();
5301 sp<ThreadBase> t = ec->mThread.promote();
5302 if (t == 0) {
5303 continue;
5304 }
5305 size_t numsessionrefs = mAudioSessionRefs.size();
5306 bool found = false;
5307 for (size_t k = 0; k < numsessionrefs; k++) {
5308 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5309 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005310 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005311 sessionid, ref->pid, ref->cnt);
5312 found = true;
5313 break;
5314 }
5315 }
5316 if (!found) {
5317 // remove all effects from the chain
5318 while (ec->mEffects.size()) {
5319 sp<EffectModule> effect = ec->mEffects[0];
5320 effect->unPin();
5321 Mutex::Autolock _l (t->mLock);
5322 t->removeEffect_l(effect);
5323 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5324 sp<EffectHandle> handle = effect->mHandles[j].promote();
5325 if (handle != 0) {
5326 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005327 if (handle->mHasControl && handle->mEnabled) {
5328 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5329 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005330 }
5331 }
5332 AudioSystem::unregisterEffect(effect->id());
5333 }
5334 }
5335 }
5336 return;
5337}
5338
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5340AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5341{
5342 PlaybackThread *thread = NULL;
5343 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5344 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5345 }
5346 return thread;
5347}
5348
5349// checkMixerThread_l() must be called with AudioFlinger::mLock held
5350AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5351{
5352 PlaybackThread *thread = checkPlaybackThread_l(output);
5353 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005354 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005355 thread = NULL;
5356 }
5357 }
5358 return (MixerThread *)thread;
5359}
5360
5361// checkRecordThread_l() must be called with AudioFlinger::mLock held
5362AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5363{
5364 RecordThread *thread = NULL;
5365 if (mRecordThreads.indexOfKey(input) >= 0) {
5366 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5367 }
5368 return thread;
5369}
5370
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005371uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005373 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005374}
5375
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005376AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5377{
5378 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5379 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005380 AudioStreamOut *output = thread->getOutput();
5381 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005382 return thread;
5383 }
5384 }
5385 return NULL;
5386}
5387
5388uint32_t AudioFlinger::primaryOutputDevice_l()
5389{
5390 PlaybackThread *thread = primaryPlaybackThread_l();
5391
5392 if (thread == NULL) {
5393 return 0;
5394 }
5395
5396 return thread->device();
5397}
5398
5399
Mathias Agopian65ab4712010-07-14 17:59:35 -07005400// ----------------------------------------------------------------------------
5401// Effect management
5402// ----------------------------------------------------------------------------
5403
5404
Mathias Agopian65ab4712010-07-14 17:59:35 -07005405status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5406{
5407 Mutex::Autolock _l(mLock);
5408 return EffectQueryNumberEffects(numEffects);
5409}
5410
5411status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5412{
5413 Mutex::Autolock _l(mLock);
5414 return EffectQueryEffect(index, descriptor);
5415}
5416
5417status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5418{
5419 Mutex::Autolock _l(mLock);
5420 return EffectGetDescriptor(pUuid, descriptor);
5421}
5422
5423
Mathias Agopian65ab4712010-07-14 17:59:35 -07005424sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5425 effect_descriptor_t *pDesc,
5426 const sp<IEffectClient>& effectClient,
5427 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005428 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005429 int sessionId,
5430 status_t *status,
5431 int *id,
5432 int *enabled)
5433{
5434 status_t lStatus = NO_ERROR;
5435 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005436 effect_descriptor_t desc;
5437 sp<Client> client;
5438 wp<Client> wclient;
5439
Steve Block3856b092011-10-20 11:56:00 +01005440 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005441 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442
5443 if (pDesc == NULL) {
5444 lStatus = BAD_VALUE;
5445 goto Exit;
5446 }
5447
Eric Laurent84e9a102010-09-23 16:10:16 -07005448 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005449 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005450 lStatus = PERMISSION_DENIED;
5451 goto Exit;
5452 }
5453
Dima Zavinfce7a472011-04-19 22:30:36 -07005454 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005455 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005456 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005457 lStatus = PERMISSION_DENIED;
5458 goto Exit;
5459 }
5460
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005461 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005462 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005463 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005464 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005465 lStatus = BAD_VALUE;
5466 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005467 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005468 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005469 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005470 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005471 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005472 }
5473 }
5474
Mathias Agopian65ab4712010-07-14 17:59:35 -07005475 {
5476 Mutex::Autolock _l(mLock);
5477
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478
5479 if (!EffectIsNullUuid(&pDesc->uuid)) {
5480 // if uuid is specified, request effect descriptor
5481 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5482 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005483 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005484 goto Exit;
5485 }
5486 } else {
5487 // if uuid is not specified, look for an available implementation
5488 // of the required type in effect factory
5489 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005490 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 lStatus = BAD_VALUE;
5492 goto Exit;
5493 }
5494 uint32_t numEffects = 0;
5495 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005496 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005497 bool found = false;
5498
5499 lStatus = EffectQueryNumberEffects(&numEffects);
5500 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005501 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005502 goto Exit;
5503 }
5504 for (uint32_t i = 0; i < numEffects; i++) {
5505 lStatus = EffectQueryEffect(i, &desc);
5506 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005507 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005508 continue;
5509 }
5510 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5511 // If matching type found save effect descriptor. If the session is
5512 // 0 and the effect is not auxiliary, continue enumeration in case
5513 // an auxiliary version of this effect type is available
5514 found = true;
5515 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005516 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005517 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5518 break;
5519 }
5520 }
5521 }
5522 if (!found) {
5523 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005524 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 goto Exit;
5526 }
5527 // For same effect type, chose auxiliary version over insert version if
5528 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005529 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005530 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5531 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5532 }
5533 }
5534
5535 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005536 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005537 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5538 lStatus = INVALID_OPERATION;
5539 goto Exit;
5540 }
5541
Eric Laurent59255e42011-07-27 19:49:51 -07005542 // check recording permission for visualizer
5543 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5544 !recordingAllowed()) {
5545 lStatus = PERMISSION_DENIED;
5546 goto Exit;
5547 }
5548
Mathias Agopian65ab4712010-07-14 17:59:35 -07005549 // return effect descriptor
5550 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5551
5552 // If output is not specified try to find a matching audio session ID in one of the
5553 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005554 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5555 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005556 // Note: io is never 0 when creating an effect on an input
5557 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005558 // look for the thread where the specified audio session is present
5559 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5560 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005561 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005562 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005563 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005564 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005565 if (io == 0) {
5566 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5567 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5568 io = mRecordThreads.keyAt(i);
5569 break;
5570 }
5571 }
5572 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005573 // If no output thread contains the requested session ID, default to
5574 // first output. The effect chain will be moved to the correct output
5575 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005576 if (io == 0 && mPlaybackThreads.size()) {
5577 io = mPlaybackThreads.keyAt(0);
5578 }
Steve Block3856b092011-10-20 11:56:00 +01005579 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005580 }
5581 ThreadBase *thread = checkRecordThread_l(io);
5582 if (thread == NULL) {
5583 thread = checkPlaybackThread_l(io);
5584 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005585 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005586 lStatus = BAD_VALUE;
5587 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005588 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005589 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005590
Mathias Agopian65ab4712010-07-14 17:59:35 -07005591 wclient = mClients.valueFor(pid);
5592
5593 if (wclient != NULL) {
5594 client = wclient.promote();
5595 } else {
5596 client = new Client(this, pid);
5597 mClients.add(pid, client);
5598 }
5599
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005600 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005601 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5602 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005603 if (handle != 0 && id != NULL) {
5604 *id = handle->id();
5605 }
5606 }
5607
5608Exit:
5609 if(status) {
5610 *status = lStatus;
5611 }
5612 return handle;
5613}
5614
Eric Laurent59255e42011-07-27 19:49:51 -07005615status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005616{
Steve Block3856b092011-10-20 11:56:00 +01005617 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005618 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005619 Mutex::Autolock _l(mLock);
5620 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005621 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005622 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005623 }
Eric Laurentde070132010-07-13 04:45:46 -07005624 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5625 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005626 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005627 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005628 }
Eric Laurentde070132010-07-13 04:45:46 -07005629 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5630 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005631 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005632 return BAD_VALUE;
5633 }
5634
5635 Mutex::Autolock _dl(dstThread->mLock);
5636 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005637 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005638
Mathias Agopian65ab4712010-07-14 17:59:35 -07005639 return NO_ERROR;
5640}
5641
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005642// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005643status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005644 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005645 AudioFlinger::PlaybackThread *dstThread,
5646 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005647{
Steve Block3856b092011-10-20 11:56:00 +01005648 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005649 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005650
Eric Laurent59255e42011-07-27 19:49:51 -07005651 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005652 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005653 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005654 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005655 return INVALID_OPERATION;
5656 }
5657
Eric Laurent39e94f82010-07-28 01:32:47 -07005658 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005659 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005660 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005661 // removed.
5662 srcThread->removeEffectChain_l(chain);
5663
5664 // transfer all effects one by one so that new effect chain is created on new thread with
5665 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005666 int dstOutput = dstThread->id();
5667 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005668 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005669 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5670 while (effect != 0) {
5671 srcThread->removeEffect_l(effect);
5672 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005673 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5674 if (effect->state() == EffectModule::ACTIVE ||
5675 effect->state() == EffectModule::STOPPING) {
5676 effect->start();
5677 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005678 // if the move request is not received from audio policy manager, the effect must be
5679 // re-registered with the new strategy and output
5680 if (dstChain == 0) {
5681 dstChain = effect->chain().promote();
5682 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005683 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005684 srcThread->addEffect_l(effect);
5685 return NO_INIT;
5686 }
5687 strategy = dstChain->strategy();
5688 }
5689 if (reRegister) {
5690 AudioSystem::unregisterEffect(effect->id());
5691 AudioSystem::registerEffect(&effect->desc(),
5692 dstOutput,
5693 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005694 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005695 effect->id());
5696 }
Eric Laurentde070132010-07-13 04:45:46 -07005697 effect = chain->getEffectFromId_l(0);
5698 }
5699
5700 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701}
5702
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005703
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005705sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005706 const sp<AudioFlinger::Client>& client,
5707 const sp<IEffectClient>& effectClient,
5708 int32_t priority,
5709 int sessionId,
5710 effect_descriptor_t *desc,
5711 int *enabled,
5712 status_t *status
5713 )
5714{
5715 sp<EffectModule> effect;
5716 sp<EffectHandle> handle;
5717 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005719 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005720 bool effectCreated = false;
5721 bool effectRegistered = false;
5722
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005723 lStatus = initCheck();
5724 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005725 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726 goto Exit;
5727 }
5728
5729 // Do not allow effects with session ID 0 on direct output or duplicating threads
5730 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005731 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005732 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005733 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734 lStatus = BAD_VALUE;
5735 goto Exit;
5736 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005737 // Only Pre processor effects are allowed on input threads and only on input threads
5738 if ((mType == RECORD &&
5739 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5740 (mType != RECORD &&
5741 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005742 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005743 desc->name, desc->flags, mType);
5744 lStatus = BAD_VALUE;
5745 goto Exit;
5746 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005747
Steve Block3856b092011-10-20 11:56:00 +01005748 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005749
5750 { // scope for mLock
5751 Mutex::Autolock _l(mLock);
5752
5753 // check for existing effect chain with the requested audio session
5754 chain = getEffectChain_l(sessionId);
5755 if (chain == 0) {
5756 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005757 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005758 chain = new EffectChain(this, sessionId);
5759 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005760 chain->setStrategy(getStrategyForSession_l(sessionId));
5761 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005763 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005764 }
5765
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005766 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005767
5768 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005769 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005770 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005771 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005772 if (lStatus != NO_ERROR) {
5773 goto Exit;
5774 }
5775 effectRegistered = true;
5776 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005777 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005778 lStatus = effect->status();
5779 if (lStatus != NO_ERROR) {
5780 goto Exit;
5781 }
Eric Laurentcab11242010-07-15 12:50:15 -07005782 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005783 if (lStatus != NO_ERROR) {
5784 goto Exit;
5785 }
5786 effectCreated = true;
5787
5788 effect->setDevice(mDevice);
5789 effect->setMode(mAudioFlinger->getMode());
5790 }
5791 // create effect handle and connect it to effect module
5792 handle = new EffectHandle(effect, client, effectClient, priority);
5793 lStatus = effect->addHandle(handle);
5794 if (enabled) {
5795 *enabled = (int)effect->isEnabled();
5796 }
5797 }
5798
5799Exit:
5800 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005801 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005802 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005803 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005804 }
5805 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005806 AudioSystem::unregisterEffect(effect->id());
5807 }
5808 if (chainCreated) {
5809 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005810 }
5811 handle.clear();
5812 }
5813
5814 if(status) {
5815 *status = lStatus;
5816 }
5817 return handle;
5818}
5819
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005820sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5821{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005822 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08005823 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005824}
5825
Eric Laurentde070132010-07-13 04:45:46 -07005826// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5827// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005828status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005829{
5830 // check for existing effect chain with the requested audio session
5831 int sessionId = effect->sessionId();
5832 sp<EffectChain> chain = getEffectChain_l(sessionId);
5833 bool chainCreated = false;
5834
5835 if (chain == 0) {
5836 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005837 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005838 chain = new EffectChain(this, sessionId);
5839 addEffectChain_l(chain);
5840 chain->setStrategy(getStrategyForSession_l(sessionId));
5841 chainCreated = true;
5842 }
Steve Block3856b092011-10-20 11:56:00 +01005843 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005844
5845 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005846 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005847 this, effect->desc().name, chain.get());
5848 return BAD_VALUE;
5849 }
5850
5851 status_t status = chain->addEffect_l(effect);
5852 if (status != NO_ERROR) {
5853 if (chainCreated) {
5854 removeEffectChain_l(chain);
5855 }
5856 return status;
5857 }
5858
5859 effect->setDevice(mDevice);
5860 effect->setMode(mAudioFlinger->getMode());
5861 return NO_ERROR;
5862}
5863
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005864void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005865
Steve Block3856b092011-10-20 11:56:00 +01005866 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005867 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005868 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5869 detachAuxEffect_l(effect->id());
5870 }
5871
5872 sp<EffectChain> chain = effect->chain().promote();
5873 if (chain != 0) {
5874 // remove effect chain if removing last effect
5875 if (chain->removeEffect_l(effect) == 0) {
5876 removeEffectChain_l(chain);
5877 }
5878 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005879 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005880 }
5881}
5882
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005883void AudioFlinger::ThreadBase::lockEffectChains_l(
5884 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5885{
5886 effectChains = mEffectChains;
5887 for (size_t i = 0; i < mEffectChains.size(); i++) {
5888 mEffectChains[i]->lock();
5889 }
5890}
5891
5892void AudioFlinger::ThreadBase::unlockEffectChains(
5893 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5894{
5895 for (size_t i = 0; i < effectChains.size(); i++) {
5896 effectChains[i]->unlock();
5897 }
5898}
5899
5900sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5901{
5902 Mutex::Autolock _l(mLock);
5903 return getEffectChain_l(sessionId);
5904}
5905
5906sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5907{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005908 size_t size = mEffectChains.size();
5909 for (size_t i = 0; i < size; i++) {
5910 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08005911 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005912 }
5913 }
Glenn Kasten090f0192012-01-30 13:00:02 -08005914 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005915}
5916
Glenn Kastenf78aee72012-01-04 11:00:47 -08005917void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005918{
5919 Mutex::Autolock _l(mLock);
5920 size_t size = mEffectChains.size();
5921 for (size_t i = 0; i < size; i++) {
5922 mEffectChains[i]->setMode_l(mode);
5923 }
5924}
5925
5926void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005927 const wp<EffectHandle>& handle,
5928 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005929
Mathias Agopian65ab4712010-07-14 17:59:35 -07005930 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005931 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005932 // delete the effect module if removing last handle on it
5933 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005934 if (!effect->isPinned() || unpiniflast) {
5935 removeEffect_l(effect);
5936 AudioSystem::unregisterEffect(effect->id());
5937 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938 }
5939}
5940
5941status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5942{
5943 int session = chain->sessionId();
5944 int16_t *buffer = mMixBuffer;
5945 bool ownsBuffer = false;
5946
Steve Block3856b092011-10-20 11:56:00 +01005947 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 if (session > 0) {
5949 // Only one effect chain can be present in direct output thread and it uses
5950 // the mix buffer as input
5951 if (mType != DIRECT) {
5952 size_t numSamples = mFrameCount * mChannelCount;
5953 buffer = new int16_t[numSamples];
5954 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005955 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 ownsBuffer = true;
5957 }
5958
5959 // Attach all tracks with same session ID to this chain.
5960 for (size_t i = 0; i < mTracks.size(); ++i) {
5961 sp<Track> track = mTracks[i];
5962 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005963 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005965 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966 }
5967 }
5968
5969 // indicate all active tracks in the chain
5970 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5971 sp<Track> track = mActiveTracks[i].promote();
5972 if (track == 0) continue;
5973 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005974 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005975 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005976 }
5977 }
5978 }
5979
5980 chain->setInBuffer(buffer, ownsBuffer);
5981 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005982 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005983 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005984 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5985 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005986 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005987 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5988 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005989 // Effect chain for other sessions are inserted at beginning of effect
5990 // chains list to be processed before output mix effects. Relative order between other
5991 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005992 size_t size = mEffectChains.size();
5993 size_t i = 0;
5994 for (i = 0; i < size; i++) {
5995 if (mEffectChains[i]->sessionId() < session) break;
5996 }
5997 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005998 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999
6000 return NO_ERROR;
6001}
6002
6003size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6004{
6005 int session = chain->sessionId();
6006
Steve Block3856b092011-10-20 11:56:00 +01006007 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008
6009 for (size_t i = 0; i < mEffectChains.size(); i++) {
6010 if (chain == mEffectChains[i]) {
6011 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006012 // detach all active tracks from the chain
6013 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6014 sp<Track> track = mActiveTracks[i].promote();
6015 if (track == 0) continue;
6016 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006017 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006018 chain.get(), session);
6019 chain->decActiveTrackCnt();
6020 }
6021 }
6022
Mathias Agopian65ab4712010-07-14 17:59:35 -07006023 // detach all tracks with same session ID from this chain
6024 for (size_t i = 0; i < mTracks.size(); ++i) {
6025 sp<Track> track = mTracks[i];
6026 if (session == track->sessionId()) {
6027 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006028 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006029 }
6030 }
Eric Laurentde070132010-07-13 04:45:46 -07006031 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006032 }
6033 }
6034 return mEffectChains.size();
6035}
6036
Eric Laurentde070132010-07-13 04:45:46 -07006037status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6038 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006039{
6040 Mutex::Autolock _l(mLock);
6041 return attachAuxEffect_l(track, EffectId);
6042}
6043
Eric Laurentde070132010-07-13 04:45:46 -07006044status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6045 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046{
6047 status_t status = NO_ERROR;
6048
6049 if (EffectId == 0) {
6050 track->setAuxBuffer(0, NULL);
6051 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006052 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6053 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054 if (effect != 0) {
6055 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6056 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6057 } else {
6058 status = INVALID_OPERATION;
6059 }
6060 } else {
6061 status = BAD_VALUE;
6062 }
6063 }
6064 return status;
6065}
6066
6067void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6068{
6069 for (size_t i = 0; i < mTracks.size(); ++i) {
6070 sp<Track> track = mTracks[i];
6071 if (track->auxEffectId() == effectId) {
6072 attachAuxEffect_l(track, 0);
6073 }
6074 }
6075}
6076
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006077status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6078{
6079 // only one chain per input thread
6080 if (mEffectChains.size() != 0) {
6081 return INVALID_OPERATION;
6082 }
Steve Block3856b092011-10-20 11:56:00 +01006083 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006084
6085 chain->setInBuffer(NULL);
6086 chain->setOutBuffer(NULL);
6087
Eric Laurent59255e42011-07-27 19:49:51 -07006088 checkSuspendOnAddEffectChain_l(chain);
6089
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006090 mEffectChains.add(chain);
6091
6092 return NO_ERROR;
6093}
6094
6095size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6096{
Steve Block3856b092011-10-20 11:56:00 +01006097 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006098 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006099 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6100 chain.get(), mEffectChains.size(), this);
6101 if (mEffectChains.size() == 1) {
6102 mEffectChains.removeAt(0);
6103 }
6104 return 0;
6105}
6106
Mathias Agopian65ab4712010-07-14 17:59:35 -07006107// ----------------------------------------------------------------------------
6108// EffectModule implementation
6109// ----------------------------------------------------------------------------
6110
6111#undef LOG_TAG
6112#define LOG_TAG "AudioFlinger::EffectModule"
6113
6114AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6115 const wp<AudioFlinger::EffectChain>& chain,
6116 effect_descriptor_t *desc,
6117 int id,
6118 int sessionId)
6119 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006120 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006121{
Steve Block3856b092011-10-20 11:56:00 +01006122 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123 int lStatus;
6124 sp<ThreadBase> thread = mThread.promote();
6125 if (thread == 0) {
6126 return;
6127 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006128
6129 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6130
6131 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006132 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006133
6134 if (mStatus != NO_ERROR) {
6135 return;
6136 }
6137 lStatus = init();
6138 if (lStatus < 0) {
6139 mStatus = lStatus;
6140 goto Error;
6141 }
6142
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006143 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6144 mPinned = true;
6145 }
Steve Block3856b092011-10-20 11:56:00 +01006146 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006147 return;
6148Error:
6149 EffectRelease(mEffectInterface);
6150 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006151 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006152}
6153
6154AudioFlinger::EffectModule::~EffectModule()
6155{
Steve Block3856b092011-10-20 11:56:00 +01006156 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006157 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006158 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6159 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6160 sp<ThreadBase> thread = mThread.promote();
6161 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006162 audio_stream_t *stream = thread->stream();
6163 if (stream != NULL) {
6164 stream->remove_audio_effect(stream, mEffectInterface);
6165 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006166 }
6167 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006168 // release effect engine
6169 EffectRelease(mEffectInterface);
6170 }
6171}
6172
6173status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6174{
6175 status_t status;
6176
6177 Mutex::Autolock _l(mLock);
6178 // First handle in mHandles has highest priority and controls the effect module
6179 int priority = handle->priority();
6180 size_t size = mHandles.size();
6181 sp<EffectHandle> h;
6182 size_t i;
6183 for (i = 0; i < size; i++) {
6184 h = mHandles[i].promote();
6185 if (h == 0) continue;
6186 if (h->priority() <= priority) break;
6187 }
6188 // if inserted in first place, move effect control from previous owner to this handle
6189 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006190 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006191 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006192 enabled = h->enabled();
6193 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194 }
Eric Laurent59255e42011-07-27 19:49:51 -07006195 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006196 status = NO_ERROR;
6197 } else {
6198 status = ALREADY_EXISTS;
6199 }
Steve Block3856b092011-10-20 11:56:00 +01006200 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006201 mHandles.insertAt(handle, i);
6202 return status;
6203}
6204
6205size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6206{
6207 Mutex::Autolock _l(mLock);
6208 size_t size = mHandles.size();
6209 size_t i;
6210 for (i = 0; i < size; i++) {
6211 if (mHandles[i] == handle) break;
6212 }
6213 if (i == size) {
6214 return size;
6215 }
Steve Block3856b092011-10-20 11:56:00 +01006216 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006217
6218 bool enabled = false;
6219 EffectHandle *hdl = handle.unsafe_get();
6220 if (hdl) {
Steve Block3856b092011-10-20 11:56:00 +01006221 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006222 enabled = hdl->enabled();
6223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006224 mHandles.removeAt(i);
6225 size = mHandles.size();
6226 // if removed from first place, move effect control from this handle to next in line
6227 if (i == 0 && size != 0) {
6228 sp<EffectHandle> h = mHandles[0].promote();
6229 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006230 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006231 }
6232 }
6233
Eric Laurentec437d82011-07-26 20:54:46 -07006234 // Prevent calls to process() and other functions on effect interface from now on.
6235 // The effect engine will be released by the destructor when the last strong reference on
6236 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006237 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006238 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006239 }
6240
Mathias Agopian65ab4712010-07-14 17:59:35 -07006241 return size;
6242}
6243
Eric Laurent59255e42011-07-27 19:49:51 -07006244sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6245{
6246 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006247 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006248}
6249
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006250void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251{
Steve Block3856b092011-10-20 11:56:00 +01006252 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006253 // keep a strong reference on this EffectModule to avoid calling the
6254 // destructor before we exit
6255 sp<EffectModule> keep(this);
6256 {
6257 sp<ThreadBase> thread = mThread.promote();
6258 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006259 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260 }
6261 }
6262}
6263
6264void AudioFlinger::EffectModule::updateState() {
6265 Mutex::Autolock _l(mLock);
6266
6267 switch (mState) {
6268 case RESTART:
6269 reset_l();
6270 // FALL THROUGH
6271
6272 case STARTING:
6273 // clear auxiliary effect input buffer for next accumulation
6274 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6275 memset(mConfig.inputCfg.buffer.raw,
6276 0,
6277 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6278 }
6279 start_l();
6280 mState = ACTIVE;
6281 break;
6282 case STOPPING:
6283 stop_l();
6284 mDisableWaitCnt = mMaxDisableWaitCnt;
6285 mState = STOPPED;
6286 break;
6287 case STOPPED:
6288 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6289 // turn off sequence.
6290 if (--mDisableWaitCnt == 0) {
6291 reset_l();
6292 mState = IDLE;
6293 }
6294 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006295 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 break;
6297 }
6298}
6299
6300void AudioFlinger::EffectModule::process()
6301{
6302 Mutex::Autolock _l(mLock);
6303
Eric Laurentec437d82011-07-26 20:54:46 -07006304 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305 mConfig.inputCfg.buffer.raw == NULL ||
6306 mConfig.outputCfg.buffer.raw == NULL) {
6307 return;
6308 }
6309
Eric Laurent8f45bd72010-08-31 13:50:07 -07006310 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6312 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006313 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006314 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006315 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006316 }
6317
6318 // do the actual processing in the effect engine
6319 int ret = (*mEffectInterface)->process(mEffectInterface,
6320 &mConfig.inputCfg.buffer,
6321 &mConfig.outputCfg.buffer);
6322
6323 // force transition to IDLE state when engine is ready
6324 if (mState == STOPPED && ret == -ENODATA) {
6325 mDisableWaitCnt = 1;
6326 }
6327
6328 // clear auxiliary effect input buffer for next accumulation
6329 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006330 memset(mConfig.inputCfg.buffer.raw, 0,
6331 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006332 }
6333 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006334 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6335 // If an insert effect is idle and input buffer is different from output buffer,
6336 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006337 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006338 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006339 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6340 int16_t *in = mConfig.inputCfg.buffer.s16;
6341 int16_t *out = mConfig.outputCfg.buffer.s16;
6342 for (size_t i = 0; i < frameCnt; i++) {
6343 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006344 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345 }
6346 }
6347}
6348
6349void AudioFlinger::EffectModule::reset_l()
6350{
6351 if (mEffectInterface == NULL) {
6352 return;
6353 }
6354 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6355}
6356
6357status_t AudioFlinger::EffectModule::configure()
6358{
6359 uint32_t channels;
6360 if (mEffectInterface == NULL) {
6361 return NO_INIT;
6362 }
6363
6364 sp<ThreadBase> thread = mThread.promote();
6365 if (thread == 0) {
6366 return DEAD_OBJECT;
6367 }
6368
6369 // TODO: handle configuration of effects replacing track process
6370 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006371 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006372 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006373 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 }
6375
6376 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006377 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 } else {
6379 mConfig.inputCfg.channels = channels;
6380 }
6381 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006382 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6383 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006384 mConfig.inputCfg.samplingRate = thread->sampleRate();
6385 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6386 mConfig.inputCfg.bufferProvider.cookie = NULL;
6387 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6388 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6389 mConfig.outputCfg.bufferProvider.cookie = NULL;
6390 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6391 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6392 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6393 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006394 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006395 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006396 // - in other sessions:
6397 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6398 // other effect: overwrites output buffer: input buffer == output buffer
6399 // Auxiliary effect:
6400 // accumulates in output buffer: input buffer != output buffer
6401 // Therefore: accumulate <=> input buffer != output buffer
6402 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6403 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6404 } else {
6405 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6406 }
6407 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6408 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6409 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6410 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6411
Steve Block3856b092011-10-20 11:56:00 +01006412 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006413 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6414
Mathias Agopian65ab4712010-07-14 17:59:35 -07006415 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006416 uint32_t size = sizeof(int);
6417 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006418 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006419 sizeof(effect_config_t),
6420 &mConfig,
6421 &size,
6422 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006423 if (status == 0) {
6424 status = cmdStatus;
6425 }
6426
6427 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6428 (1000 * mConfig.outputCfg.buffer.frameCount);
6429
6430 return status;
6431}
6432
6433status_t AudioFlinger::EffectModule::init()
6434{
6435 Mutex::Autolock _l(mLock);
6436 if (mEffectInterface == NULL) {
6437 return NO_INIT;
6438 }
6439 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006440 uint32_t size = sizeof(status_t);
6441 status_t status = (*mEffectInterface)->command(mEffectInterface,
6442 EFFECT_CMD_INIT,
6443 0,
6444 NULL,
6445 &size,
6446 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006447 if (status == 0) {
6448 status = cmdStatus;
6449 }
6450 return status;
6451}
6452
Eric Laurentec35a142011-10-05 17:42:25 -07006453status_t AudioFlinger::EffectModule::start()
6454{
6455 Mutex::Autolock _l(mLock);
6456 return start_l();
6457}
6458
Mathias Agopian65ab4712010-07-14 17:59:35 -07006459status_t AudioFlinger::EffectModule::start_l()
6460{
6461 if (mEffectInterface == NULL) {
6462 return NO_INIT;
6463 }
6464 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006465 uint32_t size = sizeof(status_t);
6466 status_t status = (*mEffectInterface)->command(mEffectInterface,
6467 EFFECT_CMD_ENABLE,
6468 0,
6469 NULL,
6470 &size,
6471 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006472 if (status == 0) {
6473 status = cmdStatus;
6474 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006475 if (status == 0 &&
6476 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6477 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6478 sp<ThreadBase> thread = mThread.promote();
6479 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006480 audio_stream_t *stream = thread->stream();
6481 if (stream != NULL) {
6482 stream->add_audio_effect(stream, mEffectInterface);
6483 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006484 }
6485 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486 return status;
6487}
6488
Eric Laurentec437d82011-07-26 20:54:46 -07006489status_t AudioFlinger::EffectModule::stop()
6490{
6491 Mutex::Autolock _l(mLock);
6492 return stop_l();
6493}
6494
Mathias Agopian65ab4712010-07-14 17:59:35 -07006495status_t AudioFlinger::EffectModule::stop_l()
6496{
6497 if (mEffectInterface == NULL) {
6498 return NO_INIT;
6499 }
6500 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006501 uint32_t size = sizeof(status_t);
6502 status_t status = (*mEffectInterface)->command(mEffectInterface,
6503 EFFECT_CMD_DISABLE,
6504 0,
6505 NULL,
6506 &size,
6507 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006508 if (status == 0) {
6509 status = cmdStatus;
6510 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006511 if (status == 0 &&
6512 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6513 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6514 sp<ThreadBase> thread = mThread.promote();
6515 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006516 audio_stream_t *stream = thread->stream();
6517 if (stream != NULL) {
6518 stream->remove_audio_effect(stream, mEffectInterface);
6519 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006520 }
6521 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006522 return status;
6523}
6524
Eric Laurent25f43952010-07-28 05:40:18 -07006525status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6526 uint32_t cmdSize,
6527 void *pCmdData,
6528 uint32_t *replySize,
6529 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530{
6531 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006532// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006533
Eric Laurentec437d82011-07-26 20:54:46 -07006534 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006535 return NO_INIT;
6536 }
Eric Laurent25f43952010-07-28 05:40:18 -07006537 status_t status = (*mEffectInterface)->command(mEffectInterface,
6538 cmdCode,
6539 cmdSize,
6540 pCmdData,
6541 replySize,
6542 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006544 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006545 for (size_t i = 1; i < mHandles.size(); i++) {
6546 sp<EffectHandle> h = mHandles[i].promote();
6547 if (h != 0) {
6548 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6549 }
6550 }
6551 }
6552 return status;
6553}
6554
6555status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6556{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006557
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006559 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006560
6561 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006562 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6563 if (enabled && status != NO_ERROR) {
6564 return status;
6565 }
6566
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567 switch (mState) {
6568 // going from disabled to enabled
6569 case IDLE:
6570 mState = STARTING;
6571 break;
6572 case STOPPED:
6573 mState = RESTART;
6574 break;
6575 case STOPPING:
6576 mState = ACTIVE;
6577 break;
6578
6579 // going from enabled to disabled
6580 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006581 mState = STOPPED;
6582 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006583 case STARTING:
6584 mState = IDLE;
6585 break;
6586 case ACTIVE:
6587 mState = STOPPING;
6588 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006589 case DESTROYED:
6590 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006591 }
6592 for (size_t i = 1; i < mHandles.size(); i++) {
6593 sp<EffectHandle> h = mHandles[i].promote();
6594 if (h != 0) {
6595 h->setEnabled(enabled);
6596 }
6597 }
6598 }
6599 return NO_ERROR;
6600}
6601
6602bool AudioFlinger::EffectModule::isEnabled()
6603{
6604 switch (mState) {
6605 case RESTART:
6606 case STARTING:
6607 case ACTIVE:
6608 return true;
6609 case IDLE:
6610 case STOPPING:
6611 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006612 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006613 default:
6614 return false;
6615 }
6616}
6617
Eric Laurent8f45bd72010-08-31 13:50:07 -07006618bool AudioFlinger::EffectModule::isProcessEnabled()
6619{
6620 switch (mState) {
6621 case RESTART:
6622 case ACTIVE:
6623 case STOPPING:
6624 case STOPPED:
6625 return true;
6626 case IDLE:
6627 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006628 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006629 default:
6630 return false;
6631 }
6632}
6633
Mathias Agopian65ab4712010-07-14 17:59:35 -07006634status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6635{
6636 Mutex::Autolock _l(mLock);
6637 status_t status = NO_ERROR;
6638
6639 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6640 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006641 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006642 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6643 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006644 status_t cmdStatus;
6645 uint32_t volume[2];
6646 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006647 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006648 volume[0] = *left;
6649 volume[1] = *right;
6650 if (controller) {
6651 pVolume = volume;
6652 }
Eric Laurent25f43952010-07-28 05:40:18 -07006653 status = (*mEffectInterface)->command(mEffectInterface,
6654 EFFECT_CMD_SET_VOLUME,
6655 size,
6656 volume,
6657 &size,
6658 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006659 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6660 *left = volume[0];
6661 *right = volume[1];
6662 }
6663 }
6664 return status;
6665}
6666
6667status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6668{
6669 Mutex::Autolock _l(mLock);
6670 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006671 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6672 // audio pre processing modules on RecordThread can receive both output and
6673 // input device indication in the same call
6674 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6675 if (dev) {
6676 status_t cmdStatus;
6677 uint32_t size = sizeof(status_t);
6678
6679 status = (*mEffectInterface)->command(mEffectInterface,
6680 EFFECT_CMD_SET_DEVICE,
6681 sizeof(uint32_t),
6682 &dev,
6683 &size,
6684 &cmdStatus);
6685 if (status == NO_ERROR) {
6686 status = cmdStatus;
6687 }
6688 }
6689 dev = device & AUDIO_DEVICE_IN_ALL;
6690 if (dev) {
6691 status_t cmdStatus;
6692 uint32_t size = sizeof(status_t);
6693
6694 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6695 EFFECT_CMD_SET_INPUT_DEVICE,
6696 sizeof(uint32_t),
6697 &dev,
6698 &size,
6699 &cmdStatus);
6700 if (status2 == NO_ERROR) {
6701 status2 = cmdStatus;
6702 }
6703 if (status == NO_ERROR) {
6704 status = status2;
6705 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006706 }
6707 }
6708 return status;
6709}
6710
Glenn Kastenf78aee72012-01-04 11:00:47 -08006711status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006712{
6713 Mutex::Autolock _l(mLock);
6714 status_t status = NO_ERROR;
6715 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006716 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006717 uint32_t size = sizeof(status_t);
6718 status = (*mEffectInterface)->command(mEffectInterface,
6719 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006720 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006721 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006722 &size,
6723 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006724 if (status == NO_ERROR) {
6725 status = cmdStatus;
6726 }
6727 }
6728 return status;
6729}
6730
Eric Laurent59255e42011-07-27 19:49:51 -07006731void AudioFlinger::EffectModule::setSuspended(bool suspended)
6732{
6733 Mutex::Autolock _l(mLock);
6734 mSuspended = suspended;
6735}
Glenn Kastena3a85482012-01-04 11:01:11 -08006736
6737bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006738{
6739 Mutex::Autolock _l(mLock);
6740 return mSuspended;
6741}
6742
Mathias Agopian65ab4712010-07-14 17:59:35 -07006743status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6744{
6745 const size_t SIZE = 256;
6746 char buffer[SIZE];
6747 String8 result;
6748
6749 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6750 result.append(buffer);
6751
6752 bool locked = tryLock(mLock);
6753 // failed to lock - AudioFlinger is probably deadlocked
6754 if (!locked) {
6755 result.append("\t\tCould not lock Fx mutex:\n");
6756 }
6757
6758 result.append("\t\tSession Status State Engine:\n");
6759 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6760 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6761 result.append(buffer);
6762
6763 result.append("\t\tDescriptor:\n");
6764 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6765 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6766 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6767 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6768 result.append(buffer);
6769 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6770 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6771 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6772 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6773 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006774 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775 mDescriptor.apiVersion,
6776 mDescriptor.flags);
6777 result.append(buffer);
6778 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6779 mDescriptor.name);
6780 result.append(buffer);
6781 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6782 mDescriptor.implementor);
6783 result.append(buffer);
6784
6785 result.append("\t\t- Input configuration:\n");
6786 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6787 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6788 (uint32_t)mConfig.inputCfg.buffer.raw,
6789 mConfig.inputCfg.buffer.frameCount,
6790 mConfig.inputCfg.samplingRate,
6791 mConfig.inputCfg.channels,
6792 mConfig.inputCfg.format);
6793 result.append(buffer);
6794
6795 result.append("\t\t- Output configuration:\n");
6796 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6797 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6798 (uint32_t)mConfig.outputCfg.buffer.raw,
6799 mConfig.outputCfg.buffer.frameCount,
6800 mConfig.outputCfg.samplingRate,
6801 mConfig.outputCfg.channels,
6802 mConfig.outputCfg.format);
6803 result.append(buffer);
6804
6805 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6806 result.append(buffer);
6807 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6808 for (size_t i = 0; i < mHandles.size(); ++i) {
6809 sp<EffectHandle> handle = mHandles[i].promote();
6810 if (handle != 0) {
6811 handle->dump(buffer, SIZE);
6812 result.append(buffer);
6813 }
6814 }
6815
6816 result.append("\n");
6817
6818 write(fd, result.string(), result.length());
6819
6820 if (locked) {
6821 mLock.unlock();
6822 }
6823
6824 return NO_ERROR;
6825}
6826
6827// ----------------------------------------------------------------------------
6828// EffectHandle implementation
6829// ----------------------------------------------------------------------------
6830
6831#undef LOG_TAG
6832#define LOG_TAG "AudioFlinger::EffectHandle"
6833
6834AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6835 const sp<AudioFlinger::Client>& client,
6836 const sp<IEffectClient>& effectClient,
6837 int32_t priority)
6838 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006839 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006840 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841{
Steve Block3856b092011-10-20 11:56:00 +01006842 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006843
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006844 if (client == 0) {
6845 return;
6846 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006847 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6848 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6849 if (mCblkMemory != 0) {
6850 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6851
6852 if (mCblk) {
6853 new(mCblk) effect_param_cblk_t();
6854 mBuffer = (uint8_t *)mCblk + bufOffset;
6855 }
6856 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006857 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006858 return;
6859 }
6860}
6861
6862AudioFlinger::EffectHandle::~EffectHandle()
6863{
Steve Block3856b092011-10-20 11:56:00 +01006864 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006865 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006866 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006867}
6868
6869status_t AudioFlinger::EffectHandle::enable()
6870{
Steve Block3856b092011-10-20 11:56:00 +01006871 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006872 if (!mHasControl) return INVALID_OPERATION;
6873 if (mEffect == 0) return DEAD_OBJECT;
6874
Eric Laurentdb7c0792011-08-10 10:37:50 -07006875 if (mEnabled) {
6876 return NO_ERROR;
6877 }
6878
Eric Laurent59255e42011-07-27 19:49:51 -07006879 mEnabled = true;
6880
6881 sp<ThreadBase> thread = mEffect->thread().promote();
6882 if (thread != 0) {
6883 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6884 }
6885
6886 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6887 if (mEffect->suspended()) {
6888 return NO_ERROR;
6889 }
6890
Eric Laurentdb7c0792011-08-10 10:37:50 -07006891 status_t status = mEffect->setEnabled(true);
6892 if (status != NO_ERROR) {
6893 if (thread != 0) {
6894 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6895 }
6896 mEnabled = false;
6897 }
6898 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899}
6900
6901status_t AudioFlinger::EffectHandle::disable()
6902{
Steve Block3856b092011-10-20 11:56:00 +01006903 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006905 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906
Eric Laurentdb7c0792011-08-10 10:37:50 -07006907 if (!mEnabled) {
6908 return NO_ERROR;
6909 }
Eric Laurent59255e42011-07-27 19:49:51 -07006910 mEnabled = false;
6911
6912 if (mEffect->suspended()) {
6913 return NO_ERROR;
6914 }
6915
6916 status_t status = mEffect->setEnabled(false);
6917
6918 sp<ThreadBase> thread = mEffect->thread().promote();
6919 if (thread != 0) {
6920 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6921 }
6922
6923 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924}
6925
6926void AudioFlinger::EffectHandle::disconnect()
6927{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006928 disconnect(true);
6929}
6930
6931void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6932{
Steve Block3856b092011-10-20 11:56:00 +01006933 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934 if (mEffect == 0) {
6935 return;
6936 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006937 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006938
Eric Laurenta85a74a2011-10-19 11:44:54 -07006939 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006940 sp<ThreadBase> thread = mEffect->thread().promote();
6941 if (thread != 0) {
6942 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6943 }
Eric Laurent59255e42011-07-27 19:49:51 -07006944 }
6945
Mathias Agopian65ab4712010-07-14 17:59:35 -07006946 // release sp on module => module destructor can be called now
6947 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006949 if (mCblk) {
6950 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6951 }
6952 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6954 mClient.clear();
6955 }
6956}
6957
Eric Laurent25f43952010-07-28 05:40:18 -07006958status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6959 uint32_t cmdSize,
6960 void *pCmdData,
6961 uint32_t *replySize,
6962 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006963{
Steve Block3856b092011-10-20 11:56:00 +01006964// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006965// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006966
6967 // only get parameter command is permitted for applications not controlling the effect
6968 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6969 return INVALID_OPERATION;
6970 }
6971 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006972 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973
6974 // handle commands that are not forwarded transparently to effect engine
6975 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6976 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6977 // no risk to block the whole media server process or mixer threads is we are stuck here
6978 Mutex::Autolock _l(mCblk->lock);
6979 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6980 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6981 mCblk->serverIndex = 0;
6982 mCblk->clientIndex = 0;
6983 return BAD_VALUE;
6984 }
6985 status_t status = NO_ERROR;
6986 while (mCblk->serverIndex < mCblk->clientIndex) {
6987 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006988 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006989 int *p = (int *)(mBuffer + mCblk->serverIndex);
6990 int size = *p++;
6991 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006992 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993 break;
6994 }
6995 effect_param_t *param = (effect_param_t *)p;
6996 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006997 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998 mCblk->serverIndex += size;
6999 continue;
7000 }
Eric Laurent25f43952010-07-28 05:40:18 -07007001 uint32_t psize = sizeof(effect_param_t) +
7002 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7003 param->vsize;
7004 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7005 psize,
7006 p,
7007 &rsize,
7008 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007009 // stop at first error encountered
7010 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007011 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007012 *(int *)pReplyData = reply;
7013 break;
7014 } else if (reply != NO_ERROR) {
7015 *(int *)pReplyData = reply;
7016 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007017 }
7018 mCblk->serverIndex += size;
7019 }
7020 mCblk->serverIndex = 0;
7021 mCblk->clientIndex = 0;
7022 return status;
7023 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007024 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025 return enable();
7026 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007027 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007028 return disable();
7029 }
7030
7031 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7032}
7033
7034sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7035 return mCblkMemory;
7036}
7037
Eric Laurent59255e42011-07-27 19:49:51 -07007038void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007039{
Steve Block3856b092011-10-20 11:56:00 +01007040 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041
7042 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007043 mEnabled = enabled;
7044
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045 if (signal && mEffectClient != 0) {
7046 mEffectClient->controlStatusChanged(hasControl);
7047 }
7048}
7049
Eric Laurent25f43952010-07-28 05:40:18 -07007050void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7051 uint32_t cmdSize,
7052 void *pCmdData,
7053 uint32_t replySize,
7054 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055{
7056 if (mEffectClient != 0) {
7057 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7058 }
7059}
7060
7061
7062
7063void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7064{
7065 if (mEffectClient != 0) {
7066 mEffectClient->enableStatusChanged(enabled);
7067 }
7068}
7069
7070status_t AudioFlinger::EffectHandle::onTransact(
7071 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7072{
7073 return BnEffect::onTransact(code, data, reply, flags);
7074}
7075
7076
7077void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7078{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007079 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007080
7081 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7082 (mClient == NULL) ? getpid() : mClient->pid(),
7083 mPriority,
7084 mHasControl,
7085 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007086 mCblk ? mCblk->clientIndex : 0,
7087 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007088 );
7089
7090 if (locked) {
7091 mCblk->lock.unlock();
7092 }
7093}
7094
7095#undef LOG_TAG
7096#define LOG_TAG "AudioFlinger::EffectChain"
7097
7098AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7099 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007100 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007101 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7102 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103{
Dima Zavinfce7a472011-04-19 22:30:36 -07007104 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007105 sp<ThreadBase> thread = mThread.promote();
7106 if (thread == 0) {
7107 return;
7108 }
7109 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7110 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007111}
7112
7113AudioFlinger::EffectChain::~EffectChain()
7114{
7115 if (mOwnInBuffer) {
7116 delete mInBuffer;
7117 }
7118
7119}
7120
Eric Laurent59255e42011-07-27 19:49:51 -07007121// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007122sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007123{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007124 size_t size = mEffects.size();
7125
7126 for (size_t i = 0; i < size; i++) {
7127 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007128 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007129 }
7130 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007131 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007132}
7133
Eric Laurent59255e42011-07-27 19:49:51 -07007134// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007135sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007136{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137 size_t size = mEffects.size();
7138
7139 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007140 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7141 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007142 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007143 }
7144 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007145 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007146}
7147
Eric Laurent59255e42011-07-27 19:49:51 -07007148// getEffectFromType_l() must be called with ThreadBase::mLock held
7149sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7150 const effect_uuid_t *type)
7151{
Eric Laurent59255e42011-07-27 19:49:51 -07007152 size_t size = mEffects.size();
7153
7154 for (size_t i = 0; i < size; i++) {
7155 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007156 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007157 }
7158 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007159 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007160}
7161
Mathias Agopian65ab4712010-07-14 17:59:35 -07007162// Must be called with EffectChain::mLock locked
7163void AudioFlinger::EffectChain::process_l()
7164{
Eric Laurentdac69112010-09-28 14:09:57 -07007165 sp<ThreadBase> thread = mThread.promote();
7166 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007167 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007168 return;
7169 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007170 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7171 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007172 // always process effects unless no more tracks are on the session and the effect tail
7173 // has been rendered
7174 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007175 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007176 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007177
Eric Laurent544fe9b2011-11-11 15:42:52 -08007178 if (!tracksOnSession && mTailBufferCount == 0) {
7179 doProcess = false;
7180 }
7181
7182 if (activeTrackCnt() == 0) {
7183 // if no track is active and the effect tail has not been rendered,
7184 // the input buffer must be cleared here as the mixer process will not do it
7185 if (tracksOnSession || mTailBufferCount > 0) {
7186 size_t numSamples = thread->frameCount() * thread->channelCount();
7187 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7188 if (mTailBufferCount > 0) {
7189 mTailBufferCount--;
7190 }
7191 }
7192 }
Eric Laurentdac69112010-09-28 14:09:57 -07007193 }
7194
Mathias Agopian65ab4712010-07-14 17:59:35 -07007195 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007196 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007197 for (size_t i = 0; i < size; i++) {
7198 mEffects[i]->process();
7199 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007200 }
7201 for (size_t i = 0; i < size; i++) {
7202 mEffects[i]->updateState();
7203 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204}
7205
Eric Laurentcab11242010-07-15 12:50:15 -07007206// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007207status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208{
7209 effect_descriptor_t desc = effect->desc();
7210 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7211
7212 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007213 effect->setChain(this);
7214 sp<ThreadBase> thread = mThread.promote();
7215 if (thread == 0) {
7216 return NO_INIT;
7217 }
7218 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007219
7220 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7221 // Auxiliary effects are inserted at the beginning of mEffects vector as
7222 // they are processed first and accumulated in chain input buffer
7223 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007224
Mathias Agopian65ab4712010-07-14 17:59:35 -07007225 // the input buffer for auxiliary effect contains mono samples in
7226 // 32 bit format. This is to avoid saturation in AudoMixer
7227 // accumulation stage. Saturation is done in EffectModule::process() before
7228 // calling the process in effect engine
7229 size_t numSamples = thread->frameCount();
7230 int32_t *buffer = new int32_t[numSamples];
7231 memset(buffer, 0, numSamples * sizeof(int32_t));
7232 effect->setInBuffer((int16_t *)buffer);
7233 // auxiliary effects output samples to chain input buffer for further processing
7234 // by insert effects
7235 effect->setOutBuffer(mInBuffer);
7236 } else {
7237 // Insert effects are inserted at the end of mEffects vector as they are processed
7238 // after track and auxiliary effects.
7239 // Insert effect order as a function of indicated preference:
7240 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7241 // another effect is present
7242 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7243 // last effect claiming first position
7244 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7245 // first effect claiming last position
7246 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7247 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7248 // already present
7249
7250 int size = (int)mEffects.size();
7251 int idx_insert = size;
7252 int idx_insert_first = -1;
7253 int idx_insert_last = -1;
7254
7255 for (int i = 0; i < size; i++) {
7256 effect_descriptor_t d = mEffects[i]->desc();
7257 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7258 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7259 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7260 // check invalid effect chaining combinations
7261 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7262 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007263 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007264 return INVALID_OPERATION;
7265 }
7266 // remember position of first insert effect and by default
7267 // select this as insert position for new effect
7268 if (idx_insert == size) {
7269 idx_insert = i;
7270 }
7271 // remember position of last insert effect claiming
7272 // first position
7273 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7274 idx_insert_first = i;
7275 }
7276 // remember position of first insert effect claiming
7277 // last position
7278 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7279 idx_insert_last == -1) {
7280 idx_insert_last = i;
7281 }
7282 }
7283 }
7284
7285 // modify idx_insert from first position if needed
7286 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7287 if (idx_insert_last != -1) {
7288 idx_insert = idx_insert_last;
7289 } else {
7290 idx_insert = size;
7291 }
7292 } else {
7293 if (idx_insert_first != -1) {
7294 idx_insert = idx_insert_first + 1;
7295 }
7296 }
7297
7298 // always read samples from chain input buffer
7299 effect->setInBuffer(mInBuffer);
7300
7301 // if last effect in the chain, output samples to chain
7302 // output buffer, otherwise to chain input buffer
7303 if (idx_insert == size) {
7304 if (idx_insert != 0) {
7305 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7306 mEffects[idx_insert-1]->configure();
7307 }
7308 effect->setOutBuffer(mOutBuffer);
7309 } else {
7310 effect->setOutBuffer(mInBuffer);
7311 }
7312 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007313
Steve Block3856b092011-10-20 11:56:00 +01007314 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007315 }
7316 effect->configure();
7317 return NO_ERROR;
7318}
7319
Eric Laurentcab11242010-07-15 12:50:15 -07007320// removeEffect_l() must be called with PlaybackThread::mLock held
7321size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007322{
7323 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 int size = (int)mEffects.size();
7325 int i;
7326 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7327
7328 for (i = 0; i < size; i++) {
7329 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007330 // calling stop here will remove pre-processing effect from the audio HAL.
7331 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7332 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007333 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7334 mEffects[i]->state() == EffectModule::STOPPING) {
7335 mEffects[i]->stop();
7336 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7338 delete[] effect->inBuffer();
7339 } else {
7340 if (i == size - 1 && i != 0) {
7341 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7342 mEffects[i - 1]->configure();
7343 }
7344 }
7345 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007346 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007347 break;
7348 }
7349 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007350
7351 return mEffects.size();
7352}
7353
Eric Laurentcab11242010-07-15 12:50:15 -07007354// setDevice_l() must be called with PlaybackThread::mLock held
7355void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007356{
7357 size_t size = mEffects.size();
7358 for (size_t i = 0; i < size; i++) {
7359 mEffects[i]->setDevice(device);
7360 }
7361}
7362
Eric Laurentcab11242010-07-15 12:50:15 -07007363// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007364void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007365{
7366 size_t size = mEffects.size();
7367 for (size_t i = 0; i < size; i++) {
7368 mEffects[i]->setMode(mode);
7369 }
7370}
7371
Eric Laurentcab11242010-07-15 12:50:15 -07007372// setVolume_l() must be called with PlaybackThread::mLock held
7373bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007374{
7375 uint32_t newLeft = *left;
7376 uint32_t newRight = *right;
7377 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007378 int ctrlIdx = -1;
7379 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380
Eric Laurentcab11242010-07-15 12:50:15 -07007381 // first update volume controller
7382 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007383 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007384 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7385 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007386 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007387 break;
7388 }
7389 }
7390
7391 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007392 if (hasControl) {
7393 *left = mNewLeftVolume;
7394 *right = mNewRightVolume;
7395 }
7396 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007397 }
7398
7399 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007400 mLeftVolume = newLeft;
7401 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007402
7403 // second get volume update from volume controller
7404 if (ctrlIdx >= 0) {
7405 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007406 mNewLeftVolume = newLeft;
7407 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007408 }
7409 // then indicate volume to all other effects in chain.
7410 // Pass altered volume to effects before volume controller
7411 // and requested volume to effects after controller
7412 uint32_t lVol = newLeft;
7413 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007414
Mathias Agopian65ab4712010-07-14 17:59:35 -07007415 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007416 if ((int)i == ctrlIdx) continue;
7417 // this also works for ctrlIdx == -1 when there is no volume controller
7418 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007419 lVol = *left;
7420 rVol = *right;
7421 }
7422 mEffects[i]->setVolume(&lVol, &rVol, false);
7423 }
7424 *left = newLeft;
7425 *right = newRight;
7426
7427 return hasControl;
7428}
7429
Mathias Agopian65ab4712010-07-14 17:59:35 -07007430status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7431{
7432 const size_t SIZE = 256;
7433 char buffer[SIZE];
7434 String8 result;
7435
7436 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7437 result.append(buffer);
7438
7439 bool locked = tryLock(mLock);
7440 // failed to lock - AudioFlinger is probably deadlocked
7441 if (!locked) {
7442 result.append("\tCould not lock mutex:\n");
7443 }
7444
Eric Laurentcab11242010-07-15 12:50:15 -07007445 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7446 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007447 mEffects.size(),
7448 (uint32_t)mInBuffer,
7449 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450 mActiveTrackCnt);
7451 result.append(buffer);
7452 write(fd, result.string(), result.size());
7453
7454 for (size_t i = 0; i < mEffects.size(); ++i) {
7455 sp<EffectModule> effect = mEffects[i];
7456 if (effect != 0) {
7457 effect->dump(fd, args);
7458 }
7459 }
7460
7461 if (locked) {
7462 mLock.unlock();
7463 }
7464
7465 return NO_ERROR;
7466}
7467
Eric Laurent59255e42011-07-27 19:49:51 -07007468// must be called with ThreadBase::mLock held
7469void AudioFlinger::EffectChain::setEffectSuspended_l(
7470 const effect_uuid_t *type, bool suspend)
7471{
7472 sp<SuspendedEffectDesc> desc;
7473 // use effect type UUID timelow as key as there is no real risk of identical
7474 // timeLow fields among effect type UUIDs.
7475 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7476 if (suspend) {
7477 if (index >= 0) {
7478 desc = mSuspendedEffects.valueAt(index);
7479 } else {
7480 desc = new SuspendedEffectDesc();
7481 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7482 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007483 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007484 }
7485 if (desc->mRefCount++ == 0) {
7486 sp<EffectModule> effect = getEffectIfEnabled(type);
7487 if (effect != 0) {
7488 desc->mEffect = effect;
7489 effect->setSuspended(true);
7490 effect->setEnabled(false);
7491 }
7492 }
7493 } else {
7494 if (index < 0) {
7495 return;
7496 }
7497 desc = mSuspendedEffects.valueAt(index);
7498 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007499 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007500 desc->mRefCount = 1;
7501 }
7502 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007503 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007504 if (desc->mEffect != 0) {
7505 sp<EffectModule> effect = desc->mEffect.promote();
7506 if (effect != 0) {
7507 effect->setSuspended(false);
7508 sp<EffectHandle> handle = effect->controlHandle();
7509 if (handle != 0) {
7510 effect->setEnabled(handle->enabled());
7511 }
7512 }
7513 desc->mEffect.clear();
7514 }
7515 mSuspendedEffects.removeItemsAt(index);
7516 }
7517 }
7518}
7519
7520// must be called with ThreadBase::mLock held
7521void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7522{
7523 sp<SuspendedEffectDesc> desc;
7524
7525 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7526 if (suspend) {
7527 if (index >= 0) {
7528 desc = mSuspendedEffects.valueAt(index);
7529 } else {
7530 desc = new SuspendedEffectDesc();
7531 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007532 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007533 }
7534 if (desc->mRefCount++ == 0) {
7535 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7536 for (size_t i = 0; i < effects.size(); i++) {
7537 setEffectSuspended_l(&effects[i]->desc().type, true);
7538 }
7539 }
7540 } else {
7541 if (index < 0) {
7542 return;
7543 }
7544 desc = mSuspendedEffects.valueAt(index);
7545 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007546 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007547 desc->mRefCount = 1;
7548 }
7549 if (--desc->mRefCount == 0) {
7550 Vector<const effect_uuid_t *> types;
7551 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7552 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7553 continue;
7554 }
7555 types.add(&mSuspendedEffects.valueAt(i)->mType);
7556 }
7557 for (size_t i = 0; i < types.size(); i++) {
7558 setEffectSuspended_l(types[i], false);
7559 }
Steve Block3856b092011-10-20 11:56:00 +01007560 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007561 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7562 }
7563 }
7564}
7565
Eric Laurent6bffdb82011-09-23 08:40:41 -07007566
7567// The volume effect is used for automated tests only
7568#ifndef OPENSL_ES_H_
7569static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7570 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7571const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7572#endif //OPENSL_ES_H_
7573
Eric Laurentdb7c0792011-08-10 10:37:50 -07007574bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7575{
7576 // auxiliary effects and visualizer are never suspended on output mix
7577 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7578 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007579 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7580 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007581 return false;
7582 }
7583 return true;
7584}
7585
Eric Laurent59255e42011-07-27 19:49:51 -07007586Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7587{
7588 Vector< sp<EffectModule> > effects;
7589 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007590 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007591 continue;
7592 }
7593 effects.add(mEffects[i]);
7594 }
7595 return effects;
7596}
7597
7598sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7599 const effect_uuid_t *type)
7600{
Glenn Kasten090f0192012-01-30 13:00:02 -08007601 sp<EffectModule> effect = getEffectFromType_l(type);
7602 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007603}
7604
7605void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7606 bool enabled)
7607{
7608 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7609 if (enabled) {
7610 if (index < 0) {
7611 // if the effect is not suspend check if all effects are suspended
7612 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7613 if (index < 0) {
7614 return;
7615 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007616 if (!isEffectEligibleForSuspend(effect->desc())) {
7617 return;
7618 }
Eric Laurent59255e42011-07-27 19:49:51 -07007619 setEffectSuspended_l(&effect->desc().type, enabled);
7620 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007621 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007622 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007623 return;
7624 }
Eric Laurent59255e42011-07-27 19:49:51 -07007625 }
Steve Block3856b092011-10-20 11:56:00 +01007626 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007627 effect->desc().type.timeLow);
7628 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7629 // if effect is requested to suspended but was not yet enabled, supend it now.
7630 if (desc->mEffect == 0) {
7631 desc->mEffect = effect;
7632 effect->setEnabled(false);
7633 effect->setSuspended(true);
7634 }
7635 } else {
7636 if (index < 0) {
7637 return;
7638 }
Steve Block3856b092011-10-20 11:56:00 +01007639 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007640 effect->desc().type.timeLow);
7641 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7642 desc->mEffect.clear();
7643 effect->setSuspended(false);
7644 }
7645}
7646
Mathias Agopian65ab4712010-07-14 17:59:35 -07007647#undef LOG_TAG
7648#define LOG_TAG "AudioFlinger"
7649
7650// ----------------------------------------------------------------------------
7651
7652status_t AudioFlinger::onTransact(
7653 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7654{
7655 return BnAudioFlinger::onTransact(code, data, reply, flags);
7656}
7657
Mathias Agopian65ab4712010-07-14 17:59:35 -07007658}; // namespace android