blob: d05e9d947b3035a637ae3a510c60a25d9c202554 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Gloria Wang9ee159b2011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten3b21c502011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070061// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
62
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Eric Laurentde070132010-07-13 04:45:46 -070065
Mathias Agopian65ab4712010-07-14 17:59:35 -070066namespace android {
67
Glenn Kastenec1d6b52011-12-12 09:04:45 -080068static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
69static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
72static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080073static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
79// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
83
84static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080085static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Glenn Kasten7dede872011-12-13 11:04:14 -080087// don't warn about blocked writes or record buffer overflows more often than this
88static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Eric Laurent7c7f10b2011-06-17 21:29:58 -070090// RecordThread loop sleep time upon application overrun or audio HAL read error
91static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
Glenn Kasten7dede872011-12-13 11:04:14 -080093// maximum time to wait for setParameters to complete
94static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070095
Eric Laurent7cafbb32011-11-22 18:50:29 -080096// minimum sleep time for the mixer thread loop when tracks are active but in underrun
97static const uint32_t kMinThreadSleepTimeUs = 5000;
98// maximum divider applied to the active sleep time in the mixer thread loop
99static const uint32_t kMaxThreadSleepTimeShift = 2;
100
101
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102// ----------------------------------------------------------------------------
103
104static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block29357bc2012-01-06 19:20:56 +0000107 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109}
110
111static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
113 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block29357bc2012-01-06 19:20:56 +0000114 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116}
117
Gloria Wang9ee159b2011-02-24 14:51:45 -0800118// To collect the amplifier usage
119static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800120 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
121 if (service == NULL) {
122 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800123 return;
124 }
125
126 service->addBatteryData(params);
127}
128
Dima Zavin799a70e2011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800152static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
162 : BnAudioFlinger(),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800163 mPrimaryHardwareDev(NULL),
164 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
165 mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
166 mMode(AUDIO_MODE_INVALID),
Eric Laurentbee53372011-08-29 12:42:48 -0700167 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700169}
170
171void AudioFlinger::onFirstRef()
172{
Dima Zavin799a70e2011-04-18 16:57:27 -0700173 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700174
Eric Laurent93575202011-01-18 18:39:02 -0800175 Mutex::Autolock _l(mLock);
176
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700178
Dima Zavin799a70e2011-04-18 16:57:27 -0700179 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
180 const hw_module_t *mod;
181 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700182
Dima Zavin799a70e2011-04-18 16:57:27 -0700183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184 if (rc)
185 continue;
186
Steve Blockdf64d152012-01-04 20:05:49 +0000187 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 mod->name, mod->id);
189 mAudioHwDevs.push(dev);
190
191 if (!mPrimaryHardwareDev) {
192 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000193 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700194 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 }
196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700197
198 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700199
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000201 ALOGE("Primary audio interface not found");
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 return;
203 }
204
205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
206 audio_hw_device_t *dev = mAudioHwDevs[i];
207
208 mHardwareStatus = AUDIO_HW_INIT;
209 rc = dev->init_check(dev);
210 if (rc == 0) {
211 AutoMutex lock(mHardwareLock);
212
213 mMode = AUDIO_MODE_NORMAL;
214 mHardwareStatus = AUDIO_HW_SET_MODE;
215 dev->set_mode(dev, mMode);
216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
217 dev->set_master_volume(dev, 1.0f);
218 mHardwareStatus = AUDIO_HW_IDLE;
219 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221}
222
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700223status_t AudioFlinger::initCheck() const
224{
225 Mutex::Autolock _l(mLock);
226 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
227 return NO_INIT;
228 return NO_ERROR;
229}
230
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231AudioFlinger::~AudioFlinger()
232{
Dima Zavin799a70e2011-04-18 16:57:27 -0700233 int num_devs = mAudioHwDevs.size();
234
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235 while (!mRecordThreads.isEmpty()) {
236 // closeInput() will remove first entry from mRecordThreads
237 closeInput(mRecordThreads.keyAt(0));
238 }
239 while (!mPlaybackThreads.isEmpty()) {
240 // closeOutput() will remove first entry from mPlaybackThreads
241 closeOutput(mPlaybackThreads.keyAt(0));
242 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700243
244 for (int i = 0; i < num_devs; i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247 }
248}
249
Dima Zavin799a70e2011-04-18 16:57:27 -0700250audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
251{
252 /* first matching HW device is returned */
253 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
254 audio_hw_device_t *dev = mAudioHwDevs[i];
255 if ((dev->get_supported_devices(dev) & devices) == devices)
256 return dev;
257 }
258 return NULL;
259}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700260
261status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
262{
263 const size_t SIZE = 256;
264 char buffer[SIZE];
265 String8 result;
266
267 result.append("Clients:\n");
268 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800269 sp<Client> client = mClients.valueAt(i).promote();
270 if (client != 0) {
271 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
272 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700273 }
274 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700275
276 result.append("Global session refs:\n");
277 result.append(" session pid cnt\n");
278 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
279 AudioSessionRef *r = mAudioSessionRefs[i];
280 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
281 result.append(buffer);
282 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700283 write(fd, result.string(), result.size());
284 return NO_ERROR;
285}
286
287
288status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
289{
290 const size_t SIZE = 256;
291 char buffer[SIZE];
292 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800293 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700294
295 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
296 result.append(buffer);
297 write(fd, result.string(), result.size());
298 return NO_ERROR;
299}
300
301status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
302{
303 const size_t SIZE = 256;
304 char buffer[SIZE];
305 String8 result;
306 snprintf(buffer, SIZE, "Permission Denial: "
307 "can't dump AudioFlinger from pid=%d, uid=%d\n",
308 IPCThreadState::self()->getCallingPid(),
309 IPCThreadState::self()->getCallingUid());
310 result.append(buffer);
311 write(fd, result.string(), result.size());
312 return NO_ERROR;
313}
314
315static bool tryLock(Mutex& mutex)
316{
317 bool locked = false;
318 for (int i = 0; i < kDumpLockRetries; ++i) {
319 if (mutex.tryLock() == NO_ERROR) {
320 locked = true;
321 break;
322 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800323 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700324 }
325 return locked;
326}
327
328status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
329{
Glenn Kastenf1d45922012-01-13 15:54:24 -0800330 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700331 dumpPermissionDenial(fd, args);
332 } else {
333 // get state of hardware lock
334 bool hardwareLocked = tryLock(mHardwareLock);
335 if (!hardwareLocked) {
336 String8 result(kHardwareLockedString);
337 write(fd, result.string(), result.size());
338 } else {
339 mHardwareLock.unlock();
340 }
341
342 bool locked = tryLock(mLock);
343
344 // failed to lock - AudioFlinger is probably deadlocked
345 if (!locked) {
346 String8 result(kDeadlockedString);
347 write(fd, result.string(), result.size());
348 }
349
350 dumpClients(fd, args);
351 dumpInternals(fd, args);
352
353 // dump playback threads
354 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
355 mPlaybackThreads.valueAt(i)->dump(fd, args);
356 }
357
358 // dump record threads
359 for (size_t i = 0; i < mRecordThreads.size(); i++) {
360 mRecordThreads.valueAt(i)->dump(fd, args);
361 }
362
Dima Zavin799a70e2011-04-18 16:57:27 -0700363 // dump all hardware devs
364 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
365 audio_hw_device_t *dev = mAudioHwDevs[i];
366 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700367 }
368 if (locked) mLock.unlock();
369 }
370 return NO_ERROR;
371}
372
373
374// IAudioFlinger interface
375
376
377sp<IAudioTrack> AudioFlinger::createTrack(
378 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800379 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800381 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700382 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700383 int frameCount,
384 uint32_t flags,
385 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800386 audio_io_handle_t output,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 int *sessionId,
388 status_t *status)
389{
390 sp<PlaybackThread::Track> track;
391 sp<TrackHandle> trackHandle;
392 sp<Client> client;
393 wp<Client> wclient;
394 status_t lStatus;
395 int lSessionId;
396
Glenn Kasten263709e2012-01-06 08:40:01 -0800397 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
398 // but if someone uses binder directly they could bypass that and cause us to crash
399 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000400 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401 lStatus = BAD_VALUE;
402 goto Exit;
403 }
404
405 {
406 Mutex::Autolock _l(mLock);
407 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700408 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000410 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 lStatus = BAD_VALUE;
412 goto Exit;
413 }
414
415 wclient = mClients.valueFor(pid);
416
417 if (wclient != NULL) {
418 client = wclient.promote();
419 } else {
420 client = new Client(this, pid);
421 mClients.add(pid, client);
422 }
423
Steve Block3856b092011-10-20 11:56:00 +0100424 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700425 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700426 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700427 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
428 if (mPlaybackThreads.keyAt(i) != output) {
429 // prevent same audio session on different output threads
430 uint32_t sessions = t->hasAudioSession(*sessionId);
431 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000432 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700433 lStatus = BAD_VALUE;
434 goto Exit;
435 }
436 // check if an effect with same session ID is waiting for a track to be created
437 if (sessions & PlaybackThread::EFFECT_SESSION) {
438 effectThread = t.get();
439 }
Eric Laurentde070132010-07-13 04:45:46 -0700440 }
441 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700442 lSessionId = *sessionId;
443 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700444 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700445 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 if (sessionId != NULL) {
447 *sessionId = lSessionId;
448 }
449 }
Steve Block3856b092011-10-20 11:56:00 +0100450 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700451
452 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700453 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700454
455 // move effect chain to this output thread if an effect on same session was waiting
456 // for a track to be created
457 if (lStatus == NO_ERROR && effectThread != NULL) {
458 Mutex::Autolock _dl(thread->mLock);
459 Mutex::Autolock _sl(effectThread->mLock);
460 moveEffectChain_l(lSessionId, effectThread, thread, true);
461 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462 }
463 if (lStatus == NO_ERROR) {
464 trackHandle = new TrackHandle(track);
465 } else {
466 // remove local strong reference to Client before deleting the Track so that the Client
467 // destructor is called by the TrackBase destructor with mLock held
468 client.clear();
469 track.clear();
470 }
471
472Exit:
473 if(status) {
474 *status = lStatus;
475 }
476 return trackHandle;
477}
478
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800479uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480{
481 Mutex::Autolock _l(mLock);
482 PlaybackThread *thread = checkPlaybackThread_l(output);
483 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000484 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700485 return 0;
486 }
487 return thread->sampleRate();
488}
489
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800490int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700491{
492 Mutex::Autolock _l(mLock);
493 PlaybackThread *thread = checkPlaybackThread_l(output);
494 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000495 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496 return 0;
497 }
498 return thread->channelCount();
499}
500
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800501audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700502{
503 Mutex::Autolock _l(mLock);
504 PlaybackThread *thread = checkPlaybackThread_l(output);
505 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000506 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800507 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700508 }
509 return thread->format();
510}
511
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800512size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700513{
514 Mutex::Autolock _l(mLock);
515 PlaybackThread *thread = checkPlaybackThread_l(output);
516 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000517 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700518 return 0;
519 }
520 return thread->frameCount();
521}
522
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800523uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700524{
525 Mutex::Autolock _l(mLock);
526 PlaybackThread *thread = checkPlaybackThread_l(output);
527 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000528 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529 return 0;
530 }
531 return thread->latency();
532}
533
534status_t AudioFlinger::setMasterVolume(float value)
535{
Eric Laurenta1884f92011-08-23 08:25:03 -0700536 status_t ret = initCheck();
537 if (ret != NO_ERROR) {
538 return ret;
539 }
540
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 // check calling permissions
542 if (!settingsAllowed()) {
543 return PERMISSION_DENIED;
544 }
545
546 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800547 { // scope for the lock
548 AutoMutex lock(mHardwareLock);
549 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700550 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800551 value = 1.0f;
552 }
553 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555
Eric Laurent93575202011-01-18 18:39:02 -0800556 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557 mMasterVolume = value;
558 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
559 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
560
561 return NO_ERROR;
562}
563
Glenn Kastenf78aee72012-01-04 11:00:47 -0800564status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565{
Eric Laurenta1884f92011-08-23 08:25:03 -0700566 status_t ret = initCheck();
567 if (ret != NO_ERROR) {
568 return ret;
569 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570
571 // check calling permissions
572 if (!settingsAllowed()) {
573 return PERMISSION_DENIED;
574 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800575 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000576 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 return BAD_VALUE;
578 }
579
580 { // scope for the lock
581 AutoMutex lock(mHardwareLock);
582 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700583 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584 mHardwareStatus = AUDIO_HW_IDLE;
585 }
586
587 if (NO_ERROR == ret) {
588 Mutex::Autolock _l(mLock);
589 mMode = mode;
590 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
591 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 }
593
594 return ret;
595}
596
597status_t AudioFlinger::setMicMute(bool state)
598{
Eric Laurenta1884f92011-08-23 08:25:03 -0700599 status_t ret = initCheck();
600 if (ret != NO_ERROR) {
601 return ret;
602 }
603
Mathias Agopian65ab4712010-07-14 17:59:35 -0700604 // check calling permissions
605 if (!settingsAllowed()) {
606 return PERMISSION_DENIED;
607 }
608
609 AutoMutex lock(mHardwareLock);
610 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700611 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612 mHardwareStatus = AUDIO_HW_IDLE;
613 return ret;
614}
615
616bool AudioFlinger::getMicMute() const
617{
Eric Laurenta1884f92011-08-23 08:25:03 -0700618 status_t ret = initCheck();
619 if (ret != NO_ERROR) {
620 return false;
621 }
622
Dima Zavinfce7a472011-04-19 22:30:36 -0700623 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700625 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626 mHardwareStatus = AUDIO_HW_IDLE;
627 return state;
628}
629
630status_t AudioFlinger::setMasterMute(bool muted)
631{
632 // check calling permissions
633 if (!settingsAllowed()) {
634 return PERMISSION_DENIED;
635 }
636
Eric Laurent93575202011-01-18 18:39:02 -0800637 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700638 mMasterMute = muted;
639 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
640 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
641
642 return NO_ERROR;
643}
644
645float AudioFlinger::masterVolume() const
646{
Glenn Kasten98067102011-12-13 11:47:54 -0800647 Mutex::Autolock _l(mLock);
648 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700649}
650
651bool AudioFlinger::masterMute() const
652{
Glenn Kasten98067102011-12-13 11:47:54 -0800653 Mutex::Autolock _l(mLock);
654 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700655}
656
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800657status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
658 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659{
660 // check calling permissions
661 if (!settingsAllowed()) {
662 return PERMISSION_DENIED;
663 }
664
Glenn Kasten263709e2012-01-06 08:40:01 -0800665 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000666 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700667 return BAD_VALUE;
668 }
669
670 AutoMutex lock(mLock);
671 PlaybackThread *thread = NULL;
672 if (output) {
673 thread = checkPlaybackThread_l(output);
674 if (thread == NULL) {
675 return BAD_VALUE;
676 }
677 }
678
679 mStreamTypes[stream].volume = value;
680
681 if (thread == NULL) {
682 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
683 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
684 }
685 } else {
686 thread->setStreamVolume(stream, value);
687 }
688
689 return NO_ERROR;
690}
691
Glenn Kastenfff6d712012-01-12 16:38:12 -0800692status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700693{
694 // check calling permissions
695 if (!settingsAllowed()) {
696 return PERMISSION_DENIED;
697 }
698
Glenn Kasten263709e2012-01-06 08:40:01 -0800699 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700700 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000701 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700702 return BAD_VALUE;
703 }
704
Eric Laurent93575202011-01-18 18:39:02 -0800705 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 mStreamTypes[stream].mute = muted;
707 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
708 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
709
710 return NO_ERROR;
711}
712
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800713float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714{
Glenn Kasten263709e2012-01-06 08:40:01 -0800715 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700716 return 0.0f;
717 }
718
719 AutoMutex lock(mLock);
720 float volume;
721 if (output) {
722 PlaybackThread *thread = checkPlaybackThread_l(output);
723 if (thread == NULL) {
724 return 0.0f;
725 }
726 volume = thread->streamVolume(stream);
727 } else {
728 volume = mStreamTypes[stream].volume;
729 }
730
731 return volume;
732}
733
Glenn Kastenfff6d712012-01-12 16:38:12 -0800734bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735{
Glenn Kasten263709e2012-01-06 08:40:01 -0800736 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737 return true;
738 }
739
740 return mStreamTypes[stream].mute;
741}
742
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800743status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700744{
745 status_t result;
746
Steve Block3856b092011-10-20 11:56:00 +0100747 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
749 // check calling permissions
750 if (!settingsAllowed()) {
751 return PERMISSION_DENIED;
752 }
753
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754 // ioHandle == 0 means the parameters are global to the audio hardware interface
755 if (ioHandle == 0) {
756 AutoMutex lock(mHardwareLock);
757 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700758 status_t final_result = NO_ERROR;
759 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
760 audio_hw_device_t *dev = mAudioHwDevs[i];
761 result = dev->set_parameters(dev, keyValuePairs.string());
762 final_result = result ?: final_result;
763 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700765 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
766 AudioParameter param = AudioParameter(keyValuePairs);
767 String8 value;
768 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
769 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700770 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
771 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700772 for (size_t i = 0; i < mRecordThreads.size(); i++) {
773 sp<RecordThread> thread = mRecordThreads.valueAt(i);
774 RecordThread::RecordTrack *track = thread->track();
775 if (track != NULL) {
776 audio_devices_t device = (audio_devices_t)(
777 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700778 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700779 thread->setEffectSuspended(FX_IID_AEC,
780 suspend,
781 track->sessionId());
782 thread->setEffectSuspended(FX_IID_NS,
783 suspend,
784 track->sessionId());
785 }
786 }
Eric Laurentbee53372011-08-29 12:42:48 -0700787 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700788 }
789 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700790 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791 }
792
793 // hold a strong ref on thread in case closeOutput() or closeInput() is called
794 // and the thread is exited once the lock is released
795 sp<ThreadBase> thread;
796 {
797 Mutex::Autolock _l(mLock);
798 thread = checkPlaybackThread_l(ioHandle);
799 if (thread == NULL) {
800 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800801 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700802 // indicate output device change to all input threads for pre processing
803 AudioParameter param = AudioParameter(keyValuePairs);
804 int value;
805 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
806 for (size_t i = 0; i < mRecordThreads.size(); i++) {
807 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
808 }
809 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810 }
811 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800812 if (thread != 0) {
813 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 }
815 return BAD_VALUE;
816}
817
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800818String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819{
Steve Block3856b092011-10-20 11:56:00 +0100820// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
822
823 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700824 String8 out_s8;
825
Dima Zavin799a70e2011-04-18 16:57:27 -0700826 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
827 audio_hw_device_t *dev = mAudioHwDevs[i];
828 char *s = dev->get_parameters(dev, keys.string());
829 out_s8 += String8(s);
830 free(s);
831 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700832 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 }
834
835 Mutex::Autolock _l(mLock);
836
837 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
838 if (playbackThread != NULL) {
839 return playbackThread->getParameters(keys);
840 }
841 RecordThread *recordThread = checkRecordThread_l(ioHandle);
842 if (recordThread != NULL) {
843 return recordThread->getParameters(keys);
844 }
845 return String8("");
846}
847
Glenn Kastenf587ba52012-01-26 16:25:10 -0800848size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849{
Eric Laurenta1884f92011-08-23 08:25:03 -0700850 status_t ret = initCheck();
851 if (ret != NO_ERROR) {
852 return 0;
853 }
854
Dima Zavin799a70e2011-04-18 16:57:27 -0700855 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856}
857
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800858unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700859{
860 if (ioHandle == 0) {
861 return 0;
862 }
863
864 Mutex::Autolock _l(mLock);
865
866 RecordThread *recordThread = checkRecordThread_l(ioHandle);
867 if (recordThread != NULL) {
868 return recordThread->getInputFramesLost();
869 }
870 return 0;
871}
872
873status_t AudioFlinger::setVoiceVolume(float value)
874{
Eric Laurenta1884f92011-08-23 08:25:03 -0700875 status_t ret = initCheck();
876 if (ret != NO_ERROR) {
877 return ret;
878 }
879
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880 // check calling permissions
881 if (!settingsAllowed()) {
882 return PERMISSION_DENIED;
883 }
884
885 AutoMutex lock(mHardwareLock);
886 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700887 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888 mHardwareStatus = AUDIO_HW_IDLE;
889
890 return ret;
891}
892
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800893status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
894 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895{
896 status_t status;
897
898 Mutex::Autolock _l(mLock);
899
900 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
901 if (playbackThread != NULL) {
902 return playbackThread->getRenderPosition(halFrames, dspFrames);
903 }
904
905 return BAD_VALUE;
906}
907
908void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
909{
910
911 Mutex::Autolock _l(mLock);
912
Glenn Kastenbb001922012-02-03 11:10:26 -0800913 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700914 if (mNotificationClients.indexOfKey(pid) < 0) {
915 sp<NotificationClient> notificationClient = new NotificationClient(this,
916 client,
917 pid);
Steve Block3856b092011-10-20 11:56:00 +0100918 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919
920 mNotificationClients.add(pid, notificationClient);
921
922 sp<IBinder> binder = client->asBinder();
923 binder->linkToDeath(notificationClient);
924
925 // the config change is always sent from playback or record threads to avoid deadlock
926 // with AudioSystem::gLock
927 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
928 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
929 }
930
931 for (size_t i = 0; i < mRecordThreads.size(); i++) {
932 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
933 }
934 }
935}
936
937void AudioFlinger::removeNotificationClient(pid_t pid)
938{
939 Mutex::Autolock _l(mLock);
940
941 int index = mNotificationClients.indexOfKey(pid);
942 if (index >= 0) {
943 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100944 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700945 mNotificationClients.removeItem(pid);
946 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700947
Steve Block3856b092011-10-20 11:56:00 +0100948 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700949 int num = mAudioSessionRefs.size();
950 bool removed = false;
951 for (int i = 0; i< num; i++) {
952 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100953 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700954 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100955 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700956 mAudioSessionRefs.removeAt(i);
957 delete ref;
958 removed = true;
959 i--;
960 num--;
961 }
962 }
963 if (removed) {
964 purgeStaleEffects_l();
965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700966}
967
968// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800969void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700970{
971 size_t size = mNotificationClients.size();
972 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800973 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
974 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975 }
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
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800988AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
989 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800991 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800992 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
993 // mChannelMask
994 mChannelCount(0),
995 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
996 mParamStatus(NO_ERROR),
997 mStandby(false), mId(id), mExiting(false),
998 mDevice(device),
999 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000{
1001}
1002
1003AudioFlinger::ThreadBase::~ThreadBase()
1004{
1005 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001006 // do not lock the mutex in destructor
1007 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001008 if (mPowerManager != 0) {
1009 sp<IBinder> binder = mPowerManager->asBinder();
1010 binder->unlinkToDeath(mDeathRecipient);
1011 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001012}
1013
1014void AudioFlinger::ThreadBase::exit()
1015{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001016 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017 // destroyed in the middle of requestExitAndWait()
1018 sp <ThreadBase> strongMe = this;
1019
Steve Block3856b092011-10-20 11:56:00 +01001020 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001022 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023 mExiting = true;
1024 requestExit();
1025 mWaitWorkCV.signal();
1026 }
1027 requestExitAndWait();
1028}
1029
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1031{
1032 status_t status;
1033
Steve Block3856b092011-10-20 11:56:00 +01001034 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 Mutex::Autolock _l(mLock);
1036
1037 mNewParameters.add(keyValuePairs);
1038 mWaitWorkCV.signal();
1039 // wait condition with timeout in case the thread loop has exited
1040 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001041 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 status = mParamStatus;
1043 mWaitWorkCV.signal();
1044 } else {
1045 status = TIMED_OUT;
1046 }
1047 return status;
1048}
1049
1050void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1051{
1052 Mutex::Autolock _l(mLock);
1053 sendConfigEvent_l(event, param);
1054}
1055
1056// sendConfigEvent_l() must be called with ThreadBase::mLock held
1057void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1058{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001059 ConfigEvent configEvent;
1060 configEvent.mEvent = event;
1061 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001063 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064 mWaitWorkCV.signal();
1065}
1066
1067void AudioFlinger::ThreadBase::processConfigEvents()
1068{
1069 mLock.lock();
1070 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001071 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001072 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 mConfigEvents.removeAt(0);
1074 // release mLock before locking AudioFlinger mLock: lock order is always
1075 // AudioFlinger then ThreadBase to avoid cross deadlock
1076 mLock.unlock();
1077 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001078 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080 mLock.lock();
1081 }
1082 mLock.unlock();
1083}
1084
1085status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1086{
1087 const size_t SIZE = 256;
1088 char buffer[SIZE];
1089 String8 result;
1090
1091 bool locked = tryLock(mLock);
1092 if (!locked) {
1093 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1094 write(fd, buffer, strlen(buffer));
1095 }
1096
1097 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1098 result.append(buffer);
1099 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1100 result.append(buffer);
1101 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1102 result.append(buffer);
1103 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1104 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001105 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1106 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1108 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001109 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110 result.append(buffer);
1111
1112 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1113 result.append(buffer);
1114 result.append(" Index Command");
1115 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1116 snprintf(buffer, SIZE, "\n %02d ", i);
1117 result.append(buffer);
1118 result.append(mNewParameters[i]);
1119 }
1120
1121 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1122 result.append(buffer);
1123 snprintf(buffer, SIZE, " Index event param\n");
1124 result.append(buffer);
1125 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001126 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 result.append(buffer);
1128 }
1129 result.append("\n");
1130
1131 write(fd, result.string(), result.size());
1132
1133 if (locked) {
1134 mLock.unlock();
1135 }
1136 return NO_ERROR;
1137}
1138
Eric Laurent1d2bff02011-07-24 17:49:51 -07001139status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1140{
1141 const size_t SIZE = 256;
1142 char buffer[SIZE];
1143 String8 result;
1144
1145 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1146 write(fd, buffer, strlen(buffer));
1147
1148 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1149 sp<EffectChain> chain = mEffectChains[i];
1150 if (chain != 0) {
1151 chain->dump(fd, args);
1152 }
1153 }
1154 return NO_ERROR;
1155}
1156
Eric Laurentfeb0db62011-07-22 09:04:31 -07001157void AudioFlinger::ThreadBase::acquireWakeLock()
1158{
1159 Mutex::Autolock _l(mLock);
1160 acquireWakeLock_l();
1161}
1162
1163void AudioFlinger::ThreadBase::acquireWakeLock_l()
1164{
1165 if (mPowerManager == 0) {
1166 // use checkService() to avoid blocking if power service is not up yet
1167 sp<IBinder> binder =
1168 defaultServiceManager()->checkService(String16("power"));
1169 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001170 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001171 } else {
1172 mPowerManager = interface_cast<IPowerManager>(binder);
1173 binder->linkToDeath(mDeathRecipient);
1174 }
1175 }
1176 if (mPowerManager != 0) {
1177 sp<IBinder> binder = new BBinder();
1178 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1179 binder,
1180 String16(mName));
1181 if (status == NO_ERROR) {
1182 mWakeLockToken = binder;
1183 }
Steve Block3856b092011-10-20 11:56:00 +01001184 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001185 }
1186}
1187
1188void AudioFlinger::ThreadBase::releaseWakeLock()
1189{
1190 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001191 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001192}
1193
1194void AudioFlinger::ThreadBase::releaseWakeLock_l()
1195{
1196 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001197 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001198 if (mPowerManager != 0) {
1199 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1200 }
1201 mWakeLockToken.clear();
1202 }
1203}
1204
1205void AudioFlinger::ThreadBase::clearPowerManager()
1206{
1207 Mutex::Autolock _l(mLock);
1208 releaseWakeLock_l();
1209 mPowerManager.clear();
1210}
1211
1212void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1213{
1214 sp<ThreadBase> thread = mThread.promote();
1215 if (thread != 0) {
1216 thread->clearPowerManager();
1217 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001218 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001219}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001220
Eric Laurent59255e42011-07-27 19:49:51 -07001221void AudioFlinger::ThreadBase::setEffectSuspended(
1222 const effect_uuid_t *type, bool suspend, int sessionId)
1223{
1224 Mutex::Autolock _l(mLock);
1225 setEffectSuspended_l(type, suspend, sessionId);
1226}
1227
1228void AudioFlinger::ThreadBase::setEffectSuspended_l(
1229 const effect_uuid_t *type, bool suspend, int sessionId)
1230{
Glenn Kasten090f0192012-01-30 13:00:02 -08001231 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001232 if (chain != 0) {
1233 if (type != NULL) {
1234 chain->setEffectSuspended_l(type, suspend);
1235 } else {
1236 chain->setEffectSuspendedAll_l(suspend);
1237 }
1238 }
1239
1240 updateSuspendedSessions_l(type, suspend, sessionId);
1241}
1242
1243void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1244{
1245 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1246 if (index < 0) {
1247 return;
1248 }
1249
1250 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1251 mSuspendedSessions.editValueAt(index);
1252
1253 for (size_t i = 0; i < sessionEffects.size(); i++) {
1254 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1255 for (int j = 0; j < desc->mRefCount; j++) {
1256 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1257 chain->setEffectSuspendedAll_l(true);
1258 } else {
Steve Block3856b092011-10-20 11:56:00 +01001259 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001260 desc->mType.timeLow);
1261 chain->setEffectSuspended_l(&desc->mType, true);
1262 }
1263 }
1264 }
1265}
1266
Eric Laurent59255e42011-07-27 19:49:51 -07001267void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1268 bool suspend,
1269 int sessionId)
1270{
1271 int index = mSuspendedSessions.indexOfKey(sessionId);
1272
1273 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1274
1275 if (suspend) {
1276 if (index >= 0) {
1277 sessionEffects = mSuspendedSessions.editValueAt(index);
1278 } else {
1279 mSuspendedSessions.add(sessionId, sessionEffects);
1280 }
1281 } else {
1282 if (index < 0) {
1283 return;
1284 }
1285 sessionEffects = mSuspendedSessions.editValueAt(index);
1286 }
1287
1288
1289 int key = EffectChain::kKeyForSuspendAll;
1290 if (type != NULL) {
1291 key = type->timeLow;
1292 }
1293 index = sessionEffects.indexOfKey(key);
1294
1295 sp <SuspendedSessionDesc> desc;
1296 if (suspend) {
1297 if (index >= 0) {
1298 desc = sessionEffects.valueAt(index);
1299 } else {
1300 desc = new SuspendedSessionDesc();
1301 if (type != NULL) {
1302 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1303 }
1304 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001305 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001306 }
1307 desc->mRefCount++;
1308 } else {
1309 if (index < 0) {
1310 return;
1311 }
1312 desc = sessionEffects.valueAt(index);
1313 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001314 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001315 sessionEffects.removeItemsAt(index);
1316 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001317 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001318 sessionId);
1319 mSuspendedSessions.removeItem(sessionId);
1320 }
1321 }
1322 }
1323 if (!sessionEffects.isEmpty()) {
1324 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1325 }
1326}
1327
1328void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1329 bool enabled,
1330 int sessionId)
1331{
1332 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001333 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1334}
Eric Laurent59255e42011-07-27 19:49:51 -07001335
Eric Laurenta85a74a2011-10-19 11:44:54 -07001336void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1337 bool enabled,
1338 int sessionId)
1339{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001340 if (mType != RECORD) {
1341 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1342 // another session. This gives the priority to well behaved effect control panels
1343 // and applications not using global effects.
1344 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1345 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1346 }
1347 }
Eric Laurent59255e42011-07-27 19:49:51 -07001348
1349 sp<EffectChain> chain = getEffectChain_l(sessionId);
1350 if (chain != 0) {
1351 chain->checkSuspendOnEffectEnabled(effect, enabled);
1352 }
1353}
1354
Mathias Agopian65ab4712010-07-14 17:59:35 -07001355// ----------------------------------------------------------------------------
1356
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001357AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1358 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001359 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001360 uint32_t device,
1361 type_t type)
1362 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001363 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1364 // Assumes constructor is called by AudioFlinger with it's mLock held,
1365 // but it would be safer to explicitly pass initial masterMute as parameter
1366 mMasterMute(audioFlinger->masterMute_l()),
1367 // mStreamTypes[] initialized in constructor body
1368 mOutput(output),
1369 // Assumes constructor is called by AudioFlinger with it's mLock held,
1370 // but it would be safer to explicitly pass initial masterVolume as parameter
1371 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001372 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001373{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001374 snprintf(mName, kNameLength, "AudioOut_%d", id);
1375
Mathias Agopian65ab4712010-07-14 17:59:35 -07001376 readOutputParameters();
1377
Glenn Kasten263709e2012-01-06 08:40:01 -08001378 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001379 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1380 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1381 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001382 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1383 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001384 // initialized by stream_type_t default constructor
1385 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386 }
1387}
1388
1389AudioFlinger::PlaybackThread::~PlaybackThread()
1390{
1391 delete [] mMixBuffer;
1392}
1393
1394status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1395{
1396 dumpInternals(fd, args);
1397 dumpTracks(fd, args);
1398 dumpEffectChains(fd, args);
1399 return NO_ERROR;
1400}
1401
1402status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1403{
1404 const size_t SIZE = 256;
1405 char buffer[SIZE];
1406 String8 result;
1407
1408 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1409 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001410 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 -07001411 for (size_t i = 0; i < mTracks.size(); ++i) {
1412 sp<Track> track = mTracks[i];
1413 if (track != 0) {
1414 track->dump(buffer, SIZE);
1415 result.append(buffer);
1416 }
1417 }
1418
1419 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1420 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001421 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 -07001422 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001423 sp<Track> track = mActiveTracks[i].promote();
1424 if (track != 0) {
1425 track->dump(buffer, SIZE);
1426 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427 }
1428 }
1429 write(fd, result.string(), result.size());
1430 return NO_ERROR;
1431}
1432
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1434{
1435 const size_t SIZE = 256;
1436 char buffer[SIZE];
1437 String8 result;
1438
1439 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1440 result.append(buffer);
1441 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1442 result.append(buffer);
1443 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1444 result.append(buffer);
1445 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1446 result.append(buffer);
1447 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1448 result.append(buffer);
1449 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1450 result.append(buffer);
1451 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1452 result.append(buffer);
1453 write(fd, result.string(), result.size());
1454
1455 dumpBase(fd, args);
1456
1457 return NO_ERROR;
1458}
1459
1460// Thread virtuals
1461status_t AudioFlinger::PlaybackThread::readyToRun()
1462{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001463 status_t status = initCheck();
1464 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001465 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001466 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001467 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001469 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470}
1471
1472void AudioFlinger::PlaybackThread::onFirstRef()
1473{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001474 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475}
1476
1477// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1478sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1479 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001480 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001482 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001483 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484 int frameCount,
1485 const sp<IMemory>& sharedBuffer,
1486 int sessionId,
1487 status_t *status)
1488{
1489 sp<Track> track;
1490 status_t lStatus;
1491
1492 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001493 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1494 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001495 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001496 "for output %p with format %d",
1497 sampleRate, format, channelMask, mOutput, mFormat);
1498 lStatus = BAD_VALUE;
1499 goto Exit;
1500 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501 }
1502 } else {
1503 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1504 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001505 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001506 lStatus = BAD_VALUE;
1507 goto Exit;
1508 }
1509 }
1510
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001511 lStatus = initCheck();
1512 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001513 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514 goto Exit;
1515 }
1516
1517 { // scope for mLock
1518 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001519
1520 // all tracks in same audio session must share the same routing strategy otherwise
1521 // conflicts will happen when tracks are moved from one output to another by audio policy
1522 // manager
1523 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001524 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001525 for (size_t i = 0; i < mTracks.size(); ++i) {
1526 sp<Track> t = mTracks[i];
1527 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001528 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1529 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001530 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001531 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001532 lStatus = BAD_VALUE;
1533 goto Exit;
1534 }
1535 }
1536 }
1537
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001539 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001540 if (track->getCblk() == NULL || track->name() < 0) {
1541 lStatus = NO_MEMORY;
1542 goto Exit;
1543 }
1544 mTracks.add(track);
1545
1546 sp<EffectChain> chain = getEffectChain_l(sessionId);
1547 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001548 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001550 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001551 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001553
1554 // invalidate track immediately if the stream type was moved to another thread since
1555 // createTrack() was called by the client process.
1556 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001557 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001558 this, streamType);
1559 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1560 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 }
1562 lStatus = NO_ERROR;
1563
1564Exit:
1565 if(status) {
1566 *status = lStatus;
1567 }
1568 return track;
1569}
1570
1571uint32_t AudioFlinger::PlaybackThread::latency() const
1572{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001573 Mutex::Autolock _l(mLock);
1574 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001575 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001576 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577 return 0;
1578 }
1579}
1580
1581status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1582{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583 mMasterVolume = value;
1584 return NO_ERROR;
1585}
1586
1587status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1588{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 mMasterMute = muted;
1590 return NO_ERROR;
1591}
1592
Glenn Kastenfff6d712012-01-12 16:38:12 -08001593status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595 mStreamTypes[stream].volume = value;
1596 return NO_ERROR;
1597}
1598
Glenn Kastenfff6d712012-01-12 16:38:12 -08001599status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601 mStreamTypes[stream].mute = muted;
1602 return NO_ERROR;
1603}
1604
Glenn Kastenfff6d712012-01-12 16:38:12 -08001605float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606{
1607 return mStreamTypes[stream].volume;
1608}
1609
Glenn Kastenfff6d712012-01-12 16:38:12 -08001610bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611{
1612 return mStreamTypes[stream].mute;
1613}
1614
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615// addTrack_l() must be called with ThreadBase::mLock held
1616status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1617{
1618 status_t status = ALREADY_EXISTS;
1619
1620 // set retry count for buffer fill
1621 track->mRetryCount = kMaxTrackStartupRetries;
1622 if (mActiveTracks.indexOf(track) < 0) {
1623 // the track is newly added, make sure it fills up all its
1624 // buffers before playing. This is to ensure the client will
1625 // effectively get the latency it requested.
1626 track->mFillingUpStatus = Track::FS_FILLING;
1627 track->mResetDone = false;
1628 mActiveTracks.add(track);
1629 if (track->mainBuffer() != mMixBuffer) {
1630 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1631 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001632 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001633 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001634 }
1635 }
1636
1637 status = NO_ERROR;
1638 }
1639
Steve Block3856b092011-10-20 11:56:00 +01001640 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641 mWaitWorkCV.broadcast();
1642
1643 return status;
1644}
1645
1646// destroyTrack_l() must be called with ThreadBase::mLock held
1647void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1648{
1649 track->mState = TrackBase::TERMINATED;
1650 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001651 removeTrack_l(track);
1652 }
1653}
1654
1655void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1656{
1657 mTracks.remove(track);
1658 deleteTrackName_l(track->name());
1659 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1660 if (chain != 0) {
1661 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662 }
1663}
1664
1665String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1666{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001667 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001668 char *s;
1669
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001670 Mutex::Autolock _l(mLock);
1671 if (initCheck() != NO_ERROR) {
1672 return out_s8;
1673 }
1674
Dima Zavin799a70e2011-04-18 16:57:27 -07001675 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001676 out_s8 = String8(s);
1677 free(s);
1678 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679}
1680
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001681// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1683 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001684 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685
Steve Block3856b092011-10-20 11:56:00 +01001686 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687
1688 switch (event) {
1689 case AudioSystem::OUTPUT_OPENED:
1690 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001691 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001692 desc.samplingRate = mSampleRate;
1693 desc.format = mFormat;
1694 desc.frameCount = mFrameCount;
1695 desc.latency = latency();
1696 param2 = &desc;
1697 break;
1698
1699 case AudioSystem::STREAM_CONFIG_CHANGED:
1700 param2 = &param;
1701 case AudioSystem::OUTPUT_CLOSED:
1702 default:
1703 break;
1704 }
1705 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1706}
1707
1708void AudioFlinger::PlaybackThread::readOutputParameters()
1709{
Dima Zavin799a70e2011-04-18 16:57:27 -07001710 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001711 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1712 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001713 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001714 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001715 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716
1717 // FIXME - Current mixer implementation only supports stereo output: Always
1718 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001719 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 mMixBuffer = new int16_t[mFrameCount * 2];
1721 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1722
Eric Laurentde070132010-07-13 04:45:46 -07001723 // force reconfiguration of effect chains and engines to take new buffer size and audio
1724 // parameters into account
1725 // Note that mLock is not held when readOutputParameters() is called from the constructor
1726 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1727 // matter.
1728 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1729 Vector< sp<EffectChain> > effectChains = mEffectChains;
1730 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001731 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001732 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001733}
1734
1735status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1736{
Glenn Kastena0d68332012-01-27 16:47:15 -08001737 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738 return BAD_VALUE;
1739 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001740 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001741 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 return INVALID_OPERATION;
1743 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001744 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745
Dima Zavin799a70e2011-04-18 16:57:27 -07001746 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747}
1748
Eric Laurent39e94f82010-07-28 01:32:47 -07001749uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750{
1751 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001752 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001754 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755 }
1756
1757 for (size_t i = 0; i < mTracks.size(); ++i) {
1758 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001759 if (sessionId == track->sessionId() &&
1760 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001761 result |= TRACK_SESSION;
1762 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763 }
1764 }
1765
Eric Laurent39e94f82010-07-28 01:32:47 -07001766 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767}
1768
Eric Laurentde070132010-07-13 04:45:46 -07001769uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1770{
Dima Zavinfce7a472011-04-19 22:30:36 -07001771 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001772 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001773 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1774 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001775 }
1776 for (size_t i = 0; i < mTracks.size(); i++) {
1777 sp<Track> track = mTracks[i];
1778 if (sessionId == track->sessionId() &&
1779 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001780 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001781 }
1782 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001783 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001784}
1785
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786
Glenn Kastenaed850d2012-01-26 09:46:34 -08001787AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001788{
1789 Mutex::Autolock _l(mLock);
1790 return mOutput;
1791}
1792
1793AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1794{
1795 Mutex::Autolock _l(mLock);
1796 AudioStreamOut *output = mOutput;
1797 mOutput = NULL;
1798 return output;
1799}
1800
1801// this method must always be called either with ThreadBase mLock held or inside the thread loop
1802audio_stream_t* AudioFlinger::PlaybackThread::stream()
1803{
1804 if (mOutput == NULL) {
1805 return NULL;
1806 }
1807 return &mOutput->stream->common;
1808}
1809
Eric Laurent162b40b2011-12-05 09:47:19 -08001810uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1811{
1812 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1813 // decoding and transfer time. So sleeping for half of the latency would likely cause
1814 // underruns
1815 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1816 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1817 } else {
1818 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1819 }
1820}
1821
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822// ----------------------------------------------------------------------------
1823
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001824AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001825 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001826 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001827 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1828 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830 // FIXME - Current mixer implementation only supports stereo output
1831 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001832 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 }
1834}
1835
1836AudioFlinger::MixerThread::~MixerThread()
1837{
1838 delete mAudioMixer;
1839}
1840
1841bool AudioFlinger::MixerThread::threadLoop()
1842{
1843 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001844 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845 nsecs_t standbyTime = systemTime();
1846 size_t mixBufferSize = mFrameCount * mFrameSize;
1847 // FIXME: Relaxed timing because of a certain device that can't meet latency
1848 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001849 // increase threshold again due to low power audio mode. The way this warning threshold is
1850 // calculated and its usefulness should be reconsidered anyway.
1851 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852 nsecs_t lastWarning = 0;
1853 bool longStandbyExit = false;
1854 uint32_t activeSleepTime = activeSleepTimeUs();
1855 uint32_t idleSleepTime = idleSleepTimeUs();
1856 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001857 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001859#ifdef DEBUG_CPU_USAGE
1860 ThreadCpuUsage cpu;
1861 const CentralTendencyStatistics& stats = cpu.statistics();
1862#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863
Eric Laurentfeb0db62011-07-22 09:04:31 -07001864 acquireWakeLock();
1865
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866 while (!exitPending())
1867 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001868#ifdef DEBUG_CPU_USAGE
1869 cpu.sampleAndEnable();
1870 unsigned n = stats.n();
1871 // cpu.elapsed() is expensive, so don't call it every loop
1872 if ((n & 127) == 1) {
1873 long long elapsed = cpu.elapsed();
1874 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1875 double perLoop = elapsed / (double) n;
1876 double perLoop100 = perLoop * 0.01;
1877 double mean = stats.mean();
1878 double stddev = stats.stddev();
1879 double minimum = stats.minimum();
1880 double maximum = stats.maximum();
1881 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001882 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 -07001883 elapsed * .000000001, n, perLoop * .000001,
1884 mean * .001,
1885 stddev * .001,
1886 minimum * .001,
1887 maximum * .001,
1888 mean / perLoop100,
1889 stddev / perLoop100,
1890 minimum / perLoop100,
1891 maximum / perLoop100);
1892 }
1893 }
1894#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895 processConfigEvents();
1896
1897 mixerStatus = MIXER_IDLE;
1898 { // scope for mLock
1899
1900 Mutex::Autolock _l(mLock);
1901
1902 if (checkForNewParameters_l()) {
1903 mixBufferSize = mFrameCount * mFrameSize;
1904 // FIXME: Relaxed timing because of a certain device that can't meet latency
1905 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001906 // increase threshold again due to low power audio mode. The way this warning
1907 // threshold is calculated and its usefulness should be reconsidered anyway.
1908 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909 activeSleepTime = activeSleepTimeUs();
1910 idleSleepTime = idleSleepTimeUs();
1911 }
1912
1913 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1914
1915 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001916 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1917 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001919 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001920 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 mStandby = true;
1922 mBytesWritten = 0;
1923 }
1924
1925 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1926 // we're about to wait, flush the binder command buffer
1927 IPCThreadState::self()->flushCommands();
1928
1929 if (exitPending()) break;
1930
Eric Laurentfeb0db62011-07-22 09:04:31 -07001931 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001933 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001935 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001936 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937
Eric Laurent27741442012-01-17 19:20:12 -08001938 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001939 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940 char value[PROPERTY_VALUE_MAX];
1941 property_get("ro.audio.silent", value, "0");
1942 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001943 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 setMasterMute(true);
1945 }
1946 }
1947
1948 standbyTime = systemTime() + kStandbyTimeInNsecs;
1949 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001950 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 continue;
1952 }
1953 }
1954
1955 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1956
1957 // prevent any changes in effect chain list and in each effect chain
1958 // during mixing and effect process as the audio buffers could be deleted
1959 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001960 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001961 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962
Glenn Kastenf6b16782011-12-15 09:51:17 -08001963 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964 // mix buffers...
1965 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001966 // increase sleep time progressively when application underrun condition clears.
1967 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1968 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1969 // such that we would underrun the audio HAL.
1970 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001971 sleepTimeShift--;
1972 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001973 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974 standbyTime = systemTime() + kStandbyTimeInNsecs;
1975 //TODO: delay standby when effects have a tail
1976 } else {
1977 // If no tracks are ready, sleep once for the duration of an output
1978 // buffer size, then write 0s to the output
1979 if (sleepTime == 0) {
1980 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001981 sleepTime = activeSleepTime >> sleepTimeShift;
1982 if (sleepTime < kMinThreadSleepTimeUs) {
1983 sleepTime = kMinThreadSleepTimeUs;
1984 }
1985 // reduce sleep time in case of consecutive application underruns to avoid
1986 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1987 // duration we would end up writing less data than needed by the audio HAL if
1988 // the condition persists.
1989 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1990 sleepTimeShift++;
1991 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 } else {
1993 sleepTime = idleSleepTime;
1994 }
1995 } else if (mBytesWritten != 0 ||
1996 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1997 memset (mMixBuffer, 0, mixBufferSize);
1998 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01001999 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000 }
2001 // TODO add standby time extension fct of effect tail
2002 }
2003
2004 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002005 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006 }
2007 // sleepTime == 0 means we must write to audio hardware
2008 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002009 for (size_t i = 0; i < effectChains.size(); i ++) {
2010 effectChains[i]->process_l();
2011 }
2012 // enable changes in effect chain
2013 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014 mLastWriteTime = systemTime();
2015 mInWrite = true;
2016 mBytesWritten += mixBufferSize;
2017
Dima Zavin799a70e2011-04-18 16:57:27 -07002018 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2020 mNumWrites++;
2021 mInWrite = false;
2022 nsecs_t now = systemTime();
2023 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002024 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002026 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002027 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002028 ns2ms(delta), mNumDelayedWrites, this);
2029 lastWarning = now;
2030 }
2031 if (mStandby) {
2032 longStandbyExit = true;
2033 }
2034 }
2035 mStandby = false;
2036 } else {
2037 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002038 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002039 usleep(sleepTime);
2040 }
2041
2042 // finally let go of all our tracks, without the lock held
2043 // since we can't guarantee the destructors won't acquire that
2044 // same lock.
2045 tracksToRemove.clear();
2046
2047 // Effect chains will be actually deleted here if they were removed from
2048 // mEffectChains list during mixing or effects processing
2049 effectChains.clear();
2050 }
2051
2052 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002053 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 }
2055
Eric Laurentfeb0db62011-07-22 09:04:31 -07002056 releaseWakeLock();
2057
Steve Block3856b092011-10-20 11:56:00 +01002058 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059 return false;
2060}
2061
2062// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002063AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2064 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065{
2066
Glenn Kasten29c23c32012-01-26 13:37:52 -08002067 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068 // find out which tracks need to be processed
2069 size_t count = activeTracks.size();
2070 size_t mixedTracks = 0;
2071 size_t tracksWithEffect = 0;
2072
2073 float masterVolume = mMasterVolume;
2074 bool masterMute = mMasterMute;
2075
Eric Laurent571d49c2010-08-11 05:20:11 -07002076 if (masterMute) {
2077 masterVolume = 0;
2078 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002080 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002081 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002082 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002083 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 masterVolume = (float)((v + (1 << 23)) >> 24);
2085 chain.clear();
2086 }
2087
2088 for (size_t i=0 ; i<count ; i++) {
2089 sp<Track> t = activeTracks[i].promote();
2090 if (t == 0) continue;
2091
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002092 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093 Track* const track = t.get();
2094 audio_track_cblk_t* cblk = track->cblk();
2095
2096 // The first time a track is added we wait
2097 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002098 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002099 // make sure that we have enough frames to mix one full buffer.
2100 // enforce this condition only once to enable draining the buffer in case the client
2101 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002102 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002103 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002104 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002105 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002106 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002107 if (t->sampleRate() == (int)mSampleRate) {
2108 minFrames = mFrameCount;
2109 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002110 // +1 for rounding and +1 for additional sample needed for interpolation
2111 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2112 // add frames already consumed but not yet released by the resampler
2113 // because cblk->framesReady() will include these frames
2114 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2115 // the minimum track buffer size is normally twice the number of frames necessary
2116 // to fill one buffer and the resampler should not leave more than one buffer worth
2117 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002118 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002119 }
2120 }
2121 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002122 !track->isPaused() && !track->isTerminated())
2123 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002124 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125
2126 mixedTracks++;
2127
2128 // track->mainBuffer() != mMixBuffer means there is an effect chain
2129 // connected to the track
2130 chain.clear();
2131 if (track->mainBuffer() != mMixBuffer) {
2132 chain = getEffectChain_l(track->sessionId());
2133 // Delegate volume control to effect in track effect chain if needed
2134 if (chain != 0) {
2135 tracksWithEffect++;
2136 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002137 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002138 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002139 }
2140 }
2141
2142
2143 int param = AudioMixer::VOLUME;
2144 if (track->mFillingUpStatus == Track::FS_FILLED) {
2145 // no ramp for the first volume setting
2146 track->mFillingUpStatus = Track::FS_ACTIVE;
2147 if (track->mState == TrackBase::RESUMING) {
2148 track->mState = TrackBase::ACTIVE;
2149 param = AudioMixer::RAMP_VOLUME;
2150 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002151 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 } else if (cblk->server != 0) {
2153 // If the track is stopped before the first frame was mixed,
2154 // do not apply ramp
2155 param = AudioMixer::RAMP_VOLUME;
2156 }
2157
2158 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002159 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002160 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002162 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002163 if (track->isPausing()) {
2164 track->setPaused();
2165 }
2166 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002167
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168 // read original volumes with volume control
2169 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002170 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002171 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002172 vl = vlr & 0xFFFF;
2173 vr = vlr >> 16;
2174 // track volumes come from shared memory, so can't be trusted and must be clamped
2175 if (vl > MAX_GAIN_INT) {
2176 ALOGV("Track left volume out of range: %04X", vl);
2177 vl = MAX_GAIN_INT;
2178 }
2179 if (vr > MAX_GAIN_INT) {
2180 ALOGV("Track right volume out of range: %04X", vr);
2181 vr = MAX_GAIN_INT;
2182 }
2183 // now apply the master volume and stream type volume
2184 vl = (uint32_t)(v * vl) << 12;
2185 vr = (uint32_t)(v * vr) << 12;
2186 // assuming master volume and stream type volume each go up to 1.0,
2187 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188
Glenn Kasten05632a52012-01-03 14:22:33 -08002189 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2190 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002191 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002192 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002193 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002194 }
2195 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002197 // Delegate volume control to effect in track effect chain if needed
2198 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2199 // Do not ramp volume if volume is controlled by effect
2200 param = AudioMixer::VOLUME;
2201 track->mHasVolumeController = true;
2202 } else {
2203 // force no volume ramp when volume controller was just disabled or removed
2204 // from effect chain to avoid volume spike
2205 if (track->mHasVolumeController) {
2206 param = AudioMixer::VOLUME;
2207 }
2208 track->mHasVolumeController = false;
2209 }
2210
2211 // Convert volumes from 8.24 to 4.12 format
2212 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002213 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002214 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2215 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2216 left = int16_t(v_clamped);
2217 v_clamped = (vr + (1 << 11)) >> 12;
2218 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2219 right = int16_t(v_clamped);
2220
2221 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2222 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223
Mathias Agopian65ab4712010-07-14 17:59:35 -07002224 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002225 mAudioMixer->setBufferProvider(name, track);
2226 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002228 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2229 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2230 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002231 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002232 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 AudioMixer::TRACK,
2234 AudioMixer::FORMAT, (void *)track->format());
2235 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002236 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002238 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002240 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002241 AudioMixer::RESAMPLE,
2242 AudioMixer::SAMPLE_RATE,
2243 (void *)(cblk->sampleRate));
2244 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002245 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246 AudioMixer::TRACK,
2247 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2248 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002249 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250 AudioMixer::TRACK,
2251 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2252
2253 // reset retry count
2254 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002255 // If one track is ready, set the mixer ready if:
2256 // - the mixer was not ready during previous round OR
2257 // - no other track is not ready
2258 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2259 mixerStatus != MIXER_TRACKS_ENABLED) {
2260 mixerStatus = MIXER_TRACKS_READY;
2261 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002263 //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 -07002264 if (track->isStopped()) {
2265 track->reset();
2266 }
2267 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2268 // We have consumed all the buffers of this track.
2269 // Remove it from the list of active tracks.
2270 tracksToRemove->add(track);
2271 } else {
2272 // No buffers for this track. Give it a few chances to
2273 // fill a buffer, then remove it from active list.
2274 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002275 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002277 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002278 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002279 // If one track is not ready, mark the mixer also not ready if:
2280 // - the mixer was ready during previous round OR
2281 // - no other track is ready
2282 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2283 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002284 mixerStatus = MIXER_TRACKS_ENABLED;
2285 }
2286 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002287 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288 }
2289 }
2290
2291 // remove all the tracks that need to be...
2292 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002293 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294 for (size_t i=0 ; i<count ; i++) {
2295 const sp<Track>& track = tracksToRemove->itemAt(i);
2296 mActiveTracks.remove(track);
2297 if (track->mainBuffer() != mMixBuffer) {
2298 chain = getEffectChain_l(track->sessionId());
2299 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002300 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002301 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302 }
2303 }
2304 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002305 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306 }
2307 }
2308 }
2309
2310 // mix buffer must be cleared if all tracks are connected to an
2311 // effect chain as in this case the mixer will not write to
2312 // mix buffer and track effects will accumulate into it
2313 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2314 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2315 }
2316
Eric Laurent27741442012-01-17 19:20:12 -08002317 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318 return mixerStatus;
2319}
2320
Glenn Kastenfff6d712012-01-12 16:38:12 -08002321void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322{
Steve Block3856b092011-10-20 11:56:00 +01002323 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002324 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002325 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002326
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327 size_t size = mTracks.size();
2328 for (size_t i = 0; i < size; i++) {
2329 sp<Track> t = mTracks[i];
2330 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002331 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002333 }
2334 }
2335}
2336
Glenn Kastenfff6d712012-01-12 16:38:12 -08002337void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002338{
Steve Block3856b092011-10-20 11:56:00 +01002339 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002340 this, streamType, valid);
2341 Mutex::Autolock _l(mLock);
2342
2343 mStreamTypes[streamType].valid = valid;
2344}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002345
2346// getTrackName_l() must be called with ThreadBase::mLock held
2347int AudioFlinger::MixerThread::getTrackName_l()
2348{
2349 return mAudioMixer->getTrackName();
2350}
2351
2352// deleteTrackName_l() must be called with ThreadBase::mLock held
2353void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2354{
Steve Block3856b092011-10-20 11:56:00 +01002355 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002356 mAudioMixer->deleteTrackName(name);
2357}
2358
2359// checkForNewParameters_l() must be called with ThreadBase::mLock held
2360bool AudioFlinger::MixerThread::checkForNewParameters_l()
2361{
2362 bool reconfig = false;
2363
2364 while (!mNewParameters.isEmpty()) {
2365 status_t status = NO_ERROR;
2366 String8 keyValuePair = mNewParameters[0];
2367 AudioParameter param = AudioParameter(keyValuePair);
2368 int value;
2369
2370 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2371 reconfig = true;
2372 }
2373 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002374 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002375 status = BAD_VALUE;
2376 } else {
2377 reconfig = true;
2378 }
2379 }
2380 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002381 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382 status = BAD_VALUE;
2383 } else {
2384 reconfig = true;
2385 }
2386 }
2387 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2388 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002389 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390 // if frame count is changed after track creation
2391 if (!mTracks.isEmpty()) {
2392 status = INVALID_OPERATION;
2393 } else {
2394 reconfig = true;
2395 }
2396 }
2397 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002398 // when changing the audio output device, call addBatteryData to notify
2399 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002400 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002401 uint32_t params = 0;
2402 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002403 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002404 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2405 }
2406
2407 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002408 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002409 // check if any other device (except speaker) is on
2410 if (value & deviceWithoutSpeaker ) {
2411 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2412 }
2413
2414 if (params != 0) {
2415 addBatteryData(params);
2416 }
2417 }
2418
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 // forward device change to effects that have requested to be
2420 // aware of attached audio device.
2421 mDevice = (uint32_t)value;
2422 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002423 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424 }
2425 }
2426
2427 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002428 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002429 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002431 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 mStandby = true;
2433 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002434 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002435 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 }
2437 if (status == NO_ERROR && reconfig) {
2438 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002439 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2440 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441 readOutputParameters();
2442 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2443 for (size_t i = 0; i < mTracks.size() ; i++) {
2444 int name = getTrackName_l();
2445 if (name < 0) break;
2446 mTracks[i]->mName = name;
2447 // limit track sample rate to 2 x new output sample rate
2448 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2449 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2450 }
2451 }
2452 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2453 }
2454 }
2455
2456 mNewParameters.removeAt(0);
2457
2458 mParamStatus = status;
2459 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002460 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2461 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002462 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463 }
2464 return reconfig;
2465}
2466
2467status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2468{
2469 const size_t SIZE = 256;
2470 char buffer[SIZE];
2471 String8 result;
2472
2473 PlaybackThread::dumpInternals(fd, args);
2474
2475 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2476 result.append(buffer);
2477 write(fd, result.string(), result.size());
2478 return NO_ERROR;
2479}
2480
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2482{
Eric Laurent60e18242010-07-29 06:50:24 -07002483 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484}
2485
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002486uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2487{
2488 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2489}
2490
Mathias Agopian65ab4712010-07-14 17:59:35 -07002491// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002492AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2493 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002494 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002495 // mLeftVolFloat, mRightVolFloat
2496 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498}
2499
2500AudioFlinger::DirectOutputThread::~DirectOutputThread()
2501{
2502}
2503
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504static inline
2505int32_t mul(int16_t in, int16_t v)
2506{
2507#if defined(__arm__) && !defined(__thumb__)
2508 int32_t out;
2509 asm( "smulbb %[out], %[in], %[v] \n"
2510 : [out]"=r"(out)
2511 : [in]"%r"(in), [v]"r"(v)
2512 : );
2513 return out;
2514#else
2515 return in * int32_t(v);
2516#endif
2517}
2518
2519void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2520{
2521 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002522 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523 return;
2524 }
2525
2526 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002527 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 size_t count = mFrameCount * mChannelCount;
2529 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2530 int16_t *dst = mMixBuffer + count-1;
2531 while(count--) {
2532 *dst-- = (int16_t)(*src--^0x80) << 8;
2533 }
2534 }
2535
2536 size_t frameCount = mFrameCount;
2537 int16_t *out = mMixBuffer;
2538 if (ramp) {
2539 if (mChannelCount == 1) {
2540 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2541 int32_t vlInc = d / (int32_t)frameCount;
2542 int32_t vl = ((int32_t)mLeftVolShort << 16);
2543 do {
2544 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2545 out++;
2546 vl += vlInc;
2547 } while (--frameCount);
2548
2549 } else {
2550 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2551 int32_t vlInc = d / (int32_t)frameCount;
2552 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2553 int32_t vrInc = d / (int32_t)frameCount;
2554 int32_t vl = ((int32_t)mLeftVolShort << 16);
2555 int32_t vr = ((int32_t)mRightVolShort << 16);
2556 do {
2557 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2558 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2559 out += 2;
2560 vl += vlInc;
2561 vr += vrInc;
2562 } while (--frameCount);
2563 }
2564 } else {
2565 if (mChannelCount == 1) {
2566 do {
2567 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2568 out++;
2569 } while (--frameCount);
2570 } else {
2571 do {
2572 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2573 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2574 out += 2;
2575 } while (--frameCount);
2576 }
2577 }
2578
2579 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002580 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 size_t count = mFrameCount * mChannelCount;
2582 int16_t *src = mMixBuffer;
2583 uint8_t *dst = (uint8_t *)mMixBuffer;
2584 while(count--) {
2585 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2586 }
2587 }
2588
2589 mLeftVolShort = leftVol;
2590 mRightVolShort = rightVol;
2591}
2592
2593bool AudioFlinger::DirectOutputThread::threadLoop()
2594{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002595 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 sp<Track> trackToRemove;
2597 sp<Track> activeTrack;
2598 nsecs_t standbyTime = systemTime();
2599 int8_t *curBuf;
2600 size_t mixBufferSize = mFrameCount*mFrameSize;
2601 uint32_t activeSleepTime = activeSleepTimeUs();
2602 uint32_t idleSleepTime = idleSleepTimeUs();
2603 uint32_t sleepTime = idleSleepTime;
2604 // use shorter standby delay as on normal output to release
2605 // hardware resources as soon as possible
2606 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2607
Eric Laurentfeb0db62011-07-22 09:04:31 -07002608 acquireWakeLock();
2609
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 while (!exitPending())
2611 {
2612 bool rampVolume;
2613 uint16_t leftVol;
2614 uint16_t rightVol;
2615 Vector< sp<EffectChain> > effectChains;
2616
2617 processConfigEvents();
2618
2619 mixerStatus = MIXER_IDLE;
2620
2621 { // scope for the mLock
2622
2623 Mutex::Autolock _l(mLock);
2624
2625 if (checkForNewParameters_l()) {
2626 mixBufferSize = mFrameCount*mFrameSize;
2627 activeSleepTime = activeSleepTimeUs();
2628 idleSleepTime = idleSleepTimeUs();
2629 standbyDelay = microseconds(activeSleepTime*2);
2630 }
2631
2632 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002633 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2634 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635 // wait until we have something to do...
2636 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002637 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002638 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002639 mStandby = true;
2640 mBytesWritten = 0;
2641 }
2642
2643 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2644 // we're about to wait, flush the binder command buffer
2645 IPCThreadState::self()->flushCommands();
2646
2647 if (exitPending()) break;
2648
Eric Laurentfeb0db62011-07-22 09:04:31 -07002649 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002650 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002652 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002653 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654
Glenn Kastenf1d45922012-01-13 15:54:24 -08002655 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002656 char value[PROPERTY_VALUE_MAX];
2657 property_get("ro.audio.silent", value, "0");
2658 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002659 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660 setMasterMute(true);
2661 }
2662 }
2663
2664 standbyTime = systemTime() + standbyDelay;
2665 sleepTime = idleSleepTime;
2666 continue;
2667 }
2668 }
2669
2670 effectChains = mEffectChains;
2671
2672 // find out which tracks need to be processed
2673 if (mActiveTracks.size() != 0) {
2674 sp<Track> t = mActiveTracks[0].promote();
2675 if (t == 0) continue;
2676
2677 Track* const track = t.get();
2678 audio_track_cblk_t* cblk = track->cblk();
2679
2680 // The first time a track is added we wait
2681 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002682 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 !track->isPaused() && !track->isTerminated())
2684 {
Steve Block3856b092011-10-20 11:56:00 +01002685 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002686
2687 if (track->mFillingUpStatus == Track::FS_FILLED) {
2688 track->mFillingUpStatus = Track::FS_ACTIVE;
2689 mLeftVolFloat = mRightVolFloat = 0;
2690 mLeftVolShort = mRightVolShort = 0;
2691 if (track->mState == TrackBase::RESUMING) {
2692 track->mState = TrackBase::ACTIVE;
2693 rampVolume = true;
2694 }
2695 } else if (cblk->server != 0) {
2696 // If the track is stopped before the first frame was mixed,
2697 // do not apply ramp
2698 rampVolume = true;
2699 }
2700 // compute volume for this track
2701 float left, right;
2702 if (track->isMuted() || mMasterMute || track->isPausing() ||
2703 mStreamTypes[track->type()].mute) {
2704 left = right = 0;
2705 if (track->isPausing()) {
2706 track->setPaused();
2707 }
2708 } else {
2709 float typeVolume = mStreamTypes[track->type()].volume;
2710 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002711 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002712 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2714 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002715 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2717 right = v_clamped/MAX_GAIN;
2718 }
2719
2720 if (left != mLeftVolFloat || right != mRightVolFloat) {
2721 mLeftVolFloat = left;
2722 mRightVolFloat = right;
2723
2724 // If audio HAL implements volume control,
2725 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002726 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727 left = 1.0f;
2728 right = 1.0f;
2729 }
2730
2731 // Convert volumes from float to 8.24
2732 uint32_t vl = (uint32_t)(left * (1 << 24));
2733 uint32_t vr = (uint32_t)(right * (1 << 24));
2734
2735 // Delegate volume control to effect in track effect chain if needed
2736 // only one effect chain can be present on DirectOutputThread, so if
2737 // there is one, the track is connected to it
2738 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002739 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002740 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002741 rampVolume = false;
2742 }
2743 }
2744
2745 // Convert volumes from 8.24 to 4.12 format
2746 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2747 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2748 leftVol = (uint16_t)v_clamped;
2749 v_clamped = (vr + (1 << 11)) >> 12;
2750 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2751 rightVol = (uint16_t)v_clamped;
2752 } else {
2753 leftVol = mLeftVolShort;
2754 rightVol = mRightVolShort;
2755 rampVolume = false;
2756 }
2757
2758 // reset retry count
2759 track->mRetryCount = kMaxTrackRetriesDirect;
2760 activeTrack = t;
2761 mixerStatus = MIXER_TRACKS_READY;
2762 } else {
Steve Block3856b092011-10-20 11:56:00 +01002763 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002764 if (track->isStopped()) {
2765 track->reset();
2766 }
2767 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2768 // We have consumed all the buffers of this track.
2769 // Remove it from the list of active tracks.
2770 trackToRemove = track;
2771 } else {
2772 // No buffers for this track. Give it a few chances to
2773 // fill a buffer, then remove it from active list.
2774 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002775 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002776 trackToRemove = track;
2777 } else {
2778 mixerStatus = MIXER_TRACKS_ENABLED;
2779 }
2780 }
2781 }
2782 }
2783
2784 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002785 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002786 mActiveTracks.remove(trackToRemove);
2787 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002788 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002789 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002790 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791 }
2792 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002793 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 }
2795 }
2796
Eric Laurentde070132010-07-13 04:45:46 -07002797 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002798 }
2799
Glenn Kastenf6b16782011-12-15 09:51:17 -08002800 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801 AudioBufferProvider::Buffer buffer;
2802 size_t frameCount = mFrameCount;
2803 curBuf = (int8_t *)mMixBuffer;
2804 // output audio to hardware
2805 while (frameCount) {
2806 buffer.frameCount = frameCount;
2807 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002808 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002809 memset(curBuf, 0, frameCount * mFrameSize);
2810 break;
2811 }
2812 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2813 frameCount -= buffer.frameCount;
2814 curBuf += buffer.frameCount * mFrameSize;
2815 activeTrack->releaseBuffer(&buffer);
2816 }
2817 sleepTime = 0;
2818 standbyTime = systemTime() + standbyDelay;
2819 } else {
2820 if (sleepTime == 0) {
2821 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2822 sleepTime = activeSleepTime;
2823 } else {
2824 sleepTime = idleSleepTime;
2825 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002826 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002827 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2828 sleepTime = 0;
2829 }
2830 }
2831
2832 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002833 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 }
2835 // sleepTime == 0 means we must write to audio hardware
2836 if (sleepTime == 0) {
2837 if (mixerStatus == MIXER_TRACKS_READY) {
2838 applyVolume(leftVol, rightVol, rampVolume);
2839 }
2840 for (size_t i = 0; i < effectChains.size(); i ++) {
2841 effectChains[i]->process_l();
2842 }
Eric Laurentde070132010-07-13 04:45:46 -07002843 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844
2845 mLastWriteTime = systemTime();
2846 mInWrite = true;
2847 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002848 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002849 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2850 mNumWrites++;
2851 mInWrite = false;
2852 mStandby = false;
2853 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002854 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002855 usleep(sleepTime);
2856 }
2857
2858 // finally let go of removed track, without the lock held
2859 // since we can't guarantee the destructors won't acquire that
2860 // same lock.
2861 trackToRemove.clear();
2862 activeTrack.clear();
2863
2864 // Effect chains will be actually deleted here if they were removed from
2865 // mEffectChains list during mixing or effects processing
2866 effectChains.clear();
2867 }
2868
2869 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002870 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002871 }
2872
Eric Laurentfeb0db62011-07-22 09:04:31 -07002873 releaseWakeLock();
2874
Steve Block3856b092011-10-20 11:56:00 +01002875 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002876 return false;
2877}
2878
2879// getTrackName_l() must be called with ThreadBase::mLock held
2880int AudioFlinger::DirectOutputThread::getTrackName_l()
2881{
2882 return 0;
2883}
2884
2885// deleteTrackName_l() must be called with ThreadBase::mLock held
2886void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2887{
2888}
2889
2890// checkForNewParameters_l() must be called with ThreadBase::mLock held
2891bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2892{
2893 bool reconfig = false;
2894
2895 while (!mNewParameters.isEmpty()) {
2896 status_t status = NO_ERROR;
2897 String8 keyValuePair = mNewParameters[0];
2898 AudioParameter param = AudioParameter(keyValuePair);
2899 int value;
2900
2901 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2902 // do not accept frame count changes if tracks are open as the track buffer
2903 // size depends on frame count and correct behavior would not be garantied
2904 // if frame count is changed after track creation
2905 if (!mTracks.isEmpty()) {
2906 status = INVALID_OPERATION;
2907 } else {
2908 reconfig = true;
2909 }
2910 }
2911 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002912 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002913 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002914 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002915 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002916 mStandby = true;
2917 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002918 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002919 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002920 }
2921 if (status == NO_ERROR && reconfig) {
2922 readOutputParameters();
2923 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2924 }
2925 }
2926
2927 mNewParameters.removeAt(0);
2928
2929 mParamStatus = status;
2930 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002931 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2932 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002933 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934 }
2935 return reconfig;
2936}
2937
2938uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2939{
2940 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002941 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002942 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002943 } else {
2944 time = 10000;
2945 }
2946 return time;
2947}
2948
2949uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2950{
2951 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002952 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002953 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954 } else {
2955 time = 10000;
2956 }
2957 return time;
2958}
2959
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002960uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2961{
2962 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002963 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002964 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2965 } else {
2966 time = 10000;
2967 }
2968 return time;
2969}
2970
2971
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972// ----------------------------------------------------------------------------
2973
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002974AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002975 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002976 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2977 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979 addOutputTrack(mainThread);
2980}
2981
2982AudioFlinger::DuplicatingThread::~DuplicatingThread()
2983{
2984 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2985 mOutputTracks[i]->destroy();
2986 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987}
2988
2989bool AudioFlinger::DuplicatingThread::threadLoop()
2990{
2991 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08002992 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993 nsecs_t standbyTime = systemTime();
2994 size_t mixBufferSize = mFrameCount*mFrameSize;
2995 SortedVector< sp<OutputTrack> > outputTracks;
2996 uint32_t writeFrames = 0;
2997 uint32_t activeSleepTime = activeSleepTimeUs();
2998 uint32_t idleSleepTime = idleSleepTimeUs();
2999 uint32_t sleepTime = idleSleepTime;
3000 Vector< sp<EffectChain> > effectChains;
3001
Eric Laurentfeb0db62011-07-22 09:04:31 -07003002 acquireWakeLock();
3003
Mathias Agopian65ab4712010-07-14 17:59:35 -07003004 while (!exitPending())
3005 {
3006 processConfigEvents();
3007
3008 mixerStatus = MIXER_IDLE;
3009 { // scope for the mLock
3010
3011 Mutex::Autolock _l(mLock);
3012
3013 if (checkForNewParameters_l()) {
3014 mixBufferSize = mFrameCount*mFrameSize;
3015 updateWaitTime();
3016 activeSleepTime = activeSleepTimeUs();
3017 idleSleepTime = idleSleepTimeUs();
3018 }
3019
3020 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3021
3022 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3023 outputTracks.add(mOutputTracks[i]);
3024 }
3025
3026 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003027 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3028 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003029 if (!mStandby) {
3030 for (size_t i = 0; i < outputTracks.size(); i++) {
3031 outputTracks[i]->stop();
3032 }
3033 mStandby = true;
3034 mBytesWritten = 0;
3035 }
3036
3037 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3038 // we're about to wait, flush the binder command buffer
3039 IPCThreadState::self()->flushCommands();
3040 outputTracks.clear();
3041
3042 if (exitPending()) break;
3043
Eric Laurentfeb0db62011-07-22 09:04:31 -07003044 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003045 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003046 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003047 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003048 acquireWakeLock_l();
3049
Eric Laurent27741442012-01-17 19:20:12 -08003050 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003051 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003052 char value[PROPERTY_VALUE_MAX];
3053 property_get("ro.audio.silent", value, "0");
3054 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003055 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003056 setMasterMute(true);
3057 }
3058 }
3059
3060 standbyTime = systemTime() + kStandbyTimeInNsecs;
3061 sleepTime = idleSleepTime;
3062 continue;
3063 }
3064 }
3065
3066 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3067
3068 // prevent any changes in effect chain list and in each effect chain
3069 // during mixing and effect process as the audio buffers could be deleted
3070 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003071 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 }
3073
Glenn Kastenf6b16782011-12-15 09:51:17 -08003074 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003075 // mix buffers...
3076 if (outputsReady(outputTracks)) {
3077 mAudioMixer->process();
3078 } else {
3079 memset(mMixBuffer, 0, mixBufferSize);
3080 }
3081 sleepTime = 0;
3082 writeFrames = mFrameCount;
3083 } else {
3084 if (sleepTime == 0) {
3085 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3086 sleepTime = activeSleepTime;
3087 } else {
3088 sleepTime = idleSleepTime;
3089 }
3090 } else if (mBytesWritten != 0) {
3091 // flush remaining overflow buffers in output tracks
3092 for (size_t i = 0; i < outputTracks.size(); i++) {
3093 if (outputTracks[i]->isActive()) {
3094 sleepTime = 0;
3095 writeFrames = 0;
3096 memset(mMixBuffer, 0, mixBufferSize);
3097 break;
3098 }
3099 }
3100 }
3101 }
3102
3103 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003104 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003105 }
3106 // sleepTime == 0 means we must write to audio hardware
3107 if (sleepTime == 0) {
3108 for (size_t i = 0; i < effectChains.size(); i ++) {
3109 effectChains[i]->process_l();
3110 }
3111 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003112 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003113
3114 standbyTime = systemTime() + kStandbyTimeInNsecs;
3115 for (size_t i = 0; i < outputTracks.size(); i++) {
3116 outputTracks[i]->write(mMixBuffer, writeFrames);
3117 }
3118 mStandby = false;
3119 mBytesWritten += mixBufferSize;
3120 } else {
3121 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003122 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 usleep(sleepTime);
3124 }
3125
3126 // finally let go of all our tracks, without the lock held
3127 // since we can't guarantee the destructors won't acquire that
3128 // same lock.
3129 tracksToRemove.clear();
3130 outputTracks.clear();
3131
3132 // Effect chains will be actually deleted here if they were removed from
3133 // mEffectChains list during mixing or effects processing
3134 effectChains.clear();
3135 }
3136
Eric Laurentfeb0db62011-07-22 09:04:31 -07003137 releaseWakeLock();
3138
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139 return false;
3140}
3141
3142void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3143{
3144 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3145 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3146 this,
3147 mSampleRate,
3148 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003149 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 frameCount);
3151 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003152 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003154 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003155 updateWaitTime();
3156 }
3157}
3158
3159void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3160{
3161 Mutex::Autolock _l(mLock);
3162 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3163 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3164 mOutputTracks[i]->destroy();
3165 mOutputTracks.removeAt(i);
3166 updateWaitTime();
3167 return;
3168 }
3169 }
Steve Block3856b092011-10-20 11:56:00 +01003170 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171}
3172
3173void AudioFlinger::DuplicatingThread::updateWaitTime()
3174{
3175 mWaitTimeMs = UINT_MAX;
3176 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3177 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003178 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3180 if (waitTimeMs < mWaitTimeMs) {
3181 mWaitTimeMs = waitTimeMs;
3182 }
3183 }
3184 }
3185}
3186
3187
3188bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3189{
3190 for (size_t i = 0; i < outputTracks.size(); i++) {
3191 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3192 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003193 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194 return false;
3195 }
3196 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3197 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003198 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199 return false;
3200 }
3201 }
3202 return true;
3203}
3204
3205uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3206{
3207 return (mWaitTimeMs * 1000) / 2;
3208}
3209
3210// ----------------------------------------------------------------------------
3211
3212// TrackBase constructor must be called with AudioFlinger::mLock held
3213AudioFlinger::ThreadBase::TrackBase::TrackBase(
3214 const wp<ThreadBase>& thread,
3215 const sp<Client>& client,
3216 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003217 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003218 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003219 int frameCount,
3220 uint32_t flags,
3221 const sp<IMemory>& sharedBuffer,
3222 int sessionId)
3223 : RefBase(),
3224 mThread(thread),
3225 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003226 mCblk(NULL),
3227 // mBuffer
3228 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003229 mFrameCount(0),
3230 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231 mFormat(format),
3232 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3233 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003234 // mChannelCount
3235 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236{
Steve Block3856b092011-10-20 11:56:00 +01003237 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238
Steve Blockb8a80522011-12-20 16:23:08 +00003239 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003241 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003242 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3243 if (sharedBuffer == 0) {
3244 size += bufferSize;
3245 }
3246
3247 if (client != NULL) {
3248 mCblkMemory = client->heap()->allocate(size);
3249 if (mCblkMemory != 0) {
3250 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003251 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252 new(mCblk) audio_track_cblk_t();
3253 // clear all buffers
3254 mCblk->frameCount = frameCount;
3255 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003256 mChannelCount = channelCount;
3257 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258 if (sharedBuffer == 0) {
3259 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3260 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3261 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003262 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 mCblk->flags = CBLK_UNDERRUN_ON;
3264 } else {
3265 mBuffer = sharedBuffer->pointer();
3266 }
3267 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3268 }
3269 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003270 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 client->heap()->dump("AudioTrack");
3272 return;
3273 }
3274 } else {
3275 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003276 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277 new(mCblk) audio_track_cblk_t();
3278 // clear all buffers
3279 mCblk->frameCount = frameCount;
3280 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003281 mChannelCount = channelCount;
3282 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3284 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3285 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003286 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287 mCblk->flags = CBLK_UNDERRUN_ON;
3288 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289 }
3290}
3291
3292AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3293{
Glenn Kastena0d68332012-01-27 16:47:15 -08003294 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003295 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003297 } else {
3298 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299 }
3300 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003301 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003302 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003303 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003305 // If the client's reference count drops to zero, the associated destructor
3306 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3307 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 mClient.clear();
3309 }
3310}
3311
3312void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3313{
Glenn Kastene0feee32011-12-13 11:53:26 -08003314 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003315 mFrameCount = buffer->frameCount;
3316 step();
3317 buffer->frameCount = 0;
3318}
3319
3320bool AudioFlinger::ThreadBase::TrackBase::step() {
3321 bool result;
3322 audio_track_cblk_t* cblk = this->cblk();
3323
3324 result = cblk->stepServer(mFrameCount);
3325 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003326 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 mFlags |= STEPSERVER_FAILED;
3328 }
3329 return result;
3330}
3331
3332void AudioFlinger::ThreadBase::TrackBase::reset() {
3333 audio_track_cblk_t* cblk = this->cblk();
3334
3335 cblk->user = 0;
3336 cblk->server = 0;
3337 cblk->userBase = 0;
3338 cblk->serverBase = 0;
3339 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003340 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341}
3342
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3344 return (int)mCblk->sampleRate;
3345}
3346
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3348 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003349 size_t frameSize = cblk->frameSize;
3350 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3351 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352
3353 // Check validity of returned pointer in case the track control block would have been corrupted.
3354 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003355 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003356 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 -07003357 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003359 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003360 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 }
3362
3363 return bufferStart;
3364}
3365
3366// ----------------------------------------------------------------------------
3367
3368// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3369AudioFlinger::PlaybackThread::Track::Track(
3370 const wp<ThreadBase>& thread,
3371 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003372 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003374 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003375 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376 int frameCount,
3377 const sp<IMemory>& sharedBuffer,
3378 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003379 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003380 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3381 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382{
3383 if (mCblk != NULL) {
3384 sp<ThreadBase> baseThread = thread.promote();
3385 if (baseThread != 0) {
3386 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3387 mName = playbackThread->getTrackName_l();
3388 mMainBuffer = playbackThread->mixBuffer();
3389 }
Steve Block3856b092011-10-20 11:56:00 +01003390 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003391 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003392 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 mStreamType = streamType;
3395 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3396 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003397 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398 }
3399}
3400
3401AudioFlinger::PlaybackThread::Track::~Track()
3402{
Steve Block3856b092011-10-20 11:56:00 +01003403 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 sp<ThreadBase> thread = mThread.promote();
3405 if (thread != 0) {
3406 Mutex::Autolock _l(thread->mLock);
3407 mState = TERMINATED;
3408 }
3409}
3410
3411void AudioFlinger::PlaybackThread::Track::destroy()
3412{
3413 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3414 // by removing it from mTracks vector, so there is a risk that this Tracks's
3415 // desctructor is called. As the destructor needs to lock mLock,
3416 // we must acquire a strong reference on this Track before locking mLock
3417 // here so that the destructor is called only when exiting this function.
3418 // On the other hand, as long as Track::destroy() is only called by
3419 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3420 // this Track with its member mTrack.
3421 sp<Track> keep(this);
3422 { // scope for mLock
3423 sp<ThreadBase> thread = mThread.promote();
3424 if (thread != 0) {
3425 if (!isOutputTrack()) {
3426 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003427 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003428 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003429 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003430
3431 // to track the speaker usage
3432 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003433 }
3434 AudioSystem::releaseOutput(thread->id());
3435 }
3436 Mutex::Autolock _l(thread->mLock);
3437 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3438 playbackThread->destroyTrack_l(this);
3439 }
3440 }
3441}
3442
3443void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3444{
Glenn Kasten83d86532012-01-17 14:39:34 -08003445 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003446 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 -07003447 mName - AudioMixer::TRACK0,
Glenn Kasten7378ca52012-01-20 13:44:40 -08003448 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 mStreamType,
3450 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003451 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452 mSessionId,
3453 mFrameCount,
3454 mState,
3455 mMute,
3456 mFillingUpStatus,
3457 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003458 vlr & 0xFFFF,
3459 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460 mCblk->server,
3461 mCblk->user,
3462 (int)mMainBuffer,
3463 (int)mAuxBuffer);
3464}
3465
3466status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3467{
3468 audio_track_cblk_t* cblk = this->cblk();
3469 uint32_t framesReady;
3470 uint32_t framesReq = buffer->frameCount;
3471
3472 // Check if last stepServer failed, try to step now
3473 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3474 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003475 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3477 }
3478
3479 framesReady = cblk->framesReady();
3480
Glenn Kastenf6b16782011-12-15 09:51:17 -08003481 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482 uint32_t s = cblk->server;
3483 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3484
3485 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3486 if (framesReq > framesReady) {
3487 framesReq = framesReady;
3488 }
3489 if (s + framesReq > bufferEnd) {
3490 framesReq = bufferEnd - s;
3491 }
3492
3493 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003494 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495
3496 buffer->frameCount = framesReq;
3497 return NO_ERROR;
3498 }
3499
3500getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003501 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003502 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003503 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 return NOT_ENOUGH_DATA;
3505}
3506
3507bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003508 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003509
3510 if (mCblk->framesReady() >= mCblk->frameCount ||
3511 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3512 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003513 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003514 return true;
3515 }
3516 return false;
3517}
3518
3519status_t AudioFlinger::PlaybackThread::Track::start()
3520{
3521 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003522 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003523 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003524 sp<ThreadBase> thread = mThread.promote();
3525 if (thread != 0) {
3526 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003527 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003528 // here the track could be either new, or restarted
3529 // in both cases "unstop" the track
3530 if (mState == PAUSED) {
3531 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003532 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 } else {
3534 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003535 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003536 }
3537
3538 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3539 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003540 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003541 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003542 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003543 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003544
3545 // to track the speaker usage
3546 if (status == NO_ERROR) {
3547 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3548 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003549 }
3550 if (status == NO_ERROR) {
3551 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3552 playbackThread->addTrack_l(this);
3553 } else {
3554 mState = state;
3555 }
3556 } else {
3557 status = BAD_VALUE;
3558 }
3559 return status;
3560}
3561
3562void AudioFlinger::PlaybackThread::Track::stop()
3563{
Steve Block3856b092011-10-20 11:56:00 +01003564 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003565 sp<ThreadBase> thread = mThread.promote();
3566 if (thread != 0) {
3567 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003568 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 if (mState > STOPPED) {
3570 mState = STOPPED;
3571 // If the track is not active (PAUSED and buffers full), flush buffers
3572 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3573 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3574 reset();
3575 }
Steve Block3856b092011-10-20 11:56:00 +01003576 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003577 }
3578 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3579 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003580 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003581 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003582 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003583 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003584
3585 // to track the speaker usage
3586 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003587 }
3588 }
3589}
3590
3591void AudioFlinger::PlaybackThread::Track::pause()
3592{
Steve Block3856b092011-10-20 11:56:00 +01003593 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003594 sp<ThreadBase> thread = mThread.promote();
3595 if (thread != 0) {
3596 Mutex::Autolock _l(thread->mLock);
3597 if (mState == ACTIVE || mState == RESUMING) {
3598 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003599 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600 if (!isOutputTrack()) {
3601 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003602 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003603 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003604 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003605 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003606
3607 // to track the speaker usage
3608 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003609 }
3610 }
3611 }
3612}
3613
3614void AudioFlinger::PlaybackThread::Track::flush()
3615{
Steve Block3856b092011-10-20 11:56:00 +01003616 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617 sp<ThreadBase> thread = mThread.promote();
3618 if (thread != 0) {
3619 Mutex::Autolock _l(thread->mLock);
3620 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3621 return;
3622 }
3623 // No point remaining in PAUSED state after a flush => go to
3624 // STOPPED state
3625 mState = STOPPED;
3626
Eric Laurent38ccae22011-03-28 18:37:07 -07003627 // do not reset the track if it is still in the process of being stopped or paused.
3628 // this will be done by prepareTracks_l() when the track is stopped.
3629 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3630 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3631 reset();
3632 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633 }
3634}
3635
3636void AudioFlinger::PlaybackThread::Track::reset()
3637{
3638 // Do not reset twice to avoid discarding data written just after a flush and before
3639 // the audioflinger thread detects the track is stopped.
3640 if (!mResetDone) {
3641 TrackBase::reset();
3642 // Force underrun condition to avoid false underrun callback until first data is
3643 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003644 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3645 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003646 mFillingUpStatus = FS_FILLING;
3647 mResetDone = true;
3648 }
3649}
3650
3651void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3652{
3653 mMute = muted;
3654}
3655
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3657{
3658 status_t status = DEAD_OBJECT;
3659 sp<ThreadBase> thread = mThread.promote();
3660 if (thread != 0) {
3661 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3662 status = playbackThread->attachAuxEffect(this, EffectId);
3663 }
3664 return status;
3665}
3666
3667void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3668{
3669 mAuxEffectId = EffectId;
3670 mAuxBuffer = buffer;
3671}
3672
3673// ----------------------------------------------------------------------------
3674
3675// RecordTrack constructor must be called with AudioFlinger::mLock held
3676AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3677 const wp<ThreadBase>& thread,
3678 const sp<Client>& client,
3679 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003680 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003681 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682 int frameCount,
3683 uint32_t flags,
3684 int sessionId)
3685 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003686 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687 mOverflow(false)
3688{
3689 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003690 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003691 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003692 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003693 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003694 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003695 } else {
3696 mCblk->frameSize = sizeof(int8_t);
3697 }
3698 }
3699}
3700
3701AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3702{
3703 sp<ThreadBase> thread = mThread.promote();
3704 if (thread != 0) {
3705 AudioSystem::releaseInput(thread->id());
3706 }
3707}
3708
3709status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3710{
3711 audio_track_cblk_t* cblk = this->cblk();
3712 uint32_t framesAvail;
3713 uint32_t framesReq = buffer->frameCount;
3714
3715 // Check if last stepServer failed, try to step now
3716 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3717 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003718 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003719 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3720 }
3721
3722 framesAvail = cblk->framesAvailable_l();
3723
Glenn Kastenf6b16782011-12-15 09:51:17 -08003724 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003725 uint32_t s = cblk->server;
3726 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3727
3728 if (framesReq > framesAvail) {
3729 framesReq = framesAvail;
3730 }
3731 if (s + framesReq > bufferEnd) {
3732 framesReq = bufferEnd - s;
3733 }
3734
3735 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003736 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003737
3738 buffer->frameCount = framesReq;
3739 return NO_ERROR;
3740 }
3741
3742getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003743 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003744 buffer->frameCount = 0;
3745 return NOT_ENOUGH_DATA;
3746}
3747
3748status_t AudioFlinger::RecordThread::RecordTrack::start()
3749{
3750 sp<ThreadBase> thread = mThread.promote();
3751 if (thread != 0) {
3752 RecordThread *recordThread = (RecordThread *)thread.get();
3753 return recordThread->start(this);
3754 } else {
3755 return BAD_VALUE;
3756 }
3757}
3758
3759void AudioFlinger::RecordThread::RecordTrack::stop()
3760{
3761 sp<ThreadBase> thread = mThread.promote();
3762 if (thread != 0) {
3763 RecordThread *recordThread = (RecordThread *)thread.get();
3764 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003765 TrackBase::reset();
3766 // Force overerrun condition to avoid false overrun callback until first data is
3767 // read from buffer
3768 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769 }
3770}
3771
3772void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3773{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003774 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08003775 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003776 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003777 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003778 mSessionId,
3779 mFrameCount,
3780 mState,
3781 mCblk->sampleRate,
3782 mCblk->server,
3783 mCblk->user);
3784}
3785
3786
3787// ----------------------------------------------------------------------------
3788
3789AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3790 const wp<ThreadBase>& thread,
3791 DuplicatingThread *sourceThread,
3792 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003793 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003794 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003795 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003796 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797 mActive(false), mSourceThread(sourceThread)
3798{
3799
3800 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3801 if (mCblk != NULL) {
3802 mCblk->flags |= CBLK_DIRECTION_OUT;
3803 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003804 mOutBuffer.frameCount = 0;
3805 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003806 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003807 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3808 mCblk, mBuffer, mCblk->buffers,
3809 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003810 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003811 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003812 }
3813}
3814
3815AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3816{
3817 clearBufferQueue();
3818}
3819
3820status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3821{
3822 status_t status = Track::start();
3823 if (status != NO_ERROR) {
3824 return status;
3825 }
3826
3827 mActive = true;
3828 mRetryCount = 127;
3829 return status;
3830}
3831
3832void AudioFlinger::PlaybackThread::OutputTrack::stop()
3833{
3834 Track::stop();
3835 clearBufferQueue();
3836 mOutBuffer.frameCount = 0;
3837 mActive = false;
3838}
3839
3840bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3841{
3842 Buffer *pInBuffer;
3843 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003844 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003845 bool outputBufferFull = false;
3846 inBuffer.frameCount = frames;
3847 inBuffer.i16 = data;
3848
3849 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3850
3851 if (!mActive && frames != 0) {
3852 start();
3853 sp<ThreadBase> thread = mThread.promote();
3854 if (thread != 0) {
3855 MixerThread *mixerThread = (MixerThread *)thread.get();
3856 if (mCblk->frameCount > frames){
3857 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3858 uint32_t startFrames = (mCblk->frameCount - frames);
3859 pInBuffer = new Buffer;
3860 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3861 pInBuffer->frameCount = startFrames;
3862 pInBuffer->i16 = pInBuffer->mBuffer;
3863 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3864 mBufferQueue.add(pInBuffer);
3865 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003866 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003867 }
3868 }
3869 }
3870 }
3871
3872 while (waitTimeLeftMs) {
3873 // First write pending buffers, then new data
3874 if (mBufferQueue.size()) {
3875 pInBuffer = mBufferQueue.itemAt(0);
3876 } else {
3877 pInBuffer = &inBuffer;
3878 }
3879
3880 if (pInBuffer->frameCount == 0) {
3881 break;
3882 }
3883
3884 if (mOutBuffer.frameCount == 0) {
3885 mOutBuffer.frameCount = pInBuffer->frameCount;
3886 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003887 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003888 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003889 outputBufferFull = true;
3890 break;
3891 }
3892 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3893 if (waitTimeLeftMs >= waitTimeMs) {
3894 waitTimeLeftMs -= waitTimeMs;
3895 } else {
3896 waitTimeLeftMs = 0;
3897 }
3898 }
3899
3900 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3901 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3902 mCblk->stepUser(outFrames);
3903 pInBuffer->frameCount -= outFrames;
3904 pInBuffer->i16 += outFrames * channelCount;
3905 mOutBuffer.frameCount -= outFrames;
3906 mOutBuffer.i16 += outFrames * channelCount;
3907
3908 if (pInBuffer->frameCount == 0) {
3909 if (mBufferQueue.size()) {
3910 mBufferQueue.removeAt(0);
3911 delete [] pInBuffer->mBuffer;
3912 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003913 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003914 } else {
3915 break;
3916 }
3917 }
3918 }
3919
3920 // If we could not write all frames, allocate a buffer and queue it for next time.
3921 if (inBuffer.frameCount) {
3922 sp<ThreadBase> thread = mThread.promote();
3923 if (thread != 0 && !thread->standby()) {
3924 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3925 pInBuffer = new Buffer;
3926 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3927 pInBuffer->frameCount = inBuffer.frameCount;
3928 pInBuffer->i16 = pInBuffer->mBuffer;
3929 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3930 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003931 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003932 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003933 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003934 }
3935 }
3936 }
3937
3938 // Calling write() with a 0 length buffer, means that no more data will be written:
3939 // If no more buffers are pending, fill output track buffer to make sure it is started
3940 // by output mixer.
3941 if (frames == 0 && mBufferQueue.size() == 0) {
3942 if (mCblk->user < mCblk->frameCount) {
3943 frames = mCblk->frameCount - mCblk->user;
3944 pInBuffer = new Buffer;
3945 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3946 pInBuffer->frameCount = frames;
3947 pInBuffer->i16 = pInBuffer->mBuffer;
3948 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3949 mBufferQueue.add(pInBuffer);
3950 } else if (mActive) {
3951 stop();
3952 }
3953 }
3954
3955 return outputBufferFull;
3956}
3957
3958status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3959{
3960 int active;
3961 status_t result;
3962 audio_track_cblk_t* cblk = mCblk;
3963 uint32_t framesReq = buffer->frameCount;
3964
Steve Block3856b092011-10-20 11:56:00 +01003965// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003966 buffer->frameCount = 0;
3967
3968 uint32_t framesAvail = cblk->framesAvailable();
3969
3970
3971 if (framesAvail == 0) {
3972 Mutex::Autolock _l(cblk->lock);
3973 goto start_loop_here;
3974 while (framesAvail == 0) {
3975 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003976 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003977 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08003978 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003979 }
3980 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3981 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003982 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003983 }
3984 // read the server count again
3985 start_loop_here:
3986 framesAvail = cblk->framesAvailable_l();
3987 }
3988 }
3989
3990// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003991// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003992// }
3993
3994 if (framesReq > framesAvail) {
3995 framesReq = framesAvail;
3996 }
3997
3998 uint32_t u = cblk->user;
3999 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4000
4001 if (u + framesReq > bufferEnd) {
4002 framesReq = bufferEnd - u;
4003 }
4004
4005 buffer->frameCount = framesReq;
4006 buffer->raw = (void *)cblk->buffer(u);
4007 return NO_ERROR;
4008}
4009
4010
4011void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4012{
4013 size_t size = mBufferQueue.size();
4014 Buffer *pBuffer;
4015
4016 for (size_t i = 0; i < size; i++) {
4017 pBuffer = mBufferQueue.itemAt(i);
4018 delete [] pBuffer->mBuffer;
4019 delete pBuffer;
4020 }
4021 mBufferQueue.clear();
4022}
4023
4024// ----------------------------------------------------------------------------
4025
4026AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4027 : RefBase(),
4028 mAudioFlinger(audioFlinger),
4029 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4030 mPid(pid)
4031{
4032 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4033}
4034
4035// Client destructor must be called with AudioFlinger::mLock held
4036AudioFlinger::Client::~Client()
4037{
4038 mAudioFlinger->removeClient_l(mPid);
4039}
4040
Glenn Kasten435dbe62012-01-30 10:15:48 -08004041sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004042{
4043 return mMemoryDealer;
4044}
4045
4046// ----------------------------------------------------------------------------
4047
4048AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4049 const sp<IAudioFlingerClient>& client,
4050 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004051 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004052{
4053}
4054
4055AudioFlinger::NotificationClient::~NotificationClient()
4056{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004057}
4058
4059void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4060{
4061 sp<NotificationClient> keep(this);
4062 {
4063 mAudioFlinger->removeNotificationClient(mPid);
4064 }
4065}
4066
4067// ----------------------------------------------------------------------------
4068
4069AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4070 : BnAudioTrack(),
4071 mTrack(track)
4072{
4073}
4074
4075AudioFlinger::TrackHandle::~TrackHandle() {
4076 // just stop the track on deletion, associated resources
4077 // will be freed from the main thread once all pending buffers have
4078 // been played. Unless it's not in the active track list, in which
4079 // case we free everything now...
4080 mTrack->destroy();
4081}
4082
Glenn Kasten90716c52012-01-26 13:40:12 -08004083sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4084 return mTrack->getCblk();
4085}
4086
Mathias Agopian65ab4712010-07-14 17:59:35 -07004087status_t AudioFlinger::TrackHandle::start() {
4088 return mTrack->start();
4089}
4090
4091void AudioFlinger::TrackHandle::stop() {
4092 mTrack->stop();
4093}
4094
4095void AudioFlinger::TrackHandle::flush() {
4096 mTrack->flush();
4097}
4098
4099void AudioFlinger::TrackHandle::mute(bool e) {
4100 mTrack->mute(e);
4101}
4102
4103void AudioFlinger::TrackHandle::pause() {
4104 mTrack->pause();
4105}
4106
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4108{
4109 return mTrack->attachAuxEffect(EffectId);
4110}
4111
4112status_t AudioFlinger::TrackHandle::onTransact(
4113 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4114{
4115 return BnAudioTrack::onTransact(code, data, reply, flags);
4116}
4117
4118// ----------------------------------------------------------------------------
4119
4120sp<IAudioRecord> AudioFlinger::openRecord(
4121 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004122 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004124 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004125 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004126 int frameCount,
4127 uint32_t flags,
4128 int *sessionId,
4129 status_t *status)
4130{
4131 sp<RecordThread::RecordTrack> recordTrack;
4132 sp<RecordHandle> recordHandle;
4133 sp<Client> client;
4134 wp<Client> wclient;
4135 status_t lStatus;
4136 RecordThread *thread;
4137 size_t inFrameCount;
4138 int lSessionId;
4139
4140 // check calling permissions
4141 if (!recordingAllowed()) {
4142 lStatus = PERMISSION_DENIED;
4143 goto Exit;
4144 }
4145
4146 // add client to list
4147 { // scope for mLock
4148 Mutex::Autolock _l(mLock);
4149 thread = checkRecordThread_l(input);
4150 if (thread == NULL) {
4151 lStatus = BAD_VALUE;
4152 goto Exit;
4153 }
4154
4155 wclient = mClients.valueFor(pid);
4156 if (wclient != NULL) {
4157 client = wclient.promote();
4158 } else {
4159 client = new Client(this, pid);
4160 mClients.add(pid, client);
4161 }
4162
4163 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004164 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004165 lSessionId = *sessionId;
4166 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004167 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168 if (sessionId != NULL) {
4169 *sessionId = lSessionId;
4170 }
4171 }
4172 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004173 recordTrack = thread->createRecordTrack_l(client,
4174 sampleRate,
4175 format,
4176 channelMask,
4177 frameCount,
4178 flags,
4179 lSessionId,
4180 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004182 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004183 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4184 // destructor is called by the TrackBase destructor with mLock held
4185 client.clear();
4186 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004187 goto Exit;
4188 }
4189
4190 // return to handle to client
4191 recordHandle = new RecordHandle(recordTrack);
4192 lStatus = NO_ERROR;
4193
4194Exit:
4195 if (status) {
4196 *status = lStatus;
4197 }
4198 return recordHandle;
4199}
4200
4201// ----------------------------------------------------------------------------
4202
4203AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4204 : BnAudioRecord(),
4205 mRecordTrack(recordTrack)
4206{
4207}
4208
4209AudioFlinger::RecordHandle::~RecordHandle() {
4210 stop();
4211}
4212
Glenn Kasten90716c52012-01-26 13:40:12 -08004213sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4214 return mRecordTrack->getCblk();
4215}
4216
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004218 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219 return mRecordTrack->start();
4220}
4221
4222void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004223 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224 mRecordTrack->stop();
4225}
4226
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227status_t AudioFlinger::RecordHandle::onTransact(
4228 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4229{
4230 return BnAudioRecord::onTransact(code, data, reply, flags);
4231}
4232
4233// ----------------------------------------------------------------------------
4234
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004235AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4236 AudioStreamIn *input,
4237 uint32_t sampleRate,
4238 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004239 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004240 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004241 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004242 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4243 // mRsmpInIndex and mInputBytes set by readInputParameters()
4244 mReqChannelCount(popcount(channels)),
4245 mReqSampleRate(sampleRate)
4246 // mBytesRead is only meaningful while active, and so is cleared in start()
4247 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004248{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004249 snprintf(mName, kNameLength, "AudioIn_%d", id);
4250
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251 readInputParameters();
4252}
4253
4254
4255AudioFlinger::RecordThread::~RecordThread()
4256{
4257 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004258 delete mResampler;
4259 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260}
4261
4262void AudioFlinger::RecordThread::onFirstRef()
4263{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004264 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265}
4266
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004267status_t AudioFlinger::RecordThread::readyToRun()
4268{
4269 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004270 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004271 return status;
4272}
4273
Mathias Agopian65ab4712010-07-14 17:59:35 -07004274bool AudioFlinger::RecordThread::threadLoop()
4275{
4276 AudioBufferProvider::Buffer buffer;
4277 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004278 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279
Eric Laurent44d98482010-09-30 16:12:31 -07004280 nsecs_t lastWarning = 0;
4281
Eric Laurentfeb0db62011-07-22 09:04:31 -07004282 acquireWakeLock();
4283
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284 // start recording
4285 while (!exitPending()) {
4286
4287 processConfigEvents();
4288
4289 { // scope for mLock
4290 Mutex::Autolock _l(mLock);
4291 checkForNewParameters_l();
4292 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4293 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004294 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004295 mStandby = true;
4296 }
4297
4298 if (exitPending()) break;
4299
Eric Laurentfeb0db62011-07-22 09:04:31 -07004300 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004301 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302 // go to sleep
4303 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004304 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004305 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004306 continue;
4307 }
4308 if (mActiveTrack != 0) {
4309 if (mActiveTrack->mState == TrackBase::PAUSING) {
4310 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004311 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312 mStandby = true;
4313 }
4314 mActiveTrack.clear();
4315 mStartStopCond.broadcast();
4316 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4317 if (mReqChannelCount != mActiveTrack->channelCount()) {
4318 mActiveTrack.clear();
4319 mStartStopCond.broadcast();
4320 } else if (mBytesRead != 0) {
4321 // record start succeeds only if first read from audio input
4322 // succeeds
4323 if (mBytesRead > 0) {
4324 mActiveTrack->mState = TrackBase::ACTIVE;
4325 } else {
4326 mActiveTrack.clear();
4327 }
4328 mStartStopCond.broadcast();
4329 }
4330 mStandby = false;
4331 }
4332 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004333 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334 }
4335
4336 if (mActiveTrack != 0) {
4337 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4338 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004339 unlockEffectChains(effectChains);
4340 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004341 continue;
4342 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004343 for (size_t i = 0; i < effectChains.size(); i ++) {
4344 effectChains[i]->process_l();
4345 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004346
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004348 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004350 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004351 // no resampling
4352 while (framesOut) {
4353 size_t framesIn = mFrameCount - mRsmpInIndex;
4354 if (framesIn) {
4355 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4356 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4357 if (framesIn > framesOut)
4358 framesIn = framesOut;
4359 mRsmpInIndex += framesIn;
4360 framesOut -= framesIn;
4361 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004362 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004363 memcpy(dst, src, framesIn * mFrameSize);
4364 } else {
4365 int16_t *src16 = (int16_t *)src;
4366 int16_t *dst16 = (int16_t *)dst;
4367 if (mChannelCount == 1) {
4368 while (framesIn--) {
4369 *dst16++ = *src16;
4370 *dst16++ = *src16++;
4371 }
4372 } else {
4373 while (framesIn--) {
4374 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4375 src16 += 2;
4376 }
4377 }
4378 }
4379 }
4380 if (framesOut && mFrameCount == mRsmpInIndex) {
4381 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004382 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004383 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 framesOut = 0;
4385 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004386 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004387 mRsmpInIndex = 0;
4388 }
4389 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004390 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004391 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4392 // Force input into standby so that it tries to
4393 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004394 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004395 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004396 }
4397 mRsmpInIndex = mFrameCount;
4398 framesOut = 0;
4399 buffer.frameCount = 0;
4400 }
4401 }
4402 }
4403 } else {
4404 // resampling
4405
4406 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4407 // alter output frame count as if we were expecting stereo samples
4408 if (mChannelCount == 1 && mReqChannelCount == 1) {
4409 framesOut >>= 1;
4410 }
4411 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4412 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4413 // are 32 bit aligned which should be always true.
4414 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004415 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004416 // the resampler always outputs stereo samples: do post stereo to mono conversion
4417 int16_t *src = (int16_t *)mRsmpOutBuffer;
4418 int16_t *dst = buffer.i16;
4419 while (framesOut--) {
4420 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4421 src += 2;
4422 }
4423 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004424 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425 }
4426
4427 }
4428 mActiveTrack->releaseBuffer(&buffer);
4429 mActiveTrack->overflow();
4430 }
4431 // client isn't retrieving buffers fast enough
4432 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004433 if (!mActiveTrack->setOverflow()) {
4434 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004435 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004436 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004437 lastWarning = now;
4438 }
4439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004440 // Release the processor for a while before asking for a new buffer.
4441 // This will give the application more chance to read from the buffer and
4442 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004443 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444 }
4445 }
Eric Laurentec437d82011-07-26 20:54:46 -07004446 // enable changes in effect chain
4447 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004448 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 }
4450
4451 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004452 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453 }
4454 mActiveTrack.clear();
4455
4456 mStartStopCond.broadcast();
4457
Eric Laurentfeb0db62011-07-22 09:04:31 -07004458 releaseWakeLock();
4459
Steve Block3856b092011-10-20 11:56:00 +01004460 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004461 return false;
4462}
4463
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004464
4465sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4466 const sp<AudioFlinger::Client>& client,
4467 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004468 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004469 int channelMask,
4470 int frameCount,
4471 uint32_t flags,
4472 int sessionId,
4473 status_t *status)
4474{
4475 sp<RecordTrack> track;
4476 status_t lStatus;
4477
4478 lStatus = initCheck();
4479 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004480 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004481 goto Exit;
4482 }
4483
4484 { // scope for mLock
4485 Mutex::Autolock _l(mLock);
4486
4487 track = new RecordTrack(this, client, sampleRate,
4488 format, channelMask, frameCount, flags, sessionId);
4489
Glenn Kasten7378ca52012-01-20 13:44:40 -08004490 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004491 lStatus = NO_MEMORY;
4492 goto Exit;
4493 }
4494
4495 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004496 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4497 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004498 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004499 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4500 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004501 }
4502 lStatus = NO_ERROR;
4503
4504Exit:
4505 if (status) {
4506 *status = lStatus;
4507 }
4508 return track;
4509}
4510
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4512{
Steve Block3856b092011-10-20 11:56:00 +01004513 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 sp <ThreadBase> strongMe = this;
4515 status_t status = NO_ERROR;
4516 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004517 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004518 if (mActiveTrack != 0) {
4519 if (recordTrack != mActiveTrack.get()) {
4520 status = -EBUSY;
4521 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4522 mActiveTrack->mState = TrackBase::ACTIVE;
4523 }
4524 return status;
4525 }
4526
4527 recordTrack->mState = TrackBase::IDLE;
4528 mActiveTrack = recordTrack;
4529 mLock.unlock();
4530 status_t status = AudioSystem::startInput(mId);
4531 mLock.lock();
4532 if (status != NO_ERROR) {
4533 mActiveTrack.clear();
4534 return status;
4535 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004536 mRsmpInIndex = mFrameCount;
4537 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004538 if (mResampler != NULL) {
4539 mResampler->reset();
4540 }
4541 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004543 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004544 mWaitWorkCV.signal();
4545 // do not wait for mStartStopCond if exiting
4546 if (mExiting) {
4547 mActiveTrack.clear();
4548 status = INVALID_OPERATION;
4549 goto startError;
4550 }
4551 mStartStopCond.wait(mLock);
4552 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004553 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004554 status = BAD_VALUE;
4555 goto startError;
4556 }
Steve Block3856b092011-10-20 11:56:00 +01004557 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558 return status;
4559 }
4560startError:
4561 AudioSystem::stopInput(mId);
4562 return status;
4563}
4564
4565void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004566 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567 sp <ThreadBase> strongMe = this;
4568 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004569 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4571 mActiveTrack->mState = TrackBase::PAUSING;
4572 // do not wait for mStartStopCond if exiting
4573 if (mExiting) {
4574 return;
4575 }
4576 mStartStopCond.wait(mLock);
4577 // if we have been restarted, recordTrack == mActiveTrack.get() here
4578 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4579 mLock.unlock();
4580 AudioSystem::stopInput(mId);
4581 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004582 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004583 }
4584 }
4585 }
4586}
4587
4588status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4589{
4590 const size_t SIZE = 256;
4591 char buffer[SIZE];
4592 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004593
4594 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4595 result.append(buffer);
4596
4597 if (mActiveTrack != 0) {
4598 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004599 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004600 mActiveTrack->dump(buffer, SIZE);
4601 result.append(buffer);
4602
4603 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4604 result.append(buffer);
4605 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4606 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004607 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 result.append(buffer);
4609 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4610 result.append(buffer);
4611 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4612 result.append(buffer);
4613
4614
4615 } else {
4616 result.append("No record client\n");
4617 }
4618 write(fd, result.string(), result.size());
4619
4620 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004621 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622
4623 return NO_ERROR;
4624}
4625
4626status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4627{
4628 size_t framesReq = buffer->frameCount;
4629 size_t framesReady = mFrameCount - mRsmpInIndex;
4630 int channelCount;
4631
4632 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004633 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004634 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004635 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004636 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4637 // Force input into standby so that it tries to
4638 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004639 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004640 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004641 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004642 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004643 buffer->frameCount = 0;
4644 return NOT_ENOUGH_DATA;
4645 }
4646 mRsmpInIndex = 0;
4647 framesReady = mFrameCount;
4648 }
4649
4650 if (framesReq > framesReady) {
4651 framesReq = framesReady;
4652 }
4653
4654 if (mChannelCount == 1 && mReqChannelCount == 2) {
4655 channelCount = 1;
4656 } else {
4657 channelCount = 2;
4658 }
4659 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4660 buffer->frameCount = framesReq;
4661 return NO_ERROR;
4662}
4663
4664void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4665{
4666 mRsmpInIndex += buffer->frameCount;
4667 buffer->frameCount = 0;
4668}
4669
4670bool AudioFlinger::RecordThread::checkForNewParameters_l()
4671{
4672 bool reconfig = false;
4673
4674 while (!mNewParameters.isEmpty()) {
4675 status_t status = NO_ERROR;
4676 String8 keyValuePair = mNewParameters[0];
4677 AudioParameter param = AudioParameter(keyValuePair);
4678 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004679 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004680 int reqSamplingRate = mReqSampleRate;
4681 int reqChannelCount = mReqChannelCount;
4682
4683 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4684 reqSamplingRate = value;
4685 reconfig = true;
4686 }
4687 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004688 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689 reconfig = true;
4690 }
4691 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004692 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004693 reconfig = true;
4694 }
4695 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4696 // do not accept frame count changes if tracks are open as the track buffer
4697 // size depends on frame count and correct behavior would not be garantied
4698 // if frame count is changed after track creation
4699 if (mActiveTrack != 0) {
4700 status = INVALID_OPERATION;
4701 } else {
4702 reconfig = true;
4703 }
4704 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004705 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4706 // forward device change to effects that have requested to be
4707 // aware of attached audio device.
4708 for (size_t i = 0; i < mEffectChains.size(); i++) {
4709 mEffectChains[i]->setDevice_l(value);
4710 }
4711 // store input device and output device but do not forward output device to audio HAL.
4712 // Note that status is ignored by the caller for output device
4713 // (see AudioFlinger::setParameters()
4714 if (value & AUDIO_DEVICE_OUT_ALL) {
4715 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4716 status = BAD_VALUE;
4717 } else {
4718 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004719 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4720 if (mTrack != NULL) {
4721 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004722 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004723 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4724 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4725 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004726 }
4727 mDevice |= (uint32_t)value;
4728 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004729 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004730 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004731 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004732 mInput->stream->common.standby(&mInput->stream->common);
4733 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004734 }
4735 if (reconfig) {
4736 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004737 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004738 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004739 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4740 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004741 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004742 status = NO_ERROR;
4743 }
4744 if (status == NO_ERROR) {
4745 readInputParameters();
4746 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4747 }
4748 }
4749 }
4750
4751 mNewParameters.removeAt(0);
4752
4753 mParamStatus = status;
4754 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004755 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4756 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004757 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004758 }
4759 return reconfig;
4760}
4761
4762String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4763{
Dima Zavinfce7a472011-04-19 22:30:36 -07004764 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004765 String8 out_s8 = String8();
4766
4767 Mutex::Autolock _l(mLock);
4768 if (initCheck() != NO_ERROR) {
4769 return out_s8;
4770 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004771
Dima Zavin799a70e2011-04-18 16:57:27 -07004772 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004773 out_s8 = String8(s);
4774 free(s);
4775 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004776}
4777
4778void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4779 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08004780 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004781
4782 switch (event) {
4783 case AudioSystem::INPUT_OPENED:
4784 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004785 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004786 desc.samplingRate = mSampleRate;
4787 desc.format = mFormat;
4788 desc.frameCount = mFrameCount;
4789 desc.latency = 0;
4790 param2 = &desc;
4791 break;
4792
4793 case AudioSystem::INPUT_CLOSED:
4794 default:
4795 break;
4796 }
4797 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4798}
4799
4800void AudioFlinger::RecordThread::readInputParameters()
4801{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004802 delete mRsmpInBuffer;
4803 // mRsmpInBuffer is always assigned a new[] below
4804 delete mRsmpOutBuffer;
4805 mRsmpOutBuffer = NULL;
4806 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004807 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004808
Dima Zavin799a70e2011-04-18 16:57:27 -07004809 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004810 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4811 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004812 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004813 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004814 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004815 mFrameCount = mInputBytes / mFrameSize;
4816 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4817
4818 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4819 {
4820 int channelCount;
4821 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4822 // stereo to mono post process as the resampler always outputs stereo.
4823 if (mChannelCount == 1 && mReqChannelCount == 2) {
4824 channelCount = 1;
4825 } else {
4826 channelCount = 2;
4827 }
4828 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4829 mResampler->setSampleRate(mSampleRate);
4830 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4831 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4832
4833 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4834 if (mChannelCount == 1 && mReqChannelCount == 1) {
4835 mFrameCount >>= 1;
4836 }
4837
4838 }
4839 mRsmpInIndex = mFrameCount;
4840}
4841
4842unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4843{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004844 Mutex::Autolock _l(mLock);
4845 if (initCheck() != NO_ERROR) {
4846 return 0;
4847 }
4848
Dima Zavin799a70e2011-04-18 16:57:27 -07004849 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004850}
4851
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004852uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4853{
4854 Mutex::Autolock _l(mLock);
4855 uint32_t result = 0;
4856 if (getEffectChain_l(sessionId) != 0) {
4857 result = EFFECT_SESSION;
4858 }
4859
4860 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4861 result |= TRACK_SESSION;
4862 }
4863
4864 return result;
4865}
4866
Eric Laurent59bd0da2011-08-01 09:52:20 -07004867AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4868{
4869 Mutex::Autolock _l(mLock);
4870 return mTrack;
4871}
4872
Glenn Kastenaed850d2012-01-26 09:46:34 -08004873AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004874{
4875 Mutex::Autolock _l(mLock);
4876 return mInput;
4877}
4878
4879AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4880{
4881 Mutex::Autolock _l(mLock);
4882 AudioStreamIn *input = mInput;
4883 mInput = NULL;
4884 return input;
4885}
4886
4887// this method must always be called either with ThreadBase mLock held or inside the thread loop
4888audio_stream_t* AudioFlinger::RecordThread::stream()
4889{
4890 if (mInput == NULL) {
4891 return NULL;
4892 }
4893 return &mInput->stream->common;
4894}
4895
4896
Mathias Agopian65ab4712010-07-14 17:59:35 -07004897// ----------------------------------------------------------------------------
4898
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004899audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004900 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004901 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004902 uint32_t *pChannels,
4903 uint32_t *pLatencyMs,
4904 uint32_t flags)
4905{
4906 status_t status;
4907 PlaybackThread *thread = NULL;
4908 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4909 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004910 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004911 uint32_t channels = pChannels ? *pChannels : 0;
4912 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004913 audio_stream_out_t *outStream;
4914 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004915
Steve Block3856b092011-10-20 11:56:00 +01004916 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917 pDevices ? *pDevices : 0,
4918 samplingRate,
4919 format,
4920 channels,
4921 flags);
4922
4923 if (pDevices == NULL || *pDevices == 0) {
4924 return 0;
4925 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004926
Mathias Agopian65ab4712010-07-14 17:59:35 -07004927 Mutex::Autolock _l(mLock);
4928
Dima Zavin799a70e2011-04-18 16:57:27 -07004929 outHwDev = findSuitableHwDev_l(*pDevices);
4930 if (outHwDev == NULL)
4931 return 0;
4932
Glenn Kasten58f30212012-01-12 12:27:51 -08004933 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004934 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004935 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004936 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004937 samplingRate,
4938 format,
4939 channels,
4940 status);
4941
4942 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004943 if (outStream != NULL) {
4944 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004945 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004946
Dima Zavinfce7a472011-04-19 22:30:36 -07004947 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4948 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4949 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004950 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004951 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004952 } else {
4953 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004954 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004955 }
4956 mPlaybackThreads.add(id, thread);
4957
Glenn Kastena0d68332012-01-27 16:47:15 -08004958 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4959 if (pFormat != NULL) *pFormat = format;
4960 if (pChannels != NULL) *pChannels = channels;
4961 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004962
4963 // notify client processes of the new output creation
4964 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4965 return id;
4966 }
4967
4968 return 0;
4969}
4970
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004971audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
4972 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004973{
4974 Mutex::Autolock _l(mLock);
4975 MixerThread *thread1 = checkMixerThread_l(output1);
4976 MixerThread *thread2 = checkMixerThread_l(output2);
4977
4978 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004979 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 return 0;
4981 }
4982
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004983 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004984 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4985 thread->addOutputTrack(thread2);
4986 mPlaybackThreads.add(id, thread);
4987 // notify client processes of the new output creation
4988 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4989 return id;
4990}
4991
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004992status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993{
4994 // keep strong reference on the playback thread so that
4995 // it is not destroyed while exit() is executed
4996 sp <PlaybackThread> thread;
4997 {
4998 Mutex::Autolock _l(mLock);
4999 thread = checkPlaybackThread_l(output);
5000 if (thread == NULL) {
5001 return BAD_VALUE;
5002 }
5003
Steve Block3856b092011-10-20 11:56:00 +01005004 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005005
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005006 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005007 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005008 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005009 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5010 dupThread->removeOutputTrack((MixerThread *)thread.get());
5011 }
5012 }
5013 }
Glenn Kastena0d68332012-01-27 16:47:15 -08005014 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005015 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5016 mPlaybackThreads.removeItem(output);
5017 }
5018 thread->exit();
5019
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005020 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005021 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005022 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005023 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005024 out->hwDev->close_output_stream(out->hwDev, out->stream);
5025 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005026 }
5027 return NO_ERROR;
5028}
5029
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005030status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005031{
5032 Mutex::Autolock _l(mLock);
5033 PlaybackThread *thread = checkPlaybackThread_l(output);
5034
5035 if (thread == NULL) {
5036 return BAD_VALUE;
5037 }
5038
Steve Block3856b092011-10-20 11:56:00 +01005039 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005040 thread->suspend();
5041
5042 return NO_ERROR;
5043}
5044
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005045status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005046{
5047 Mutex::Autolock _l(mLock);
5048 PlaybackThread *thread = checkPlaybackThread_l(output);
5049
5050 if (thread == NULL) {
5051 return BAD_VALUE;
5052 }
5053
Steve Block3856b092011-10-20 11:56:00 +01005054 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005055
5056 thread->restore();
5057
5058 return NO_ERROR;
5059}
5060
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005061audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005063 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005064 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005065 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005066{
5067 status_t status;
5068 RecordThread *thread = NULL;
5069 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005070 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005071 uint32_t channels = pChannels ? *pChannels : 0;
5072 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005073 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005074 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005075 audio_stream_in_t *inStream;
5076 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005077
5078 if (pDevices == NULL || *pDevices == 0) {
5079 return 0;
5080 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005081
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082 Mutex::Autolock _l(mLock);
5083
Dima Zavin799a70e2011-04-18 16:57:27 -07005084 inHwDev = findSuitableHwDev_l(*pDevices);
5085 if (inHwDev == NULL)
5086 return 0;
5087
Glenn Kasten58f30212012-01-12 12:27:51 -08005088 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005089 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005090 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005091 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005092 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005093 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005094 samplingRate,
5095 format,
5096 channels,
5097 acoustics,
5098 status);
5099
5100 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5101 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5102 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005103 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005104 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005105 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005106 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005107 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005108 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005109 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005110 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005111 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005112 }
5113
Dima Zavin799a70e2011-04-18 16:57:27 -07005114 if (inStream != NULL) {
5115 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5116
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005117 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005118 // Start record thread
5119 // RecorThread require both input and output device indication to forward to audio
5120 // pre processing modules
5121 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5122 thread = new RecordThread(this,
5123 input,
5124 reqSamplingRate,
5125 reqChannels,
5126 id,
5127 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005128 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005129 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005130 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5131 if (pFormat != NULL) *pFormat = format;
5132 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005133
Dima Zavin799a70e2011-04-18 16:57:27 -07005134 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005135
5136 // notify client processes of the new input creation
5137 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5138 return id;
5139 }
5140
5141 return 0;
5142}
5143
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005144status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005145{
5146 // keep strong reference on the record thread so that
5147 // it is not destroyed while exit() is executed
5148 sp <RecordThread> thread;
5149 {
5150 Mutex::Autolock _l(mLock);
5151 thread = checkRecordThread_l(input);
5152 if (thread == NULL) {
5153 return BAD_VALUE;
5154 }
5155
Steve Block3856b092011-10-20 11:56:00 +01005156 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005157 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005158 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5159 mRecordThreads.removeItem(input);
5160 }
5161 thread->exit();
5162
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005163 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005164 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005165 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005166 in->hwDev->close_input_stream(in->hwDev, in->stream);
5167 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005168
5169 return NO_ERROR;
5170}
5171
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005172status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005173{
5174 Mutex::Autolock _l(mLock);
5175 MixerThread *dstThread = checkMixerThread_l(output);
5176 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005177 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178 return BAD_VALUE;
5179 }
5180
Steve Block3856b092011-10-20 11:56:00 +01005181 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005182 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5183
Eric Laurent9f6530f2011-08-30 10:18:54 -07005184 dstThread->setStreamValid(stream, true);
5185
Mathias Agopian65ab4712010-07-14 17:59:35 -07005186 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5187 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5188 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005189 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005190 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005191 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005192 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005193 }
Eric Laurentde070132010-07-13 04:45:46 -07005194 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005195
5196 return NO_ERROR;
5197}
5198
5199
5200int AudioFlinger::newAudioSessionId()
5201{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005202 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005203}
5204
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005205void AudioFlinger::acquireAudioSessionId(int audioSession)
5206{
5207 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005208 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005209 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005210 int num = mAudioSessionRefs.size();
5211 for (int i = 0; i< num; i++) {
5212 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5213 if (ref->sessionid == audioSession && ref->pid == caller) {
5214 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005215 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005216 return;
5217 }
5218 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005219 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5220 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005221}
5222
5223void AudioFlinger::releaseAudioSessionId(int audioSession)
5224{
5225 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005226 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005227 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005228 int num = mAudioSessionRefs.size();
5229 for (int i = 0; i< num; i++) {
5230 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5231 if (ref->sessionid == audioSession && ref->pid == caller) {
5232 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005233 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005234 if (ref->cnt == 0) {
5235 mAudioSessionRefs.removeAt(i);
5236 delete ref;
5237 purgeStaleEffects_l();
5238 }
5239 return;
5240 }
5241 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005242 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005243}
5244
5245void AudioFlinger::purgeStaleEffects_l() {
5246
Steve Block3856b092011-10-20 11:56:00 +01005247 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005248
5249 Vector< sp<EffectChain> > chains;
5250
5251 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5252 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5253 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5254 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005255 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5256 chains.push(ec);
5257 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005258 }
5259 }
5260 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5261 sp<RecordThread> t = mRecordThreads.valueAt(i);
5262 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5263 sp<EffectChain> ec = t->mEffectChains[j];
5264 chains.push(ec);
5265 }
5266 }
5267
5268 for (size_t i = 0; i < chains.size(); i++) {
5269 sp<EffectChain> ec = chains[i];
5270 int sessionid = ec->sessionId();
5271 sp<ThreadBase> t = ec->mThread.promote();
5272 if (t == 0) {
5273 continue;
5274 }
5275 size_t numsessionrefs = mAudioSessionRefs.size();
5276 bool found = false;
5277 for (size_t k = 0; k < numsessionrefs; k++) {
5278 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5279 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005280 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005281 sessionid, ref->pid, ref->cnt);
5282 found = true;
5283 break;
5284 }
5285 }
5286 if (!found) {
5287 // remove all effects from the chain
5288 while (ec->mEffects.size()) {
5289 sp<EffectModule> effect = ec->mEffects[0];
5290 effect->unPin();
5291 Mutex::Autolock _l (t->mLock);
5292 t->removeEffect_l(effect);
5293 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5294 sp<EffectHandle> handle = effect->mHandles[j].promote();
5295 if (handle != 0) {
5296 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005297 if (handle->mHasControl && handle->mEnabled) {
5298 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5299 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005300 }
5301 }
5302 AudioSystem::unregisterEffect(effect->id());
5303 }
5304 }
5305 }
5306 return;
5307}
5308
Mathias Agopian65ab4712010-07-14 17:59:35 -07005309// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005310AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005311{
5312 PlaybackThread *thread = NULL;
5313 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5314 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5315 }
5316 return thread;
5317}
5318
5319// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005320AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321{
5322 PlaybackThread *thread = checkPlaybackThread_l(output);
5323 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005324 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325 thread = NULL;
5326 }
5327 }
5328 return (MixerThread *)thread;
5329}
5330
5331// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005332AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005333{
5334 RecordThread *thread = NULL;
5335 if (mRecordThreads.indexOfKey(input) >= 0) {
5336 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5337 }
5338 return thread;
5339}
5340
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005341uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005343 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005344}
5345
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005346AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5347{
5348 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5349 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005350 AudioStreamOut *output = thread->getOutput();
5351 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005352 return thread;
5353 }
5354 }
5355 return NULL;
5356}
5357
5358uint32_t AudioFlinger::primaryOutputDevice_l()
5359{
5360 PlaybackThread *thread = primaryPlaybackThread_l();
5361
5362 if (thread == NULL) {
5363 return 0;
5364 }
5365
5366 return thread->device();
5367}
5368
5369
Mathias Agopian65ab4712010-07-14 17:59:35 -07005370// ----------------------------------------------------------------------------
5371// Effect management
5372// ----------------------------------------------------------------------------
5373
5374
Glenn Kastenf587ba52012-01-26 16:25:10 -08005375status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005376{
5377 Mutex::Autolock _l(mLock);
5378 return EffectQueryNumberEffects(numEffects);
5379}
5380
Glenn Kastenf587ba52012-01-26 16:25:10 -08005381status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005382{
5383 Mutex::Autolock _l(mLock);
5384 return EffectQueryEffect(index, descriptor);
5385}
5386
Glenn Kasten5e92a782012-01-30 07:40:52 -08005387status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005388 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389{
5390 Mutex::Autolock _l(mLock);
5391 return EffectGetDescriptor(pUuid, descriptor);
5392}
5393
5394
Mathias Agopian65ab4712010-07-14 17:59:35 -07005395sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5396 effect_descriptor_t *pDesc,
5397 const sp<IEffectClient>& effectClient,
5398 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005399 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005400 int sessionId,
5401 status_t *status,
5402 int *id,
5403 int *enabled)
5404{
5405 status_t lStatus = NO_ERROR;
5406 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005407 effect_descriptor_t desc;
5408 sp<Client> client;
5409 wp<Client> wclient;
5410
Steve Block3856b092011-10-20 11:56:00 +01005411 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005412 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413
5414 if (pDesc == NULL) {
5415 lStatus = BAD_VALUE;
5416 goto Exit;
5417 }
5418
Eric Laurent84e9a102010-09-23 16:10:16 -07005419 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005420 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005421 lStatus = PERMISSION_DENIED;
5422 goto Exit;
5423 }
5424
Dima Zavinfce7a472011-04-19 22:30:36 -07005425 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005426 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005427 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005428 lStatus = PERMISSION_DENIED;
5429 goto Exit;
5430 }
5431
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005432 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005433 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005434 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005435 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005436 lStatus = BAD_VALUE;
5437 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005438 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005439 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005440 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005441 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005442 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005443 }
5444 }
5445
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 {
5447 Mutex::Autolock _l(mLock);
5448
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449
5450 if (!EffectIsNullUuid(&pDesc->uuid)) {
5451 // if uuid is specified, request effect descriptor
5452 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5453 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005454 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455 goto Exit;
5456 }
5457 } else {
5458 // if uuid is not specified, look for an available implementation
5459 // of the required type in effect factory
5460 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005461 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005462 lStatus = BAD_VALUE;
5463 goto Exit;
5464 }
5465 uint32_t numEffects = 0;
5466 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005467 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468 bool found = false;
5469
5470 lStatus = EffectQueryNumberEffects(&numEffects);
5471 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005472 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473 goto Exit;
5474 }
5475 for (uint32_t i = 0; i < numEffects; i++) {
5476 lStatus = EffectQueryEffect(i, &desc);
5477 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005478 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005479 continue;
5480 }
5481 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5482 // If matching type found save effect descriptor. If the session is
5483 // 0 and the effect is not auxiliary, continue enumeration in case
5484 // an auxiliary version of this effect type is available
5485 found = true;
5486 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005487 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005488 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5489 break;
5490 }
5491 }
5492 }
5493 if (!found) {
5494 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005495 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005496 goto Exit;
5497 }
5498 // For same effect type, chose auxiliary version over insert version if
5499 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005500 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5502 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5503 }
5504 }
5505
5506 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005507 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005508 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5509 lStatus = INVALID_OPERATION;
5510 goto Exit;
5511 }
5512
Eric Laurent59255e42011-07-27 19:49:51 -07005513 // check recording permission for visualizer
5514 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5515 !recordingAllowed()) {
5516 lStatus = PERMISSION_DENIED;
5517 goto Exit;
5518 }
5519
Mathias Agopian65ab4712010-07-14 17:59:35 -07005520 // return effect descriptor
5521 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5522
5523 // If output is not specified try to find a matching audio session ID in one of the
5524 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005525 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5526 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005527 // Note: io is never 0 when creating an effect on an input
5528 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005529 // look for the thread where the specified audio session is present
5530 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5531 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005532 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005533 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005534 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005535 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005536 if (io == 0) {
5537 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5538 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5539 io = mRecordThreads.keyAt(i);
5540 break;
5541 }
5542 }
5543 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005544 // If no output thread contains the requested session ID, default to
5545 // first output. The effect chain will be moved to the correct output
5546 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005547 if (io == 0 && mPlaybackThreads.size()) {
5548 io = mPlaybackThreads.keyAt(0);
5549 }
Steve Block3856b092011-10-20 11:56:00 +01005550 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005551 }
5552 ThreadBase *thread = checkRecordThread_l(io);
5553 if (thread == NULL) {
5554 thread = checkPlaybackThread_l(io);
5555 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005556 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005557 lStatus = BAD_VALUE;
5558 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005559 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005560 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005561
Mathias Agopian65ab4712010-07-14 17:59:35 -07005562 wclient = mClients.valueFor(pid);
5563
5564 if (wclient != NULL) {
5565 client = wclient.promote();
5566 } else {
5567 client = new Client(this, pid);
5568 mClients.add(pid, client);
5569 }
5570
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005571 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005572 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5573 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005574 if (handle != 0 && id != NULL) {
5575 *id = handle->id();
5576 }
5577 }
5578
5579Exit:
5580 if(status) {
5581 *status = lStatus;
5582 }
5583 return handle;
5584}
5585
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005586status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
5587 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005588{
Steve Block3856b092011-10-20 11:56:00 +01005589 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005590 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005591 Mutex::Autolock _l(mLock);
5592 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005593 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005594 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 }
Eric Laurentde070132010-07-13 04:45:46 -07005596 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5597 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005598 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005599 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005600 }
Eric Laurentde070132010-07-13 04:45:46 -07005601 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5602 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005603 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005604 return BAD_VALUE;
5605 }
5606
5607 Mutex::Autolock _dl(dstThread->mLock);
5608 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005609 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005610
Mathias Agopian65ab4712010-07-14 17:59:35 -07005611 return NO_ERROR;
5612}
5613
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005614// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005615status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005616 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005617 AudioFlinger::PlaybackThread *dstThread,
5618 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005619{
Steve Block3856b092011-10-20 11:56:00 +01005620 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005621 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005622
Eric Laurent59255e42011-07-27 19:49:51 -07005623 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005624 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005625 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005626 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005627 return INVALID_OPERATION;
5628 }
5629
Eric Laurent39e94f82010-07-28 01:32:47 -07005630 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005631 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005632 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005633 // removed.
5634 srcThread->removeEffectChain_l(chain);
5635
5636 // transfer all effects one by one so that new effect chain is created on new thread with
5637 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005638 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07005639 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005640 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005641 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5642 while (effect != 0) {
5643 srcThread->removeEffect_l(effect);
5644 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005645 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5646 if (effect->state() == EffectModule::ACTIVE ||
5647 effect->state() == EffectModule::STOPPING) {
5648 effect->start();
5649 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005650 // if the move request is not received from audio policy manager, the effect must be
5651 // re-registered with the new strategy and output
5652 if (dstChain == 0) {
5653 dstChain = effect->chain().promote();
5654 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005655 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005656 srcThread->addEffect_l(effect);
5657 return NO_INIT;
5658 }
5659 strategy = dstChain->strategy();
5660 }
5661 if (reRegister) {
5662 AudioSystem::unregisterEffect(effect->id());
5663 AudioSystem::registerEffect(&effect->desc(),
5664 dstOutput,
5665 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005666 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005667 effect->id());
5668 }
Eric Laurentde070132010-07-13 04:45:46 -07005669 effect = chain->getEffectFromId_l(0);
5670 }
5671
5672 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005673}
5674
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005675
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005677sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 const sp<AudioFlinger::Client>& client,
5679 const sp<IEffectClient>& effectClient,
5680 int32_t priority,
5681 int sessionId,
5682 effect_descriptor_t *desc,
5683 int *enabled,
5684 status_t *status
5685 )
5686{
5687 sp<EffectModule> effect;
5688 sp<EffectHandle> handle;
5689 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005691 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692 bool effectCreated = false;
5693 bool effectRegistered = false;
5694
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005695 lStatus = initCheck();
5696 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005697 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698 goto Exit;
5699 }
5700
5701 // Do not allow effects with session ID 0 on direct output or duplicating threads
5702 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005703 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005704 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005705 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005706 lStatus = BAD_VALUE;
5707 goto Exit;
5708 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005709 // Only Pre processor effects are allowed on input threads and only on input threads
5710 if ((mType == RECORD &&
5711 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5712 (mType != RECORD &&
5713 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005714 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005715 desc->name, desc->flags, mType);
5716 lStatus = BAD_VALUE;
5717 goto Exit;
5718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005719
Steve Block3856b092011-10-20 11:56:00 +01005720 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721
5722 { // scope for mLock
5723 Mutex::Autolock _l(mLock);
5724
5725 // check for existing effect chain with the requested audio session
5726 chain = getEffectChain_l(sessionId);
5727 if (chain == 0) {
5728 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005729 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005730 chain = new EffectChain(this, sessionId);
5731 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005732 chain->setStrategy(getStrategyForSession_l(sessionId));
5733 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005735 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005736 }
5737
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005738 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739
5740 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005741 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005743 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005744 if (lStatus != NO_ERROR) {
5745 goto Exit;
5746 }
5747 effectRegistered = true;
5748 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005749 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 lStatus = effect->status();
5751 if (lStatus != NO_ERROR) {
5752 goto Exit;
5753 }
Eric Laurentcab11242010-07-15 12:50:15 -07005754 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005755 if (lStatus != NO_ERROR) {
5756 goto Exit;
5757 }
5758 effectCreated = true;
5759
5760 effect->setDevice(mDevice);
5761 effect->setMode(mAudioFlinger->getMode());
5762 }
5763 // create effect handle and connect it to effect module
5764 handle = new EffectHandle(effect, client, effectClient, priority);
5765 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08005766 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005767 *enabled = (int)effect->isEnabled();
5768 }
5769 }
5770
5771Exit:
5772 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005773 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005775 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005776 }
5777 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005778 AudioSystem::unregisterEffect(effect->id());
5779 }
5780 if (chainCreated) {
5781 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005782 }
5783 handle.clear();
5784 }
5785
5786 if(status) {
5787 *status = lStatus;
5788 }
5789 return handle;
5790}
5791
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005792sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5793{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005794 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08005795 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005796}
5797
Eric Laurentde070132010-07-13 04:45:46 -07005798// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5799// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005800status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005801{
5802 // check for existing effect chain with the requested audio session
5803 int sessionId = effect->sessionId();
5804 sp<EffectChain> chain = getEffectChain_l(sessionId);
5805 bool chainCreated = false;
5806
5807 if (chain == 0) {
5808 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005809 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005810 chain = new EffectChain(this, sessionId);
5811 addEffectChain_l(chain);
5812 chain->setStrategy(getStrategyForSession_l(sessionId));
5813 chainCreated = true;
5814 }
Steve Block3856b092011-10-20 11:56:00 +01005815 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005816
5817 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005818 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005819 this, effect->desc().name, chain.get());
5820 return BAD_VALUE;
5821 }
5822
5823 status_t status = chain->addEffect_l(effect);
5824 if (status != NO_ERROR) {
5825 if (chainCreated) {
5826 removeEffectChain_l(chain);
5827 }
5828 return status;
5829 }
5830
5831 effect->setDevice(mDevice);
5832 effect->setMode(mAudioFlinger->getMode());
5833 return NO_ERROR;
5834}
5835
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005836void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005837
Steve Block3856b092011-10-20 11:56:00 +01005838 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005840 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5841 detachAuxEffect_l(effect->id());
5842 }
5843
5844 sp<EffectChain> chain = effect->chain().promote();
5845 if (chain != 0) {
5846 // remove effect chain if removing last effect
5847 if (chain->removeEffect_l(effect) == 0) {
5848 removeEffectChain_l(chain);
5849 }
5850 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005851 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005852 }
5853}
5854
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005855void AudioFlinger::ThreadBase::lockEffectChains_l(
5856 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5857{
5858 effectChains = mEffectChains;
5859 for (size_t i = 0; i < mEffectChains.size(); i++) {
5860 mEffectChains[i]->lock();
5861 }
5862}
5863
5864void AudioFlinger::ThreadBase::unlockEffectChains(
5865 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5866{
5867 for (size_t i = 0; i < effectChains.size(); i++) {
5868 effectChains[i]->unlock();
5869 }
5870}
5871
5872sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5873{
5874 Mutex::Autolock _l(mLock);
5875 return getEffectChain_l(sessionId);
5876}
5877
5878sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5879{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005880 size_t size = mEffectChains.size();
5881 for (size_t i = 0; i < size; i++) {
5882 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08005883 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005884 }
5885 }
Glenn Kasten090f0192012-01-30 13:00:02 -08005886 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005887}
5888
Glenn Kastenf78aee72012-01-04 11:00:47 -08005889void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005890{
5891 Mutex::Autolock _l(mLock);
5892 size_t size = mEffectChains.size();
5893 for (size_t i = 0; i < size; i++) {
5894 mEffectChains[i]->setMode_l(mode);
5895 }
5896}
5897
5898void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005899 const wp<EffectHandle>& handle,
5900 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005901
Mathias Agopian65ab4712010-07-14 17:59:35 -07005902 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005903 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904 // delete the effect module if removing last handle on it
5905 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005906 if (!effect->isPinned() || unpiniflast) {
5907 removeEffect_l(effect);
5908 AudioSystem::unregisterEffect(effect->id());
5909 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910 }
5911}
5912
5913status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5914{
5915 int session = chain->sessionId();
5916 int16_t *buffer = mMixBuffer;
5917 bool ownsBuffer = false;
5918
Steve Block3856b092011-10-20 11:56:00 +01005919 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920 if (session > 0) {
5921 // Only one effect chain can be present in direct output thread and it uses
5922 // the mix buffer as input
5923 if (mType != DIRECT) {
5924 size_t numSamples = mFrameCount * mChannelCount;
5925 buffer = new int16_t[numSamples];
5926 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005927 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 ownsBuffer = true;
5929 }
5930
5931 // Attach all tracks with same session ID to this chain.
5932 for (size_t i = 0; i < mTracks.size(); ++i) {
5933 sp<Track> track = mTracks[i];
5934 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005935 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005936 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005937 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938 }
5939 }
5940
5941 // indicate all active tracks in the chain
5942 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5943 sp<Track> track = mActiveTracks[i].promote();
5944 if (track == 0) continue;
5945 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005946 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005947 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 }
5949 }
5950 }
5951
5952 chain->setInBuffer(buffer, ownsBuffer);
5953 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005954 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005955 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005956 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5957 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005959 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5960 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005961 // Effect chain for other sessions are inserted at beginning of effect
5962 // chains list to be processed before output mix effects. Relative order between other
5963 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964 size_t size = mEffectChains.size();
5965 size_t i = 0;
5966 for (i = 0; i < size; i++) {
5967 if (mEffectChains[i]->sessionId() < session) break;
5968 }
5969 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005970 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971
5972 return NO_ERROR;
5973}
5974
5975size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5976{
5977 int session = chain->sessionId();
5978
Steve Block3856b092011-10-20 11:56:00 +01005979 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005980
5981 for (size_t i = 0; i < mEffectChains.size(); i++) {
5982 if (chain == mEffectChains[i]) {
5983 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005984 // detach all active tracks from the chain
5985 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5986 sp<Track> track = mActiveTracks[i].promote();
5987 if (track == 0) continue;
5988 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005989 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005990 chain.get(), session);
5991 chain->decActiveTrackCnt();
5992 }
5993 }
5994
Mathias Agopian65ab4712010-07-14 17:59:35 -07005995 // detach all tracks with same session ID from this chain
5996 for (size_t i = 0; i < mTracks.size(); ++i) {
5997 sp<Track> track = mTracks[i];
5998 if (session == track->sessionId()) {
5999 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006000 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001 }
6002 }
Eric Laurentde070132010-07-13 04:45:46 -07006003 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004 }
6005 }
6006 return mEffectChains.size();
6007}
6008
Eric Laurentde070132010-07-13 04:45:46 -07006009status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6010 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011{
6012 Mutex::Autolock _l(mLock);
6013 return attachAuxEffect_l(track, EffectId);
6014}
6015
Eric Laurentde070132010-07-13 04:45:46 -07006016status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6017 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006018{
6019 status_t status = NO_ERROR;
6020
6021 if (EffectId == 0) {
6022 track->setAuxBuffer(0, NULL);
6023 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006024 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6025 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006026 if (effect != 0) {
6027 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6028 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6029 } else {
6030 status = INVALID_OPERATION;
6031 }
6032 } else {
6033 status = BAD_VALUE;
6034 }
6035 }
6036 return status;
6037}
6038
6039void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6040{
6041 for (size_t i = 0; i < mTracks.size(); ++i) {
6042 sp<Track> track = mTracks[i];
6043 if (track->auxEffectId() == effectId) {
6044 attachAuxEffect_l(track, 0);
6045 }
6046 }
6047}
6048
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006049status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6050{
6051 // only one chain per input thread
6052 if (mEffectChains.size() != 0) {
6053 return INVALID_OPERATION;
6054 }
Steve Block3856b092011-10-20 11:56:00 +01006055 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006056
6057 chain->setInBuffer(NULL);
6058 chain->setOutBuffer(NULL);
6059
Eric Laurent59255e42011-07-27 19:49:51 -07006060 checkSuspendOnAddEffectChain_l(chain);
6061
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006062 mEffectChains.add(chain);
6063
6064 return NO_ERROR;
6065}
6066
6067size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6068{
Steve Block3856b092011-10-20 11:56:00 +01006069 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006070 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006071 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6072 chain.get(), mEffectChains.size(), this);
6073 if (mEffectChains.size() == 1) {
6074 mEffectChains.removeAt(0);
6075 }
6076 return 0;
6077}
6078
Mathias Agopian65ab4712010-07-14 17:59:35 -07006079// ----------------------------------------------------------------------------
6080// EffectModule implementation
6081// ----------------------------------------------------------------------------
6082
6083#undef LOG_TAG
6084#define LOG_TAG "AudioFlinger::EffectModule"
6085
6086AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6087 const wp<AudioFlinger::EffectChain>& chain,
6088 effect_descriptor_t *desc,
6089 int id,
6090 int sessionId)
6091 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006092 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093{
Steve Block3856b092011-10-20 11:56:00 +01006094 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095 int lStatus;
6096 sp<ThreadBase> thread = mThread.promote();
6097 if (thread == 0) {
6098 return;
6099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006100
6101 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6102
6103 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006104 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006105
6106 if (mStatus != NO_ERROR) {
6107 return;
6108 }
6109 lStatus = init();
6110 if (lStatus < 0) {
6111 mStatus = lStatus;
6112 goto Error;
6113 }
6114
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006115 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6116 mPinned = true;
6117 }
Steve Block3856b092011-10-20 11:56:00 +01006118 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119 return;
6120Error:
6121 EffectRelease(mEffectInterface);
6122 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006123 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124}
6125
6126AudioFlinger::EffectModule::~EffectModule()
6127{
Steve Block3856b092011-10-20 11:56:00 +01006128 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006130 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6131 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6132 sp<ThreadBase> thread = mThread.promote();
6133 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006134 audio_stream_t *stream = thread->stream();
6135 if (stream != NULL) {
6136 stream->remove_audio_effect(stream, mEffectInterface);
6137 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006138 }
6139 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006140 // release effect engine
6141 EffectRelease(mEffectInterface);
6142 }
6143}
6144
Glenn Kasten435dbe62012-01-30 10:15:48 -08006145status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146{
6147 status_t status;
6148
6149 Mutex::Autolock _l(mLock);
6150 // First handle in mHandles has highest priority and controls the effect module
6151 int priority = handle->priority();
6152 size_t size = mHandles.size();
6153 sp<EffectHandle> h;
6154 size_t i;
6155 for (i = 0; i < size; i++) {
6156 h = mHandles[i].promote();
6157 if (h == 0) continue;
6158 if (h->priority() <= priority) break;
6159 }
6160 // if inserted in first place, move effect control from previous owner to this handle
6161 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006162 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006163 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006164 enabled = h->enabled();
6165 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006166 }
Eric Laurent59255e42011-07-27 19:49:51 -07006167 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006168 status = NO_ERROR;
6169 } else {
6170 status = ALREADY_EXISTS;
6171 }
Steve Block3856b092011-10-20 11:56:00 +01006172 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006173 mHandles.insertAt(handle, i);
6174 return status;
6175}
6176
6177size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6178{
6179 Mutex::Autolock _l(mLock);
6180 size_t size = mHandles.size();
6181 size_t i;
6182 for (i = 0; i < size; i++) {
6183 if (mHandles[i] == handle) break;
6184 }
6185 if (i == size) {
6186 return size;
6187 }
Steve Block3856b092011-10-20 11:56:00 +01006188 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006189
6190 bool enabled = false;
6191 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006192 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006193 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006194 enabled = hdl->enabled();
6195 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006196 mHandles.removeAt(i);
6197 size = mHandles.size();
6198 // if removed from first place, move effect control from this handle to next in line
6199 if (i == 0 && size != 0) {
6200 sp<EffectHandle> h = mHandles[0].promote();
6201 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006202 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203 }
6204 }
6205
Eric Laurentec437d82011-07-26 20:54:46 -07006206 // Prevent calls to process() and other functions on effect interface from now on.
6207 // The effect engine will be released by the destructor when the last strong reference on
6208 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006209 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006210 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006211 }
6212
Mathias Agopian65ab4712010-07-14 17:59:35 -07006213 return size;
6214}
6215
Eric Laurent59255e42011-07-27 19:49:51 -07006216sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6217{
6218 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006219 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006220}
6221
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006222void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006223{
Steve Block3856b092011-10-20 11:56:00 +01006224 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006225 // keep a strong reference on this EffectModule to avoid calling the
6226 // destructor before we exit
6227 sp<EffectModule> keep(this);
6228 {
6229 sp<ThreadBase> thread = mThread.promote();
6230 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006231 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006232 }
6233 }
6234}
6235
6236void AudioFlinger::EffectModule::updateState() {
6237 Mutex::Autolock _l(mLock);
6238
6239 switch (mState) {
6240 case RESTART:
6241 reset_l();
6242 // FALL THROUGH
6243
6244 case STARTING:
6245 // clear auxiliary effect input buffer for next accumulation
6246 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6247 memset(mConfig.inputCfg.buffer.raw,
6248 0,
6249 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6250 }
6251 start_l();
6252 mState = ACTIVE;
6253 break;
6254 case STOPPING:
6255 stop_l();
6256 mDisableWaitCnt = mMaxDisableWaitCnt;
6257 mState = STOPPED;
6258 break;
6259 case STOPPED:
6260 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6261 // turn off sequence.
6262 if (--mDisableWaitCnt == 0) {
6263 reset_l();
6264 mState = IDLE;
6265 }
6266 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006267 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006268 break;
6269 }
6270}
6271
6272void AudioFlinger::EffectModule::process()
6273{
6274 Mutex::Autolock _l(mLock);
6275
Eric Laurentec437d82011-07-26 20:54:46 -07006276 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 mConfig.inputCfg.buffer.raw == NULL ||
6278 mConfig.outputCfg.buffer.raw == NULL) {
6279 return;
6280 }
6281
Eric Laurent8f45bd72010-08-31 13:50:07 -07006282 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006283 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6284 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006285 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006286 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006287 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006288 }
6289
6290 // do the actual processing in the effect engine
6291 int ret = (*mEffectInterface)->process(mEffectInterface,
6292 &mConfig.inputCfg.buffer,
6293 &mConfig.outputCfg.buffer);
6294
6295 // force transition to IDLE state when engine is ready
6296 if (mState == STOPPED && ret == -ENODATA) {
6297 mDisableWaitCnt = 1;
6298 }
6299
6300 // clear auxiliary effect input buffer for next accumulation
6301 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006302 memset(mConfig.inputCfg.buffer.raw, 0,
6303 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 }
6305 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006306 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6307 // If an insert effect is idle and input buffer is different from output buffer,
6308 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006309 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006310 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006311 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6312 int16_t *in = mConfig.inputCfg.buffer.s16;
6313 int16_t *out = mConfig.outputCfg.buffer.s16;
6314 for (size_t i = 0; i < frameCnt; i++) {
6315 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006316 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006317 }
6318 }
6319}
6320
6321void AudioFlinger::EffectModule::reset_l()
6322{
6323 if (mEffectInterface == NULL) {
6324 return;
6325 }
6326 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6327}
6328
6329status_t AudioFlinger::EffectModule::configure()
6330{
6331 uint32_t channels;
6332 if (mEffectInterface == NULL) {
6333 return NO_INIT;
6334 }
6335
6336 sp<ThreadBase> thread = mThread.promote();
6337 if (thread == 0) {
6338 return DEAD_OBJECT;
6339 }
6340
6341 // TODO: handle configuration of effects replacing track process
6342 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006343 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006344 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006345 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006346 }
6347
6348 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006349 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006350 } else {
6351 mConfig.inputCfg.channels = channels;
6352 }
6353 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006354 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6355 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006356 mConfig.inputCfg.samplingRate = thread->sampleRate();
6357 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6358 mConfig.inputCfg.bufferProvider.cookie = NULL;
6359 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6360 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6361 mConfig.outputCfg.bufferProvider.cookie = NULL;
6362 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6363 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6364 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6365 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006366 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006367 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006368 // - in other sessions:
6369 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6370 // other effect: overwrites output buffer: input buffer == output buffer
6371 // Auxiliary effect:
6372 // accumulates in output buffer: input buffer != output buffer
6373 // Therefore: accumulate <=> input buffer != output buffer
6374 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6375 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6376 } else {
6377 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6378 }
6379 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6380 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6381 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6382 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6383
Steve Block3856b092011-10-20 11:56:00 +01006384 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006385 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6386
Mathias Agopian65ab4712010-07-14 17:59:35 -07006387 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006388 uint32_t size = sizeof(int);
6389 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006390 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006391 sizeof(effect_config_t),
6392 &mConfig,
6393 &size,
6394 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006395 if (status == 0) {
6396 status = cmdStatus;
6397 }
6398
6399 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6400 (1000 * mConfig.outputCfg.buffer.frameCount);
6401
6402 return status;
6403}
6404
6405status_t AudioFlinger::EffectModule::init()
6406{
6407 Mutex::Autolock _l(mLock);
6408 if (mEffectInterface == NULL) {
6409 return NO_INIT;
6410 }
6411 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006412 uint32_t size = sizeof(status_t);
6413 status_t status = (*mEffectInterface)->command(mEffectInterface,
6414 EFFECT_CMD_INIT,
6415 0,
6416 NULL,
6417 &size,
6418 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006419 if (status == 0) {
6420 status = cmdStatus;
6421 }
6422 return status;
6423}
6424
Eric Laurentec35a142011-10-05 17:42:25 -07006425status_t AudioFlinger::EffectModule::start()
6426{
6427 Mutex::Autolock _l(mLock);
6428 return start_l();
6429}
6430
Mathias Agopian65ab4712010-07-14 17:59:35 -07006431status_t AudioFlinger::EffectModule::start_l()
6432{
6433 if (mEffectInterface == NULL) {
6434 return NO_INIT;
6435 }
6436 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006437 uint32_t size = sizeof(status_t);
6438 status_t status = (*mEffectInterface)->command(mEffectInterface,
6439 EFFECT_CMD_ENABLE,
6440 0,
6441 NULL,
6442 &size,
6443 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444 if (status == 0) {
6445 status = cmdStatus;
6446 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006447 if (status == 0 &&
6448 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6449 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6450 sp<ThreadBase> thread = mThread.promote();
6451 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006452 audio_stream_t *stream = thread->stream();
6453 if (stream != NULL) {
6454 stream->add_audio_effect(stream, mEffectInterface);
6455 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006456 }
6457 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006458 return status;
6459}
6460
Eric Laurentec437d82011-07-26 20:54:46 -07006461status_t AudioFlinger::EffectModule::stop()
6462{
6463 Mutex::Autolock _l(mLock);
6464 return stop_l();
6465}
6466
Mathias Agopian65ab4712010-07-14 17:59:35 -07006467status_t AudioFlinger::EffectModule::stop_l()
6468{
6469 if (mEffectInterface == NULL) {
6470 return NO_INIT;
6471 }
6472 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006473 uint32_t size = sizeof(status_t);
6474 status_t status = (*mEffectInterface)->command(mEffectInterface,
6475 EFFECT_CMD_DISABLE,
6476 0,
6477 NULL,
6478 &size,
6479 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006480 if (status == 0) {
6481 status = cmdStatus;
6482 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006483 if (status == 0 &&
6484 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6485 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6486 sp<ThreadBase> thread = mThread.promote();
6487 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006488 audio_stream_t *stream = thread->stream();
6489 if (stream != NULL) {
6490 stream->remove_audio_effect(stream, mEffectInterface);
6491 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006492 }
6493 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494 return status;
6495}
6496
Eric Laurent25f43952010-07-28 05:40:18 -07006497status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6498 uint32_t cmdSize,
6499 void *pCmdData,
6500 uint32_t *replySize,
6501 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502{
6503 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006504// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006505
Eric Laurentec437d82011-07-26 20:54:46 -07006506 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006507 return NO_INIT;
6508 }
Eric Laurent25f43952010-07-28 05:40:18 -07006509 status_t status = (*mEffectInterface)->command(mEffectInterface,
6510 cmdCode,
6511 cmdSize,
6512 pCmdData,
6513 replySize,
6514 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006515 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006516 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517 for (size_t i = 1; i < mHandles.size(); i++) {
6518 sp<EffectHandle> h = mHandles[i].promote();
6519 if (h != 0) {
6520 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6521 }
6522 }
6523 }
6524 return status;
6525}
6526
6527status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6528{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006529
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006531 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006532
6533 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006534 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6535 if (enabled && status != NO_ERROR) {
6536 return status;
6537 }
6538
Mathias Agopian65ab4712010-07-14 17:59:35 -07006539 switch (mState) {
6540 // going from disabled to enabled
6541 case IDLE:
6542 mState = STARTING;
6543 break;
6544 case STOPPED:
6545 mState = RESTART;
6546 break;
6547 case STOPPING:
6548 mState = ACTIVE;
6549 break;
6550
6551 // going from enabled to disabled
6552 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006553 mState = STOPPED;
6554 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006555 case STARTING:
6556 mState = IDLE;
6557 break;
6558 case ACTIVE:
6559 mState = STOPPING;
6560 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006561 case DESTROYED:
6562 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006563 }
6564 for (size_t i = 1; i < mHandles.size(); i++) {
6565 sp<EffectHandle> h = mHandles[i].promote();
6566 if (h != 0) {
6567 h->setEnabled(enabled);
6568 }
6569 }
6570 }
6571 return NO_ERROR;
6572}
6573
Glenn Kastenc59c0042012-02-02 14:06:11 -08006574bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006575{
6576 switch (mState) {
6577 case RESTART:
6578 case STARTING:
6579 case ACTIVE:
6580 return true;
6581 case IDLE:
6582 case STOPPING:
6583 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006584 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006585 default:
6586 return false;
6587 }
6588}
6589
Glenn Kastenc59c0042012-02-02 14:06:11 -08006590bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07006591{
6592 switch (mState) {
6593 case RESTART:
6594 case ACTIVE:
6595 case STOPPING:
6596 case STOPPED:
6597 return true;
6598 case IDLE:
6599 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006600 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006601 default:
6602 return false;
6603 }
6604}
6605
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6607{
6608 Mutex::Autolock _l(mLock);
6609 status_t status = NO_ERROR;
6610
6611 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6612 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006613 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006614 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6615 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 status_t cmdStatus;
6617 uint32_t volume[2];
6618 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006619 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006620 volume[0] = *left;
6621 volume[1] = *right;
6622 if (controller) {
6623 pVolume = volume;
6624 }
Eric Laurent25f43952010-07-28 05:40:18 -07006625 status = (*mEffectInterface)->command(mEffectInterface,
6626 EFFECT_CMD_SET_VOLUME,
6627 size,
6628 volume,
6629 &size,
6630 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006631 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6632 *left = volume[0];
6633 *right = volume[1];
6634 }
6635 }
6636 return status;
6637}
6638
6639status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6640{
6641 Mutex::Autolock _l(mLock);
6642 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006643 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6644 // audio pre processing modules on RecordThread can receive both output and
6645 // input device indication in the same call
6646 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6647 if (dev) {
6648 status_t cmdStatus;
6649 uint32_t size = sizeof(status_t);
6650
6651 status = (*mEffectInterface)->command(mEffectInterface,
6652 EFFECT_CMD_SET_DEVICE,
6653 sizeof(uint32_t),
6654 &dev,
6655 &size,
6656 &cmdStatus);
6657 if (status == NO_ERROR) {
6658 status = cmdStatus;
6659 }
6660 }
6661 dev = device & AUDIO_DEVICE_IN_ALL;
6662 if (dev) {
6663 status_t cmdStatus;
6664 uint32_t size = sizeof(status_t);
6665
6666 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6667 EFFECT_CMD_SET_INPUT_DEVICE,
6668 sizeof(uint32_t),
6669 &dev,
6670 &size,
6671 &cmdStatus);
6672 if (status2 == NO_ERROR) {
6673 status2 = cmdStatus;
6674 }
6675 if (status == NO_ERROR) {
6676 status = status2;
6677 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006678 }
6679 }
6680 return status;
6681}
6682
Glenn Kastenf78aee72012-01-04 11:00:47 -08006683status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006684{
6685 Mutex::Autolock _l(mLock);
6686 status_t status = NO_ERROR;
6687 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006688 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006689 uint32_t size = sizeof(status_t);
6690 status = (*mEffectInterface)->command(mEffectInterface,
6691 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006692 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006693 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006694 &size,
6695 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006696 if (status == NO_ERROR) {
6697 status = cmdStatus;
6698 }
6699 }
6700 return status;
6701}
6702
Eric Laurent59255e42011-07-27 19:49:51 -07006703void AudioFlinger::EffectModule::setSuspended(bool suspended)
6704{
6705 Mutex::Autolock _l(mLock);
6706 mSuspended = suspended;
6707}
Glenn Kastena3a85482012-01-04 11:01:11 -08006708
6709bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006710{
6711 Mutex::Autolock _l(mLock);
6712 return mSuspended;
6713}
6714
Mathias Agopian65ab4712010-07-14 17:59:35 -07006715status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6716{
6717 const size_t SIZE = 256;
6718 char buffer[SIZE];
6719 String8 result;
6720
6721 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6722 result.append(buffer);
6723
6724 bool locked = tryLock(mLock);
6725 // failed to lock - AudioFlinger is probably deadlocked
6726 if (!locked) {
6727 result.append("\t\tCould not lock Fx mutex:\n");
6728 }
6729
6730 result.append("\t\tSession Status State Engine:\n");
6731 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6732 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6733 result.append(buffer);
6734
6735 result.append("\t\tDescriptor:\n");
6736 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6737 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6738 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6739 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6740 result.append(buffer);
6741 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6742 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6743 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6744 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6745 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006746 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006747 mDescriptor.apiVersion,
6748 mDescriptor.flags);
6749 result.append(buffer);
6750 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6751 mDescriptor.name);
6752 result.append(buffer);
6753 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6754 mDescriptor.implementor);
6755 result.append(buffer);
6756
6757 result.append("\t\t- Input configuration:\n");
6758 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6759 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6760 (uint32_t)mConfig.inputCfg.buffer.raw,
6761 mConfig.inputCfg.buffer.frameCount,
6762 mConfig.inputCfg.samplingRate,
6763 mConfig.inputCfg.channels,
6764 mConfig.inputCfg.format);
6765 result.append(buffer);
6766
6767 result.append("\t\t- Output configuration:\n");
6768 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6769 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6770 (uint32_t)mConfig.outputCfg.buffer.raw,
6771 mConfig.outputCfg.buffer.frameCount,
6772 mConfig.outputCfg.samplingRate,
6773 mConfig.outputCfg.channels,
6774 mConfig.outputCfg.format);
6775 result.append(buffer);
6776
6777 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6778 result.append(buffer);
6779 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6780 for (size_t i = 0; i < mHandles.size(); ++i) {
6781 sp<EffectHandle> handle = mHandles[i].promote();
6782 if (handle != 0) {
6783 handle->dump(buffer, SIZE);
6784 result.append(buffer);
6785 }
6786 }
6787
6788 result.append("\n");
6789
6790 write(fd, result.string(), result.length());
6791
6792 if (locked) {
6793 mLock.unlock();
6794 }
6795
6796 return NO_ERROR;
6797}
6798
6799// ----------------------------------------------------------------------------
6800// EffectHandle implementation
6801// ----------------------------------------------------------------------------
6802
6803#undef LOG_TAG
6804#define LOG_TAG "AudioFlinger::EffectHandle"
6805
6806AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6807 const sp<AudioFlinger::Client>& client,
6808 const sp<IEffectClient>& effectClient,
6809 int32_t priority)
6810 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006811 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006812 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006813{
Steve Block3856b092011-10-20 11:56:00 +01006814 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006815
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006816 if (client == 0) {
6817 return;
6818 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006819 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6820 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6821 if (mCblkMemory != 0) {
6822 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6823
Glenn Kastena0d68332012-01-27 16:47:15 -08006824 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006825 new(mCblk) effect_param_cblk_t();
6826 mBuffer = (uint8_t *)mCblk + bufOffset;
6827 }
6828 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006829 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006830 return;
6831 }
6832}
6833
6834AudioFlinger::EffectHandle::~EffectHandle()
6835{
Steve Block3856b092011-10-20 11:56:00 +01006836 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006837 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006838 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006839}
6840
6841status_t AudioFlinger::EffectHandle::enable()
6842{
Steve Block3856b092011-10-20 11:56:00 +01006843 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006844 if (!mHasControl) return INVALID_OPERATION;
6845 if (mEffect == 0) return DEAD_OBJECT;
6846
Eric Laurentdb7c0792011-08-10 10:37:50 -07006847 if (mEnabled) {
6848 return NO_ERROR;
6849 }
6850
Eric Laurent59255e42011-07-27 19:49:51 -07006851 mEnabled = true;
6852
6853 sp<ThreadBase> thread = mEffect->thread().promote();
6854 if (thread != 0) {
6855 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6856 }
6857
6858 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6859 if (mEffect->suspended()) {
6860 return NO_ERROR;
6861 }
6862
Eric Laurentdb7c0792011-08-10 10:37:50 -07006863 status_t status = mEffect->setEnabled(true);
6864 if (status != NO_ERROR) {
6865 if (thread != 0) {
6866 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6867 }
6868 mEnabled = false;
6869 }
6870 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871}
6872
6873status_t AudioFlinger::EffectHandle::disable()
6874{
Steve Block3856b092011-10-20 11:56:00 +01006875 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006876 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006877 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006878
Eric Laurentdb7c0792011-08-10 10:37:50 -07006879 if (!mEnabled) {
6880 return NO_ERROR;
6881 }
Eric Laurent59255e42011-07-27 19:49:51 -07006882 mEnabled = false;
6883
6884 if (mEffect->suspended()) {
6885 return NO_ERROR;
6886 }
6887
6888 status_t status = mEffect->setEnabled(false);
6889
6890 sp<ThreadBase> thread = mEffect->thread().promote();
6891 if (thread != 0) {
6892 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6893 }
6894
6895 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006896}
6897
6898void AudioFlinger::EffectHandle::disconnect()
6899{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006900 disconnect(true);
6901}
6902
6903void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6904{
Steve Block3856b092011-10-20 11:56:00 +01006905 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906 if (mEffect == 0) {
6907 return;
6908 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006909 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006910
Eric Laurenta85a74a2011-10-19 11:44:54 -07006911 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006912 sp<ThreadBase> thread = mEffect->thread().promote();
6913 if (thread != 0) {
6914 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6915 }
Eric Laurent59255e42011-07-27 19:49:51 -07006916 }
6917
Mathias Agopian65ab4712010-07-14 17:59:35 -07006918 // release sp on module => module destructor can be called now
6919 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006920 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08006921 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08006922 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006923 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6924 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08006925 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6927 mClient.clear();
6928 }
6929}
6930
Eric Laurent25f43952010-07-28 05:40:18 -07006931status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6932 uint32_t cmdSize,
6933 void *pCmdData,
6934 uint32_t *replySize,
6935 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006936{
Steve Block3856b092011-10-20 11:56:00 +01006937// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006938// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006939
6940 // only get parameter command is permitted for applications not controlling the effect
6941 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6942 return INVALID_OPERATION;
6943 }
6944 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006945 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006946
6947 // handle commands that are not forwarded transparently to effect engine
6948 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6949 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6950 // no risk to block the whole media server process or mixer threads is we are stuck here
6951 Mutex::Autolock _l(mCblk->lock);
6952 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6953 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6954 mCblk->serverIndex = 0;
6955 mCblk->clientIndex = 0;
6956 return BAD_VALUE;
6957 }
6958 status_t status = NO_ERROR;
6959 while (mCblk->serverIndex < mCblk->clientIndex) {
6960 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006961 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006962 int *p = (int *)(mBuffer + mCblk->serverIndex);
6963 int size = *p++;
6964 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006965 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006966 break;
6967 }
6968 effect_param_t *param = (effect_param_t *)p;
6969 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006970 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006971 mCblk->serverIndex += size;
6972 continue;
6973 }
Eric Laurent25f43952010-07-28 05:40:18 -07006974 uint32_t psize = sizeof(effect_param_t) +
6975 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6976 param->vsize;
6977 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6978 psize,
6979 p,
6980 &rsize,
6981 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006982 // stop at first error encountered
6983 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006985 *(int *)pReplyData = reply;
6986 break;
6987 } else if (reply != NO_ERROR) {
6988 *(int *)pReplyData = reply;
6989 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006990 }
6991 mCblk->serverIndex += size;
6992 }
6993 mCblk->serverIndex = 0;
6994 mCblk->clientIndex = 0;
6995 return status;
6996 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006997 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998 return enable();
6999 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007000 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007001 return disable();
7002 }
7003
7004 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7005}
7006
Eric Laurent59255e42011-07-27 19:49:51 -07007007void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007008{
Steve Block3856b092011-10-20 11:56:00 +01007009 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010
7011 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007012 mEnabled = enabled;
7013
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 if (signal && mEffectClient != 0) {
7015 mEffectClient->controlStatusChanged(hasControl);
7016 }
7017}
7018
Eric Laurent25f43952010-07-28 05:40:18 -07007019void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7020 uint32_t cmdSize,
7021 void *pCmdData,
7022 uint32_t replySize,
7023 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024{
7025 if (mEffectClient != 0) {
7026 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7027 }
7028}
7029
7030
7031
7032void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7033{
7034 if (mEffectClient != 0) {
7035 mEffectClient->enableStatusChanged(enabled);
7036 }
7037}
7038
7039status_t AudioFlinger::EffectHandle::onTransact(
7040 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7041{
7042 return BnEffect::onTransact(code, data, reply, flags);
7043}
7044
7045
7046void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7047{
Glenn Kastena0d68332012-01-27 16:47:15 -08007048 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049
7050 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08007051 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007052 mPriority,
7053 mHasControl,
7054 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007055 mCblk ? mCblk->clientIndex : 0,
7056 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057 );
7058
7059 if (locked) {
7060 mCblk->lock.unlock();
7061 }
7062}
7063
7064#undef LOG_TAG
7065#define LOG_TAG "AudioFlinger::EffectChain"
7066
7067AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7068 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007069 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007070 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7071 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007072{
Dima Zavinfce7a472011-04-19 22:30:36 -07007073 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007074 sp<ThreadBase> thread = mThread.promote();
7075 if (thread == 0) {
7076 return;
7077 }
7078 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7079 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007080}
7081
7082AudioFlinger::EffectChain::~EffectChain()
7083{
7084 if (mOwnInBuffer) {
7085 delete mInBuffer;
7086 }
7087
7088}
7089
Eric Laurent59255e42011-07-27 19:49:51 -07007090// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007091sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007092{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093 size_t size = mEffects.size();
7094
7095 for (size_t i = 0; i < size; i++) {
7096 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007097 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007098 }
7099 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007100 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101}
7102
Eric Laurent59255e42011-07-27 19:49:51 -07007103// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007104sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007106 size_t size = mEffects.size();
7107
7108 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007109 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7110 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007111 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007112 }
7113 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007114 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007115}
7116
Eric Laurent59255e42011-07-27 19:49:51 -07007117// getEffectFromType_l() must be called with ThreadBase::mLock held
7118sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7119 const effect_uuid_t *type)
7120{
Eric Laurent59255e42011-07-27 19:49:51 -07007121 size_t size = mEffects.size();
7122
7123 for (size_t i = 0; i < size; i++) {
7124 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007125 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007126 }
7127 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007128 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007129}
7130
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131// Must be called with EffectChain::mLock locked
7132void AudioFlinger::EffectChain::process_l()
7133{
Eric Laurentdac69112010-09-28 14:09:57 -07007134 sp<ThreadBase> thread = mThread.promote();
7135 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007136 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007137 return;
7138 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007139 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7140 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007141 // always process effects unless no more tracks are on the session and the effect tail
7142 // has been rendered
7143 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007144 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007145 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007146
Eric Laurent544fe9b2011-11-11 15:42:52 -08007147 if (!tracksOnSession && mTailBufferCount == 0) {
7148 doProcess = false;
7149 }
7150
7151 if (activeTrackCnt() == 0) {
7152 // if no track is active and the effect tail has not been rendered,
7153 // the input buffer must be cleared here as the mixer process will not do it
7154 if (tracksOnSession || mTailBufferCount > 0) {
7155 size_t numSamples = thread->frameCount() * thread->channelCount();
7156 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7157 if (mTailBufferCount > 0) {
7158 mTailBufferCount--;
7159 }
7160 }
7161 }
Eric Laurentdac69112010-09-28 14:09:57 -07007162 }
7163
Mathias Agopian65ab4712010-07-14 17:59:35 -07007164 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007165 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007166 for (size_t i = 0; i < size; i++) {
7167 mEffects[i]->process();
7168 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007169 }
7170 for (size_t i = 0; i < size; i++) {
7171 mEffects[i]->updateState();
7172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007173}
7174
Eric Laurentcab11242010-07-15 12:50:15 -07007175// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007176status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177{
7178 effect_descriptor_t desc = effect->desc();
7179 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7180
7181 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007182 effect->setChain(this);
7183 sp<ThreadBase> thread = mThread.promote();
7184 if (thread == 0) {
7185 return NO_INIT;
7186 }
7187 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188
7189 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7190 // Auxiliary effects are inserted at the beginning of mEffects vector as
7191 // they are processed first and accumulated in chain input buffer
7192 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007193
Mathias Agopian65ab4712010-07-14 17:59:35 -07007194 // the input buffer for auxiliary effect contains mono samples in
7195 // 32 bit format. This is to avoid saturation in AudoMixer
7196 // accumulation stage. Saturation is done in EffectModule::process() before
7197 // calling the process in effect engine
7198 size_t numSamples = thread->frameCount();
7199 int32_t *buffer = new int32_t[numSamples];
7200 memset(buffer, 0, numSamples * sizeof(int32_t));
7201 effect->setInBuffer((int16_t *)buffer);
7202 // auxiliary effects output samples to chain input buffer for further processing
7203 // by insert effects
7204 effect->setOutBuffer(mInBuffer);
7205 } else {
7206 // Insert effects are inserted at the end of mEffects vector as they are processed
7207 // after track and auxiliary effects.
7208 // Insert effect order as a function of indicated preference:
7209 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7210 // another effect is present
7211 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7212 // last effect claiming first position
7213 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7214 // first effect claiming last position
7215 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7216 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7217 // already present
7218
7219 int size = (int)mEffects.size();
7220 int idx_insert = size;
7221 int idx_insert_first = -1;
7222 int idx_insert_last = -1;
7223
7224 for (int i = 0; i < size; i++) {
7225 effect_descriptor_t d = mEffects[i]->desc();
7226 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7227 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7228 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7229 // check invalid effect chaining combinations
7230 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7231 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007232 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007233 return INVALID_OPERATION;
7234 }
7235 // remember position of first insert effect and by default
7236 // select this as insert position for new effect
7237 if (idx_insert == size) {
7238 idx_insert = i;
7239 }
7240 // remember position of last insert effect claiming
7241 // first position
7242 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7243 idx_insert_first = i;
7244 }
7245 // remember position of first insert effect claiming
7246 // last position
7247 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7248 idx_insert_last == -1) {
7249 idx_insert_last = i;
7250 }
7251 }
7252 }
7253
7254 // modify idx_insert from first position if needed
7255 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7256 if (idx_insert_last != -1) {
7257 idx_insert = idx_insert_last;
7258 } else {
7259 idx_insert = size;
7260 }
7261 } else {
7262 if (idx_insert_first != -1) {
7263 idx_insert = idx_insert_first + 1;
7264 }
7265 }
7266
7267 // always read samples from chain input buffer
7268 effect->setInBuffer(mInBuffer);
7269
7270 // if last effect in the chain, output samples to chain
7271 // output buffer, otherwise to chain input buffer
7272 if (idx_insert == size) {
7273 if (idx_insert != 0) {
7274 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7275 mEffects[idx_insert-1]->configure();
7276 }
7277 effect->setOutBuffer(mOutBuffer);
7278 } else {
7279 effect->setOutBuffer(mInBuffer);
7280 }
7281 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007282
Steve Block3856b092011-10-20 11:56:00 +01007283 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284 }
7285 effect->configure();
7286 return NO_ERROR;
7287}
7288
Eric Laurentcab11242010-07-15 12:50:15 -07007289// removeEffect_l() must be called with PlaybackThread::mLock held
7290size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007291{
7292 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007293 int size = (int)mEffects.size();
7294 int i;
7295 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7296
7297 for (i = 0; i < size; i++) {
7298 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007299 // calling stop here will remove pre-processing effect from the audio HAL.
7300 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7301 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007302 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7303 mEffects[i]->state() == EffectModule::STOPPING) {
7304 mEffects[i]->stop();
7305 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007306 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7307 delete[] effect->inBuffer();
7308 } else {
7309 if (i == size - 1 && i != 0) {
7310 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7311 mEffects[i - 1]->configure();
7312 }
7313 }
7314 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007315 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007316 break;
7317 }
7318 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007319
7320 return mEffects.size();
7321}
7322
Eric Laurentcab11242010-07-15 12:50:15 -07007323// setDevice_l() must be called with PlaybackThread::mLock held
7324void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007325{
7326 size_t size = mEffects.size();
7327 for (size_t i = 0; i < size; i++) {
7328 mEffects[i]->setDevice(device);
7329 }
7330}
7331
Eric Laurentcab11242010-07-15 12:50:15 -07007332// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007333void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007334{
7335 size_t size = mEffects.size();
7336 for (size_t i = 0; i < size; i++) {
7337 mEffects[i]->setMode(mode);
7338 }
7339}
7340
Eric Laurentcab11242010-07-15 12:50:15 -07007341// setVolume_l() must be called with PlaybackThread::mLock held
7342bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343{
7344 uint32_t newLeft = *left;
7345 uint32_t newRight = *right;
7346 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007347 int ctrlIdx = -1;
7348 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007349
Eric Laurentcab11242010-07-15 12:50:15 -07007350 // first update volume controller
7351 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007352 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007353 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7354 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007355 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007356 break;
7357 }
7358 }
7359
7360 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007361 if (hasControl) {
7362 *left = mNewLeftVolume;
7363 *right = mNewRightVolume;
7364 }
7365 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007366 }
7367
7368 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007369 mLeftVolume = newLeft;
7370 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007371
7372 // second get volume update from volume controller
7373 if (ctrlIdx >= 0) {
7374 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007375 mNewLeftVolume = newLeft;
7376 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377 }
7378 // then indicate volume to all other effects in chain.
7379 // Pass altered volume to effects before volume controller
7380 // and requested volume to effects after controller
7381 uint32_t lVol = newLeft;
7382 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007383
Mathias Agopian65ab4712010-07-14 17:59:35 -07007384 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007385 if ((int)i == ctrlIdx) continue;
7386 // this also works for ctrlIdx == -1 when there is no volume controller
7387 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388 lVol = *left;
7389 rVol = *right;
7390 }
7391 mEffects[i]->setVolume(&lVol, &rVol, false);
7392 }
7393 *left = newLeft;
7394 *right = newRight;
7395
7396 return hasControl;
7397}
7398
Mathias Agopian65ab4712010-07-14 17:59:35 -07007399status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7400{
7401 const size_t SIZE = 256;
7402 char buffer[SIZE];
7403 String8 result;
7404
7405 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7406 result.append(buffer);
7407
7408 bool locked = tryLock(mLock);
7409 // failed to lock - AudioFlinger is probably deadlocked
7410 if (!locked) {
7411 result.append("\tCould not lock mutex:\n");
7412 }
7413
Eric Laurentcab11242010-07-15 12:50:15 -07007414 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7415 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007416 mEffects.size(),
7417 (uint32_t)mInBuffer,
7418 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007419 mActiveTrackCnt);
7420 result.append(buffer);
7421 write(fd, result.string(), result.size());
7422
7423 for (size_t i = 0; i < mEffects.size(); ++i) {
7424 sp<EffectModule> effect = mEffects[i];
7425 if (effect != 0) {
7426 effect->dump(fd, args);
7427 }
7428 }
7429
7430 if (locked) {
7431 mLock.unlock();
7432 }
7433
7434 return NO_ERROR;
7435}
7436
Eric Laurent59255e42011-07-27 19:49:51 -07007437// must be called with ThreadBase::mLock held
7438void AudioFlinger::EffectChain::setEffectSuspended_l(
7439 const effect_uuid_t *type, bool suspend)
7440{
7441 sp<SuspendedEffectDesc> desc;
7442 // use effect type UUID timelow as key as there is no real risk of identical
7443 // timeLow fields among effect type UUIDs.
7444 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7445 if (suspend) {
7446 if (index >= 0) {
7447 desc = mSuspendedEffects.valueAt(index);
7448 } else {
7449 desc = new SuspendedEffectDesc();
7450 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7451 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007452 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007453 }
7454 if (desc->mRefCount++ == 0) {
7455 sp<EffectModule> effect = getEffectIfEnabled(type);
7456 if (effect != 0) {
7457 desc->mEffect = effect;
7458 effect->setSuspended(true);
7459 effect->setEnabled(false);
7460 }
7461 }
7462 } else {
7463 if (index < 0) {
7464 return;
7465 }
7466 desc = mSuspendedEffects.valueAt(index);
7467 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007468 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007469 desc->mRefCount = 1;
7470 }
7471 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007472 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007473 if (desc->mEffect != 0) {
7474 sp<EffectModule> effect = desc->mEffect.promote();
7475 if (effect != 0) {
7476 effect->setSuspended(false);
7477 sp<EffectHandle> handle = effect->controlHandle();
7478 if (handle != 0) {
7479 effect->setEnabled(handle->enabled());
7480 }
7481 }
7482 desc->mEffect.clear();
7483 }
7484 mSuspendedEffects.removeItemsAt(index);
7485 }
7486 }
7487}
7488
7489// must be called with ThreadBase::mLock held
7490void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7491{
7492 sp<SuspendedEffectDesc> desc;
7493
7494 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7495 if (suspend) {
7496 if (index >= 0) {
7497 desc = mSuspendedEffects.valueAt(index);
7498 } else {
7499 desc = new SuspendedEffectDesc();
7500 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007501 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007502 }
7503 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007504 Vector< sp<EffectModule> > effects;
7505 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007506 for (size_t i = 0; i < effects.size(); i++) {
7507 setEffectSuspended_l(&effects[i]->desc().type, true);
7508 }
7509 }
7510 } else {
7511 if (index < 0) {
7512 return;
7513 }
7514 desc = mSuspendedEffects.valueAt(index);
7515 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007516 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007517 desc->mRefCount = 1;
7518 }
7519 if (--desc->mRefCount == 0) {
7520 Vector<const effect_uuid_t *> types;
7521 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7522 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7523 continue;
7524 }
7525 types.add(&mSuspendedEffects.valueAt(i)->mType);
7526 }
7527 for (size_t i = 0; i < types.size(); i++) {
7528 setEffectSuspended_l(types[i], false);
7529 }
Steve Block3856b092011-10-20 11:56:00 +01007530 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007531 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7532 }
7533 }
7534}
7535
Eric Laurent6bffdb82011-09-23 08:40:41 -07007536
7537// The volume effect is used for automated tests only
7538#ifndef OPENSL_ES_H_
7539static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7540 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7541const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7542#endif //OPENSL_ES_H_
7543
Eric Laurentdb7c0792011-08-10 10:37:50 -07007544bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7545{
7546 // auxiliary effects and visualizer are never suspended on output mix
7547 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7548 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007549 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7550 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007551 return false;
7552 }
7553 return true;
7554}
7555
Glenn Kastend0539712012-01-30 12:56:03 -08007556void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007557{
Glenn Kastend0539712012-01-30 12:56:03 -08007558 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07007559 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08007560 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7561 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07007562 }
Eric Laurent59255e42011-07-27 19:49:51 -07007563 }
Eric Laurent59255e42011-07-27 19:49:51 -07007564}
7565
7566sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7567 const effect_uuid_t *type)
7568{
Glenn Kasten090f0192012-01-30 13:00:02 -08007569 sp<EffectModule> effect = getEffectFromType_l(type);
7570 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007571}
7572
7573void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7574 bool enabled)
7575{
7576 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7577 if (enabled) {
7578 if (index < 0) {
7579 // if the effect is not suspend check if all effects are suspended
7580 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7581 if (index < 0) {
7582 return;
7583 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007584 if (!isEffectEligibleForSuspend(effect->desc())) {
7585 return;
7586 }
Eric Laurent59255e42011-07-27 19:49:51 -07007587 setEffectSuspended_l(&effect->desc().type, enabled);
7588 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007589 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007590 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007591 return;
7592 }
Eric Laurent59255e42011-07-27 19:49:51 -07007593 }
Steve Block3856b092011-10-20 11:56:00 +01007594 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007595 effect->desc().type.timeLow);
7596 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7597 // if effect is requested to suspended but was not yet enabled, supend it now.
7598 if (desc->mEffect == 0) {
7599 desc->mEffect = effect;
7600 effect->setEnabled(false);
7601 effect->setSuspended(true);
7602 }
7603 } else {
7604 if (index < 0) {
7605 return;
7606 }
Steve Block3856b092011-10-20 11:56:00 +01007607 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007608 effect->desc().type.timeLow);
7609 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7610 desc->mEffect.clear();
7611 effect->setSuspended(false);
7612 }
7613}
7614
Mathias Agopian65ab4712010-07-14 17:59:35 -07007615#undef LOG_TAG
7616#define LOG_TAG "AudioFlinger"
7617
7618// ----------------------------------------------------------------------------
7619
7620status_t AudioFlinger::onTransact(
7621 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7622{
7623 return BnAudioFlinger::onTransact(code, data, reply, flags);
7624}
7625
Mathias Agopian65ab4712010-07-14 17:59:35 -07007626}; // namespace android