blob: 7d87d92c24f652675c995bf96c5f8134d5737dc7 [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 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700248 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249}
250
Dima Zavin799a70e2011-04-18 16:57:27 -0700251audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
252{
253 /* first matching HW device is returned */
254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
255 audio_hw_device_t *dev = mAudioHwDevs[i];
256 if ((dev->get_supported_devices(dev) & devices) == devices)
257 return dev;
258 }
259 return NULL;
260}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261
262status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
263{
264 const size_t SIZE = 256;
265 char buffer[SIZE];
266 String8 result;
267
268 result.append("Clients:\n");
269 for (size_t i = 0; i < mClients.size(); ++i) {
270 wp<Client> wClient = mClients.valueAt(i);
271 if (wClient != 0) {
272 sp<Client> client = wClient.promote();
273 if (client != 0) {
274 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
275 result.append(buffer);
276 }
277 }
278 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700279
280 result.append("Global session refs:\n");
281 result.append(" session pid cnt\n");
282 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
283 AudioSessionRef *r = mAudioSessionRefs[i];
284 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
285 result.append(buffer);
286 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700287 write(fd, result.string(), result.size());
288 return NO_ERROR;
289}
290
291
292status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
293{
294 const size_t SIZE = 256;
295 char buffer[SIZE];
296 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800297 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700298
299 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
300 result.append(buffer);
301 write(fd, result.string(), result.size());
302 return NO_ERROR;
303}
304
305status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
306{
307 const size_t SIZE = 256;
308 char buffer[SIZE];
309 String8 result;
310 snprintf(buffer, SIZE, "Permission Denial: "
311 "can't dump AudioFlinger from pid=%d, uid=%d\n",
312 IPCThreadState::self()->getCallingPid(),
313 IPCThreadState::self()->getCallingUid());
314 result.append(buffer);
315 write(fd, result.string(), result.size());
316 return NO_ERROR;
317}
318
319static bool tryLock(Mutex& mutex)
320{
321 bool locked = false;
322 for (int i = 0; i < kDumpLockRetries; ++i) {
323 if (mutex.tryLock() == NO_ERROR) {
324 locked = true;
325 break;
326 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800327 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700328 }
329 return locked;
330}
331
332status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
333{
Glenn Kastenf1d45922012-01-13 15:54:24 -0800334 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335 dumpPermissionDenial(fd, args);
336 } else {
337 // get state of hardware lock
338 bool hardwareLocked = tryLock(mHardwareLock);
339 if (!hardwareLocked) {
340 String8 result(kHardwareLockedString);
341 write(fd, result.string(), result.size());
342 } else {
343 mHardwareLock.unlock();
344 }
345
346 bool locked = tryLock(mLock);
347
348 // failed to lock - AudioFlinger is probably deadlocked
349 if (!locked) {
350 String8 result(kDeadlockedString);
351 write(fd, result.string(), result.size());
352 }
353
354 dumpClients(fd, args);
355 dumpInternals(fd, args);
356
357 // dump playback threads
358 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
359 mPlaybackThreads.valueAt(i)->dump(fd, args);
360 }
361
362 // dump record threads
363 for (size_t i = 0; i < mRecordThreads.size(); i++) {
364 mRecordThreads.valueAt(i)->dump(fd, args);
365 }
366
Dima Zavin799a70e2011-04-18 16:57:27 -0700367 // dump all hardware devs
368 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
369 audio_hw_device_t *dev = mAudioHwDevs[i];
370 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371 }
372 if (locked) mLock.unlock();
373 }
374 return NO_ERROR;
375}
376
377
378// IAudioFlinger interface
379
380
381sp<IAudioTrack> AudioFlinger::createTrack(
382 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800383 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700384 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800385 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700386 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 int frameCount,
388 uint32_t flags,
389 const sp<IMemory>& sharedBuffer,
390 int output,
391 int *sessionId,
392 status_t *status)
393{
394 sp<PlaybackThread::Track> track;
395 sp<TrackHandle> trackHandle;
396 sp<Client> client;
397 wp<Client> wclient;
398 status_t lStatus;
399 int lSessionId;
400
Glenn Kasten263709e2012-01-06 08:40:01 -0800401 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
402 // but if someone uses binder directly they could bypass that and cause us to crash
403 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000404 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700405 lStatus = BAD_VALUE;
406 goto Exit;
407 }
408
409 {
410 Mutex::Autolock _l(mLock);
411 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700412 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700413 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000414 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700415 lStatus = BAD_VALUE;
416 goto Exit;
417 }
418
419 wclient = mClients.valueFor(pid);
420
421 if (wclient != NULL) {
422 client = wclient.promote();
423 } else {
424 client = new Client(this, pid);
425 mClients.add(pid, client);
426 }
427
Steve Block3856b092011-10-20 11:56:00 +0100428 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700429 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700430 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700431 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
432 if (mPlaybackThreads.keyAt(i) != output) {
433 // prevent same audio session on different output threads
434 uint32_t sessions = t->hasAudioSession(*sessionId);
435 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000436 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700437 lStatus = BAD_VALUE;
438 goto Exit;
439 }
440 // check if an effect with same session ID is waiting for a track to be created
441 if (sessions & PlaybackThread::EFFECT_SESSION) {
442 effectThread = t.get();
443 }
Eric Laurentde070132010-07-13 04:45:46 -0700444 }
445 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 lSessionId = *sessionId;
447 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700448 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700449 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 if (sessionId != NULL) {
451 *sessionId = lSessionId;
452 }
453 }
Steve Block3856b092011-10-20 11:56:00 +0100454 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455
456 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700457 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700458
459 // move effect chain to this output thread if an effect on same session was waiting
460 // for a track to be created
461 if (lStatus == NO_ERROR && effectThread != NULL) {
462 Mutex::Autolock _dl(thread->mLock);
463 Mutex::Autolock _sl(effectThread->mLock);
464 moveEffectChain_l(lSessionId, effectThread, thread, true);
465 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700466 }
467 if (lStatus == NO_ERROR) {
468 trackHandle = new TrackHandle(track);
469 } else {
470 // remove local strong reference to Client before deleting the Track so that the Client
471 // destructor is called by the TrackBase destructor with mLock held
472 client.clear();
473 track.clear();
474 }
475
476Exit:
477 if(status) {
478 *status = lStatus;
479 }
480 return trackHandle;
481}
482
483uint32_t AudioFlinger::sampleRate(int output) const
484{
485 Mutex::Autolock _l(mLock);
486 PlaybackThread *thread = checkPlaybackThread_l(output);
487 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000488 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700489 return 0;
490 }
491 return thread->sampleRate();
492}
493
494int AudioFlinger::channelCount(int output) const
495{
496 Mutex::Autolock _l(mLock);
497 PlaybackThread *thread = checkPlaybackThread_l(output);
498 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000499 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 return 0;
501 }
502 return thread->channelCount();
503}
504
Glenn Kasten58f30212012-01-12 12:27:51 -0800505audio_format_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506{
507 Mutex::Autolock _l(mLock);
508 PlaybackThread *thread = checkPlaybackThread_l(output);
509 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000510 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800511 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700512 }
513 return thread->format();
514}
515
516size_t AudioFlinger::frameCount(int output) const
517{
518 Mutex::Autolock _l(mLock);
519 PlaybackThread *thread = checkPlaybackThread_l(output);
520 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000521 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700522 return 0;
523 }
524 return thread->frameCount();
525}
526
527uint32_t AudioFlinger::latency(int output) const
528{
529 Mutex::Autolock _l(mLock);
530 PlaybackThread *thread = checkPlaybackThread_l(output);
531 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000532 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700533 return 0;
534 }
535 return thread->latency();
536}
537
538status_t AudioFlinger::setMasterVolume(float value)
539{
Eric Laurenta1884f92011-08-23 08:25:03 -0700540 status_t ret = initCheck();
541 if (ret != NO_ERROR) {
542 return ret;
543 }
544
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 // check calling permissions
546 if (!settingsAllowed()) {
547 return PERMISSION_DENIED;
548 }
549
550 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800551 { // scope for the lock
552 AutoMutex lock(mHardwareLock);
553 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700554 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800555 value = 1.0f;
556 }
557 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559
Eric Laurent93575202011-01-18 18:39:02 -0800560 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561 mMasterVolume = value;
562 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
563 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
564
565 return NO_ERROR;
566}
567
Glenn Kastenf78aee72012-01-04 11:00:47 -0800568status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569{
Eric Laurenta1884f92011-08-23 08:25:03 -0700570 status_t ret = initCheck();
571 if (ret != NO_ERROR) {
572 return ret;
573 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700574
575 // check calling permissions
576 if (!settingsAllowed()) {
577 return PERMISSION_DENIED;
578 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800579 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000580 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581 return BAD_VALUE;
582 }
583
584 { // scope for the lock
585 AutoMutex lock(mHardwareLock);
586 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700587 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588 mHardwareStatus = AUDIO_HW_IDLE;
589 }
590
591 if (NO_ERROR == ret) {
592 Mutex::Autolock _l(mLock);
593 mMode = mode;
594 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
595 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596 }
597
598 return ret;
599}
600
601status_t AudioFlinger::setMicMute(bool state)
602{
Eric Laurenta1884f92011-08-23 08:25:03 -0700603 status_t ret = initCheck();
604 if (ret != NO_ERROR) {
605 return ret;
606 }
607
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608 // check calling permissions
609 if (!settingsAllowed()) {
610 return PERMISSION_DENIED;
611 }
612
613 AutoMutex lock(mHardwareLock);
614 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700615 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700616 mHardwareStatus = AUDIO_HW_IDLE;
617 return ret;
618}
619
620bool AudioFlinger::getMicMute() const
621{
Eric Laurenta1884f92011-08-23 08:25:03 -0700622 status_t ret = initCheck();
623 if (ret != NO_ERROR) {
624 return false;
625 }
626
Dima Zavinfce7a472011-04-19 22:30:36 -0700627 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700629 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700630 mHardwareStatus = AUDIO_HW_IDLE;
631 return state;
632}
633
634status_t AudioFlinger::setMasterMute(bool muted)
635{
636 // check calling permissions
637 if (!settingsAllowed()) {
638 return PERMISSION_DENIED;
639 }
640
Eric Laurent93575202011-01-18 18:39:02 -0800641 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642 mMasterMute = muted;
643 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
644 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
645
646 return NO_ERROR;
647}
648
649float AudioFlinger::masterVolume() const
650{
Glenn Kasten98067102011-12-13 11:47:54 -0800651 Mutex::Autolock _l(mLock);
652 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653}
654
655bool AudioFlinger::masterMute() const
656{
Glenn Kasten98067102011-12-13 11:47:54 -0800657 Mutex::Autolock _l(mLock);
658 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659}
660
Glenn Kastenfff6d712012-01-12 16:38:12 -0800661status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662{
663 // check calling permissions
664 if (!settingsAllowed()) {
665 return PERMISSION_DENIED;
666 }
667
Glenn Kasten263709e2012-01-06 08:40:01 -0800668 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000669 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700670 return BAD_VALUE;
671 }
672
673 AutoMutex lock(mLock);
674 PlaybackThread *thread = NULL;
675 if (output) {
676 thread = checkPlaybackThread_l(output);
677 if (thread == NULL) {
678 return BAD_VALUE;
679 }
680 }
681
682 mStreamTypes[stream].volume = value;
683
684 if (thread == NULL) {
685 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
686 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
687 }
688 } else {
689 thread->setStreamVolume(stream, value);
690 }
691
692 return NO_ERROR;
693}
694
Glenn Kastenfff6d712012-01-12 16:38:12 -0800695status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696{
697 // check calling permissions
698 if (!settingsAllowed()) {
699 return PERMISSION_DENIED;
700 }
701
Glenn Kasten263709e2012-01-06 08:40:01 -0800702 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700703 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000704 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 return BAD_VALUE;
706 }
707
Eric Laurent93575202011-01-18 18:39:02 -0800708 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 mStreamTypes[stream].mute = muted;
710 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
711 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
712
713 return NO_ERROR;
714}
715
Glenn Kastenfff6d712012-01-12 16:38:12 -0800716float AudioFlinger::streamVolume(audio_stream_type_t stream, int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717{
Glenn Kasten263709e2012-01-06 08:40:01 -0800718 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719 return 0.0f;
720 }
721
722 AutoMutex lock(mLock);
723 float volume;
724 if (output) {
725 PlaybackThread *thread = checkPlaybackThread_l(output);
726 if (thread == NULL) {
727 return 0.0f;
728 }
729 volume = thread->streamVolume(stream);
730 } else {
731 volume = mStreamTypes[stream].volume;
732 }
733
734 return volume;
735}
736
Glenn Kastenfff6d712012-01-12 16:38:12 -0800737bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738{
Glenn Kasten263709e2012-01-06 08:40:01 -0800739 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740 return true;
741 }
742
743 return mStreamTypes[stream].mute;
744}
745
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
747{
748 status_t result;
749
Steve Block3856b092011-10-20 11:56:00 +0100750 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700751 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
752 // check calling permissions
753 if (!settingsAllowed()) {
754 return PERMISSION_DENIED;
755 }
756
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757 // ioHandle == 0 means the parameters are global to the audio hardware interface
758 if (ioHandle == 0) {
759 AutoMutex lock(mHardwareLock);
760 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700761 status_t final_result = NO_ERROR;
762 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
763 audio_hw_device_t *dev = mAudioHwDevs[i];
764 result = dev->set_parameters(dev, keyValuePairs.string());
765 final_result = result ?: final_result;
766 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700767 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700768 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
769 AudioParameter param = AudioParameter(keyValuePairs);
770 String8 value;
771 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
772 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700773 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
774 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700775 for (size_t i = 0; i < mRecordThreads.size(); i++) {
776 sp<RecordThread> thread = mRecordThreads.valueAt(i);
777 RecordThread::RecordTrack *track = thread->track();
778 if (track != NULL) {
779 audio_devices_t device = (audio_devices_t)(
780 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700781 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700782 thread->setEffectSuspended(FX_IID_AEC,
783 suspend,
784 track->sessionId());
785 thread->setEffectSuspended(FX_IID_NS,
786 suspend,
787 track->sessionId());
788 }
789 }
Eric Laurentbee53372011-08-29 12:42:48 -0700790 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700791 }
792 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700793 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794 }
795
796 // hold a strong ref on thread in case closeOutput() or closeInput() is called
797 // and the thread is exited once the lock is released
798 sp<ThreadBase> thread;
799 {
800 Mutex::Autolock _l(mLock);
801 thread = checkPlaybackThread_l(ioHandle);
802 if (thread == NULL) {
803 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800804 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700805 // indicate output device change to all input threads for pre processing
806 AudioParameter param = AudioParameter(keyValuePairs);
807 int value;
808 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
809 for (size_t i = 0; i < mRecordThreads.size(); i++) {
810 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
811 }
812 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 }
814 }
815 if (thread != NULL) {
816 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return result;
818 }
819 return BAD_VALUE;
820}
821
822String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
823{
Steve Block3856b092011-10-20 11:56:00 +0100824// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
826
827 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700828 String8 out_s8;
829
Dima Zavin799a70e2011-04-18 16:57:27 -0700830 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
831 audio_hw_device_t *dev = mAudioHwDevs[i];
832 char *s = dev->get_parameters(dev, keys.string());
833 out_s8 += String8(s);
834 free(s);
835 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700836 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837 }
838
839 Mutex::Autolock _l(mLock);
840
841 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
842 if (playbackThread != NULL) {
843 return playbackThread->getParameters(keys);
844 }
845 RecordThread *recordThread = checkRecordThread_l(ioHandle);
846 if (recordThread != NULL) {
847 return recordThread->getParameters(keys);
848 }
849 return String8("");
850}
851
Glenn Kasten58f30212012-01-12 12:27:51 -0800852size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700853{
Eric Laurenta1884f92011-08-23 08:25:03 -0700854 status_t ret = initCheck();
855 if (ret != NO_ERROR) {
856 return 0;
857 }
858
Dima Zavin799a70e2011-04-18 16:57:27 -0700859 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700860}
861
862unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
863{
864 if (ioHandle == 0) {
865 return 0;
866 }
867
868 Mutex::Autolock _l(mLock);
869
870 RecordThread *recordThread = checkRecordThread_l(ioHandle);
871 if (recordThread != NULL) {
872 return recordThread->getInputFramesLost();
873 }
874 return 0;
875}
876
877status_t AudioFlinger::setVoiceVolume(float value)
878{
Eric Laurenta1884f92011-08-23 08:25:03 -0700879 status_t ret = initCheck();
880 if (ret != NO_ERROR) {
881 return ret;
882 }
883
Mathias Agopian65ab4712010-07-14 17:59:35 -0700884 // check calling permissions
885 if (!settingsAllowed()) {
886 return PERMISSION_DENIED;
887 }
888
889 AutoMutex lock(mHardwareLock);
890 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700891 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700892 mHardwareStatus = AUDIO_HW_IDLE;
893
894 return ret;
895}
896
897status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
898{
899 status_t status;
900
901 Mutex::Autolock _l(mLock);
902
903 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
904 if (playbackThread != NULL) {
905 return playbackThread->getRenderPosition(halFrames, dspFrames);
906 }
907
908 return BAD_VALUE;
909}
910
911void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
912{
913
914 Mutex::Autolock _l(mLock);
915
916 int pid = IPCThreadState::self()->getCallingPid();
917 if (mNotificationClients.indexOfKey(pid) < 0) {
918 sp<NotificationClient> notificationClient = new NotificationClient(this,
919 client,
920 pid);
Steve Block3856b092011-10-20 11:56:00 +0100921 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922
923 mNotificationClients.add(pid, notificationClient);
924
925 sp<IBinder> binder = client->asBinder();
926 binder->linkToDeath(notificationClient);
927
928 // the config change is always sent from playback or record threads to avoid deadlock
929 // with AudioSystem::gLock
930 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
931 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
932 }
933
934 for (size_t i = 0; i < mRecordThreads.size(); i++) {
935 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
936 }
937 }
938}
939
940void AudioFlinger::removeNotificationClient(pid_t pid)
941{
942 Mutex::Autolock _l(mLock);
943
944 int index = mNotificationClients.indexOfKey(pid);
945 if (index >= 0) {
946 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100947 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 mNotificationClients.removeItem(pid);
949 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700950
Steve Block3856b092011-10-20 11:56:00 +0100951 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700952 int num = mAudioSessionRefs.size();
953 bool removed = false;
954 for (int i = 0; i< num; i++) {
955 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100956 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700957 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100958 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700959 mAudioSessionRefs.removeAt(i);
960 delete ref;
961 removed = true;
962 i--;
963 num--;
964 }
965 }
966 if (removed) {
967 purgeStaleEffects_l();
968 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700969}
970
971// audioConfigChanged_l() must be called with AudioFlinger::mLock held
972void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
973{
974 size_t size = mNotificationClients.size();
975 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800976 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
977 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700978 }
979}
980
981// removeClient_l() must be called with AudioFlinger::mLock held
982void AudioFlinger::removeClient_l(pid_t pid)
983{
Steve Block3856b092011-10-20 11:56:00 +0100984 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700985 mClients.removeItem(pid);
986}
987
988
989// ----------------------------------------------------------------------------
990
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800991AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device,
992 type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800994 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800995 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
996 // mChannelMask
997 mChannelCount(0),
998 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
999 mParamStatus(NO_ERROR),
1000 mStandby(false), mId(id), mExiting(false),
1001 mDevice(device),
1002 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001003{
1004}
1005
1006AudioFlinger::ThreadBase::~ThreadBase()
1007{
1008 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001009 // do not lock the mutex in destructor
1010 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001011 if (mPowerManager != 0) {
1012 sp<IBinder> binder = mPowerManager->asBinder();
1013 binder->unlinkToDeath(mDeathRecipient);
1014 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015}
1016
1017void AudioFlinger::ThreadBase::exit()
1018{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001019 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020 // destroyed in the middle of requestExitAndWait()
1021 sp <ThreadBase> strongMe = this;
1022
Steve Block3856b092011-10-20 11:56:00 +01001023 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001024 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001025 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001026 mExiting = true;
1027 requestExit();
1028 mWaitWorkCV.signal();
1029 }
1030 requestExitAndWait();
1031}
1032
1033uint32_t AudioFlinger::ThreadBase::sampleRate() const
1034{
1035 return mSampleRate;
1036}
1037
1038int AudioFlinger::ThreadBase::channelCount() const
1039{
1040 return (int)mChannelCount;
1041}
1042
Glenn Kasten58f30212012-01-12 12:27:51 -08001043audio_format_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001044{
1045 return mFormat;
1046}
1047
1048size_t AudioFlinger::ThreadBase::frameCount() const
1049{
1050 return mFrameCount;
1051}
1052
1053status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1054{
1055 status_t status;
1056
Steve Block3856b092011-10-20 11:56:00 +01001057 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058 Mutex::Autolock _l(mLock);
1059
1060 mNewParameters.add(keyValuePairs);
1061 mWaitWorkCV.signal();
1062 // wait condition with timeout in case the thread loop has exited
1063 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001064 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065 status = mParamStatus;
1066 mWaitWorkCV.signal();
1067 } else {
1068 status = TIMED_OUT;
1069 }
1070 return status;
1071}
1072
1073void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1074{
1075 Mutex::Autolock _l(mLock);
1076 sendConfigEvent_l(event, param);
1077}
1078
1079// sendConfigEvent_l() must be called with ThreadBase::mLock held
1080void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1081{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001082 ConfigEvent configEvent;
1083 configEvent.mEvent = event;
1084 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001086 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087 mWaitWorkCV.signal();
1088}
1089
1090void AudioFlinger::ThreadBase::processConfigEvents()
1091{
1092 mLock.lock();
1093 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001094 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001095 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 mConfigEvents.removeAt(0);
1097 // release mLock before locking AudioFlinger mLock: lock order is always
1098 // AudioFlinger then ThreadBase to avoid cross deadlock
1099 mLock.unlock();
1100 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001101 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103 mLock.lock();
1104 }
1105 mLock.unlock();
1106}
1107
1108status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1109{
1110 const size_t SIZE = 256;
1111 char buffer[SIZE];
1112 String8 result;
1113
1114 bool locked = tryLock(mLock);
1115 if (!locked) {
1116 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1117 write(fd, buffer, strlen(buffer));
1118 }
1119
1120 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1121 result.append(buffer);
1122 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1123 result.append(buffer);
1124 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1125 result.append(buffer);
1126 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1127 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001128 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1129 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1131 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001132 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 result.append(buffer);
1134
1135 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1136 result.append(buffer);
1137 result.append(" Index Command");
1138 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1139 snprintf(buffer, SIZE, "\n %02d ", i);
1140 result.append(buffer);
1141 result.append(mNewParameters[i]);
1142 }
1143
1144 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1145 result.append(buffer);
1146 snprintf(buffer, SIZE, " Index event param\n");
1147 result.append(buffer);
1148 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001149 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150 result.append(buffer);
1151 }
1152 result.append("\n");
1153
1154 write(fd, result.string(), result.size());
1155
1156 if (locked) {
1157 mLock.unlock();
1158 }
1159 return NO_ERROR;
1160}
1161
Eric Laurent1d2bff02011-07-24 17:49:51 -07001162status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1163{
1164 const size_t SIZE = 256;
1165 char buffer[SIZE];
1166 String8 result;
1167
1168 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1169 write(fd, buffer, strlen(buffer));
1170
1171 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1172 sp<EffectChain> chain = mEffectChains[i];
1173 if (chain != 0) {
1174 chain->dump(fd, args);
1175 }
1176 }
1177 return NO_ERROR;
1178}
1179
Eric Laurentfeb0db62011-07-22 09:04:31 -07001180void AudioFlinger::ThreadBase::acquireWakeLock()
1181{
1182 Mutex::Autolock _l(mLock);
1183 acquireWakeLock_l();
1184}
1185
1186void AudioFlinger::ThreadBase::acquireWakeLock_l()
1187{
1188 if (mPowerManager == 0) {
1189 // use checkService() to avoid blocking if power service is not up yet
1190 sp<IBinder> binder =
1191 defaultServiceManager()->checkService(String16("power"));
1192 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001193 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001194 } else {
1195 mPowerManager = interface_cast<IPowerManager>(binder);
1196 binder->linkToDeath(mDeathRecipient);
1197 }
1198 }
1199 if (mPowerManager != 0) {
1200 sp<IBinder> binder = new BBinder();
1201 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1202 binder,
1203 String16(mName));
1204 if (status == NO_ERROR) {
1205 mWakeLockToken = binder;
1206 }
Steve Block3856b092011-10-20 11:56:00 +01001207 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001208 }
1209}
1210
1211void AudioFlinger::ThreadBase::releaseWakeLock()
1212{
1213 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001214 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001215}
1216
1217void AudioFlinger::ThreadBase::releaseWakeLock_l()
1218{
1219 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001220 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001221 if (mPowerManager != 0) {
1222 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1223 }
1224 mWakeLockToken.clear();
1225 }
1226}
1227
1228void AudioFlinger::ThreadBase::clearPowerManager()
1229{
1230 Mutex::Autolock _l(mLock);
1231 releaseWakeLock_l();
1232 mPowerManager.clear();
1233}
1234
1235void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1236{
1237 sp<ThreadBase> thread = mThread.promote();
1238 if (thread != 0) {
1239 thread->clearPowerManager();
1240 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001241 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001242}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001243
Eric Laurent59255e42011-07-27 19:49:51 -07001244void AudioFlinger::ThreadBase::setEffectSuspended(
1245 const effect_uuid_t *type, bool suspend, int sessionId)
1246{
1247 Mutex::Autolock _l(mLock);
1248 setEffectSuspended_l(type, suspend, sessionId);
1249}
1250
1251void AudioFlinger::ThreadBase::setEffectSuspended_l(
1252 const effect_uuid_t *type, bool suspend, int sessionId)
1253{
1254 sp<EffectChain> chain;
1255 chain = getEffectChain_l(sessionId);
1256 if (chain != 0) {
1257 if (type != NULL) {
1258 chain->setEffectSuspended_l(type, suspend);
1259 } else {
1260 chain->setEffectSuspendedAll_l(suspend);
1261 }
1262 }
1263
1264 updateSuspendedSessions_l(type, suspend, sessionId);
1265}
1266
1267void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1268{
1269 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1270 if (index < 0) {
1271 return;
1272 }
1273
1274 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1275 mSuspendedSessions.editValueAt(index);
1276
1277 for (size_t i = 0; i < sessionEffects.size(); i++) {
1278 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1279 for (int j = 0; j < desc->mRefCount; j++) {
1280 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1281 chain->setEffectSuspendedAll_l(true);
1282 } else {
Steve Block3856b092011-10-20 11:56:00 +01001283 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001284 desc->mType.timeLow);
1285 chain->setEffectSuspended_l(&desc->mType, true);
1286 }
1287 }
1288 }
1289}
1290
Eric Laurent59255e42011-07-27 19:49:51 -07001291void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1292 bool suspend,
1293 int sessionId)
1294{
1295 int index = mSuspendedSessions.indexOfKey(sessionId);
1296
1297 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1298
1299 if (suspend) {
1300 if (index >= 0) {
1301 sessionEffects = mSuspendedSessions.editValueAt(index);
1302 } else {
1303 mSuspendedSessions.add(sessionId, sessionEffects);
1304 }
1305 } else {
1306 if (index < 0) {
1307 return;
1308 }
1309 sessionEffects = mSuspendedSessions.editValueAt(index);
1310 }
1311
1312
1313 int key = EffectChain::kKeyForSuspendAll;
1314 if (type != NULL) {
1315 key = type->timeLow;
1316 }
1317 index = sessionEffects.indexOfKey(key);
1318
1319 sp <SuspendedSessionDesc> desc;
1320 if (suspend) {
1321 if (index >= 0) {
1322 desc = sessionEffects.valueAt(index);
1323 } else {
1324 desc = new SuspendedSessionDesc();
1325 if (type != NULL) {
1326 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1327 }
1328 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001329 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001330 }
1331 desc->mRefCount++;
1332 } else {
1333 if (index < 0) {
1334 return;
1335 }
1336 desc = sessionEffects.valueAt(index);
1337 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001338 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001339 sessionEffects.removeItemsAt(index);
1340 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001341 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001342 sessionId);
1343 mSuspendedSessions.removeItem(sessionId);
1344 }
1345 }
1346 }
1347 if (!sessionEffects.isEmpty()) {
1348 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1349 }
1350}
1351
1352void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1353 bool enabled,
1354 int sessionId)
1355{
1356 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001357 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1358}
Eric Laurent59255e42011-07-27 19:49:51 -07001359
Eric Laurenta85a74a2011-10-19 11:44:54 -07001360void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1361 bool enabled,
1362 int sessionId)
1363{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001364 if (mType != RECORD) {
1365 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1366 // another session. This gives the priority to well behaved effect control panels
1367 // and applications not using global effects.
1368 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1369 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1370 }
1371 }
Eric Laurent59255e42011-07-27 19:49:51 -07001372
1373 sp<EffectChain> chain = getEffectChain_l(sessionId);
1374 if (chain != 0) {
1375 chain->checkSuspendOnEffectEnabled(effect, enabled);
1376 }
1377}
1378
Mathias Agopian65ab4712010-07-14 17:59:35 -07001379// ----------------------------------------------------------------------------
1380
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001381AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1382 AudioStreamOut* output,
1383 int id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001384 uint32_t device,
1385 type_t type)
1386 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001387 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1388 // Assumes constructor is called by AudioFlinger with it's mLock held,
1389 // but it would be safer to explicitly pass initial masterMute as parameter
1390 mMasterMute(audioFlinger->masterMute_l()),
1391 // mStreamTypes[] initialized in constructor body
1392 mOutput(output),
1393 // Assumes constructor is called by AudioFlinger with it's mLock held,
1394 // but it would be safer to explicitly pass initial masterVolume as parameter
1395 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001396 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001397{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001398 snprintf(mName, kNameLength, "AudioOut_%d", id);
1399
Mathias Agopian65ab4712010-07-14 17:59:35 -07001400 readOutputParameters();
1401
Glenn Kasten263709e2012-01-06 08:40:01 -08001402 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001403 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1404 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1405 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1407 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001408 // initialized by stream_type_t default constructor
1409 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001410 }
1411}
1412
1413AudioFlinger::PlaybackThread::~PlaybackThread()
1414{
1415 delete [] mMixBuffer;
1416}
1417
1418status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1419{
1420 dumpInternals(fd, args);
1421 dumpTracks(fd, args);
1422 dumpEffectChains(fd, args);
1423 return NO_ERROR;
1424}
1425
1426status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1427{
1428 const size_t SIZE = 256;
1429 char buffer[SIZE];
1430 String8 result;
1431
1432 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1433 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001434 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 -07001435 for (size_t i = 0; i < mTracks.size(); ++i) {
1436 sp<Track> track = mTracks[i];
1437 if (track != 0) {
1438 track->dump(buffer, SIZE);
1439 result.append(buffer);
1440 }
1441 }
1442
1443 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1444 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001445 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 -07001446 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1447 wp<Track> wTrack = mActiveTracks[i];
1448 if (wTrack != 0) {
1449 sp<Track> track = wTrack.promote();
1450 if (track != 0) {
1451 track->dump(buffer, SIZE);
1452 result.append(buffer);
1453 }
1454 }
1455 }
1456 write(fd, result.string(), result.size());
1457 return NO_ERROR;
1458}
1459
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1461{
1462 const size_t SIZE = 256;
1463 char buffer[SIZE];
1464 String8 result;
1465
1466 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1467 result.append(buffer);
1468 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1469 result.append(buffer);
1470 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1471 result.append(buffer);
1472 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1473 result.append(buffer);
1474 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1475 result.append(buffer);
1476 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1477 result.append(buffer);
1478 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1479 result.append(buffer);
1480 write(fd, result.string(), result.size());
1481
1482 dumpBase(fd, args);
1483
1484 return NO_ERROR;
1485}
1486
1487// Thread virtuals
1488status_t AudioFlinger::PlaybackThread::readyToRun()
1489{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001490 status_t status = initCheck();
1491 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001492 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001493 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001494 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001496 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497}
1498
1499void AudioFlinger::PlaybackThread::onFirstRef()
1500{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001501 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502}
1503
1504// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1505sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1506 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001507 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001509 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001510 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001511 int frameCount,
1512 const sp<IMemory>& sharedBuffer,
1513 int sessionId,
1514 status_t *status)
1515{
1516 sp<Track> track;
1517 status_t lStatus;
1518
1519 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001520 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1521 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001522 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001523 "for output %p with format %d",
1524 sampleRate, format, channelMask, mOutput, mFormat);
1525 lStatus = BAD_VALUE;
1526 goto Exit;
1527 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001528 }
1529 } else {
1530 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1531 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001532 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533 lStatus = BAD_VALUE;
1534 goto Exit;
1535 }
1536 }
1537
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001538 lStatus = initCheck();
1539 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001540 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541 goto Exit;
1542 }
1543
1544 { // scope for mLock
1545 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001546
1547 // all tracks in same audio session must share the same routing strategy otherwise
1548 // conflicts will happen when tracks are moved from one output to another by audio policy
1549 // manager
1550 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001551 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001552 for (size_t i = 0; i < mTracks.size(); ++i) {
1553 sp<Track> t = mTracks[i];
1554 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001555 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1556 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001557 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001558 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001559 lStatus = BAD_VALUE;
1560 goto Exit;
1561 }
1562 }
1563 }
1564
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001566 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 if (track->getCblk() == NULL || track->name() < 0) {
1568 lStatus = NO_MEMORY;
1569 goto Exit;
1570 }
1571 mTracks.add(track);
1572
1573 sp<EffectChain> chain = getEffectChain_l(sessionId);
1574 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001575 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001577 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001578 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001580
1581 // invalidate track immediately if the stream type was moved to another thread since
1582 // createTrack() was called by the client process.
1583 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001584 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001585 this, streamType);
1586 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1587 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588 }
1589 lStatus = NO_ERROR;
1590
1591Exit:
1592 if(status) {
1593 *status = lStatus;
1594 }
1595 return track;
1596}
1597
1598uint32_t AudioFlinger::PlaybackThread::latency() const
1599{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001600 Mutex::Autolock _l(mLock);
1601 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001602 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001603 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604 return 0;
1605 }
1606}
1607
1608status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1609{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 mMasterVolume = value;
1611 return NO_ERROR;
1612}
1613
1614status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1615{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616 mMasterMute = muted;
1617 return NO_ERROR;
1618}
1619
1620float AudioFlinger::PlaybackThread::masterVolume() const
1621{
1622 return mMasterVolume;
1623}
1624
1625bool AudioFlinger::PlaybackThread::masterMute() const
1626{
1627 return mMasterMute;
1628}
1629
Glenn Kastenfff6d712012-01-12 16:38:12 -08001630status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001632 mStreamTypes[stream].volume = value;
1633 return NO_ERROR;
1634}
1635
Glenn Kastenfff6d712012-01-12 16:38:12 -08001636status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638 mStreamTypes[stream].mute = muted;
1639 return NO_ERROR;
1640}
1641
Glenn Kastenfff6d712012-01-12 16:38:12 -08001642float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643{
1644 return mStreamTypes[stream].volume;
1645}
1646
Glenn Kastenfff6d712012-01-12 16:38:12 -08001647bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001648{
1649 return mStreamTypes[stream].mute;
1650}
1651
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652// addTrack_l() must be called with ThreadBase::mLock held
1653status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1654{
1655 status_t status = ALREADY_EXISTS;
1656
1657 // set retry count for buffer fill
1658 track->mRetryCount = kMaxTrackStartupRetries;
1659 if (mActiveTracks.indexOf(track) < 0) {
1660 // the track is newly added, make sure it fills up all its
1661 // buffers before playing. This is to ensure the client will
1662 // effectively get the latency it requested.
1663 track->mFillingUpStatus = Track::FS_FILLING;
1664 track->mResetDone = false;
1665 mActiveTracks.add(track);
1666 if (track->mainBuffer() != mMixBuffer) {
1667 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1668 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001669 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001670 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671 }
1672 }
1673
1674 status = NO_ERROR;
1675 }
1676
Steve Block3856b092011-10-20 11:56:00 +01001677 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678 mWaitWorkCV.broadcast();
1679
1680 return status;
1681}
1682
1683// destroyTrack_l() must be called with ThreadBase::mLock held
1684void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1685{
1686 track->mState = TrackBase::TERMINATED;
1687 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001688 removeTrack_l(track);
1689 }
1690}
1691
1692void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1693{
1694 mTracks.remove(track);
1695 deleteTrackName_l(track->name());
1696 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1697 if (chain != 0) {
1698 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699 }
1700}
1701
1702String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1703{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001704 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001705 char *s;
1706
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001707 Mutex::Autolock _l(mLock);
1708 if (initCheck() != NO_ERROR) {
1709 return out_s8;
1710 }
1711
Dima Zavin799a70e2011-04-18 16:57:27 -07001712 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001713 out_s8 = String8(s);
1714 free(s);
1715 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716}
1717
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001718// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1720 AudioSystem::OutputDescriptor desc;
1721 void *param2 = 0;
1722
Steve Block3856b092011-10-20 11:56:00 +01001723 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724
1725 switch (event) {
1726 case AudioSystem::OUTPUT_OPENED:
1727 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001728 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729 desc.samplingRate = mSampleRate;
1730 desc.format = mFormat;
1731 desc.frameCount = mFrameCount;
1732 desc.latency = latency();
1733 param2 = &desc;
1734 break;
1735
1736 case AudioSystem::STREAM_CONFIG_CHANGED:
1737 param2 = &param;
1738 case AudioSystem::OUTPUT_CLOSED:
1739 default:
1740 break;
1741 }
1742 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1743}
1744
1745void AudioFlinger::PlaybackThread::readOutputParameters()
1746{
Dima Zavin799a70e2011-04-18 16:57:27 -07001747 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001748 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1749 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001750 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001751 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001752 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753
1754 // FIXME - Current mixer implementation only supports stereo output: Always
1755 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001756 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757 mMixBuffer = new int16_t[mFrameCount * 2];
1758 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1759
Eric Laurentde070132010-07-13 04:45:46 -07001760 // force reconfiguration of effect chains and engines to take new buffer size and audio
1761 // parameters into account
1762 // Note that mLock is not held when readOutputParameters() is called from the constructor
1763 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1764 // matter.
1765 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1766 Vector< sp<EffectChain> > effectChains = mEffectChains;
1767 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001768 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001769 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770}
1771
1772status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1773{
1774 if (halFrames == 0 || dspFrames == 0) {
1775 return BAD_VALUE;
1776 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001777 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001778 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779 return INVALID_OPERATION;
1780 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001781 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782
Dima Zavin799a70e2011-04-18 16:57:27 -07001783 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784}
1785
Eric Laurent39e94f82010-07-28 01:32:47 -07001786uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787{
1788 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001789 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001790 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001791 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792 }
1793
1794 for (size_t i = 0; i < mTracks.size(); ++i) {
1795 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001796 if (sessionId == track->sessionId() &&
1797 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001798 result |= TRACK_SESSION;
1799 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800 }
1801 }
1802
Eric Laurent39e94f82010-07-28 01:32:47 -07001803 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804}
1805
Eric Laurentde070132010-07-13 04:45:46 -07001806uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1807{
Dima Zavinfce7a472011-04-19 22:30:36 -07001808 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001809 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001810 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1811 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001812 }
1813 for (size_t i = 0; i < mTracks.size(); i++) {
1814 sp<Track> track = mTracks[i];
1815 if (sessionId == track->sessionId() &&
1816 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001817 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001818 }
1819 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001820 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001821}
1822
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823
Glenn Kastenaed850d2012-01-26 09:46:34 -08001824AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001825{
1826 Mutex::Autolock _l(mLock);
1827 return mOutput;
1828}
1829
1830AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1831{
1832 Mutex::Autolock _l(mLock);
1833 AudioStreamOut *output = mOutput;
1834 mOutput = NULL;
1835 return output;
1836}
1837
1838// this method must always be called either with ThreadBase mLock held or inside the thread loop
1839audio_stream_t* AudioFlinger::PlaybackThread::stream()
1840{
1841 if (mOutput == NULL) {
1842 return NULL;
1843 }
1844 return &mOutput->stream->common;
1845}
1846
Eric Laurent162b40b2011-12-05 09:47:19 -08001847uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1848{
1849 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1850 // decoding and transfer time. So sleeping for half of the latency would likely cause
1851 // underruns
1852 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1853 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1854 } else {
1855 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1856 }
1857}
1858
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859// ----------------------------------------------------------------------------
1860
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001861AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1862 int id, uint32_t device, type_t type)
1863 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001864 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1865 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867 // FIXME - Current mixer implementation only supports stereo output
1868 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001869 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870 }
1871}
1872
1873AudioFlinger::MixerThread::~MixerThread()
1874{
1875 delete mAudioMixer;
1876}
1877
1878bool AudioFlinger::MixerThread::threadLoop()
1879{
1880 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001881 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882 nsecs_t standbyTime = systemTime();
1883 size_t mixBufferSize = mFrameCount * mFrameSize;
1884 // FIXME: Relaxed timing because of a certain device that can't meet latency
1885 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001886 // increase threshold again due to low power audio mode. The way this warning threshold is
1887 // calculated and its usefulness should be reconsidered anyway.
1888 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889 nsecs_t lastWarning = 0;
1890 bool longStandbyExit = false;
1891 uint32_t activeSleepTime = activeSleepTimeUs();
1892 uint32_t idleSleepTime = idleSleepTimeUs();
1893 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001894 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001896#ifdef DEBUG_CPU_USAGE
1897 ThreadCpuUsage cpu;
1898 const CentralTendencyStatistics& stats = cpu.statistics();
1899#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900
Eric Laurentfeb0db62011-07-22 09:04:31 -07001901 acquireWakeLock();
1902
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903 while (!exitPending())
1904 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001905#ifdef DEBUG_CPU_USAGE
1906 cpu.sampleAndEnable();
1907 unsigned n = stats.n();
1908 // cpu.elapsed() is expensive, so don't call it every loop
1909 if ((n & 127) == 1) {
1910 long long elapsed = cpu.elapsed();
1911 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1912 double perLoop = elapsed / (double) n;
1913 double perLoop100 = perLoop * 0.01;
1914 double mean = stats.mean();
1915 double stddev = stats.stddev();
1916 double minimum = stats.minimum();
1917 double maximum = stats.maximum();
1918 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001919 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 -07001920 elapsed * .000000001, n, perLoop * .000001,
1921 mean * .001,
1922 stddev * .001,
1923 minimum * .001,
1924 maximum * .001,
1925 mean / perLoop100,
1926 stddev / perLoop100,
1927 minimum / perLoop100,
1928 maximum / perLoop100);
1929 }
1930 }
1931#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 processConfigEvents();
1933
1934 mixerStatus = MIXER_IDLE;
1935 { // scope for mLock
1936
1937 Mutex::Autolock _l(mLock);
1938
1939 if (checkForNewParameters_l()) {
1940 mixBufferSize = mFrameCount * mFrameSize;
1941 // FIXME: Relaxed timing because of a certain device that can't meet latency
1942 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001943 // increase threshold again due to low power audio mode. The way this warning
1944 // threshold is calculated and its usefulness should be reconsidered anyway.
1945 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 activeSleepTime = activeSleepTimeUs();
1947 idleSleepTime = idleSleepTimeUs();
1948 }
1949
1950 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1951
1952 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001953 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1954 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001956 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001957 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958 mStandby = true;
1959 mBytesWritten = 0;
1960 }
1961
1962 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1963 // we're about to wait, flush the binder command buffer
1964 IPCThreadState::self()->flushCommands();
1965
1966 if (exitPending()) break;
1967
Eric Laurentfeb0db62011-07-22 09:04:31 -07001968 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001969 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001970 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001972 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001973 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974
Eric Laurent27741442012-01-17 19:20:12 -08001975 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001976 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001977 char value[PROPERTY_VALUE_MAX];
1978 property_get("ro.audio.silent", value, "0");
1979 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001980 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981 setMasterMute(true);
1982 }
1983 }
1984
1985 standbyTime = systemTime() + kStandbyTimeInNsecs;
1986 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001987 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 continue;
1989 }
1990 }
1991
1992 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1993
1994 // prevent any changes in effect chain list and in each effect chain
1995 // during mixing and effect process as the audio buffers could be deleted
1996 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001997 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001998 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999
Glenn Kastenf6b16782011-12-15 09:51:17 -08002000 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001 // mix buffers...
2002 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002003 // increase sleep time progressively when application underrun condition clears.
2004 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2005 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2006 // such that we would underrun the audio HAL.
2007 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002008 sleepTimeShift--;
2009 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002010 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 standbyTime = systemTime() + kStandbyTimeInNsecs;
2012 //TODO: delay standby when effects have a tail
2013 } else {
2014 // If no tracks are ready, sleep once for the duration of an output
2015 // buffer size, then write 0s to the output
2016 if (sleepTime == 0) {
2017 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002018 sleepTime = activeSleepTime >> sleepTimeShift;
2019 if (sleepTime < kMinThreadSleepTimeUs) {
2020 sleepTime = kMinThreadSleepTimeUs;
2021 }
2022 // reduce sleep time in case of consecutive application underruns to avoid
2023 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2024 // duration we would end up writing less data than needed by the audio HAL if
2025 // the condition persists.
2026 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2027 sleepTimeShift++;
2028 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029 } else {
2030 sleepTime = idleSleepTime;
2031 }
2032 } else if (mBytesWritten != 0 ||
2033 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2034 memset (mMixBuffer, 0, mixBufferSize);
2035 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002036 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 }
2038 // TODO add standby time extension fct of effect tail
2039 }
2040
2041 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002042 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002043 }
2044 // sleepTime == 0 means we must write to audio hardware
2045 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002046 for (size_t i = 0; i < effectChains.size(); i ++) {
2047 effectChains[i]->process_l();
2048 }
2049 // enable changes in effect chain
2050 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051 mLastWriteTime = systemTime();
2052 mInWrite = true;
2053 mBytesWritten += mixBufferSize;
2054
Dima Zavin799a70e2011-04-18 16:57:27 -07002055 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2057 mNumWrites++;
2058 mInWrite = false;
2059 nsecs_t now = systemTime();
2060 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002061 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002063 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002064 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065 ns2ms(delta), mNumDelayedWrites, this);
2066 lastWarning = now;
2067 }
2068 if (mStandby) {
2069 longStandbyExit = true;
2070 }
2071 }
2072 mStandby = false;
2073 } else {
2074 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002075 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002076 usleep(sleepTime);
2077 }
2078
2079 // finally let go of all our tracks, without the lock held
2080 // since we can't guarantee the destructors won't acquire that
2081 // same lock.
2082 tracksToRemove.clear();
2083
2084 // Effect chains will be actually deleted here if they were removed from
2085 // mEffectChains list during mixing or effects processing
2086 effectChains.clear();
2087 }
2088
2089 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002090 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091 }
2092
Eric Laurentfeb0db62011-07-22 09:04:31 -07002093 releaseWakeLock();
2094
Steve Block3856b092011-10-20 11:56:00 +01002095 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096 return false;
2097}
2098
2099// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002100AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2101 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102{
2103
Glenn Kasten29c23c32012-01-26 13:37:52 -08002104 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 // find out which tracks need to be processed
2106 size_t count = activeTracks.size();
2107 size_t mixedTracks = 0;
2108 size_t tracksWithEffect = 0;
2109
2110 float masterVolume = mMasterVolume;
2111 bool masterMute = mMasterMute;
2112
Eric Laurent571d49c2010-08-11 05:20:11 -07002113 if (masterMute) {
2114 masterVolume = 0;
2115 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002116 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002117 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002118 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002119 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002120 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121 masterVolume = (float)((v + (1 << 23)) >> 24);
2122 chain.clear();
2123 }
2124
2125 for (size_t i=0 ; i<count ; i++) {
2126 sp<Track> t = activeTracks[i].promote();
2127 if (t == 0) continue;
2128
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002129 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130 Track* const track = t.get();
2131 audio_track_cblk_t* cblk = track->cblk();
2132
2133 // The first time a track is added we wait
2134 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002135 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002136 // make sure that we have enough frames to mix one full buffer.
2137 // enforce this condition only once to enable draining the buffer in case the client
2138 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002139 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002140 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002141 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002142 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002143 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002144 if (t->sampleRate() == (int)mSampleRate) {
2145 minFrames = mFrameCount;
2146 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002147 // +1 for rounding and +1 for additional sample needed for interpolation
2148 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2149 // add frames already consumed but not yet released by the resampler
2150 // because cblk->framesReady() will include these frames
2151 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2152 // the minimum track buffer size is normally twice the number of frames necessary
2153 // to fill one buffer and the resampler should not leave more than one buffer worth
2154 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002155 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002156 }
2157 }
2158 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159 !track->isPaused() && !track->isTerminated())
2160 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002161 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002162
2163 mixedTracks++;
2164
2165 // track->mainBuffer() != mMixBuffer means there is an effect chain
2166 // connected to the track
2167 chain.clear();
2168 if (track->mainBuffer() != mMixBuffer) {
2169 chain = getEffectChain_l(track->sessionId());
2170 // Delegate volume control to effect in track effect chain if needed
2171 if (chain != 0) {
2172 tracksWithEffect++;
2173 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002174 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002175 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 }
2177 }
2178
2179
2180 int param = AudioMixer::VOLUME;
2181 if (track->mFillingUpStatus == Track::FS_FILLED) {
2182 // no ramp for the first volume setting
2183 track->mFillingUpStatus = Track::FS_ACTIVE;
2184 if (track->mState == TrackBase::RESUMING) {
2185 track->mState = TrackBase::ACTIVE;
2186 param = AudioMixer::RAMP_VOLUME;
2187 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002188 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189 } else if (cblk->server != 0) {
2190 // If the track is stopped before the first frame was mixed,
2191 // do not apply ramp
2192 param = AudioMixer::RAMP_VOLUME;
2193 }
2194
2195 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002196 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002197 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002198 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002199 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002200 if (track->isPausing()) {
2201 track->setPaused();
2202 }
2203 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002204
Mathias Agopian65ab4712010-07-14 17:59:35 -07002205 // read original volumes with volume control
2206 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002208 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002209 vl = vlr & 0xFFFF;
2210 vr = vlr >> 16;
2211 // track volumes come from shared memory, so can't be trusted and must be clamped
2212 if (vl > MAX_GAIN_INT) {
2213 ALOGV("Track left volume out of range: %04X", vl);
2214 vl = MAX_GAIN_INT;
2215 }
2216 if (vr > MAX_GAIN_INT) {
2217 ALOGV("Track right volume out of range: %04X", vr);
2218 vr = MAX_GAIN_INT;
2219 }
2220 // now apply the master volume and stream type volume
2221 vl = (uint32_t)(v * vl) << 12;
2222 vr = (uint32_t)(v * vr) << 12;
2223 // assuming master volume and stream type volume each go up to 1.0,
2224 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225
Glenn Kasten05632a52012-01-03 14:22:33 -08002226 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2227 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002228 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002229 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002230 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002231 }
2232 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002234 // Delegate volume control to effect in track effect chain if needed
2235 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2236 // Do not ramp volume if volume is controlled by effect
2237 param = AudioMixer::VOLUME;
2238 track->mHasVolumeController = true;
2239 } else {
2240 // force no volume ramp when volume controller was just disabled or removed
2241 // from effect chain to avoid volume spike
2242 if (track->mHasVolumeController) {
2243 param = AudioMixer::VOLUME;
2244 }
2245 track->mHasVolumeController = false;
2246 }
2247
2248 // Convert volumes from 8.24 to 4.12 format
2249 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002250 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002251 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2252 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2253 left = int16_t(v_clamped);
2254 v_clamped = (vr + (1 << 11)) >> 12;
2255 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2256 right = int16_t(v_clamped);
2257
2258 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2259 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002260
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002262 mAudioMixer->setBufferProvider(name, track);
2263 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002264
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002265 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2266 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2267 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002269 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 AudioMixer::TRACK,
2271 AudioMixer::FORMAT, (void *)track->format());
2272 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002273 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002275 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002277 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278 AudioMixer::RESAMPLE,
2279 AudioMixer::SAMPLE_RATE,
2280 (void *)(cblk->sampleRate));
2281 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002282 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002283 AudioMixer::TRACK,
2284 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2285 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002286 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287 AudioMixer::TRACK,
2288 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2289
2290 // reset retry count
2291 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002292 // If one track is ready, set the mixer ready if:
2293 // - the mixer was not ready during previous round OR
2294 // - no other track is not ready
2295 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2296 mixerStatus != MIXER_TRACKS_ENABLED) {
2297 mixerStatus = MIXER_TRACKS_READY;
2298 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002299 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002300 //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 -07002301 if (track->isStopped()) {
2302 track->reset();
2303 }
2304 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2305 // We have consumed all the buffers of this track.
2306 // Remove it from the list of active tracks.
2307 tracksToRemove->add(track);
2308 } else {
2309 // No buffers for this track. Give it a few chances to
2310 // fill a buffer, then remove it from active list.
2311 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002312 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002313 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002314 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002315 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002316 // If one track is not ready, mark the mixer also not ready if:
2317 // - the mixer was ready during previous round OR
2318 // - no other track is ready
2319 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2320 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002321 mixerStatus = MIXER_TRACKS_ENABLED;
2322 }
2323 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002324 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002325 }
2326 }
2327
2328 // remove all the tracks that need to be...
2329 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002330 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331 for (size_t i=0 ; i<count ; i++) {
2332 const sp<Track>& track = tracksToRemove->itemAt(i);
2333 mActiveTracks.remove(track);
2334 if (track->mainBuffer() != mMixBuffer) {
2335 chain = getEffectChain_l(track->sessionId());
2336 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002337 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002338 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002339 }
2340 }
2341 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002342 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002343 }
2344 }
2345 }
2346
2347 // mix buffer must be cleared if all tracks are connected to an
2348 // effect chain as in this case the mixer will not write to
2349 // mix buffer and track effects will accumulate into it
2350 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2351 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2352 }
2353
Eric Laurent27741442012-01-17 19:20:12 -08002354 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002355 return mixerStatus;
2356}
2357
Glenn Kastenfff6d712012-01-12 16:38:12 -08002358void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359{
Steve Block3856b092011-10-20 11:56:00 +01002360 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002361 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002362 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002363
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364 size_t size = mTracks.size();
2365 for (size_t i = 0; i < size; i++) {
2366 sp<Track> t = mTracks[i];
2367 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002368 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002369 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002370 }
2371 }
2372}
2373
Glenn Kastenfff6d712012-01-12 16:38:12 -08002374void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002375{
Steve Block3856b092011-10-20 11:56:00 +01002376 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002377 this, streamType, valid);
2378 Mutex::Autolock _l(mLock);
2379
2380 mStreamTypes[streamType].valid = valid;
2381}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382
2383// getTrackName_l() must be called with ThreadBase::mLock held
2384int AudioFlinger::MixerThread::getTrackName_l()
2385{
2386 return mAudioMixer->getTrackName();
2387}
2388
2389// deleteTrackName_l() must be called with ThreadBase::mLock held
2390void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2391{
Steve Block3856b092011-10-20 11:56:00 +01002392 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393 mAudioMixer->deleteTrackName(name);
2394}
2395
2396// checkForNewParameters_l() must be called with ThreadBase::mLock held
2397bool AudioFlinger::MixerThread::checkForNewParameters_l()
2398{
2399 bool reconfig = false;
2400
2401 while (!mNewParameters.isEmpty()) {
2402 status_t status = NO_ERROR;
2403 String8 keyValuePair = mNewParameters[0];
2404 AudioParameter param = AudioParameter(keyValuePair);
2405 int value;
2406
2407 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2408 reconfig = true;
2409 }
2410 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002411 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002412 status = BAD_VALUE;
2413 } else {
2414 reconfig = true;
2415 }
2416 }
2417 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002418 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 status = BAD_VALUE;
2420 } else {
2421 reconfig = true;
2422 }
2423 }
2424 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2425 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002426 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427 // if frame count is changed after track creation
2428 if (!mTracks.isEmpty()) {
2429 status = INVALID_OPERATION;
2430 } else {
2431 reconfig = true;
2432 }
2433 }
2434 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002435 // when changing the audio output device, call addBatteryData to notify
2436 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002437 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002438 uint32_t params = 0;
2439 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002440 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002441 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2442 }
2443
2444 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002445 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002446 // check if any other device (except speaker) is on
2447 if (value & deviceWithoutSpeaker ) {
2448 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2449 }
2450
2451 if (params != 0) {
2452 addBatteryData(params);
2453 }
2454 }
2455
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 // forward device change to effects that have requested to be
2457 // aware of attached audio device.
2458 mDevice = (uint32_t)value;
2459 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002460 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461 }
2462 }
2463
2464 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002465 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002466 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002468 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002469 mStandby = true;
2470 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002471 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002472 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473 }
2474 if (status == NO_ERROR && reconfig) {
2475 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002476 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2477 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478 readOutputParameters();
2479 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2480 for (size_t i = 0; i < mTracks.size() ; i++) {
2481 int name = getTrackName_l();
2482 if (name < 0) break;
2483 mTracks[i]->mName = name;
2484 // limit track sample rate to 2 x new output sample rate
2485 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2486 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2487 }
2488 }
2489 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2490 }
2491 }
2492
2493 mNewParameters.removeAt(0);
2494
2495 mParamStatus = status;
2496 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002497 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2498 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002499 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500 }
2501 return reconfig;
2502}
2503
2504status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2505{
2506 const size_t SIZE = 256;
2507 char buffer[SIZE];
2508 String8 result;
2509
2510 PlaybackThread::dumpInternals(fd, args);
2511
2512 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2513 result.append(buffer);
2514 write(fd, result.string(), result.size());
2515 return NO_ERROR;
2516}
2517
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2519{
Eric Laurent60e18242010-07-29 06:50:24 -07002520 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521}
2522
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002523uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2524{
2525 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2526}
2527
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002529AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002530 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002531 // mLeftVolFloat, mRightVolFloat
2532 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002533{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534}
2535
2536AudioFlinger::DirectOutputThread::~DirectOutputThread()
2537{
2538}
2539
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540static inline
2541int32_t mul(int16_t in, int16_t v)
2542{
2543#if defined(__arm__) && !defined(__thumb__)
2544 int32_t out;
2545 asm( "smulbb %[out], %[in], %[v] \n"
2546 : [out]"=r"(out)
2547 : [in]"%r"(in), [v]"r"(v)
2548 : );
2549 return out;
2550#else
2551 return in * int32_t(v);
2552#endif
2553}
2554
2555void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2556{
2557 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002558 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559 return;
2560 }
2561
2562 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002563 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002564 size_t count = mFrameCount * mChannelCount;
2565 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2566 int16_t *dst = mMixBuffer + count-1;
2567 while(count--) {
2568 *dst-- = (int16_t)(*src--^0x80) << 8;
2569 }
2570 }
2571
2572 size_t frameCount = mFrameCount;
2573 int16_t *out = mMixBuffer;
2574 if (ramp) {
2575 if (mChannelCount == 1) {
2576 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2577 int32_t vlInc = d / (int32_t)frameCount;
2578 int32_t vl = ((int32_t)mLeftVolShort << 16);
2579 do {
2580 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2581 out++;
2582 vl += vlInc;
2583 } while (--frameCount);
2584
2585 } else {
2586 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2587 int32_t vlInc = d / (int32_t)frameCount;
2588 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2589 int32_t vrInc = d / (int32_t)frameCount;
2590 int32_t vl = ((int32_t)mLeftVolShort << 16);
2591 int32_t vr = ((int32_t)mRightVolShort << 16);
2592 do {
2593 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2594 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2595 out += 2;
2596 vl += vlInc;
2597 vr += vrInc;
2598 } while (--frameCount);
2599 }
2600 } else {
2601 if (mChannelCount == 1) {
2602 do {
2603 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2604 out++;
2605 } while (--frameCount);
2606 } else {
2607 do {
2608 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2609 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2610 out += 2;
2611 } while (--frameCount);
2612 }
2613 }
2614
2615 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002616 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617 size_t count = mFrameCount * mChannelCount;
2618 int16_t *src = mMixBuffer;
2619 uint8_t *dst = (uint8_t *)mMixBuffer;
2620 while(count--) {
2621 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2622 }
2623 }
2624
2625 mLeftVolShort = leftVol;
2626 mRightVolShort = rightVol;
2627}
2628
2629bool AudioFlinger::DirectOutputThread::threadLoop()
2630{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002631 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632 sp<Track> trackToRemove;
2633 sp<Track> activeTrack;
2634 nsecs_t standbyTime = systemTime();
2635 int8_t *curBuf;
2636 size_t mixBufferSize = mFrameCount*mFrameSize;
2637 uint32_t activeSleepTime = activeSleepTimeUs();
2638 uint32_t idleSleepTime = idleSleepTimeUs();
2639 uint32_t sleepTime = idleSleepTime;
2640 // use shorter standby delay as on normal output to release
2641 // hardware resources as soon as possible
2642 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2643
Eric Laurentfeb0db62011-07-22 09:04:31 -07002644 acquireWakeLock();
2645
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646 while (!exitPending())
2647 {
2648 bool rampVolume;
2649 uint16_t leftVol;
2650 uint16_t rightVol;
2651 Vector< sp<EffectChain> > effectChains;
2652
2653 processConfigEvents();
2654
2655 mixerStatus = MIXER_IDLE;
2656
2657 { // scope for the mLock
2658
2659 Mutex::Autolock _l(mLock);
2660
2661 if (checkForNewParameters_l()) {
2662 mixBufferSize = mFrameCount*mFrameSize;
2663 activeSleepTime = activeSleepTimeUs();
2664 idleSleepTime = idleSleepTimeUs();
2665 standbyDelay = microseconds(activeSleepTime*2);
2666 }
2667
2668 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002669 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2670 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002671 // wait until we have something to do...
2672 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002673 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002674 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002675 mStandby = true;
2676 mBytesWritten = 0;
2677 }
2678
2679 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2680 // we're about to wait, flush the binder command buffer
2681 IPCThreadState::self()->flushCommands();
2682
2683 if (exitPending()) break;
2684
Eric Laurentfeb0db62011-07-22 09:04:31 -07002685 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002686 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002688 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002689 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690
Glenn Kastenf1d45922012-01-13 15:54:24 -08002691 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002692 char value[PROPERTY_VALUE_MAX];
2693 property_get("ro.audio.silent", value, "0");
2694 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002695 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 setMasterMute(true);
2697 }
2698 }
2699
2700 standbyTime = systemTime() + standbyDelay;
2701 sleepTime = idleSleepTime;
2702 continue;
2703 }
2704 }
2705
2706 effectChains = mEffectChains;
2707
2708 // find out which tracks need to be processed
2709 if (mActiveTracks.size() != 0) {
2710 sp<Track> t = mActiveTracks[0].promote();
2711 if (t == 0) continue;
2712
2713 Track* const track = t.get();
2714 audio_track_cblk_t* cblk = track->cblk();
2715
2716 // The first time a track is added we wait
2717 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002718 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719 !track->isPaused() && !track->isTerminated())
2720 {
Steve Block3856b092011-10-20 11:56:00 +01002721 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722
2723 if (track->mFillingUpStatus == Track::FS_FILLED) {
2724 track->mFillingUpStatus = Track::FS_ACTIVE;
2725 mLeftVolFloat = mRightVolFloat = 0;
2726 mLeftVolShort = mRightVolShort = 0;
2727 if (track->mState == TrackBase::RESUMING) {
2728 track->mState = TrackBase::ACTIVE;
2729 rampVolume = true;
2730 }
2731 } else if (cblk->server != 0) {
2732 // If the track is stopped before the first frame was mixed,
2733 // do not apply ramp
2734 rampVolume = true;
2735 }
2736 // compute volume for this track
2737 float left, right;
2738 if (track->isMuted() || mMasterMute || track->isPausing() ||
2739 mStreamTypes[track->type()].mute) {
2740 left = right = 0;
2741 if (track->isPausing()) {
2742 track->setPaused();
2743 }
2744 } else {
2745 float typeVolume = mStreamTypes[track->type()].volume;
2746 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002747 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002748 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002749 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2750 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002751 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002752 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2753 right = v_clamped/MAX_GAIN;
2754 }
2755
2756 if (left != mLeftVolFloat || right != mRightVolFloat) {
2757 mLeftVolFloat = left;
2758 mRightVolFloat = right;
2759
2760 // If audio HAL implements volume control,
2761 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002762 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002763 left = 1.0f;
2764 right = 1.0f;
2765 }
2766
2767 // Convert volumes from float to 8.24
2768 uint32_t vl = (uint32_t)(left * (1 << 24));
2769 uint32_t vr = (uint32_t)(right * (1 << 24));
2770
2771 // Delegate volume control to effect in track effect chain if needed
2772 // only one effect chain can be present on DirectOutputThread, so if
2773 // there is one, the track is connected to it
2774 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002775 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002776 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002777 rampVolume = false;
2778 }
2779 }
2780
2781 // Convert volumes from 8.24 to 4.12 format
2782 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2783 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2784 leftVol = (uint16_t)v_clamped;
2785 v_clamped = (vr + (1 << 11)) >> 12;
2786 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2787 rightVol = (uint16_t)v_clamped;
2788 } else {
2789 leftVol = mLeftVolShort;
2790 rightVol = mRightVolShort;
2791 rampVolume = false;
2792 }
2793
2794 // reset retry count
2795 track->mRetryCount = kMaxTrackRetriesDirect;
2796 activeTrack = t;
2797 mixerStatus = MIXER_TRACKS_READY;
2798 } else {
Steve Block3856b092011-10-20 11:56:00 +01002799 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800 if (track->isStopped()) {
2801 track->reset();
2802 }
2803 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2804 // We have consumed all the buffers of this track.
2805 // Remove it from the list of active tracks.
2806 trackToRemove = track;
2807 } else {
2808 // No buffers for this track. Give it a few chances to
2809 // fill a buffer, then remove it from active list.
2810 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002811 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812 trackToRemove = track;
2813 } else {
2814 mixerStatus = MIXER_TRACKS_ENABLED;
2815 }
2816 }
2817 }
2818 }
2819
2820 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002821 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002822 mActiveTracks.remove(trackToRemove);
2823 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002824 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002825 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002826 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002827 }
2828 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002829 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830 }
2831 }
2832
Eric Laurentde070132010-07-13 04:45:46 -07002833 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 }
2835
Glenn Kastenf6b16782011-12-15 09:51:17 -08002836 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837 AudioBufferProvider::Buffer buffer;
2838 size_t frameCount = mFrameCount;
2839 curBuf = (int8_t *)mMixBuffer;
2840 // output audio to hardware
2841 while (frameCount) {
2842 buffer.frameCount = frameCount;
2843 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002844 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002845 memset(curBuf, 0, frameCount * mFrameSize);
2846 break;
2847 }
2848 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2849 frameCount -= buffer.frameCount;
2850 curBuf += buffer.frameCount * mFrameSize;
2851 activeTrack->releaseBuffer(&buffer);
2852 }
2853 sleepTime = 0;
2854 standbyTime = systemTime() + standbyDelay;
2855 } else {
2856 if (sleepTime == 0) {
2857 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2858 sleepTime = activeSleepTime;
2859 } else {
2860 sleepTime = idleSleepTime;
2861 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002862 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2864 sleepTime = 0;
2865 }
2866 }
2867
2868 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002869 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870 }
2871 // sleepTime == 0 means we must write to audio hardware
2872 if (sleepTime == 0) {
2873 if (mixerStatus == MIXER_TRACKS_READY) {
2874 applyVolume(leftVol, rightVol, rampVolume);
2875 }
2876 for (size_t i = 0; i < effectChains.size(); i ++) {
2877 effectChains[i]->process_l();
2878 }
Eric Laurentde070132010-07-13 04:45:46 -07002879 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880
2881 mLastWriteTime = systemTime();
2882 mInWrite = true;
2883 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002884 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002885 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2886 mNumWrites++;
2887 mInWrite = false;
2888 mStandby = false;
2889 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002890 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002891 usleep(sleepTime);
2892 }
2893
2894 // finally let go of removed track, without the lock held
2895 // since we can't guarantee the destructors won't acquire that
2896 // same lock.
2897 trackToRemove.clear();
2898 activeTrack.clear();
2899
2900 // Effect chains will be actually deleted here if they were removed from
2901 // mEffectChains list during mixing or effects processing
2902 effectChains.clear();
2903 }
2904
2905 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002906 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002907 }
2908
Eric Laurentfeb0db62011-07-22 09:04:31 -07002909 releaseWakeLock();
2910
Steve Block3856b092011-10-20 11:56:00 +01002911 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912 return false;
2913}
2914
2915// getTrackName_l() must be called with ThreadBase::mLock held
2916int AudioFlinger::DirectOutputThread::getTrackName_l()
2917{
2918 return 0;
2919}
2920
2921// deleteTrackName_l() must be called with ThreadBase::mLock held
2922void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2923{
2924}
2925
2926// checkForNewParameters_l() must be called with ThreadBase::mLock held
2927bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2928{
2929 bool reconfig = false;
2930
2931 while (!mNewParameters.isEmpty()) {
2932 status_t status = NO_ERROR;
2933 String8 keyValuePair = mNewParameters[0];
2934 AudioParameter param = AudioParameter(keyValuePair);
2935 int value;
2936
2937 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2938 // do not accept frame count changes if tracks are open as the track buffer
2939 // size depends on frame count and correct behavior would not be garantied
2940 // if frame count is changed after track creation
2941 if (!mTracks.isEmpty()) {
2942 status = INVALID_OPERATION;
2943 } else {
2944 reconfig = true;
2945 }
2946 }
2947 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002948 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002949 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002950 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002951 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952 mStandby = true;
2953 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002954 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002955 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002956 }
2957 if (status == NO_ERROR && reconfig) {
2958 readOutputParameters();
2959 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2960 }
2961 }
2962
2963 mNewParameters.removeAt(0);
2964
2965 mParamStatus = status;
2966 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002967 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2968 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002969 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002970 }
2971 return reconfig;
2972}
2973
2974uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2975{
2976 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002977 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002978 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979 } else {
2980 time = 10000;
2981 }
2982 return time;
2983}
2984
2985uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2986{
2987 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002988 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002989 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990 } else {
2991 time = 10000;
2992 }
2993 return time;
2994}
2995
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002996uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2997{
2998 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002999 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003000 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3001 } else {
3002 time = 10000;
3003 }
3004 return time;
3005}
3006
3007
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008// ----------------------------------------------------------------------------
3009
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003010AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3011 AudioFlinger::MixerThread* mainThread, int id)
3012 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3013 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003014{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015 addOutputTrack(mainThread);
3016}
3017
3018AudioFlinger::DuplicatingThread::~DuplicatingThread()
3019{
3020 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3021 mOutputTracks[i]->destroy();
3022 }
3023 mOutputTracks.clear();
3024}
3025
3026bool AudioFlinger::DuplicatingThread::threadLoop()
3027{
3028 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08003029 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030 nsecs_t standbyTime = systemTime();
3031 size_t mixBufferSize = mFrameCount*mFrameSize;
3032 SortedVector< sp<OutputTrack> > outputTracks;
3033 uint32_t writeFrames = 0;
3034 uint32_t activeSleepTime = activeSleepTimeUs();
3035 uint32_t idleSleepTime = idleSleepTimeUs();
3036 uint32_t sleepTime = idleSleepTime;
3037 Vector< sp<EffectChain> > effectChains;
3038
Eric Laurentfeb0db62011-07-22 09:04:31 -07003039 acquireWakeLock();
3040
Mathias Agopian65ab4712010-07-14 17:59:35 -07003041 while (!exitPending())
3042 {
3043 processConfigEvents();
3044
3045 mixerStatus = MIXER_IDLE;
3046 { // scope for the mLock
3047
3048 Mutex::Autolock _l(mLock);
3049
3050 if (checkForNewParameters_l()) {
3051 mixBufferSize = mFrameCount*mFrameSize;
3052 updateWaitTime();
3053 activeSleepTime = activeSleepTimeUs();
3054 idleSleepTime = idleSleepTimeUs();
3055 }
3056
3057 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3058
3059 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3060 outputTracks.add(mOutputTracks[i]);
3061 }
3062
3063 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003064 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3065 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003066 if (!mStandby) {
3067 for (size_t i = 0; i < outputTracks.size(); i++) {
3068 outputTracks[i]->stop();
3069 }
3070 mStandby = true;
3071 mBytesWritten = 0;
3072 }
3073
3074 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3075 // we're about to wait, flush the binder command buffer
3076 IPCThreadState::self()->flushCommands();
3077 outputTracks.clear();
3078
3079 if (exitPending()) break;
3080
Eric Laurentfeb0db62011-07-22 09:04:31 -07003081 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003082 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003083 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003084 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003085 acquireWakeLock_l();
3086
Eric Laurent27741442012-01-17 19:20:12 -08003087 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003088 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089 char value[PROPERTY_VALUE_MAX];
3090 property_get("ro.audio.silent", value, "0");
3091 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003092 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003093 setMasterMute(true);
3094 }
3095 }
3096
3097 standbyTime = systemTime() + kStandbyTimeInNsecs;
3098 sleepTime = idleSleepTime;
3099 continue;
3100 }
3101 }
3102
3103 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3104
3105 // prevent any changes in effect chain list and in each effect chain
3106 // during mixing and effect process as the audio buffers could be deleted
3107 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003108 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109 }
3110
Glenn Kastenf6b16782011-12-15 09:51:17 -08003111 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003112 // mix buffers...
3113 if (outputsReady(outputTracks)) {
3114 mAudioMixer->process();
3115 } else {
3116 memset(mMixBuffer, 0, mixBufferSize);
3117 }
3118 sleepTime = 0;
3119 writeFrames = mFrameCount;
3120 } else {
3121 if (sleepTime == 0) {
3122 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3123 sleepTime = activeSleepTime;
3124 } else {
3125 sleepTime = idleSleepTime;
3126 }
3127 } else if (mBytesWritten != 0) {
3128 // flush remaining overflow buffers in output tracks
3129 for (size_t i = 0; i < outputTracks.size(); i++) {
3130 if (outputTracks[i]->isActive()) {
3131 sleepTime = 0;
3132 writeFrames = 0;
3133 memset(mMixBuffer, 0, mixBufferSize);
3134 break;
3135 }
3136 }
3137 }
3138 }
3139
3140 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003141 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003142 }
3143 // sleepTime == 0 means we must write to audio hardware
3144 if (sleepTime == 0) {
3145 for (size_t i = 0; i < effectChains.size(); i ++) {
3146 effectChains[i]->process_l();
3147 }
3148 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003149 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150
3151 standbyTime = systemTime() + kStandbyTimeInNsecs;
3152 for (size_t i = 0; i < outputTracks.size(); i++) {
3153 outputTracks[i]->write(mMixBuffer, writeFrames);
3154 }
3155 mStandby = false;
3156 mBytesWritten += mixBufferSize;
3157 } else {
3158 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003159 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160 usleep(sleepTime);
3161 }
3162
3163 // finally let go of all our tracks, without the lock held
3164 // since we can't guarantee the destructors won't acquire that
3165 // same lock.
3166 tracksToRemove.clear();
3167 outputTracks.clear();
3168
3169 // Effect chains will be actually deleted here if they were removed from
3170 // mEffectChains list during mixing or effects processing
3171 effectChains.clear();
3172 }
3173
Eric Laurentfeb0db62011-07-22 09:04:31 -07003174 releaseWakeLock();
3175
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 return false;
3177}
3178
3179void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3180{
3181 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3182 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3183 this,
3184 mSampleRate,
3185 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003186 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 frameCount);
3188 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003189 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003191 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192 updateWaitTime();
3193 }
3194}
3195
3196void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3197{
3198 Mutex::Autolock _l(mLock);
3199 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3200 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3201 mOutputTracks[i]->destroy();
3202 mOutputTracks.removeAt(i);
3203 updateWaitTime();
3204 return;
3205 }
3206 }
Steve Block3856b092011-10-20 11:56:00 +01003207 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208}
3209
3210void AudioFlinger::DuplicatingThread::updateWaitTime()
3211{
3212 mWaitTimeMs = UINT_MAX;
3213 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3214 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3215 if (strong != NULL) {
3216 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3217 if (waitTimeMs < mWaitTimeMs) {
3218 mWaitTimeMs = waitTimeMs;
3219 }
3220 }
3221 }
3222}
3223
3224
3225bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3226{
3227 for (size_t i = 0; i < outputTracks.size(); i++) {
3228 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3229 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003230 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231 return false;
3232 }
3233 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3234 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003235 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 return false;
3237 }
3238 }
3239 return true;
3240}
3241
3242uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3243{
3244 return (mWaitTimeMs * 1000) / 2;
3245}
3246
3247// ----------------------------------------------------------------------------
3248
3249// TrackBase constructor must be called with AudioFlinger::mLock held
3250AudioFlinger::ThreadBase::TrackBase::TrackBase(
3251 const wp<ThreadBase>& thread,
3252 const sp<Client>& client,
3253 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003254 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003255 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 int frameCount,
3257 uint32_t flags,
3258 const sp<IMemory>& sharedBuffer,
3259 int sessionId)
3260 : RefBase(),
3261 mThread(thread),
3262 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003263 mCblk(NULL),
3264 // mBuffer
3265 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266 mFrameCount(0),
3267 mState(IDLE),
3268 mClientTid(-1),
3269 mFormat(format),
3270 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3271 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003272 // mChannelCount
3273 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274{
Steve Block3856b092011-10-20 11:56:00 +01003275 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276
Steve Blockb8a80522011-12-20 16:23:08 +00003277 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003278 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003279 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3281 if (sharedBuffer == 0) {
3282 size += bufferSize;
3283 }
3284
3285 if (client != NULL) {
3286 mCblkMemory = client->heap()->allocate(size);
3287 if (mCblkMemory != 0) {
3288 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3289 if (mCblk) { // construct the shared structure in-place.
3290 new(mCblk) audio_track_cblk_t();
3291 // clear all buffers
3292 mCblk->frameCount = frameCount;
3293 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003294 mChannelCount = channelCount;
3295 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296 if (sharedBuffer == 0) {
3297 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3298 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3299 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003300 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 mCblk->flags = CBLK_UNDERRUN_ON;
3302 } else {
3303 mBuffer = sharedBuffer->pointer();
3304 }
3305 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3306 }
3307 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003308 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309 client->heap()->dump("AudioTrack");
3310 return;
3311 }
3312 } else {
3313 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003314 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003315 new(mCblk) audio_track_cblk_t();
3316 // clear all buffers
3317 mCblk->frameCount = frameCount;
3318 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003319 mChannelCount = channelCount;
3320 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3322 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3323 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003324 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325 mCblk->flags = CBLK_UNDERRUN_ON;
3326 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 }
3328}
3329
3330AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3331{
3332 if (mCblk) {
3333 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3334 if (mClient == NULL) {
3335 delete mCblk;
3336 }
3337 }
3338 mCblkMemory.clear(); // and free the shared memory
3339 if (mClient != NULL) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003340 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3342 mClient.clear();
3343 }
3344}
3345
3346void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3347{
Glenn Kastene0feee32011-12-13 11:53:26 -08003348 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349 mFrameCount = buffer->frameCount;
3350 step();
3351 buffer->frameCount = 0;
3352}
3353
3354bool AudioFlinger::ThreadBase::TrackBase::step() {
3355 bool result;
3356 audio_track_cblk_t* cblk = this->cblk();
3357
3358 result = cblk->stepServer(mFrameCount);
3359 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003360 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 mFlags |= STEPSERVER_FAILED;
3362 }
3363 return result;
3364}
3365
3366void AudioFlinger::ThreadBase::TrackBase::reset() {
3367 audio_track_cblk_t* cblk = this->cblk();
3368
3369 cblk->user = 0;
3370 cblk->server = 0;
3371 cblk->userBase = 0;
3372 cblk->serverBase = 0;
3373 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003374 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375}
3376
3377sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3378{
3379 return mCblkMemory;
3380}
3381
3382int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3383 return (int)mCblk->sampleRate;
3384}
3385
3386int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003387 return (const int)mChannelCount;
3388}
3389
3390uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3391 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392}
3393
3394void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3395 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003396 size_t frameSize = cblk->frameSize;
3397 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3398 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399
3400 // Check validity of returned pointer in case the track control block would have been corrupted.
3401 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003402 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003403 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 -07003404 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003406 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 return 0;
3408 }
3409
3410 return bufferStart;
3411}
3412
3413// ----------------------------------------------------------------------------
3414
3415// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3416AudioFlinger::PlaybackThread::Track::Track(
3417 const wp<ThreadBase>& thread,
3418 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003419 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003420 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003421 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003422 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 int frameCount,
3424 const sp<IMemory>& sharedBuffer,
3425 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003426 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003427 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3428 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429{
3430 if (mCblk != NULL) {
3431 sp<ThreadBase> baseThread = thread.promote();
3432 if (baseThread != 0) {
3433 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3434 mName = playbackThread->getTrackName_l();
3435 mMainBuffer = playbackThread->mixBuffer();
3436 }
Steve Block3856b092011-10-20 11:56:00 +01003437 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003439 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003440 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003441 mStreamType = streamType;
3442 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3443 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003444 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003445 }
3446}
3447
3448AudioFlinger::PlaybackThread::Track::~Track()
3449{
Steve Block3856b092011-10-20 11:56:00 +01003450 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003451 sp<ThreadBase> thread = mThread.promote();
3452 if (thread != 0) {
3453 Mutex::Autolock _l(thread->mLock);
3454 mState = TERMINATED;
3455 }
3456}
3457
3458void AudioFlinger::PlaybackThread::Track::destroy()
3459{
3460 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3461 // by removing it from mTracks vector, so there is a risk that this Tracks's
3462 // desctructor is called. As the destructor needs to lock mLock,
3463 // we must acquire a strong reference on this Track before locking mLock
3464 // here so that the destructor is called only when exiting this function.
3465 // On the other hand, as long as Track::destroy() is only called by
3466 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3467 // this Track with its member mTrack.
3468 sp<Track> keep(this);
3469 { // scope for mLock
3470 sp<ThreadBase> thread = mThread.promote();
3471 if (thread != 0) {
3472 if (!isOutputTrack()) {
3473 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003474 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003475 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003476 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003477
3478 // to track the speaker usage
3479 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480 }
3481 AudioSystem::releaseOutput(thread->id());
3482 }
3483 Mutex::Autolock _l(thread->mLock);
3484 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3485 playbackThread->destroyTrack_l(this);
3486 }
3487 }
3488}
3489
3490void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3491{
Glenn Kasten83d86532012-01-17 14:39:34 -08003492 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003493 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 -07003494 mName - AudioMixer::TRACK0,
3495 (mClient == NULL) ? getpid() : mClient->pid(),
3496 mStreamType,
3497 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003498 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499 mSessionId,
3500 mFrameCount,
3501 mState,
3502 mMute,
3503 mFillingUpStatus,
3504 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003505 vlr & 0xFFFF,
3506 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003507 mCblk->server,
3508 mCblk->user,
3509 (int)mMainBuffer,
3510 (int)mAuxBuffer);
3511}
3512
3513status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3514{
3515 audio_track_cblk_t* cblk = this->cblk();
3516 uint32_t framesReady;
3517 uint32_t framesReq = buffer->frameCount;
3518
3519 // Check if last stepServer failed, try to step now
3520 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3521 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003522 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003523 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3524 }
3525
3526 framesReady = cblk->framesReady();
3527
Glenn Kastenf6b16782011-12-15 09:51:17 -08003528 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529 uint32_t s = cblk->server;
3530 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3531
3532 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3533 if (framesReq > framesReady) {
3534 framesReq = framesReady;
3535 }
3536 if (s + framesReq > bufferEnd) {
3537 framesReq = bufferEnd - s;
3538 }
3539
3540 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003541 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003542
3543 buffer->frameCount = framesReq;
3544 return NO_ERROR;
3545 }
3546
3547getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003548 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003549 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003550 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551 return NOT_ENOUGH_DATA;
3552}
3553
3554bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003555 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556
3557 if (mCblk->framesReady() >= mCblk->frameCount ||
3558 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3559 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003560 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003561 return true;
3562 }
3563 return false;
3564}
3565
3566status_t AudioFlinger::PlaybackThread::Track::start()
3567{
3568 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003569 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003570 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 sp<ThreadBase> thread = mThread.promote();
3572 if (thread != 0) {
3573 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003574 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575 // here the track could be either new, or restarted
3576 // in both cases "unstop" the track
3577 if (mState == PAUSED) {
3578 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003579 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580 } else {
3581 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003582 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003583 }
3584
3585 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3586 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003587 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003588 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003589 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003591
3592 // to track the speaker usage
3593 if (status == NO_ERROR) {
3594 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3595 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596 }
3597 if (status == NO_ERROR) {
3598 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3599 playbackThread->addTrack_l(this);
3600 } else {
3601 mState = state;
3602 }
3603 } else {
3604 status = BAD_VALUE;
3605 }
3606 return status;
3607}
3608
3609void AudioFlinger::PlaybackThread::Track::stop()
3610{
Steve Block3856b092011-10-20 11:56:00 +01003611 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612 sp<ThreadBase> thread = mThread.promote();
3613 if (thread != 0) {
3614 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003615 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616 if (mState > STOPPED) {
3617 mState = STOPPED;
3618 // If the track is not active (PAUSED and buffers full), flush buffers
3619 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3620 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3621 reset();
3622 }
Steve Block3856b092011-10-20 11:56:00 +01003623 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624 }
3625 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3626 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003627 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003628 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003629 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003631
3632 // to track the speaker usage
3633 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634 }
3635 }
3636}
3637
3638void AudioFlinger::PlaybackThread::Track::pause()
3639{
Steve Block3856b092011-10-20 11:56:00 +01003640 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641 sp<ThreadBase> thread = mThread.promote();
3642 if (thread != 0) {
3643 Mutex::Autolock _l(thread->mLock);
3644 if (mState == ACTIVE || mState == RESUMING) {
3645 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003646 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003647 if (!isOutputTrack()) {
3648 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003649 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003650 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003651 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003652 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003653
3654 // to track the speaker usage
3655 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656 }
3657 }
3658 }
3659}
3660
3661void AudioFlinger::PlaybackThread::Track::flush()
3662{
Steve Block3856b092011-10-20 11:56:00 +01003663 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003664 sp<ThreadBase> thread = mThread.promote();
3665 if (thread != 0) {
3666 Mutex::Autolock _l(thread->mLock);
3667 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3668 return;
3669 }
3670 // No point remaining in PAUSED state after a flush => go to
3671 // STOPPED state
3672 mState = STOPPED;
3673
Eric Laurent38ccae22011-03-28 18:37:07 -07003674 // do not reset the track if it is still in the process of being stopped or paused.
3675 // this will be done by prepareTracks_l() when the track is stopped.
3676 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3677 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3678 reset();
3679 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680 }
3681}
3682
3683void AudioFlinger::PlaybackThread::Track::reset()
3684{
3685 // Do not reset twice to avoid discarding data written just after a flush and before
3686 // the audioflinger thread detects the track is stopped.
3687 if (!mResetDone) {
3688 TrackBase::reset();
3689 // Force underrun condition to avoid false underrun callback until first data is
3690 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003691 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3692 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693 mFillingUpStatus = FS_FILLING;
3694 mResetDone = true;
3695 }
3696}
3697
3698void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3699{
3700 mMute = muted;
3701}
3702
Mathias Agopian65ab4712010-07-14 17:59:35 -07003703status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3704{
3705 status_t status = DEAD_OBJECT;
3706 sp<ThreadBase> thread = mThread.promote();
3707 if (thread != 0) {
3708 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3709 status = playbackThread->attachAuxEffect(this, EffectId);
3710 }
3711 return status;
3712}
3713
3714void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3715{
3716 mAuxEffectId = EffectId;
3717 mAuxBuffer = buffer;
3718}
3719
3720// ----------------------------------------------------------------------------
3721
3722// RecordTrack constructor must be called with AudioFlinger::mLock held
3723AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3724 const wp<ThreadBase>& thread,
3725 const sp<Client>& client,
3726 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003727 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003728 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003729 int frameCount,
3730 uint32_t flags,
3731 int sessionId)
3732 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003733 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003734 mOverflow(false)
3735{
3736 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003737 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003738 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003739 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003740 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003741 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003742 } else {
3743 mCblk->frameSize = sizeof(int8_t);
3744 }
3745 }
3746}
3747
3748AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3749{
3750 sp<ThreadBase> thread = mThread.promote();
3751 if (thread != 0) {
3752 AudioSystem::releaseInput(thread->id());
3753 }
3754}
3755
3756status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3757{
3758 audio_track_cblk_t* cblk = this->cblk();
3759 uint32_t framesAvail;
3760 uint32_t framesReq = buffer->frameCount;
3761
3762 // Check if last stepServer failed, try to step now
3763 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3764 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003765 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3767 }
3768
3769 framesAvail = cblk->framesAvailable_l();
3770
Glenn Kastenf6b16782011-12-15 09:51:17 -08003771 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003772 uint32_t s = cblk->server;
3773 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3774
3775 if (framesReq > framesAvail) {
3776 framesReq = framesAvail;
3777 }
3778 if (s + framesReq > bufferEnd) {
3779 framesReq = bufferEnd - s;
3780 }
3781
3782 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003783 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003784
3785 buffer->frameCount = framesReq;
3786 return NO_ERROR;
3787 }
3788
3789getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003790 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003791 buffer->frameCount = 0;
3792 return NOT_ENOUGH_DATA;
3793}
3794
3795status_t AudioFlinger::RecordThread::RecordTrack::start()
3796{
3797 sp<ThreadBase> thread = mThread.promote();
3798 if (thread != 0) {
3799 RecordThread *recordThread = (RecordThread *)thread.get();
3800 return recordThread->start(this);
3801 } else {
3802 return BAD_VALUE;
3803 }
3804}
3805
3806void AudioFlinger::RecordThread::RecordTrack::stop()
3807{
3808 sp<ThreadBase> thread = mThread.promote();
3809 if (thread != 0) {
3810 RecordThread *recordThread = (RecordThread *)thread.get();
3811 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003812 TrackBase::reset();
3813 // Force overerrun condition to avoid false overrun callback until first data is
3814 // read from buffer
3815 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003816 }
3817}
3818
3819void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3820{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003821 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822 (mClient == NULL) ? getpid() : mClient->pid(),
3823 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003824 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003825 mSessionId,
3826 mFrameCount,
3827 mState,
3828 mCblk->sampleRate,
3829 mCblk->server,
3830 mCblk->user);
3831}
3832
3833
3834// ----------------------------------------------------------------------------
3835
3836AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3837 const wp<ThreadBase>& thread,
3838 DuplicatingThread *sourceThread,
3839 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003840 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003841 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003842 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003843 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003844 mActive(false), mSourceThread(sourceThread)
3845{
3846
3847 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3848 if (mCblk != NULL) {
3849 mCblk->flags |= CBLK_DIRECTION_OUT;
3850 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003851 mOutBuffer.frameCount = 0;
3852 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003853 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003854 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3855 mCblk, mBuffer, mCblk->buffers,
3856 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003857 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003858 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003859 }
3860}
3861
3862AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3863{
3864 clearBufferQueue();
3865}
3866
3867status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3868{
3869 status_t status = Track::start();
3870 if (status != NO_ERROR) {
3871 return status;
3872 }
3873
3874 mActive = true;
3875 mRetryCount = 127;
3876 return status;
3877}
3878
3879void AudioFlinger::PlaybackThread::OutputTrack::stop()
3880{
3881 Track::stop();
3882 clearBufferQueue();
3883 mOutBuffer.frameCount = 0;
3884 mActive = false;
3885}
3886
3887bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3888{
3889 Buffer *pInBuffer;
3890 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003891 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892 bool outputBufferFull = false;
3893 inBuffer.frameCount = frames;
3894 inBuffer.i16 = data;
3895
3896 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3897
3898 if (!mActive && frames != 0) {
3899 start();
3900 sp<ThreadBase> thread = mThread.promote();
3901 if (thread != 0) {
3902 MixerThread *mixerThread = (MixerThread *)thread.get();
3903 if (mCblk->frameCount > frames){
3904 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3905 uint32_t startFrames = (mCblk->frameCount - frames);
3906 pInBuffer = new Buffer;
3907 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3908 pInBuffer->frameCount = startFrames;
3909 pInBuffer->i16 = pInBuffer->mBuffer;
3910 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3911 mBufferQueue.add(pInBuffer);
3912 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003913 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003914 }
3915 }
3916 }
3917 }
3918
3919 while (waitTimeLeftMs) {
3920 // First write pending buffers, then new data
3921 if (mBufferQueue.size()) {
3922 pInBuffer = mBufferQueue.itemAt(0);
3923 } else {
3924 pInBuffer = &inBuffer;
3925 }
3926
3927 if (pInBuffer->frameCount == 0) {
3928 break;
3929 }
3930
3931 if (mOutBuffer.frameCount == 0) {
3932 mOutBuffer.frameCount = pInBuffer->frameCount;
3933 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003934 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003935 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003936 outputBufferFull = true;
3937 break;
3938 }
3939 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3940 if (waitTimeLeftMs >= waitTimeMs) {
3941 waitTimeLeftMs -= waitTimeMs;
3942 } else {
3943 waitTimeLeftMs = 0;
3944 }
3945 }
3946
3947 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3948 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3949 mCblk->stepUser(outFrames);
3950 pInBuffer->frameCount -= outFrames;
3951 pInBuffer->i16 += outFrames * channelCount;
3952 mOutBuffer.frameCount -= outFrames;
3953 mOutBuffer.i16 += outFrames * channelCount;
3954
3955 if (pInBuffer->frameCount == 0) {
3956 if (mBufferQueue.size()) {
3957 mBufferQueue.removeAt(0);
3958 delete [] pInBuffer->mBuffer;
3959 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003960 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003961 } else {
3962 break;
3963 }
3964 }
3965 }
3966
3967 // If we could not write all frames, allocate a buffer and queue it for next time.
3968 if (inBuffer.frameCount) {
3969 sp<ThreadBase> thread = mThread.promote();
3970 if (thread != 0 && !thread->standby()) {
3971 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3972 pInBuffer = new Buffer;
3973 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3974 pInBuffer->frameCount = inBuffer.frameCount;
3975 pInBuffer->i16 = pInBuffer->mBuffer;
3976 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3977 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003978 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003979 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003980 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003981 }
3982 }
3983 }
3984
3985 // Calling write() with a 0 length buffer, means that no more data will be written:
3986 // If no more buffers are pending, fill output track buffer to make sure it is started
3987 // by output mixer.
3988 if (frames == 0 && mBufferQueue.size() == 0) {
3989 if (mCblk->user < mCblk->frameCount) {
3990 frames = mCblk->frameCount - mCblk->user;
3991 pInBuffer = new Buffer;
3992 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3993 pInBuffer->frameCount = frames;
3994 pInBuffer->i16 = pInBuffer->mBuffer;
3995 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3996 mBufferQueue.add(pInBuffer);
3997 } else if (mActive) {
3998 stop();
3999 }
4000 }
4001
4002 return outputBufferFull;
4003}
4004
4005status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4006{
4007 int active;
4008 status_t result;
4009 audio_track_cblk_t* cblk = mCblk;
4010 uint32_t framesReq = buffer->frameCount;
4011
Steve Block3856b092011-10-20 11:56:00 +01004012// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004013 buffer->frameCount = 0;
4014
4015 uint32_t framesAvail = cblk->framesAvailable();
4016
4017
4018 if (framesAvail == 0) {
4019 Mutex::Autolock _l(cblk->lock);
4020 goto start_loop_here;
4021 while (framesAvail == 0) {
4022 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004023 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004024 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004025 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004026 }
4027 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4028 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004029 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030 }
4031 // read the server count again
4032 start_loop_here:
4033 framesAvail = cblk->framesAvailable_l();
4034 }
4035 }
4036
4037// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004038// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039// }
4040
4041 if (framesReq > framesAvail) {
4042 framesReq = framesAvail;
4043 }
4044
4045 uint32_t u = cblk->user;
4046 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4047
4048 if (u + framesReq > bufferEnd) {
4049 framesReq = bufferEnd - u;
4050 }
4051
4052 buffer->frameCount = framesReq;
4053 buffer->raw = (void *)cblk->buffer(u);
4054 return NO_ERROR;
4055}
4056
4057
4058void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4059{
4060 size_t size = mBufferQueue.size();
4061 Buffer *pBuffer;
4062
4063 for (size_t i = 0; i < size; i++) {
4064 pBuffer = mBufferQueue.itemAt(i);
4065 delete [] pBuffer->mBuffer;
4066 delete pBuffer;
4067 }
4068 mBufferQueue.clear();
4069}
4070
4071// ----------------------------------------------------------------------------
4072
4073AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4074 : RefBase(),
4075 mAudioFlinger(audioFlinger),
4076 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4077 mPid(pid)
4078{
4079 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4080}
4081
4082// Client destructor must be called with AudioFlinger::mLock held
4083AudioFlinger::Client::~Client()
4084{
4085 mAudioFlinger->removeClient_l(mPid);
4086}
4087
Glenn Kasten435dbe62012-01-30 10:15:48 -08004088sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089{
4090 return mMemoryDealer;
4091}
4092
4093// ----------------------------------------------------------------------------
4094
4095AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4096 const sp<IAudioFlingerClient>& client,
4097 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004098 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004099{
4100}
4101
4102AudioFlinger::NotificationClient::~NotificationClient()
4103{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104}
4105
4106void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4107{
4108 sp<NotificationClient> keep(this);
4109 {
4110 mAudioFlinger->removeNotificationClient(mPid);
4111 }
4112}
4113
4114// ----------------------------------------------------------------------------
4115
4116AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4117 : BnAudioTrack(),
4118 mTrack(track)
4119{
4120}
4121
4122AudioFlinger::TrackHandle::~TrackHandle() {
4123 // just stop the track on deletion, associated resources
4124 // will be freed from the main thread once all pending buffers have
4125 // been played. Unless it's not in the active track list, in which
4126 // case we free everything now...
4127 mTrack->destroy();
4128}
4129
Glenn Kasten90716c52012-01-26 13:40:12 -08004130sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4131 return mTrack->getCblk();
4132}
4133
Mathias Agopian65ab4712010-07-14 17:59:35 -07004134status_t AudioFlinger::TrackHandle::start() {
4135 return mTrack->start();
4136}
4137
4138void AudioFlinger::TrackHandle::stop() {
4139 mTrack->stop();
4140}
4141
4142void AudioFlinger::TrackHandle::flush() {
4143 mTrack->flush();
4144}
4145
4146void AudioFlinger::TrackHandle::mute(bool e) {
4147 mTrack->mute(e);
4148}
4149
4150void AudioFlinger::TrackHandle::pause() {
4151 mTrack->pause();
4152}
4153
Mathias Agopian65ab4712010-07-14 17:59:35 -07004154status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4155{
4156 return mTrack->attachAuxEffect(EffectId);
4157}
4158
4159status_t AudioFlinger::TrackHandle::onTransact(
4160 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4161{
4162 return BnAudioTrack::onTransact(code, data, reply, flags);
4163}
4164
4165// ----------------------------------------------------------------------------
4166
4167sp<IAudioRecord> AudioFlinger::openRecord(
4168 pid_t pid,
4169 int input,
4170 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004171 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004172 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173 int frameCount,
4174 uint32_t flags,
4175 int *sessionId,
4176 status_t *status)
4177{
4178 sp<RecordThread::RecordTrack> recordTrack;
4179 sp<RecordHandle> recordHandle;
4180 sp<Client> client;
4181 wp<Client> wclient;
4182 status_t lStatus;
4183 RecordThread *thread;
4184 size_t inFrameCount;
4185 int lSessionId;
4186
4187 // check calling permissions
4188 if (!recordingAllowed()) {
4189 lStatus = PERMISSION_DENIED;
4190 goto Exit;
4191 }
4192
4193 // add client to list
4194 { // scope for mLock
4195 Mutex::Autolock _l(mLock);
4196 thread = checkRecordThread_l(input);
4197 if (thread == NULL) {
4198 lStatus = BAD_VALUE;
4199 goto Exit;
4200 }
4201
4202 wclient = mClients.valueFor(pid);
4203 if (wclient != NULL) {
4204 client = wclient.promote();
4205 } else {
4206 client = new Client(this, pid);
4207 mClients.add(pid, client);
4208 }
4209
4210 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004211 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004212 lSessionId = *sessionId;
4213 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004214 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215 if (sessionId != NULL) {
4216 *sessionId = lSessionId;
4217 }
4218 }
4219 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004220 recordTrack = thread->createRecordTrack_l(client,
4221 sampleRate,
4222 format,
4223 channelMask,
4224 frameCount,
4225 flags,
4226 lSessionId,
4227 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004229 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4231 // destructor is called by the TrackBase destructor with mLock held
4232 client.clear();
4233 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004234 goto Exit;
4235 }
4236
4237 // return to handle to client
4238 recordHandle = new RecordHandle(recordTrack);
4239 lStatus = NO_ERROR;
4240
4241Exit:
4242 if (status) {
4243 *status = lStatus;
4244 }
4245 return recordHandle;
4246}
4247
4248// ----------------------------------------------------------------------------
4249
4250AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4251 : BnAudioRecord(),
4252 mRecordTrack(recordTrack)
4253{
4254}
4255
4256AudioFlinger::RecordHandle::~RecordHandle() {
4257 stop();
4258}
4259
Glenn Kasten90716c52012-01-26 13:40:12 -08004260sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4261 return mRecordTrack->getCblk();
4262}
4263
Mathias Agopian65ab4712010-07-14 17:59:35 -07004264status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004265 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004266 return mRecordTrack->start();
4267}
4268
4269void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004270 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271 mRecordTrack->stop();
4272}
4273
Mathias Agopian65ab4712010-07-14 17:59:35 -07004274status_t AudioFlinger::RecordHandle::onTransact(
4275 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4276{
4277 return BnAudioRecord::onTransact(code, data, reply, flags);
4278}
4279
4280// ----------------------------------------------------------------------------
4281
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004282AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4283 AudioStreamIn *input,
4284 uint32_t sampleRate,
4285 uint32_t channels,
4286 int id,
4287 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004288 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004289 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4290 // mRsmpInIndex and mInputBytes set by readInputParameters()
4291 mReqChannelCount(popcount(channels)),
4292 mReqSampleRate(sampleRate)
4293 // mBytesRead is only meaningful while active, and so is cleared in start()
4294 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004295{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004296 snprintf(mName, kNameLength, "AudioIn_%d", id);
4297
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298 readInputParameters();
4299}
4300
4301
4302AudioFlinger::RecordThread::~RecordThread()
4303{
4304 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004305 delete mResampler;
4306 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004307}
4308
4309void AudioFlinger::RecordThread::onFirstRef()
4310{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004311 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312}
4313
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004314status_t AudioFlinger::RecordThread::readyToRun()
4315{
4316 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004317 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004318 return status;
4319}
4320
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321bool AudioFlinger::RecordThread::threadLoop()
4322{
4323 AudioBufferProvider::Buffer buffer;
4324 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004325 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326
Eric Laurent44d98482010-09-30 16:12:31 -07004327 nsecs_t lastWarning = 0;
4328
Eric Laurentfeb0db62011-07-22 09:04:31 -07004329 acquireWakeLock();
4330
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 // start recording
4332 while (!exitPending()) {
4333
4334 processConfigEvents();
4335
4336 { // scope for mLock
4337 Mutex::Autolock _l(mLock);
4338 checkForNewParameters_l();
4339 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4340 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004341 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004342 mStandby = true;
4343 }
4344
4345 if (exitPending()) break;
4346
Eric Laurentfeb0db62011-07-22 09:04:31 -07004347 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004348 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 // go to sleep
4350 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004351 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004352 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004353 continue;
4354 }
4355 if (mActiveTrack != 0) {
4356 if (mActiveTrack->mState == TrackBase::PAUSING) {
4357 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004358 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004359 mStandby = true;
4360 }
4361 mActiveTrack.clear();
4362 mStartStopCond.broadcast();
4363 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4364 if (mReqChannelCount != mActiveTrack->channelCount()) {
4365 mActiveTrack.clear();
4366 mStartStopCond.broadcast();
4367 } else if (mBytesRead != 0) {
4368 // record start succeeds only if first read from audio input
4369 // succeeds
4370 if (mBytesRead > 0) {
4371 mActiveTrack->mState = TrackBase::ACTIVE;
4372 } else {
4373 mActiveTrack.clear();
4374 }
4375 mStartStopCond.broadcast();
4376 }
4377 mStandby = false;
4378 }
4379 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004380 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 }
4382
4383 if (mActiveTrack != 0) {
4384 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4385 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004386 unlockEffectChains(effectChains);
4387 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388 continue;
4389 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004390 for (size_t i = 0; i < effectChains.size(); i ++) {
4391 effectChains[i]->process_l();
4392 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004393
Mathias Agopian65ab4712010-07-14 17:59:35 -07004394 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004395 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004396 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004397 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004398 // no resampling
4399 while (framesOut) {
4400 size_t framesIn = mFrameCount - mRsmpInIndex;
4401 if (framesIn) {
4402 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4403 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4404 if (framesIn > framesOut)
4405 framesIn = framesOut;
4406 mRsmpInIndex += framesIn;
4407 framesOut -= framesIn;
4408 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004409 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004410 memcpy(dst, src, framesIn * mFrameSize);
4411 } else {
4412 int16_t *src16 = (int16_t *)src;
4413 int16_t *dst16 = (int16_t *)dst;
4414 if (mChannelCount == 1) {
4415 while (framesIn--) {
4416 *dst16++ = *src16;
4417 *dst16++ = *src16++;
4418 }
4419 } else {
4420 while (framesIn--) {
4421 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4422 src16 += 2;
4423 }
4424 }
4425 }
4426 }
4427 if (framesOut && mFrameCount == mRsmpInIndex) {
4428 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004429 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004430 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004431 framesOut = 0;
4432 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004433 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434 mRsmpInIndex = 0;
4435 }
4436 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004437 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004438 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4439 // Force input into standby so that it tries to
4440 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004441 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004442 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443 }
4444 mRsmpInIndex = mFrameCount;
4445 framesOut = 0;
4446 buffer.frameCount = 0;
4447 }
4448 }
4449 }
4450 } else {
4451 // resampling
4452
4453 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4454 // alter output frame count as if we were expecting stereo samples
4455 if (mChannelCount == 1 && mReqChannelCount == 1) {
4456 framesOut >>= 1;
4457 }
4458 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4459 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4460 // are 32 bit aligned which should be always true.
4461 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004462 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004463 // the resampler always outputs stereo samples: do post stereo to mono conversion
4464 int16_t *src = (int16_t *)mRsmpOutBuffer;
4465 int16_t *dst = buffer.i16;
4466 while (framesOut--) {
4467 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4468 src += 2;
4469 }
4470 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004471 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004472 }
4473
4474 }
4475 mActiveTrack->releaseBuffer(&buffer);
4476 mActiveTrack->overflow();
4477 }
4478 // client isn't retrieving buffers fast enough
4479 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004480 if (!mActiveTrack->setOverflow()) {
4481 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004482 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004483 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004484 lastWarning = now;
4485 }
4486 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487 // Release the processor for a while before asking for a new buffer.
4488 // This will give the application more chance to read from the buffer and
4489 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004490 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491 }
4492 }
Eric Laurentec437d82011-07-26 20:54:46 -07004493 // enable changes in effect chain
4494 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004495 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496 }
4497
4498 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004499 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004500 }
4501 mActiveTrack.clear();
4502
4503 mStartStopCond.broadcast();
4504
Eric Laurentfeb0db62011-07-22 09:04:31 -07004505 releaseWakeLock();
4506
Steve Block3856b092011-10-20 11:56:00 +01004507 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508 return false;
4509}
4510
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004511
4512sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4513 const sp<AudioFlinger::Client>& client,
4514 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004515 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004516 int channelMask,
4517 int frameCount,
4518 uint32_t flags,
4519 int sessionId,
4520 status_t *status)
4521{
4522 sp<RecordTrack> track;
4523 status_t lStatus;
4524
4525 lStatus = initCheck();
4526 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004527 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004528 goto Exit;
4529 }
4530
4531 { // scope for mLock
4532 Mutex::Autolock _l(mLock);
4533
4534 track = new RecordTrack(this, client, sampleRate,
4535 format, channelMask, frameCount, flags, sessionId);
4536
4537 if (track->getCblk() == NULL) {
4538 lStatus = NO_MEMORY;
4539 goto Exit;
4540 }
4541
4542 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004543 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4544 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004545 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004546 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4547 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004548 }
4549 lStatus = NO_ERROR;
4550
4551Exit:
4552 if (status) {
4553 *status = lStatus;
4554 }
4555 return track;
4556}
4557
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4559{
Steve Block3856b092011-10-20 11:56:00 +01004560 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561 sp <ThreadBase> strongMe = this;
4562 status_t status = NO_ERROR;
4563 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004564 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004565 if (mActiveTrack != 0) {
4566 if (recordTrack != mActiveTrack.get()) {
4567 status = -EBUSY;
4568 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4569 mActiveTrack->mState = TrackBase::ACTIVE;
4570 }
4571 return status;
4572 }
4573
4574 recordTrack->mState = TrackBase::IDLE;
4575 mActiveTrack = recordTrack;
4576 mLock.unlock();
4577 status_t status = AudioSystem::startInput(mId);
4578 mLock.lock();
4579 if (status != NO_ERROR) {
4580 mActiveTrack.clear();
4581 return status;
4582 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004583 mRsmpInIndex = mFrameCount;
4584 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004585 if (mResampler != NULL) {
4586 mResampler->reset();
4587 }
4588 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004589 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004590 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004591 mWaitWorkCV.signal();
4592 // do not wait for mStartStopCond if exiting
4593 if (mExiting) {
4594 mActiveTrack.clear();
4595 status = INVALID_OPERATION;
4596 goto startError;
4597 }
4598 mStartStopCond.wait(mLock);
4599 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004600 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601 status = BAD_VALUE;
4602 goto startError;
4603 }
Steve Block3856b092011-10-20 11:56:00 +01004604 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605 return status;
4606 }
4607startError:
4608 AudioSystem::stopInput(mId);
4609 return status;
4610}
4611
4612void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004613 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004614 sp <ThreadBase> strongMe = this;
4615 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004616 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004617 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4618 mActiveTrack->mState = TrackBase::PAUSING;
4619 // do not wait for mStartStopCond if exiting
4620 if (mExiting) {
4621 return;
4622 }
4623 mStartStopCond.wait(mLock);
4624 // if we have been restarted, recordTrack == mActiveTrack.get() here
4625 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4626 mLock.unlock();
4627 AudioSystem::stopInput(mId);
4628 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004629 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630 }
4631 }
4632 }
4633}
4634
4635status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4636{
4637 const size_t SIZE = 256;
4638 char buffer[SIZE];
4639 String8 result;
4640 pid_t pid = 0;
4641
4642 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4643 result.append(buffer);
4644
4645 if (mActiveTrack != 0) {
4646 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004647 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648 mActiveTrack->dump(buffer, SIZE);
4649 result.append(buffer);
4650
4651 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4652 result.append(buffer);
4653 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4654 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004655 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004656 result.append(buffer);
4657 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4658 result.append(buffer);
4659 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4660 result.append(buffer);
4661
4662
4663 } else {
4664 result.append("No record client\n");
4665 }
4666 write(fd, result.string(), result.size());
4667
4668 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004669 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004670
4671 return NO_ERROR;
4672}
4673
4674status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4675{
4676 size_t framesReq = buffer->frameCount;
4677 size_t framesReady = mFrameCount - mRsmpInIndex;
4678 int channelCount;
4679
4680 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004681 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004682 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004683 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004684 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4685 // Force input into standby so that it tries to
4686 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004687 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004688 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004690 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004691 buffer->frameCount = 0;
4692 return NOT_ENOUGH_DATA;
4693 }
4694 mRsmpInIndex = 0;
4695 framesReady = mFrameCount;
4696 }
4697
4698 if (framesReq > framesReady) {
4699 framesReq = framesReady;
4700 }
4701
4702 if (mChannelCount == 1 && mReqChannelCount == 2) {
4703 channelCount = 1;
4704 } else {
4705 channelCount = 2;
4706 }
4707 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4708 buffer->frameCount = framesReq;
4709 return NO_ERROR;
4710}
4711
4712void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4713{
4714 mRsmpInIndex += buffer->frameCount;
4715 buffer->frameCount = 0;
4716}
4717
4718bool AudioFlinger::RecordThread::checkForNewParameters_l()
4719{
4720 bool reconfig = false;
4721
4722 while (!mNewParameters.isEmpty()) {
4723 status_t status = NO_ERROR;
4724 String8 keyValuePair = mNewParameters[0];
4725 AudioParameter param = AudioParameter(keyValuePair);
4726 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004727 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004728 int reqSamplingRate = mReqSampleRate;
4729 int reqChannelCount = mReqChannelCount;
4730
4731 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4732 reqSamplingRate = value;
4733 reconfig = true;
4734 }
4735 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004736 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004737 reconfig = true;
4738 }
4739 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004740 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004741 reconfig = true;
4742 }
4743 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4744 // do not accept frame count changes if tracks are open as the track buffer
4745 // size depends on frame count and correct behavior would not be garantied
4746 // if frame count is changed after track creation
4747 if (mActiveTrack != 0) {
4748 status = INVALID_OPERATION;
4749 } else {
4750 reconfig = true;
4751 }
4752 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004753 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4754 // forward device change to effects that have requested to be
4755 // aware of attached audio device.
4756 for (size_t i = 0; i < mEffectChains.size(); i++) {
4757 mEffectChains[i]->setDevice_l(value);
4758 }
4759 // store input device and output device but do not forward output device to audio HAL.
4760 // Note that status is ignored by the caller for output device
4761 // (see AudioFlinger::setParameters()
4762 if (value & AUDIO_DEVICE_OUT_ALL) {
4763 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4764 status = BAD_VALUE;
4765 } else {
4766 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004767 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4768 if (mTrack != NULL) {
4769 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004770 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004771 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4772 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4773 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004774 }
4775 mDevice |= (uint32_t)value;
4776 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004777 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004778 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004779 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004780 mInput->stream->common.standby(&mInput->stream->common);
4781 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004782 }
4783 if (reconfig) {
4784 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004785 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004786 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004787 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4788 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004789 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004790 status = NO_ERROR;
4791 }
4792 if (status == NO_ERROR) {
4793 readInputParameters();
4794 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4795 }
4796 }
4797 }
4798
4799 mNewParameters.removeAt(0);
4800
4801 mParamStatus = status;
4802 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004803 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4804 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004805 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004806 }
4807 return reconfig;
4808}
4809
4810String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4811{
Dima Zavinfce7a472011-04-19 22:30:36 -07004812 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004813 String8 out_s8 = String8();
4814
4815 Mutex::Autolock _l(mLock);
4816 if (initCheck() != NO_ERROR) {
4817 return out_s8;
4818 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004819
Dima Zavin799a70e2011-04-18 16:57:27 -07004820 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004821 out_s8 = String8(s);
4822 free(s);
4823 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004824}
4825
4826void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4827 AudioSystem::OutputDescriptor desc;
4828 void *param2 = 0;
4829
4830 switch (event) {
4831 case AudioSystem::INPUT_OPENED:
4832 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004833 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004834 desc.samplingRate = mSampleRate;
4835 desc.format = mFormat;
4836 desc.frameCount = mFrameCount;
4837 desc.latency = 0;
4838 param2 = &desc;
4839 break;
4840
4841 case AudioSystem::INPUT_CLOSED:
4842 default:
4843 break;
4844 }
4845 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4846}
4847
4848void AudioFlinger::RecordThread::readInputParameters()
4849{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004850 delete mRsmpInBuffer;
4851 // mRsmpInBuffer is always assigned a new[] below
4852 delete mRsmpOutBuffer;
4853 mRsmpOutBuffer = NULL;
4854 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004855 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004856
Dima Zavin799a70e2011-04-18 16:57:27 -07004857 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004858 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4859 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004860 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004861 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004862 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004863 mFrameCount = mInputBytes / mFrameSize;
4864 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4865
4866 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4867 {
4868 int channelCount;
4869 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4870 // stereo to mono post process as the resampler always outputs stereo.
4871 if (mChannelCount == 1 && mReqChannelCount == 2) {
4872 channelCount = 1;
4873 } else {
4874 channelCount = 2;
4875 }
4876 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4877 mResampler->setSampleRate(mSampleRate);
4878 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4879 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4880
4881 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4882 if (mChannelCount == 1 && mReqChannelCount == 1) {
4883 mFrameCount >>= 1;
4884 }
4885
4886 }
4887 mRsmpInIndex = mFrameCount;
4888}
4889
4890unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4891{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004892 Mutex::Autolock _l(mLock);
4893 if (initCheck() != NO_ERROR) {
4894 return 0;
4895 }
4896
Dima Zavin799a70e2011-04-18 16:57:27 -07004897 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004898}
4899
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004900uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4901{
4902 Mutex::Autolock _l(mLock);
4903 uint32_t result = 0;
4904 if (getEffectChain_l(sessionId) != 0) {
4905 result = EFFECT_SESSION;
4906 }
4907
4908 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4909 result |= TRACK_SESSION;
4910 }
4911
4912 return result;
4913}
4914
Eric Laurent59bd0da2011-08-01 09:52:20 -07004915AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4916{
4917 Mutex::Autolock _l(mLock);
4918 return mTrack;
4919}
4920
Glenn Kastenaed850d2012-01-26 09:46:34 -08004921AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004922{
4923 Mutex::Autolock _l(mLock);
4924 return mInput;
4925}
4926
4927AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4928{
4929 Mutex::Autolock _l(mLock);
4930 AudioStreamIn *input = mInput;
4931 mInput = NULL;
4932 return input;
4933}
4934
4935// this method must always be called either with ThreadBase mLock held or inside the thread loop
4936audio_stream_t* AudioFlinger::RecordThread::stream()
4937{
4938 if (mInput == NULL) {
4939 return NULL;
4940 }
4941 return &mInput->stream->common;
4942}
4943
4944
Mathias Agopian65ab4712010-07-14 17:59:35 -07004945// ----------------------------------------------------------------------------
4946
4947int AudioFlinger::openOutput(uint32_t *pDevices,
4948 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004949 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004950 uint32_t *pChannels,
4951 uint32_t *pLatencyMs,
4952 uint32_t flags)
4953{
4954 status_t status;
4955 PlaybackThread *thread = NULL;
4956 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4957 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004958 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959 uint32_t channels = pChannels ? *pChannels : 0;
4960 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004961 audio_stream_out_t *outStream;
4962 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004963
Steve Block3856b092011-10-20 11:56:00 +01004964 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004965 pDevices ? *pDevices : 0,
4966 samplingRate,
4967 format,
4968 channels,
4969 flags);
4970
4971 if (pDevices == NULL || *pDevices == 0) {
4972 return 0;
4973 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004974
Mathias Agopian65ab4712010-07-14 17:59:35 -07004975 Mutex::Autolock _l(mLock);
4976
Dima Zavin799a70e2011-04-18 16:57:27 -07004977 outHwDev = findSuitableHwDev_l(*pDevices);
4978 if (outHwDev == NULL)
4979 return 0;
4980
Glenn Kasten58f30212012-01-12 12:27:51 -08004981 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004982 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004983 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004984 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004985 samplingRate,
4986 format,
4987 channels,
4988 status);
4989
4990 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004991 if (outStream != NULL) {
4992 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004993 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004994
Dima Zavinfce7a472011-04-19 22:30:36 -07004995 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4996 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4997 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004998 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004999 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005000 } else {
5001 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005002 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005003 }
5004 mPlaybackThreads.add(id, thread);
5005
5006 if (pSamplingRate) *pSamplingRate = samplingRate;
5007 if (pFormat) *pFormat = format;
5008 if (pChannels) *pChannels = channels;
5009 if (pLatencyMs) *pLatencyMs = thread->latency();
5010
5011 // notify client processes of the new output creation
5012 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5013 return id;
5014 }
5015
5016 return 0;
5017}
5018
5019int AudioFlinger::openDuplicateOutput(int output1, int output2)
5020{
5021 Mutex::Autolock _l(mLock);
5022 MixerThread *thread1 = checkMixerThread_l(output1);
5023 MixerThread *thread2 = checkMixerThread_l(output2);
5024
5025 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005026 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005027 return 0;
5028 }
5029
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005030 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005031 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5032 thread->addOutputTrack(thread2);
5033 mPlaybackThreads.add(id, thread);
5034 // notify client processes of the new output creation
5035 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5036 return id;
5037}
5038
5039status_t AudioFlinger::closeOutput(int output)
5040{
5041 // keep strong reference on the playback thread so that
5042 // it is not destroyed while exit() is executed
5043 sp <PlaybackThread> thread;
5044 {
5045 Mutex::Autolock _l(mLock);
5046 thread = checkPlaybackThread_l(output);
5047 if (thread == NULL) {
5048 return BAD_VALUE;
5049 }
5050
Steve Block3856b092011-10-20 11:56:00 +01005051 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005053 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005054 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005055 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005056 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5057 dupThread->removeOutputTrack((MixerThread *)thread.get());
5058 }
5059 }
5060 }
5061 void *param2 = 0;
5062 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5063 mPlaybackThreads.removeItem(output);
5064 }
5065 thread->exit();
5066
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005067 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005068 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005069 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005070 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005071 out->hwDev->close_output_stream(out->hwDev, out->stream);
5072 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005073 }
5074 return NO_ERROR;
5075}
5076
5077status_t AudioFlinger::suspendOutput(int output)
5078{
5079 Mutex::Autolock _l(mLock);
5080 PlaybackThread *thread = checkPlaybackThread_l(output);
5081
5082 if (thread == NULL) {
5083 return BAD_VALUE;
5084 }
5085
Steve Block3856b092011-10-20 11:56:00 +01005086 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005087 thread->suspend();
5088
5089 return NO_ERROR;
5090}
5091
5092status_t AudioFlinger::restoreOutput(int output)
5093{
5094 Mutex::Autolock _l(mLock);
5095 PlaybackThread *thread = checkPlaybackThread_l(output);
5096
5097 if (thread == NULL) {
5098 return BAD_VALUE;
5099 }
5100
Steve Block3856b092011-10-20 11:56:00 +01005101 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005102
5103 thread->restore();
5104
5105 return NO_ERROR;
5106}
5107
5108int AudioFlinger::openInput(uint32_t *pDevices,
5109 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005110 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111 uint32_t *pChannels,
5112 uint32_t acoustics)
5113{
5114 status_t status;
5115 RecordThread *thread = NULL;
5116 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005117 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005118 uint32_t channels = pChannels ? *pChannels : 0;
5119 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005120 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005121 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005122 audio_stream_in_t *inStream;
5123 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005124
5125 if (pDevices == NULL || *pDevices == 0) {
5126 return 0;
5127 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005128
Mathias Agopian65ab4712010-07-14 17:59:35 -07005129 Mutex::Autolock _l(mLock);
5130
Dima Zavin799a70e2011-04-18 16:57:27 -07005131 inHwDev = findSuitableHwDev_l(*pDevices);
5132 if (inHwDev == NULL)
5133 return 0;
5134
Glenn Kasten58f30212012-01-12 12:27:51 -08005135 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005136 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005137 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005138 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005139 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005140 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005141 samplingRate,
5142 format,
5143 channels,
5144 acoustics,
5145 status);
5146
5147 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5148 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5149 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005150 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005151 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005152 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005153 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005154 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005155 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005156 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005157 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005158 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005159 }
5160
Dima Zavin799a70e2011-04-18 16:57:27 -07005161 if (inStream != NULL) {
5162 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5163
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005164 int id = nextUniqueId();
5165 // Start record thread
5166 // RecorThread require both input and output device indication to forward to audio
5167 // pre processing modules
5168 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5169 thread = new RecordThread(this,
5170 input,
5171 reqSamplingRate,
5172 reqChannels,
5173 id,
5174 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005176 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005177 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5178 if (pFormat) *pFormat = format;
5179 if (pChannels) *pChannels = reqChannels;
5180
Dima Zavin799a70e2011-04-18 16:57:27 -07005181 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005182
5183 // notify client processes of the new input creation
5184 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5185 return id;
5186 }
5187
5188 return 0;
5189}
5190
5191status_t AudioFlinger::closeInput(int input)
5192{
5193 // keep strong reference on the record thread so that
5194 // it is not destroyed while exit() is executed
5195 sp <RecordThread> thread;
5196 {
5197 Mutex::Autolock _l(mLock);
5198 thread = checkRecordThread_l(input);
5199 if (thread == NULL) {
5200 return BAD_VALUE;
5201 }
5202
Steve Block3856b092011-10-20 11:56:00 +01005203 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005204 void *param2 = 0;
5205 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5206 mRecordThreads.removeItem(input);
5207 }
5208 thread->exit();
5209
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005210 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005211 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005212 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005213 in->hwDev->close_input_stream(in->hwDev, in->stream);
5214 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005215
5216 return NO_ERROR;
5217}
5218
Glenn Kastenfff6d712012-01-12 16:38:12 -08005219status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005220{
5221 Mutex::Autolock _l(mLock);
5222 MixerThread *dstThread = checkMixerThread_l(output);
5223 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005224 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005225 return BAD_VALUE;
5226 }
5227
Steve Block3856b092011-10-20 11:56:00 +01005228 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005229 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5230
Eric Laurent9f6530f2011-08-30 10:18:54 -07005231 dstThread->setStreamValid(stream, true);
5232
Mathias Agopian65ab4712010-07-14 17:59:35 -07005233 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5234 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5235 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005236 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005237 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005238 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005239 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005240 }
Eric Laurentde070132010-07-13 04:45:46 -07005241 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005242
5243 return NO_ERROR;
5244}
5245
5246
5247int AudioFlinger::newAudioSessionId()
5248{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005249 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005250}
5251
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005252void AudioFlinger::acquireAudioSessionId(int audioSession)
5253{
5254 Mutex::Autolock _l(mLock);
5255 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005256 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005257 int num = mAudioSessionRefs.size();
5258 for (int i = 0; i< num; i++) {
5259 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5260 if (ref->sessionid == audioSession && ref->pid == caller) {
5261 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005262 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005263 return;
5264 }
5265 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005266 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5267 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005268}
5269
5270void AudioFlinger::releaseAudioSessionId(int audioSession)
5271{
5272 Mutex::Autolock _l(mLock);
5273 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005274 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005275 int num = mAudioSessionRefs.size();
5276 for (int i = 0; i< num; i++) {
5277 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5278 if (ref->sessionid == audioSession && ref->pid == caller) {
5279 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005280 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005281 if (ref->cnt == 0) {
5282 mAudioSessionRefs.removeAt(i);
5283 delete ref;
5284 purgeStaleEffects_l();
5285 }
5286 return;
5287 }
5288 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005289 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005290}
5291
5292void AudioFlinger::purgeStaleEffects_l() {
5293
Steve Block3856b092011-10-20 11:56:00 +01005294 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005295
5296 Vector< sp<EffectChain> > chains;
5297
5298 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5299 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5300 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5301 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005302 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5303 chains.push(ec);
5304 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005305 }
5306 }
5307 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5308 sp<RecordThread> t = mRecordThreads.valueAt(i);
5309 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5310 sp<EffectChain> ec = t->mEffectChains[j];
5311 chains.push(ec);
5312 }
5313 }
5314
5315 for (size_t i = 0; i < chains.size(); i++) {
5316 sp<EffectChain> ec = chains[i];
5317 int sessionid = ec->sessionId();
5318 sp<ThreadBase> t = ec->mThread.promote();
5319 if (t == 0) {
5320 continue;
5321 }
5322 size_t numsessionrefs = mAudioSessionRefs.size();
5323 bool found = false;
5324 for (size_t k = 0; k < numsessionrefs; k++) {
5325 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5326 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005327 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005328 sessionid, ref->pid, ref->cnt);
5329 found = true;
5330 break;
5331 }
5332 }
5333 if (!found) {
5334 // remove all effects from the chain
5335 while (ec->mEffects.size()) {
5336 sp<EffectModule> effect = ec->mEffects[0];
5337 effect->unPin();
5338 Mutex::Autolock _l (t->mLock);
5339 t->removeEffect_l(effect);
5340 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5341 sp<EffectHandle> handle = effect->mHandles[j].promote();
5342 if (handle != 0) {
5343 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005344 if (handle->mHasControl && handle->mEnabled) {
5345 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5346 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005347 }
5348 }
5349 AudioSystem::unregisterEffect(effect->id());
5350 }
5351 }
5352 }
5353 return;
5354}
5355
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5357AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5358{
5359 PlaybackThread *thread = NULL;
5360 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5361 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5362 }
5363 return thread;
5364}
5365
5366// checkMixerThread_l() must be called with AudioFlinger::mLock held
5367AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5368{
5369 PlaybackThread *thread = checkPlaybackThread_l(output);
5370 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005371 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 thread = NULL;
5373 }
5374 }
5375 return (MixerThread *)thread;
5376}
5377
5378// checkRecordThread_l() must be called with AudioFlinger::mLock held
5379AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5380{
5381 RecordThread *thread = NULL;
5382 if (mRecordThreads.indexOfKey(input) >= 0) {
5383 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5384 }
5385 return thread;
5386}
5387
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005388uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005390 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391}
5392
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005393AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5394{
5395 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5396 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005397 AudioStreamOut *output = thread->getOutput();
5398 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005399 return thread;
5400 }
5401 }
5402 return NULL;
5403}
5404
5405uint32_t AudioFlinger::primaryOutputDevice_l()
5406{
5407 PlaybackThread *thread = primaryPlaybackThread_l();
5408
5409 if (thread == NULL) {
5410 return 0;
5411 }
5412
5413 return thread->device();
5414}
5415
5416
Mathias Agopian65ab4712010-07-14 17:59:35 -07005417// ----------------------------------------------------------------------------
5418// Effect management
5419// ----------------------------------------------------------------------------
5420
5421
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5423{
5424 Mutex::Autolock _l(mLock);
5425 return EffectQueryNumberEffects(numEffects);
5426}
5427
5428status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5429{
5430 Mutex::Autolock _l(mLock);
5431 return EffectQueryEffect(index, descriptor);
5432}
5433
5434status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5435{
5436 Mutex::Autolock _l(mLock);
5437 return EffectGetDescriptor(pUuid, descriptor);
5438}
5439
5440
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5442 effect_descriptor_t *pDesc,
5443 const sp<IEffectClient>& effectClient,
5444 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005445 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 int sessionId,
5447 status_t *status,
5448 int *id,
5449 int *enabled)
5450{
5451 status_t lStatus = NO_ERROR;
5452 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453 effect_descriptor_t desc;
5454 sp<Client> client;
5455 wp<Client> wclient;
5456
Steve Block3856b092011-10-20 11:56:00 +01005457 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005458 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459
5460 if (pDesc == NULL) {
5461 lStatus = BAD_VALUE;
5462 goto Exit;
5463 }
5464
Eric Laurent84e9a102010-09-23 16:10:16 -07005465 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005466 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005467 lStatus = PERMISSION_DENIED;
5468 goto Exit;
5469 }
5470
Dima Zavinfce7a472011-04-19 22:30:36 -07005471 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005472 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005473 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005474 lStatus = PERMISSION_DENIED;
5475 goto Exit;
5476 }
5477
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005478 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005479 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005480 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005481 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005482 lStatus = BAD_VALUE;
5483 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005484 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005485 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005486 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005487 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005488 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005489 }
5490 }
5491
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492 {
5493 Mutex::Autolock _l(mLock);
5494
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495
5496 if (!EffectIsNullUuid(&pDesc->uuid)) {
5497 // if uuid is specified, request effect descriptor
5498 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5499 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005500 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501 goto Exit;
5502 }
5503 } else {
5504 // if uuid is not specified, look for an available implementation
5505 // of the required type in effect factory
5506 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005507 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005508 lStatus = BAD_VALUE;
5509 goto Exit;
5510 }
5511 uint32_t numEffects = 0;
5512 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005513 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005514 bool found = false;
5515
5516 lStatus = EffectQueryNumberEffects(&numEffects);
5517 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005518 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005519 goto Exit;
5520 }
5521 for (uint32_t i = 0; i < numEffects; i++) {
5522 lStatus = EffectQueryEffect(i, &desc);
5523 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005524 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 continue;
5526 }
5527 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5528 // If matching type found save effect descriptor. If the session is
5529 // 0 and the effect is not auxiliary, continue enumeration in case
5530 // an auxiliary version of this effect type is available
5531 found = true;
5532 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005533 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5535 break;
5536 }
5537 }
5538 }
5539 if (!found) {
5540 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005541 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542 goto Exit;
5543 }
5544 // For same effect type, chose auxiliary version over insert version if
5545 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005546 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5548 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5549 }
5550 }
5551
5552 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005553 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005554 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5555 lStatus = INVALID_OPERATION;
5556 goto Exit;
5557 }
5558
Eric Laurent59255e42011-07-27 19:49:51 -07005559 // check recording permission for visualizer
5560 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5561 !recordingAllowed()) {
5562 lStatus = PERMISSION_DENIED;
5563 goto Exit;
5564 }
5565
Mathias Agopian65ab4712010-07-14 17:59:35 -07005566 // return effect descriptor
5567 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5568
5569 // If output is not specified try to find a matching audio session ID in one of the
5570 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005571 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5572 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005573 // Note: io is never 0 when creating an effect on an input
5574 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005575 // look for the thread where the specified audio session is present
5576 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5577 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005578 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005579 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005580 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005582 if (io == 0) {
5583 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5584 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5585 io = mRecordThreads.keyAt(i);
5586 break;
5587 }
5588 }
5589 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005590 // If no output thread contains the requested session ID, default to
5591 // first output. The effect chain will be moved to the correct output
5592 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005593 if (io == 0 && mPlaybackThreads.size()) {
5594 io = mPlaybackThreads.keyAt(0);
5595 }
Steve Block3856b092011-10-20 11:56:00 +01005596 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005597 }
5598 ThreadBase *thread = checkRecordThread_l(io);
5599 if (thread == NULL) {
5600 thread = checkPlaybackThread_l(io);
5601 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005602 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005603 lStatus = BAD_VALUE;
5604 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005605 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005607
Mathias Agopian65ab4712010-07-14 17:59:35 -07005608 wclient = mClients.valueFor(pid);
5609
5610 if (wclient != NULL) {
5611 client = wclient.promote();
5612 } else {
5613 client = new Client(this, pid);
5614 mClients.add(pid, client);
5615 }
5616
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005617 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005618 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5619 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005620 if (handle != 0 && id != NULL) {
5621 *id = handle->id();
5622 }
5623 }
5624
5625Exit:
5626 if(status) {
5627 *status = lStatus;
5628 }
5629 return handle;
5630}
5631
Eric Laurent59255e42011-07-27 19:49:51 -07005632status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005633{
Steve Block3856b092011-10-20 11:56:00 +01005634 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005635 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005636 Mutex::Autolock _l(mLock);
5637 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005638 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005639 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005640 }
Eric Laurentde070132010-07-13 04:45:46 -07005641 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5642 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005643 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005644 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005645 }
Eric Laurentde070132010-07-13 04:45:46 -07005646 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5647 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005648 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005649 return BAD_VALUE;
5650 }
5651
5652 Mutex::Autolock _dl(dstThread->mLock);
5653 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005654 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005655
Mathias Agopian65ab4712010-07-14 17:59:35 -07005656 return NO_ERROR;
5657}
5658
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005659// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005660status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005661 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005662 AudioFlinger::PlaybackThread *dstThread,
5663 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005664{
Steve Block3856b092011-10-20 11:56:00 +01005665 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005666 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005667
Eric Laurent59255e42011-07-27 19:49:51 -07005668 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005669 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005670 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005671 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005672 return INVALID_OPERATION;
5673 }
5674
Eric Laurent39e94f82010-07-28 01:32:47 -07005675 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005676 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005677 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005678 // removed.
5679 srcThread->removeEffectChain_l(chain);
5680
5681 // transfer all effects one by one so that new effect chain is created on new thread with
5682 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005683 int dstOutput = dstThread->id();
5684 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005685 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005686 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5687 while (effect != 0) {
5688 srcThread->removeEffect_l(effect);
5689 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005690 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5691 if (effect->state() == EffectModule::ACTIVE ||
5692 effect->state() == EffectModule::STOPPING) {
5693 effect->start();
5694 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005695 // if the move request is not received from audio policy manager, the effect must be
5696 // re-registered with the new strategy and output
5697 if (dstChain == 0) {
5698 dstChain = effect->chain().promote();
5699 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005700 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005701 srcThread->addEffect_l(effect);
5702 return NO_INIT;
5703 }
5704 strategy = dstChain->strategy();
5705 }
5706 if (reRegister) {
5707 AudioSystem::unregisterEffect(effect->id());
5708 AudioSystem::registerEffect(&effect->desc(),
5709 dstOutput,
5710 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005711 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005712 effect->id());
5713 }
Eric Laurentde070132010-07-13 04:45:46 -07005714 effect = chain->getEffectFromId_l(0);
5715 }
5716
5717 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718}
5719
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005720
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005722sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723 const sp<AudioFlinger::Client>& client,
5724 const sp<IEffectClient>& effectClient,
5725 int32_t priority,
5726 int sessionId,
5727 effect_descriptor_t *desc,
5728 int *enabled,
5729 status_t *status
5730 )
5731{
5732 sp<EffectModule> effect;
5733 sp<EffectHandle> handle;
5734 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005735 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005736 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 bool effectCreated = false;
5738 bool effectRegistered = false;
5739
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005740 lStatus = initCheck();
5741 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005742 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005743 goto Exit;
5744 }
5745
5746 // Do not allow effects with session ID 0 on direct output or duplicating threads
5747 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005748 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005749 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005750 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005751 lStatus = BAD_VALUE;
5752 goto Exit;
5753 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005754 // Only Pre processor effects are allowed on input threads and only on input threads
5755 if ((mType == RECORD &&
5756 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5757 (mType != RECORD &&
5758 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005759 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005760 desc->name, desc->flags, mType);
5761 lStatus = BAD_VALUE;
5762 goto Exit;
5763 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005764
Steve Block3856b092011-10-20 11:56:00 +01005765 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005766
5767 { // scope for mLock
5768 Mutex::Autolock _l(mLock);
5769
5770 // check for existing effect chain with the requested audio session
5771 chain = getEffectChain_l(sessionId);
5772 if (chain == 0) {
5773 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005774 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005775 chain = new EffectChain(this, sessionId);
5776 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005777 chain->setStrategy(getStrategyForSession_l(sessionId));
5778 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005780 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005781 }
5782
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005783 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005784
5785 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005786 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005787 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005788 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005789 if (lStatus != NO_ERROR) {
5790 goto Exit;
5791 }
5792 effectRegistered = true;
5793 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005794 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005795 lStatus = effect->status();
5796 if (lStatus != NO_ERROR) {
5797 goto Exit;
5798 }
Eric Laurentcab11242010-07-15 12:50:15 -07005799 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005800 if (lStatus != NO_ERROR) {
5801 goto Exit;
5802 }
5803 effectCreated = true;
5804
5805 effect->setDevice(mDevice);
5806 effect->setMode(mAudioFlinger->getMode());
5807 }
5808 // create effect handle and connect it to effect module
5809 handle = new EffectHandle(effect, client, effectClient, priority);
5810 lStatus = effect->addHandle(handle);
5811 if (enabled) {
5812 *enabled = (int)effect->isEnabled();
5813 }
5814 }
5815
5816Exit:
5817 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005818 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005819 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005820 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821 }
5822 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005823 AudioSystem::unregisterEffect(effect->id());
5824 }
5825 if (chainCreated) {
5826 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827 }
5828 handle.clear();
5829 }
5830
5831 if(status) {
5832 *status = lStatus;
5833 }
5834 return handle;
5835}
5836
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005837sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5838{
5839 sp<EffectModule> effect;
5840
5841 sp<EffectChain> chain = getEffectChain_l(sessionId);
5842 if (chain != 0) {
5843 effect = chain->getEffectFromId_l(effectId);
5844 }
5845 return effect;
5846}
5847
Eric Laurentde070132010-07-13 04:45:46 -07005848// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5849// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005850status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005851{
5852 // check for existing effect chain with the requested audio session
5853 int sessionId = effect->sessionId();
5854 sp<EffectChain> chain = getEffectChain_l(sessionId);
5855 bool chainCreated = false;
5856
5857 if (chain == 0) {
5858 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005859 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005860 chain = new EffectChain(this, sessionId);
5861 addEffectChain_l(chain);
5862 chain->setStrategy(getStrategyForSession_l(sessionId));
5863 chainCreated = true;
5864 }
Steve Block3856b092011-10-20 11:56:00 +01005865 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005866
5867 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005868 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005869 this, effect->desc().name, chain.get());
5870 return BAD_VALUE;
5871 }
5872
5873 status_t status = chain->addEffect_l(effect);
5874 if (status != NO_ERROR) {
5875 if (chainCreated) {
5876 removeEffectChain_l(chain);
5877 }
5878 return status;
5879 }
5880
5881 effect->setDevice(mDevice);
5882 effect->setMode(mAudioFlinger->getMode());
5883 return NO_ERROR;
5884}
5885
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005886void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005887
Steve Block3856b092011-10-20 11:56:00 +01005888 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005889 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005890 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5891 detachAuxEffect_l(effect->id());
5892 }
5893
5894 sp<EffectChain> chain = effect->chain().promote();
5895 if (chain != 0) {
5896 // remove effect chain if removing last effect
5897 if (chain->removeEffect_l(effect) == 0) {
5898 removeEffectChain_l(chain);
5899 }
5900 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005901 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005902 }
5903}
5904
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005905void AudioFlinger::ThreadBase::lockEffectChains_l(
5906 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5907{
5908 effectChains = mEffectChains;
5909 for (size_t i = 0; i < mEffectChains.size(); i++) {
5910 mEffectChains[i]->lock();
5911 }
5912}
5913
5914void AudioFlinger::ThreadBase::unlockEffectChains(
5915 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5916{
5917 for (size_t i = 0; i < effectChains.size(); i++) {
5918 effectChains[i]->unlock();
5919 }
5920}
5921
5922sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5923{
5924 Mutex::Autolock _l(mLock);
5925 return getEffectChain_l(sessionId);
5926}
5927
5928sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5929{
5930 sp<EffectChain> chain;
5931
5932 size_t size = mEffectChains.size();
5933 for (size_t i = 0; i < size; i++) {
5934 if (mEffectChains[i]->sessionId() == sessionId) {
5935 chain = mEffectChains[i];
5936 break;
5937 }
5938 }
5939 return chain;
5940}
5941
Glenn Kastenf78aee72012-01-04 11:00:47 -08005942void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005943{
5944 Mutex::Autolock _l(mLock);
5945 size_t size = mEffectChains.size();
5946 for (size_t i = 0; i < size; i++) {
5947 mEffectChains[i]->setMode_l(mode);
5948 }
5949}
5950
5951void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005952 const wp<EffectHandle>& handle,
5953 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005954
Mathias Agopian65ab4712010-07-14 17:59:35 -07005955 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005956 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005957 // delete the effect module if removing last handle on it
5958 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005959 if (!effect->isPinned() || unpiniflast) {
5960 removeEffect_l(effect);
5961 AudioSystem::unregisterEffect(effect->id());
5962 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005963 }
5964}
5965
5966status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5967{
5968 int session = chain->sessionId();
5969 int16_t *buffer = mMixBuffer;
5970 bool ownsBuffer = false;
5971
Steve Block3856b092011-10-20 11:56:00 +01005972 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005973 if (session > 0) {
5974 // Only one effect chain can be present in direct output thread and it uses
5975 // the mix buffer as input
5976 if (mType != DIRECT) {
5977 size_t numSamples = mFrameCount * mChannelCount;
5978 buffer = new int16_t[numSamples];
5979 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005980 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981 ownsBuffer = true;
5982 }
5983
5984 // Attach all tracks with same session ID to this chain.
5985 for (size_t i = 0; i < mTracks.size(); ++i) {
5986 sp<Track> track = mTracks[i];
5987 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005988 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005989 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005990 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 }
5992 }
5993
5994 // indicate all active tracks in the chain
5995 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5996 sp<Track> track = mActiveTracks[i].promote();
5997 if (track == 0) continue;
5998 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005999 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006000 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001 }
6002 }
6003 }
6004
6005 chain->setInBuffer(buffer, ownsBuffer);
6006 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006007 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006008 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006009 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6010 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006012 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6013 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006014 // Effect chain for other sessions are inserted at beginning of effect
6015 // chains list to be processed before output mix effects. Relative order between other
6016 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017 size_t size = mEffectChains.size();
6018 size_t i = 0;
6019 for (i = 0; i < size; i++) {
6020 if (mEffectChains[i]->sessionId() < session) break;
6021 }
6022 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006023 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006024
6025 return NO_ERROR;
6026}
6027
6028size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6029{
6030 int session = chain->sessionId();
6031
Steve Block3856b092011-10-20 11:56:00 +01006032 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006033
6034 for (size_t i = 0; i < mEffectChains.size(); i++) {
6035 if (chain == mEffectChains[i]) {
6036 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006037 // detach all active tracks from the chain
6038 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6039 sp<Track> track = mActiveTracks[i].promote();
6040 if (track == 0) continue;
6041 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006042 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006043 chain.get(), session);
6044 chain->decActiveTrackCnt();
6045 }
6046 }
6047
Mathias Agopian65ab4712010-07-14 17:59:35 -07006048 // detach all tracks with same session ID from this chain
6049 for (size_t i = 0; i < mTracks.size(); ++i) {
6050 sp<Track> track = mTracks[i];
6051 if (session == track->sessionId()) {
6052 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006053 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054 }
6055 }
Eric Laurentde070132010-07-13 04:45:46 -07006056 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006057 }
6058 }
6059 return mEffectChains.size();
6060}
6061
Eric Laurentde070132010-07-13 04:45:46 -07006062status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6063 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006064{
6065 Mutex::Autolock _l(mLock);
6066 return attachAuxEffect_l(track, EffectId);
6067}
6068
Eric Laurentde070132010-07-13 04:45:46 -07006069status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6070 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006071{
6072 status_t status = NO_ERROR;
6073
6074 if (EffectId == 0) {
6075 track->setAuxBuffer(0, NULL);
6076 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006077 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6078 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006079 if (effect != 0) {
6080 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6081 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6082 } else {
6083 status = INVALID_OPERATION;
6084 }
6085 } else {
6086 status = BAD_VALUE;
6087 }
6088 }
6089 return status;
6090}
6091
6092void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6093{
6094 for (size_t i = 0; i < mTracks.size(); ++i) {
6095 sp<Track> track = mTracks[i];
6096 if (track->auxEffectId() == effectId) {
6097 attachAuxEffect_l(track, 0);
6098 }
6099 }
6100}
6101
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006102status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6103{
6104 // only one chain per input thread
6105 if (mEffectChains.size() != 0) {
6106 return INVALID_OPERATION;
6107 }
Steve Block3856b092011-10-20 11:56:00 +01006108 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006109
6110 chain->setInBuffer(NULL);
6111 chain->setOutBuffer(NULL);
6112
Eric Laurent59255e42011-07-27 19:49:51 -07006113 checkSuspendOnAddEffectChain_l(chain);
6114
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006115 mEffectChains.add(chain);
6116
6117 return NO_ERROR;
6118}
6119
6120size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6121{
Steve Block3856b092011-10-20 11:56:00 +01006122 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006123 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006124 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6125 chain.get(), mEffectChains.size(), this);
6126 if (mEffectChains.size() == 1) {
6127 mEffectChains.removeAt(0);
6128 }
6129 return 0;
6130}
6131
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132// ----------------------------------------------------------------------------
6133// EffectModule implementation
6134// ----------------------------------------------------------------------------
6135
6136#undef LOG_TAG
6137#define LOG_TAG "AudioFlinger::EffectModule"
6138
6139AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6140 const wp<AudioFlinger::EffectChain>& chain,
6141 effect_descriptor_t *desc,
6142 int id,
6143 int sessionId)
6144 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006145 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146{
Steve Block3856b092011-10-20 11:56:00 +01006147 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006148 int lStatus;
6149 sp<ThreadBase> thread = mThread.promote();
6150 if (thread == 0) {
6151 return;
6152 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153
6154 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6155
6156 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006157 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006158
6159 if (mStatus != NO_ERROR) {
6160 return;
6161 }
6162 lStatus = init();
6163 if (lStatus < 0) {
6164 mStatus = lStatus;
6165 goto Error;
6166 }
6167
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006168 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6169 mPinned = true;
6170 }
Steve Block3856b092011-10-20 11:56:00 +01006171 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172 return;
6173Error:
6174 EffectRelease(mEffectInterface);
6175 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006176 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177}
6178
6179AudioFlinger::EffectModule::~EffectModule()
6180{
Steve Block3856b092011-10-20 11:56:00 +01006181 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006182 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006183 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6184 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6185 sp<ThreadBase> thread = mThread.promote();
6186 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006187 audio_stream_t *stream = thread->stream();
6188 if (stream != NULL) {
6189 stream->remove_audio_effect(stream, mEffectInterface);
6190 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006191 }
6192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006193 // release effect engine
6194 EffectRelease(mEffectInterface);
6195 }
6196}
6197
Glenn Kasten435dbe62012-01-30 10:15:48 -08006198status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199{
6200 status_t status;
6201
6202 Mutex::Autolock _l(mLock);
6203 // First handle in mHandles has highest priority and controls the effect module
6204 int priority = handle->priority();
6205 size_t size = mHandles.size();
6206 sp<EffectHandle> h;
6207 size_t i;
6208 for (i = 0; i < size; i++) {
6209 h = mHandles[i].promote();
6210 if (h == 0) continue;
6211 if (h->priority() <= priority) break;
6212 }
6213 // if inserted in first place, move effect control from previous owner to this handle
6214 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006215 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006217 enabled = h->enabled();
6218 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006219 }
Eric Laurent59255e42011-07-27 19:49:51 -07006220 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006221 status = NO_ERROR;
6222 } else {
6223 status = ALREADY_EXISTS;
6224 }
Steve Block3856b092011-10-20 11:56:00 +01006225 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006226 mHandles.insertAt(handle, i);
6227 return status;
6228}
6229
6230size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6231{
6232 Mutex::Autolock _l(mLock);
6233 size_t size = mHandles.size();
6234 size_t i;
6235 for (i = 0; i < size; i++) {
6236 if (mHandles[i] == handle) break;
6237 }
6238 if (i == size) {
6239 return size;
6240 }
Steve Block3856b092011-10-20 11:56:00 +01006241 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006242
6243 bool enabled = false;
6244 EffectHandle *hdl = handle.unsafe_get();
6245 if (hdl) {
Steve Block3856b092011-10-20 11:56:00 +01006246 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006247 enabled = hdl->enabled();
6248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006249 mHandles.removeAt(i);
6250 size = mHandles.size();
6251 // if removed from first place, move effect control from this handle to next in line
6252 if (i == 0 && size != 0) {
6253 sp<EffectHandle> h = mHandles[0].promote();
6254 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006255 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006256 }
6257 }
6258
Eric Laurentec437d82011-07-26 20:54:46 -07006259 // Prevent calls to process() and other functions on effect interface from now on.
6260 // The effect engine will be released by the destructor when the last strong reference on
6261 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006262 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006263 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006264 }
6265
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 return size;
6267}
6268
Eric Laurent59255e42011-07-27 19:49:51 -07006269sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6270{
6271 Mutex::Autolock _l(mLock);
6272 sp<EffectHandle> handle;
6273 if (mHandles.size() != 0) {
6274 handle = mHandles[0].promote();
6275 }
6276 return handle;
6277}
6278
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006279void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006280{
Steve Block3856b092011-10-20 11:56:00 +01006281 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 // keep a strong reference on this EffectModule to avoid calling the
6283 // destructor before we exit
6284 sp<EffectModule> keep(this);
6285 {
6286 sp<ThreadBase> thread = mThread.promote();
6287 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006288 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 }
6290 }
6291}
6292
6293void AudioFlinger::EffectModule::updateState() {
6294 Mutex::Autolock _l(mLock);
6295
6296 switch (mState) {
6297 case RESTART:
6298 reset_l();
6299 // FALL THROUGH
6300
6301 case STARTING:
6302 // clear auxiliary effect input buffer for next accumulation
6303 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6304 memset(mConfig.inputCfg.buffer.raw,
6305 0,
6306 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6307 }
6308 start_l();
6309 mState = ACTIVE;
6310 break;
6311 case STOPPING:
6312 stop_l();
6313 mDisableWaitCnt = mMaxDisableWaitCnt;
6314 mState = STOPPED;
6315 break;
6316 case STOPPED:
6317 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6318 // turn off sequence.
6319 if (--mDisableWaitCnt == 0) {
6320 reset_l();
6321 mState = IDLE;
6322 }
6323 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006324 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006325 break;
6326 }
6327}
6328
6329void AudioFlinger::EffectModule::process()
6330{
6331 Mutex::Autolock _l(mLock);
6332
Eric Laurentec437d82011-07-26 20:54:46 -07006333 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006334 mConfig.inputCfg.buffer.raw == NULL ||
6335 mConfig.outputCfg.buffer.raw == NULL) {
6336 return;
6337 }
6338
Eric Laurent8f45bd72010-08-31 13:50:07 -07006339 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6341 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006342 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006343 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006344 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345 }
6346
6347 // do the actual processing in the effect engine
6348 int ret = (*mEffectInterface)->process(mEffectInterface,
6349 &mConfig.inputCfg.buffer,
6350 &mConfig.outputCfg.buffer);
6351
6352 // force transition to IDLE state when engine is ready
6353 if (mState == STOPPED && ret == -ENODATA) {
6354 mDisableWaitCnt = 1;
6355 }
6356
6357 // clear auxiliary effect input buffer for next accumulation
6358 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006359 memset(mConfig.inputCfg.buffer.raw, 0,
6360 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006361 }
6362 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006363 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6364 // If an insert effect is idle and input buffer is different from output buffer,
6365 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006366 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006367 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006368 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6369 int16_t *in = mConfig.inputCfg.buffer.s16;
6370 int16_t *out = mConfig.outputCfg.buffer.s16;
6371 for (size_t i = 0; i < frameCnt; i++) {
6372 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006373 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 }
6375 }
6376}
6377
6378void AudioFlinger::EffectModule::reset_l()
6379{
6380 if (mEffectInterface == NULL) {
6381 return;
6382 }
6383 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6384}
6385
6386status_t AudioFlinger::EffectModule::configure()
6387{
6388 uint32_t channels;
6389 if (mEffectInterface == NULL) {
6390 return NO_INIT;
6391 }
6392
6393 sp<ThreadBase> thread = mThread.promote();
6394 if (thread == 0) {
6395 return DEAD_OBJECT;
6396 }
6397
6398 // TODO: handle configuration of effects replacing track process
6399 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006400 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006401 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006402 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006403 }
6404
6405 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006406 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006407 } else {
6408 mConfig.inputCfg.channels = channels;
6409 }
6410 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006411 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6412 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006413 mConfig.inputCfg.samplingRate = thread->sampleRate();
6414 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6415 mConfig.inputCfg.bufferProvider.cookie = NULL;
6416 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6417 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6418 mConfig.outputCfg.bufferProvider.cookie = NULL;
6419 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6420 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6421 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6422 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006423 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006424 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006425 // - in other sessions:
6426 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6427 // other effect: overwrites output buffer: input buffer == output buffer
6428 // Auxiliary effect:
6429 // accumulates in output buffer: input buffer != output buffer
6430 // Therefore: accumulate <=> input buffer != output buffer
6431 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6432 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6433 } else {
6434 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6435 }
6436 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6437 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6438 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6439 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6440
Steve Block3856b092011-10-20 11:56:00 +01006441 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006442 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6443
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006445 uint32_t size = sizeof(int);
6446 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006447 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006448 sizeof(effect_config_t),
6449 &mConfig,
6450 &size,
6451 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 if (status == 0) {
6453 status = cmdStatus;
6454 }
6455
6456 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6457 (1000 * mConfig.outputCfg.buffer.frameCount);
6458
6459 return status;
6460}
6461
6462status_t AudioFlinger::EffectModule::init()
6463{
6464 Mutex::Autolock _l(mLock);
6465 if (mEffectInterface == NULL) {
6466 return NO_INIT;
6467 }
6468 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006469 uint32_t size = sizeof(status_t);
6470 status_t status = (*mEffectInterface)->command(mEffectInterface,
6471 EFFECT_CMD_INIT,
6472 0,
6473 NULL,
6474 &size,
6475 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476 if (status == 0) {
6477 status = cmdStatus;
6478 }
6479 return status;
6480}
6481
Eric Laurentec35a142011-10-05 17:42:25 -07006482status_t AudioFlinger::EffectModule::start()
6483{
6484 Mutex::Autolock _l(mLock);
6485 return start_l();
6486}
6487
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488status_t AudioFlinger::EffectModule::start_l()
6489{
6490 if (mEffectInterface == NULL) {
6491 return NO_INIT;
6492 }
6493 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006494 uint32_t size = sizeof(status_t);
6495 status_t status = (*mEffectInterface)->command(mEffectInterface,
6496 EFFECT_CMD_ENABLE,
6497 0,
6498 NULL,
6499 &size,
6500 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501 if (status == 0) {
6502 status = cmdStatus;
6503 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006504 if (status == 0 &&
6505 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6506 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6507 sp<ThreadBase> thread = mThread.promote();
6508 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006509 audio_stream_t *stream = thread->stream();
6510 if (stream != NULL) {
6511 stream->add_audio_effect(stream, mEffectInterface);
6512 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006513 }
6514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006515 return status;
6516}
6517
Eric Laurentec437d82011-07-26 20:54:46 -07006518status_t AudioFlinger::EffectModule::stop()
6519{
6520 Mutex::Autolock _l(mLock);
6521 return stop_l();
6522}
6523
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524status_t AudioFlinger::EffectModule::stop_l()
6525{
6526 if (mEffectInterface == NULL) {
6527 return NO_INIT;
6528 }
6529 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006530 uint32_t size = sizeof(status_t);
6531 status_t status = (*mEffectInterface)->command(mEffectInterface,
6532 EFFECT_CMD_DISABLE,
6533 0,
6534 NULL,
6535 &size,
6536 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006537 if (status == 0) {
6538 status = cmdStatus;
6539 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006540 if (status == 0 &&
6541 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6542 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6543 sp<ThreadBase> thread = mThread.promote();
6544 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006545 audio_stream_t *stream = thread->stream();
6546 if (stream != NULL) {
6547 stream->remove_audio_effect(stream, mEffectInterface);
6548 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006549 }
6550 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006551 return status;
6552}
6553
Eric Laurent25f43952010-07-28 05:40:18 -07006554status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6555 uint32_t cmdSize,
6556 void *pCmdData,
6557 uint32_t *replySize,
6558 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559{
6560 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006561// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006562
Eric Laurentec437d82011-07-26 20:54:46 -07006563 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006564 return NO_INIT;
6565 }
Eric Laurent25f43952010-07-28 05:40:18 -07006566 status_t status = (*mEffectInterface)->command(mEffectInterface,
6567 cmdCode,
6568 cmdSize,
6569 pCmdData,
6570 replySize,
6571 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006572 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006573 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006574 for (size_t i = 1; i < mHandles.size(); i++) {
6575 sp<EffectHandle> h = mHandles[i].promote();
6576 if (h != 0) {
6577 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6578 }
6579 }
6580 }
6581 return status;
6582}
6583
6584status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6585{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006586
Mathias Agopian65ab4712010-07-14 17:59:35 -07006587 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006588 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006589
6590 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006591 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6592 if (enabled && status != NO_ERROR) {
6593 return status;
6594 }
6595
Mathias Agopian65ab4712010-07-14 17:59:35 -07006596 switch (mState) {
6597 // going from disabled to enabled
6598 case IDLE:
6599 mState = STARTING;
6600 break;
6601 case STOPPED:
6602 mState = RESTART;
6603 break;
6604 case STOPPING:
6605 mState = ACTIVE;
6606 break;
6607
6608 // going from enabled to disabled
6609 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006610 mState = STOPPED;
6611 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006612 case STARTING:
6613 mState = IDLE;
6614 break;
6615 case ACTIVE:
6616 mState = STOPPING;
6617 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006618 case DESTROYED:
6619 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006620 }
6621 for (size_t i = 1; i < mHandles.size(); i++) {
6622 sp<EffectHandle> h = mHandles[i].promote();
6623 if (h != 0) {
6624 h->setEnabled(enabled);
6625 }
6626 }
6627 }
6628 return NO_ERROR;
6629}
6630
6631bool AudioFlinger::EffectModule::isEnabled()
6632{
6633 switch (mState) {
6634 case RESTART:
6635 case STARTING:
6636 case ACTIVE:
6637 return true;
6638 case IDLE:
6639 case STOPPING:
6640 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006641 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006642 default:
6643 return false;
6644 }
6645}
6646
Eric Laurent8f45bd72010-08-31 13:50:07 -07006647bool AudioFlinger::EffectModule::isProcessEnabled()
6648{
6649 switch (mState) {
6650 case RESTART:
6651 case ACTIVE:
6652 case STOPPING:
6653 case STOPPED:
6654 return true;
6655 case IDLE:
6656 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006657 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006658 default:
6659 return false;
6660 }
6661}
6662
Mathias Agopian65ab4712010-07-14 17:59:35 -07006663status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6664{
6665 Mutex::Autolock _l(mLock);
6666 status_t status = NO_ERROR;
6667
6668 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6669 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006670 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006671 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6672 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006673 status_t cmdStatus;
6674 uint32_t volume[2];
6675 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006676 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006677 volume[0] = *left;
6678 volume[1] = *right;
6679 if (controller) {
6680 pVolume = volume;
6681 }
Eric Laurent25f43952010-07-28 05:40:18 -07006682 status = (*mEffectInterface)->command(mEffectInterface,
6683 EFFECT_CMD_SET_VOLUME,
6684 size,
6685 volume,
6686 &size,
6687 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006688 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6689 *left = volume[0];
6690 *right = volume[1];
6691 }
6692 }
6693 return status;
6694}
6695
6696status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6697{
6698 Mutex::Autolock _l(mLock);
6699 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006700 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6701 // audio pre processing modules on RecordThread can receive both output and
6702 // input device indication in the same call
6703 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6704 if (dev) {
6705 status_t cmdStatus;
6706 uint32_t size = sizeof(status_t);
6707
6708 status = (*mEffectInterface)->command(mEffectInterface,
6709 EFFECT_CMD_SET_DEVICE,
6710 sizeof(uint32_t),
6711 &dev,
6712 &size,
6713 &cmdStatus);
6714 if (status == NO_ERROR) {
6715 status = cmdStatus;
6716 }
6717 }
6718 dev = device & AUDIO_DEVICE_IN_ALL;
6719 if (dev) {
6720 status_t cmdStatus;
6721 uint32_t size = sizeof(status_t);
6722
6723 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6724 EFFECT_CMD_SET_INPUT_DEVICE,
6725 sizeof(uint32_t),
6726 &dev,
6727 &size,
6728 &cmdStatus);
6729 if (status2 == NO_ERROR) {
6730 status2 = cmdStatus;
6731 }
6732 if (status == NO_ERROR) {
6733 status = status2;
6734 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006735 }
6736 }
6737 return status;
6738}
6739
Glenn Kastenf78aee72012-01-04 11:00:47 -08006740status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006741{
6742 Mutex::Autolock _l(mLock);
6743 status_t status = NO_ERROR;
6744 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006746 uint32_t size = sizeof(status_t);
6747 status = (*mEffectInterface)->command(mEffectInterface,
6748 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006749 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006750 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006751 &size,
6752 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006753 if (status == NO_ERROR) {
6754 status = cmdStatus;
6755 }
6756 }
6757 return status;
6758}
6759
Eric Laurent59255e42011-07-27 19:49:51 -07006760void AudioFlinger::EffectModule::setSuspended(bool suspended)
6761{
6762 Mutex::Autolock _l(mLock);
6763 mSuspended = suspended;
6764}
Glenn Kastena3a85482012-01-04 11:01:11 -08006765
6766bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006767{
6768 Mutex::Autolock _l(mLock);
6769 return mSuspended;
6770}
6771
Mathias Agopian65ab4712010-07-14 17:59:35 -07006772status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6773{
6774 const size_t SIZE = 256;
6775 char buffer[SIZE];
6776 String8 result;
6777
6778 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6779 result.append(buffer);
6780
6781 bool locked = tryLock(mLock);
6782 // failed to lock - AudioFlinger is probably deadlocked
6783 if (!locked) {
6784 result.append("\t\tCould not lock Fx mutex:\n");
6785 }
6786
6787 result.append("\t\tSession Status State Engine:\n");
6788 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6789 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6790 result.append(buffer);
6791
6792 result.append("\t\tDescriptor:\n");
6793 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6794 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6795 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6796 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6797 result.append(buffer);
6798 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6799 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6800 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6801 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6802 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006803 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006804 mDescriptor.apiVersion,
6805 mDescriptor.flags);
6806 result.append(buffer);
6807 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6808 mDescriptor.name);
6809 result.append(buffer);
6810 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6811 mDescriptor.implementor);
6812 result.append(buffer);
6813
6814 result.append("\t\t- Input configuration:\n");
6815 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6816 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6817 (uint32_t)mConfig.inputCfg.buffer.raw,
6818 mConfig.inputCfg.buffer.frameCount,
6819 mConfig.inputCfg.samplingRate,
6820 mConfig.inputCfg.channels,
6821 mConfig.inputCfg.format);
6822 result.append(buffer);
6823
6824 result.append("\t\t- Output configuration:\n");
6825 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6826 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6827 (uint32_t)mConfig.outputCfg.buffer.raw,
6828 mConfig.outputCfg.buffer.frameCount,
6829 mConfig.outputCfg.samplingRate,
6830 mConfig.outputCfg.channels,
6831 mConfig.outputCfg.format);
6832 result.append(buffer);
6833
6834 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6835 result.append(buffer);
6836 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6837 for (size_t i = 0; i < mHandles.size(); ++i) {
6838 sp<EffectHandle> handle = mHandles[i].promote();
6839 if (handle != 0) {
6840 handle->dump(buffer, SIZE);
6841 result.append(buffer);
6842 }
6843 }
6844
6845 result.append("\n");
6846
6847 write(fd, result.string(), result.length());
6848
6849 if (locked) {
6850 mLock.unlock();
6851 }
6852
6853 return NO_ERROR;
6854}
6855
6856// ----------------------------------------------------------------------------
6857// EffectHandle implementation
6858// ----------------------------------------------------------------------------
6859
6860#undef LOG_TAG
6861#define LOG_TAG "AudioFlinger::EffectHandle"
6862
6863AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6864 const sp<AudioFlinger::Client>& client,
6865 const sp<IEffectClient>& effectClient,
6866 int32_t priority)
6867 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006868 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006869 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006870{
Steve Block3856b092011-10-20 11:56:00 +01006871 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006872
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006873 if (client == 0) {
6874 return;
6875 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006876 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6877 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6878 if (mCblkMemory != 0) {
6879 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6880
6881 if (mCblk) {
6882 new(mCblk) effect_param_cblk_t();
6883 mBuffer = (uint8_t *)mCblk + bufOffset;
6884 }
6885 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006886 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006887 return;
6888 }
6889}
6890
6891AudioFlinger::EffectHandle::~EffectHandle()
6892{
Steve Block3856b092011-10-20 11:56:00 +01006893 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006894 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006895 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006896}
6897
6898status_t AudioFlinger::EffectHandle::enable()
6899{
Steve Block3856b092011-10-20 11:56:00 +01006900 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006901 if (!mHasControl) return INVALID_OPERATION;
6902 if (mEffect == 0) return DEAD_OBJECT;
6903
Eric Laurentdb7c0792011-08-10 10:37:50 -07006904 if (mEnabled) {
6905 return NO_ERROR;
6906 }
6907
Eric Laurent59255e42011-07-27 19:49:51 -07006908 mEnabled = true;
6909
6910 sp<ThreadBase> thread = mEffect->thread().promote();
6911 if (thread != 0) {
6912 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6913 }
6914
6915 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6916 if (mEffect->suspended()) {
6917 return NO_ERROR;
6918 }
6919
Eric Laurentdb7c0792011-08-10 10:37:50 -07006920 status_t status = mEffect->setEnabled(true);
6921 if (status != NO_ERROR) {
6922 if (thread != 0) {
6923 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6924 }
6925 mEnabled = false;
6926 }
6927 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928}
6929
6930status_t AudioFlinger::EffectHandle::disable()
6931{
Steve Block3856b092011-10-20 11:56:00 +01006932 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006934 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006935
Eric Laurentdb7c0792011-08-10 10:37:50 -07006936 if (!mEnabled) {
6937 return NO_ERROR;
6938 }
Eric Laurent59255e42011-07-27 19:49:51 -07006939 mEnabled = false;
6940
6941 if (mEffect->suspended()) {
6942 return NO_ERROR;
6943 }
6944
6945 status_t status = mEffect->setEnabled(false);
6946
6947 sp<ThreadBase> thread = mEffect->thread().promote();
6948 if (thread != 0) {
6949 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6950 }
6951
6952 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953}
6954
6955void AudioFlinger::EffectHandle::disconnect()
6956{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006957 disconnect(true);
6958}
6959
6960void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6961{
Steve Block3856b092011-10-20 11:56:00 +01006962 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006963 if (mEffect == 0) {
6964 return;
6965 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006966 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006967
Eric Laurenta85a74a2011-10-19 11:44:54 -07006968 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006969 sp<ThreadBase> thread = mEffect->thread().promote();
6970 if (thread != 0) {
6971 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6972 }
Eric Laurent59255e42011-07-27 19:49:51 -07006973 }
6974
Mathias Agopian65ab4712010-07-14 17:59:35 -07006975 // release sp on module => module destructor can be called now
6976 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006977 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006978 if (mCblk) {
6979 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6980 }
6981 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6983 mClient.clear();
6984 }
6985}
6986
Eric Laurent25f43952010-07-28 05:40:18 -07006987status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6988 uint32_t cmdSize,
6989 void *pCmdData,
6990 uint32_t *replySize,
6991 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006992{
Steve Block3856b092011-10-20 11:56:00 +01006993// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006994// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006995
6996 // only get parameter command is permitted for applications not controlling the effect
6997 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6998 return INVALID_OPERATION;
6999 }
7000 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007001 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007002
7003 // handle commands that are not forwarded transparently to effect engine
7004 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7005 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7006 // no risk to block the whole media server process or mixer threads is we are stuck here
7007 Mutex::Autolock _l(mCblk->lock);
7008 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7009 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7010 mCblk->serverIndex = 0;
7011 mCblk->clientIndex = 0;
7012 return BAD_VALUE;
7013 }
7014 status_t status = NO_ERROR;
7015 while (mCblk->serverIndex < mCblk->clientIndex) {
7016 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007017 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018 int *p = (int *)(mBuffer + mCblk->serverIndex);
7019 int size = *p++;
7020 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007021 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007022 break;
7023 }
7024 effect_param_t *param = (effect_param_t *)p;
7025 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007026 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007027 mCblk->serverIndex += size;
7028 continue;
7029 }
Eric Laurent25f43952010-07-28 05:40:18 -07007030 uint32_t psize = sizeof(effect_param_t) +
7031 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7032 param->vsize;
7033 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7034 psize,
7035 p,
7036 &rsize,
7037 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007038 // stop at first error encountered
7039 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007041 *(int *)pReplyData = reply;
7042 break;
7043 } else if (reply != NO_ERROR) {
7044 *(int *)pReplyData = reply;
7045 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007046 }
7047 mCblk->serverIndex += size;
7048 }
7049 mCblk->serverIndex = 0;
7050 mCblk->clientIndex = 0;
7051 return status;
7052 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007053 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007054 return enable();
7055 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007056 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057 return disable();
7058 }
7059
7060 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7061}
7062
7063sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7064 return mCblkMemory;
7065}
7066
Eric Laurent59255e42011-07-27 19:49:51 -07007067void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068{
Steve Block3856b092011-10-20 11:56:00 +01007069 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007070
7071 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007072 mEnabled = enabled;
7073
Mathias Agopian65ab4712010-07-14 17:59:35 -07007074 if (signal && mEffectClient != 0) {
7075 mEffectClient->controlStatusChanged(hasControl);
7076 }
7077}
7078
Eric Laurent25f43952010-07-28 05:40:18 -07007079void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7080 uint32_t cmdSize,
7081 void *pCmdData,
7082 uint32_t replySize,
7083 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084{
7085 if (mEffectClient != 0) {
7086 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7087 }
7088}
7089
7090
7091
7092void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7093{
7094 if (mEffectClient != 0) {
7095 mEffectClient->enableStatusChanged(enabled);
7096 }
7097}
7098
7099status_t AudioFlinger::EffectHandle::onTransact(
7100 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7101{
7102 return BnEffect::onTransact(code, data, reply, flags);
7103}
7104
7105
7106void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7107{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007108 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007109
7110 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7111 (mClient == NULL) ? getpid() : mClient->pid(),
7112 mPriority,
7113 mHasControl,
7114 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007115 mCblk ? mCblk->clientIndex : 0,
7116 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007117 );
7118
7119 if (locked) {
7120 mCblk->lock.unlock();
7121 }
7122}
7123
7124#undef LOG_TAG
7125#define LOG_TAG "AudioFlinger::EffectChain"
7126
7127AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7128 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007129 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007130 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7131 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007132{
Dima Zavinfce7a472011-04-19 22:30:36 -07007133 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007134 sp<ThreadBase> thread = mThread.promote();
7135 if (thread == 0) {
7136 return;
7137 }
7138 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7139 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007140}
7141
7142AudioFlinger::EffectChain::~EffectChain()
7143{
7144 if (mOwnInBuffer) {
7145 delete mInBuffer;
7146 }
7147
7148}
7149
Eric Laurent59255e42011-07-27 19:49:51 -07007150// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007151sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007152{
7153 sp<EffectModule> effect;
7154 size_t size = mEffects.size();
7155
7156 for (size_t i = 0; i < size; i++) {
7157 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7158 effect = mEffects[i];
7159 break;
7160 }
7161 }
7162 return effect;
7163}
7164
Eric Laurent59255e42011-07-27 19:49:51 -07007165// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007166sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007167{
7168 sp<EffectModule> effect;
7169 size_t size = mEffects.size();
7170
7171 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007172 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7173 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007174 effect = mEffects[i];
7175 break;
7176 }
7177 }
7178 return effect;
7179}
7180
Eric Laurent59255e42011-07-27 19:49:51 -07007181// getEffectFromType_l() must be called with ThreadBase::mLock held
7182sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7183 const effect_uuid_t *type)
7184{
7185 sp<EffectModule> effect;
7186 size_t size = mEffects.size();
7187
7188 for (size_t i = 0; i < size; i++) {
7189 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7190 effect = mEffects[i];
7191 break;
7192 }
7193 }
7194 return effect;
7195}
7196
Mathias Agopian65ab4712010-07-14 17:59:35 -07007197// Must be called with EffectChain::mLock locked
7198void AudioFlinger::EffectChain::process_l()
7199{
Eric Laurentdac69112010-09-28 14:09:57 -07007200 sp<ThreadBase> thread = mThread.promote();
7201 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007202 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007203 return;
7204 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007205 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7206 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007207 // always process effects unless no more tracks are on the session and the effect tail
7208 // has been rendered
7209 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007210 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007211 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007212
Eric Laurent544fe9b2011-11-11 15:42:52 -08007213 if (!tracksOnSession && mTailBufferCount == 0) {
7214 doProcess = false;
7215 }
7216
7217 if (activeTrackCnt() == 0) {
7218 // if no track is active and the effect tail has not been rendered,
7219 // the input buffer must be cleared here as the mixer process will not do it
7220 if (tracksOnSession || mTailBufferCount > 0) {
7221 size_t numSamples = thread->frameCount() * thread->channelCount();
7222 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7223 if (mTailBufferCount > 0) {
7224 mTailBufferCount--;
7225 }
7226 }
7227 }
Eric Laurentdac69112010-09-28 14:09:57 -07007228 }
7229
Mathias Agopian65ab4712010-07-14 17:59:35 -07007230 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007231 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007232 for (size_t i = 0; i < size; i++) {
7233 mEffects[i]->process();
7234 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007235 }
7236 for (size_t i = 0; i < size; i++) {
7237 mEffects[i]->updateState();
7238 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007239}
7240
Eric Laurentcab11242010-07-15 12:50:15 -07007241// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007242status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007243{
7244 effect_descriptor_t desc = effect->desc();
7245 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7246
7247 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007248 effect->setChain(this);
7249 sp<ThreadBase> thread = mThread.promote();
7250 if (thread == 0) {
7251 return NO_INIT;
7252 }
7253 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007254
7255 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7256 // Auxiliary effects are inserted at the beginning of mEffects vector as
7257 // they are processed first and accumulated in chain input buffer
7258 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007259
Mathias Agopian65ab4712010-07-14 17:59:35 -07007260 // the input buffer for auxiliary effect contains mono samples in
7261 // 32 bit format. This is to avoid saturation in AudoMixer
7262 // accumulation stage. Saturation is done in EffectModule::process() before
7263 // calling the process in effect engine
7264 size_t numSamples = thread->frameCount();
7265 int32_t *buffer = new int32_t[numSamples];
7266 memset(buffer, 0, numSamples * sizeof(int32_t));
7267 effect->setInBuffer((int16_t *)buffer);
7268 // auxiliary effects output samples to chain input buffer for further processing
7269 // by insert effects
7270 effect->setOutBuffer(mInBuffer);
7271 } else {
7272 // Insert effects are inserted at the end of mEffects vector as they are processed
7273 // after track and auxiliary effects.
7274 // Insert effect order as a function of indicated preference:
7275 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7276 // another effect is present
7277 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7278 // last effect claiming first position
7279 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7280 // first effect claiming last position
7281 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7282 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7283 // already present
7284
7285 int size = (int)mEffects.size();
7286 int idx_insert = size;
7287 int idx_insert_first = -1;
7288 int idx_insert_last = -1;
7289
7290 for (int i = 0; i < size; i++) {
7291 effect_descriptor_t d = mEffects[i]->desc();
7292 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7293 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7294 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7295 // check invalid effect chaining combinations
7296 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7297 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007298 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007299 return INVALID_OPERATION;
7300 }
7301 // remember position of first insert effect and by default
7302 // select this as insert position for new effect
7303 if (idx_insert == size) {
7304 idx_insert = i;
7305 }
7306 // remember position of last insert effect claiming
7307 // first position
7308 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7309 idx_insert_first = i;
7310 }
7311 // remember position of first insert effect claiming
7312 // last position
7313 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7314 idx_insert_last == -1) {
7315 idx_insert_last = i;
7316 }
7317 }
7318 }
7319
7320 // modify idx_insert from first position if needed
7321 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7322 if (idx_insert_last != -1) {
7323 idx_insert = idx_insert_last;
7324 } else {
7325 idx_insert = size;
7326 }
7327 } else {
7328 if (idx_insert_first != -1) {
7329 idx_insert = idx_insert_first + 1;
7330 }
7331 }
7332
7333 // always read samples from chain input buffer
7334 effect->setInBuffer(mInBuffer);
7335
7336 // if last effect in the chain, output samples to chain
7337 // output buffer, otherwise to chain input buffer
7338 if (idx_insert == size) {
7339 if (idx_insert != 0) {
7340 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7341 mEffects[idx_insert-1]->configure();
7342 }
7343 effect->setOutBuffer(mOutBuffer);
7344 } else {
7345 effect->setOutBuffer(mInBuffer);
7346 }
7347 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348
Steve Block3856b092011-10-20 11:56:00 +01007349 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007350 }
7351 effect->configure();
7352 return NO_ERROR;
7353}
7354
Eric Laurentcab11242010-07-15 12:50:15 -07007355// removeEffect_l() must be called with PlaybackThread::mLock held
7356size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007357{
7358 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007359 int size = (int)mEffects.size();
7360 int i;
7361 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7362
7363 for (i = 0; i < size; i++) {
7364 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007365 // calling stop here will remove pre-processing effect from the audio HAL.
7366 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7367 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007368 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7369 mEffects[i]->state() == EffectModule::STOPPING) {
7370 mEffects[i]->stop();
7371 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7373 delete[] effect->inBuffer();
7374 } else {
7375 if (i == size - 1 && i != 0) {
7376 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7377 mEffects[i - 1]->configure();
7378 }
7379 }
7380 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007381 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382 break;
7383 }
7384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007385
7386 return mEffects.size();
7387}
7388
Eric Laurentcab11242010-07-15 12:50:15 -07007389// setDevice_l() must be called with PlaybackThread::mLock held
7390void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007391{
7392 size_t size = mEffects.size();
7393 for (size_t i = 0; i < size; i++) {
7394 mEffects[i]->setDevice(device);
7395 }
7396}
7397
Eric Laurentcab11242010-07-15 12:50:15 -07007398// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007399void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400{
7401 size_t size = mEffects.size();
7402 for (size_t i = 0; i < size; i++) {
7403 mEffects[i]->setMode(mode);
7404 }
7405}
7406
Eric Laurentcab11242010-07-15 12:50:15 -07007407// setVolume_l() must be called with PlaybackThread::mLock held
7408bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007409{
7410 uint32_t newLeft = *left;
7411 uint32_t newRight = *right;
7412 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007413 int ctrlIdx = -1;
7414 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007415
Eric Laurentcab11242010-07-15 12:50:15 -07007416 // first update volume controller
7417 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007418 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007419 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7420 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007421 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007422 break;
7423 }
7424 }
7425
7426 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007427 if (hasControl) {
7428 *left = mNewLeftVolume;
7429 *right = mNewRightVolume;
7430 }
7431 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007432 }
7433
7434 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007435 mLeftVolume = newLeft;
7436 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007437
7438 // second get volume update from volume controller
7439 if (ctrlIdx >= 0) {
7440 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007441 mNewLeftVolume = newLeft;
7442 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007443 }
7444 // then indicate volume to all other effects in chain.
7445 // Pass altered volume to effects before volume controller
7446 // and requested volume to effects after controller
7447 uint32_t lVol = newLeft;
7448 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007449
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007451 if ((int)i == ctrlIdx) continue;
7452 // this also works for ctrlIdx == -1 when there is no volume controller
7453 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007454 lVol = *left;
7455 rVol = *right;
7456 }
7457 mEffects[i]->setVolume(&lVol, &rVol, false);
7458 }
7459 *left = newLeft;
7460 *right = newRight;
7461
7462 return hasControl;
7463}
7464
Mathias Agopian65ab4712010-07-14 17:59:35 -07007465status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7466{
7467 const size_t SIZE = 256;
7468 char buffer[SIZE];
7469 String8 result;
7470
7471 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7472 result.append(buffer);
7473
7474 bool locked = tryLock(mLock);
7475 // failed to lock - AudioFlinger is probably deadlocked
7476 if (!locked) {
7477 result.append("\tCould not lock mutex:\n");
7478 }
7479
Eric Laurentcab11242010-07-15 12:50:15 -07007480 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7481 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007482 mEffects.size(),
7483 (uint32_t)mInBuffer,
7484 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007485 mActiveTrackCnt);
7486 result.append(buffer);
7487 write(fd, result.string(), result.size());
7488
7489 for (size_t i = 0; i < mEffects.size(); ++i) {
7490 sp<EffectModule> effect = mEffects[i];
7491 if (effect != 0) {
7492 effect->dump(fd, args);
7493 }
7494 }
7495
7496 if (locked) {
7497 mLock.unlock();
7498 }
7499
7500 return NO_ERROR;
7501}
7502
Eric Laurent59255e42011-07-27 19:49:51 -07007503// must be called with ThreadBase::mLock held
7504void AudioFlinger::EffectChain::setEffectSuspended_l(
7505 const effect_uuid_t *type, bool suspend)
7506{
7507 sp<SuspendedEffectDesc> desc;
7508 // use effect type UUID timelow as key as there is no real risk of identical
7509 // timeLow fields among effect type UUIDs.
7510 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7511 if (suspend) {
7512 if (index >= 0) {
7513 desc = mSuspendedEffects.valueAt(index);
7514 } else {
7515 desc = new SuspendedEffectDesc();
7516 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7517 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007518 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007519 }
7520 if (desc->mRefCount++ == 0) {
7521 sp<EffectModule> effect = getEffectIfEnabled(type);
7522 if (effect != 0) {
7523 desc->mEffect = effect;
7524 effect->setSuspended(true);
7525 effect->setEnabled(false);
7526 }
7527 }
7528 } else {
7529 if (index < 0) {
7530 return;
7531 }
7532 desc = mSuspendedEffects.valueAt(index);
7533 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007534 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007535 desc->mRefCount = 1;
7536 }
7537 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007538 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007539 if (desc->mEffect != 0) {
7540 sp<EffectModule> effect = desc->mEffect.promote();
7541 if (effect != 0) {
7542 effect->setSuspended(false);
7543 sp<EffectHandle> handle = effect->controlHandle();
7544 if (handle != 0) {
7545 effect->setEnabled(handle->enabled());
7546 }
7547 }
7548 desc->mEffect.clear();
7549 }
7550 mSuspendedEffects.removeItemsAt(index);
7551 }
7552 }
7553}
7554
7555// must be called with ThreadBase::mLock held
7556void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7557{
7558 sp<SuspendedEffectDesc> desc;
7559
7560 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7561 if (suspend) {
7562 if (index >= 0) {
7563 desc = mSuspendedEffects.valueAt(index);
7564 } else {
7565 desc = new SuspendedEffectDesc();
7566 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007567 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007568 }
7569 if (desc->mRefCount++ == 0) {
7570 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7571 for (size_t i = 0; i < effects.size(); i++) {
7572 setEffectSuspended_l(&effects[i]->desc().type, true);
7573 }
7574 }
7575 } else {
7576 if (index < 0) {
7577 return;
7578 }
7579 desc = mSuspendedEffects.valueAt(index);
7580 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007581 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007582 desc->mRefCount = 1;
7583 }
7584 if (--desc->mRefCount == 0) {
7585 Vector<const effect_uuid_t *> types;
7586 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7587 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7588 continue;
7589 }
7590 types.add(&mSuspendedEffects.valueAt(i)->mType);
7591 }
7592 for (size_t i = 0; i < types.size(); i++) {
7593 setEffectSuspended_l(types[i], false);
7594 }
Steve Block3856b092011-10-20 11:56:00 +01007595 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007596 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7597 }
7598 }
7599}
7600
Eric Laurent6bffdb82011-09-23 08:40:41 -07007601
7602// The volume effect is used for automated tests only
7603#ifndef OPENSL_ES_H_
7604static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7605 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7606const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7607#endif //OPENSL_ES_H_
7608
Eric Laurentdb7c0792011-08-10 10:37:50 -07007609bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7610{
7611 // auxiliary effects and visualizer are never suspended on output mix
7612 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7613 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007614 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7615 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007616 return false;
7617 }
7618 return true;
7619}
7620
Eric Laurent59255e42011-07-27 19:49:51 -07007621Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7622{
7623 Vector< sp<EffectModule> > effects;
7624 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007625 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007626 continue;
7627 }
7628 effects.add(mEffects[i]);
7629 }
7630 return effects;
7631}
7632
7633sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7634 const effect_uuid_t *type)
7635{
7636 sp<EffectModule> effect;
7637 effect = getEffectFromType_l(type);
7638 if (effect != 0 && !effect->isEnabled()) {
7639 effect.clear();
7640 }
7641 return effect;
7642}
7643
7644void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7645 bool enabled)
7646{
7647 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7648 if (enabled) {
7649 if (index < 0) {
7650 // if the effect is not suspend check if all effects are suspended
7651 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7652 if (index < 0) {
7653 return;
7654 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007655 if (!isEffectEligibleForSuspend(effect->desc())) {
7656 return;
7657 }
Eric Laurent59255e42011-07-27 19:49:51 -07007658 setEffectSuspended_l(&effect->desc().type, enabled);
7659 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007660 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007661 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007662 return;
7663 }
Eric Laurent59255e42011-07-27 19:49:51 -07007664 }
Steve Block3856b092011-10-20 11:56:00 +01007665 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007666 effect->desc().type.timeLow);
7667 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7668 // if effect is requested to suspended but was not yet enabled, supend it now.
7669 if (desc->mEffect == 0) {
7670 desc->mEffect = effect;
7671 effect->setEnabled(false);
7672 effect->setSuspended(true);
7673 }
7674 } else {
7675 if (index < 0) {
7676 return;
7677 }
Steve Block3856b092011-10-20 11:56:00 +01007678 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007679 effect->desc().type.timeLow);
7680 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7681 desc->mEffect.clear();
7682 effect->setSuspended(false);
7683 }
7684}
7685
Mathias Agopian65ab4712010-07-14 17:59:35 -07007686#undef LOG_TAG
7687#define LOG_TAG "AudioFlinger"
7688
7689// ----------------------------------------------------------------------------
7690
7691status_t AudioFlinger::onTransact(
7692 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7693{
7694 return BnAudioFlinger::onTransact(code, data, reply, flags);
7695}
7696
Mathias Agopian65ab4712010-07-14 17:59:35 -07007697}; // namespace android